Пример #1
0
void QssParser::parseListItemBlock(const QString &decl, const QString &contents)
{
    quint32 fmtType = parseItemFormatType(decl);
    if (fmtType == UiStyle::Invalid)
        return;

    _listItemFormats[fmtType].merge(parseFormat(contents));
}
Пример #2
0
void QssParser::parseChatLineBlock(const QString &decl, const QString &contents)
{
    quint64 fmtType = parseFormatType(decl);
    if (fmtType == UiStyle::Invalid)
        return;

    _formats[fmtType].merge(parseFormat(contents));
}
Пример #3
0
int vsnprintf(char *dest, int maxlen, const char *format, va_list vl){
	int destpos=0;

	maxlen--;
	
	for (int formatpos=0; format[formatpos];){
		//stop if no more space in destination
		if (destpos>=maxlen)
			break;
		
		//Ordinary character
		if (format[formatpos]!='%'){
			dest[destpos++]=format[formatpos++];
			continue;
		}
		
		//handle %%
		formatpos++;
		if (format[formatpos]=='%'){
			dest[destpos++]='%';
			formatpos++;
			continue;
		}
		
		//handle format string
		FormatType type;
		int precision;
		
		int formatLen=parseFormat(&format[formatpos], type, precision);
		if (formatLen==0){
			//Invalid format
			dest[destpos++]='%';
			formatpos++;
			continue;
		}		
		
		formatpos+=formatLen;
		
		switch (type){
			case (FT_INT):
				destpos+=toString(&dest[destpos], maxlen-destpos,  va_arg(vl, int), 10, precision, true);
				break;
			case (FT_HEX):
				destpos+=toString(&dest[destpos], maxlen-destpos,  va_arg(vl, int), 16, precision, false);
				break;
			case (FT_STRING):{
					char *str = va_arg(vl, char*);
					int len=std::min(std::max(precision, (int)strlen(str)), maxlen-destpos);
					memcpy(&dest[destpos], str, len);
					destpos+=len;
				}
				break;
		}		
	}
	
	dest[destpos]=0;
	return destpos+1;
}
Пример #4
0
JNIEXPORT jlong JNICALL Java_org_apache_harmony_awt_gl_windows_BitmapSurface_createSurfData
(JNIEnv *env, jobject obj, jlong gi, jint width, jint height){

    SURFACE_STRUCTURE *surf = (SURFACE_STRUCTURE *)calloc(sizeof(SURFACE_STRUCTURE), 1);
    surf->width = width;
    surf->height = height;
    surf->gi = (GraphicsInfo *)gi;
    parseFormat(surf);
    return (jlong)surf;
}
Пример #5
0
static ASTPtr generateCCs(std::vector<ConsistentContent>* ccs, const char* format, const char*** wordSourcesPtr, const LengthFunc** lengthFuncsPtr, va_list args) {
  ccs->clear();
  std::string evaluatedFormat;
  vsprintf(&evaluatedFormat, format, args);
  const char* f_begin = evaluatedFormat.c_str();
  const char* f_at = f_begin;
  ASTPtr root;
  try {
    //printf("\n\n%s\n", format);

    root = parseFormat(&f_at, wordSourcesPtr, lengthFuncsPtr);
    root->convertLLSharesToLength();
    root->computeStartEndCols(0, root->getFixedLength());

    std::vector<FillerPtr> topFillersStack, bottomFillersStack;
    root->flatten(root, root, ccs, true, &topFillersStack, &bottomFillersStack);
    //root->print();
    //printf("\n");

    for (ConsistentContent& cc : *ccs) {
      cc.generateCCLines();
    }

    root->computeNumContentLines();
    root->computeNumTotalLines(true);
    root->computeBlockVerticalFillersShares();

    //printf("\n");
    for (ConsistentContent& cc : *ccs) {
      /*printf("\n");
      cc.print();
      printf("\n");
      printf("content: %d  fixed: %d  total: %d\n", cc.srcAst->numContentLines, cc.srcAst->numFixedLines, cc.srcAst->numTotalLines);*/
      cc.generateLinesChars(root->numTotalLines);
    }
    //printf("\n\n");

  } catch (DSLException& e) {
    fprintf(stderr, "%s\n", f_begin);
    for (int i = 0; i < e.f_at - f_begin; ++i) {
      fputc(' ', stderr);
    }
    fprintf(stderr, "^\n");
    fprintf(stderr, "Error at %d: %s\n", e.f_at - f_begin, e.what());
    
    return ASTPtr();
  }

  return root;
}
Пример #6
0
void streamprintf(std::ostream& stream, const char* format, const T& value, Args... args)
{
	while (*format)
	{
		if (*format == '%' && *++format != '%')
		{
			auto flags = stream.flags();
			parseFormat(stream, format);
			stream << value;
			stream.flags(flags);
			streamprintf(stream, format, args...);
			return;
		}
		else
		{
			stream << *format++;
		}
	}
}
Пример #7
0
//static
Command* Command::parseTokens( Tokens& tokens, bool helpMode )
{
    if (tokens.empty()) THROW( CWDB_ERR_PARSER, "Bad syntax: no tokens to parse");
    Command* result = 0;
    try {
        switch(tokens.front().m_angen) {
            case ANGEN_CREATE:   parseCreate( tokens, helpMode, result ); break;
            case ANGEN_DESCR:    parseDescr( tokens, helpMode, result ); break;
            case ANGEN_DROP:     parseDrop( tokens, helpMode, result ); break;
            case ANGEN_DUMP:     parseDump( tokens, helpMode, result ); break;
            case ANGEN_GET:
            case ANGEN_SET:
            case ANGEN_PUT:      parseInput( tokens, helpMode, result ); break;
            case ANGEN_QUERY:    parseQuery( tokens, helpMode, result ); break;
            case ANGEN_USE:      parseUse( tokens, helpMode, result ); break;
            case ANGEN_GENERATE: parseGenerate( tokens, helpMode, result ); break;
            case ANGEN_VERSION:  parseVersion( tokens, helpMode, result ); break;
            case ANGEN_FORMAT:   parseFormat( tokens, helpMode, result ); break;
            case ANGEN_COMPACT:  parseCompact( tokens, helpMode, result ); break;
            case ANGEN_UPDATE:   parseUpdate( tokens, helpMode, result ); break;
            case ANGEN_START:
            case ANGEN_STOP:     parseStart( tokens, helpMode, result ); break;
            case ANGEN_EXPORT:   parseExport( tokens, helpMode, result ); break;
            case ANGEN_IMPORT:   parseImport( tokens, helpMode, result ); break;
            default: THROW( CWDB_ERR_PARSER, "Bad syntax: unknown command" );
        }
    }
    catch (CWDBException& e) {
        if (result != 0) {
            delete result;
            result = 0;
        }
        throw e;
    }

    return result;
}
Пример #8
0
FormatSpec::FormatSpec(const char* format_, int formatlen_): format(format_) {
	assert(format_ && (formatlen_ >= 0));
	parseFormat(formatlen_);
}
void mapcache_configuration_parse_xml(mapcache_context *ctx, const char *filename, mapcache_cfg *config) {
   ezxml_t doc, node;
   const char *mode;
   doc = ezxml_parse_file(filename);
   if (doc == NULL) {
      ctx->set_error(ctx,400, "failed to parse file %s. Is it valid XML?", filename);
      goto cleanup;
   } else {
      const char *err = ezxml_error(doc);
      if(err && *err) {
         ctx->set_error(ctx,400, "failed to parse file %s: %s", filename, err);
         goto cleanup;
      }
   }

   if(strcmp(doc->name,"mapcache")) {
      ctx->set_error(ctx,400, "failed to parse file %s. first node is not <mapcache>", filename);
      goto cleanup;
   }
   mode = ezxml_attr(doc,"mode");
   if(mode) {
      if(!strcmp(mode,"combined_mirror")) {
         config->mode = MAPCACHE_MODE_MIRROR_COMBINED;
      } else if(!strcmp(mode,"split_mirror")) {
         config->mode = MAPCACHE_MODE_MIRROR_SPLIT;
      } else if(!strcmp(mode,"normal")) {
         config->mode = MAPCACHE_MODE_NORMAL;
      } else {
         ctx->set_error(ctx,400,"unknown mode \"%s\" for <mapcache>",mode);
         goto cleanup;
      }
   } else {
         config->mode = MAPCACHE_MODE_NORMAL;
   }

   for(node = ezxml_child(doc,"metadata"); node; node = node->next) {
      parseMetadata(ctx, node, config->metadata);
      if(GC_HAS_ERROR(ctx)) goto cleanup;
   }

   for(node = ezxml_child(doc,"source"); node; node = node->next) {
      parseSource(ctx, node, config);
      if(GC_HAS_ERROR(ctx)) goto cleanup;
   }

   for(node = ezxml_child(doc,"grid"); node; node = node->next) {
      parseGrid(ctx, node, config);
      if(GC_HAS_ERROR(ctx)) goto cleanup;
   }

   for(node = ezxml_child(doc,"format"); node; node = node->next) {
      parseFormat(ctx, node, config);
      if(GC_HAS_ERROR(ctx)) goto cleanup;
   }

   for(node = ezxml_child(doc,"cache"); node; node = node->next) {
      parseCache(ctx, node, config);
      if(GC_HAS_ERROR(ctx)) goto cleanup;
   }

   for(node = ezxml_child(doc,"tileset"); node; node = node->next) {
      parseTileset(ctx, node, config);
      if(GC_HAS_ERROR(ctx)) goto cleanup;
   }

   if ((node = ezxml_child(doc,"service")) != NULL) {
      ezxml_t service_node;
      for(service_node = node; service_node; service_node = service_node->next) {
         char *enabled = (char*)ezxml_attr(service_node,"enabled");
         char *type = (char*)ezxml_attr(service_node,"type");
         if(!strcasecmp(enabled,"true")) {
            if (!strcasecmp(type,"wms")) {
               mapcache_service *new_service = mapcache_service_wms_create(ctx);
               if(new_service->configuration_parse_xml) {
                  new_service->configuration_parse_xml(ctx,service_node,new_service,config);
               }
               config->services[MAPCACHE_SERVICE_WMS] = new_service;
            }
            else if (!strcasecmp(type,"tms")) {
               mapcache_service *new_service = mapcache_service_tms_create(ctx);
               if(new_service->configuration_parse_xml) {
                  new_service->configuration_parse_xml(ctx,service_node,new_service,config);
               }
               config->services[MAPCACHE_SERVICE_TMS] = new_service;
            }
            else if (!strcasecmp(type,"wmts")) {
               mapcache_service *new_service = mapcache_service_wmts_create(ctx);
               if(new_service->configuration_parse_xml) {
                  new_service->configuration_parse_xml(ctx,service_node,new_service,config);
               }
               config->services[MAPCACHE_SERVICE_WMTS] = new_service;
            }
            else if (!strcasecmp(type,"kml")) {
               mapcache_service *new_service = mapcache_service_kml_create(ctx);
               if(new_service->configuration_parse_xml) {
                  new_service->configuration_parse_xml(ctx,service_node,new_service,config);
               }
               config->services[MAPCACHE_SERVICE_KML] = new_service;
            }
            else if (!strcasecmp(type,"gmaps")) {
               mapcache_service *new_service = mapcache_service_gmaps_create(ctx);
               if(new_service->configuration_parse_xml) {
                  new_service->configuration_parse_xml(ctx,service_node,new_service,config);
               }
               config->services[MAPCACHE_SERVICE_GMAPS] = new_service;
            }
            else if (!strcasecmp(type,"ve")) {
               mapcache_service *new_service = mapcache_service_ve_create(ctx);
               if(new_service->configuration_parse_xml) {
                  new_service->configuration_parse_xml(ctx,service_node,new_service,config);
               }
               config->services[MAPCACHE_SERVICE_VE] = new_service;
            }
            else if (!strcasecmp(type,"demo")) {
               mapcache_service *new_service = mapcache_service_demo_create(ctx);
               if(new_service->configuration_parse_xml) {
                  new_service->configuration_parse_xml(ctx,service_node,new_service,config);
               }
               config->services[MAPCACHE_SERVICE_DEMO] = new_service;
            } else {
               ctx->set_error(ctx,400,"unknown <service> type %s",type);
            }
            if(GC_HAS_ERROR(ctx)) goto cleanup;
         }
      }
   }
   else if ((node = ezxml_child(doc,"services")) != NULL) {
      ctx->log(ctx,MAPCACHE_WARN,"<services> tag is deprecated, use <service type=\"wms\" enabled=\"true|false\">");
      parseServices(ctx, node, config);
   } else {
      ctx->set_error(ctx, 400, "no <services> configured");
   }
   if(GC_HAS_ERROR(ctx)) goto cleanup;


   node = ezxml_child(doc,"default_format");
   if(!node)
      node = ezxml_child(doc,"merge_format");
   if (node) {
      mapcache_image_format *format = mapcache_configuration_get_image_format(config,node->txt);
      if(!format) {
         ctx->set_error(ctx, 400, "default_format tag references format %s but it is not configured",
               node->txt);
         goto cleanup;
      }
      config->default_image_format = format;
   }

   if ((node = ezxml_child(doc,"errors")) != NULL) {
      if(!strcmp(node->txt,"log")) {
         config->reporting = MAPCACHE_REPORT_LOG;
      } else if(!strcmp(node->txt,"report")) {
         config->reporting = MAPCACHE_REPORT_MSG;
      } else if(!strcmp(node->txt,"empty_img")) {
         config->reporting = MAPCACHE_REPORT_EMPTY_IMG;
         mapcache_image_create_empty(ctx, config);
         if(GC_HAS_ERROR(ctx)) goto cleanup;
      } else if(!strcmp(node->txt, "report_img")) {
         config->reporting = MAPCACHE_REPORT_ERROR_IMG;
         ctx->set_error(ctx,501,"<errors>: report_img not implemented");
         goto cleanup;
      } else {
         ctx->set_error(ctx,400,"<errors>: unknown value %s (allowed are log, report, empty_img, report_img)",
               node->txt);
         goto cleanup;
      }
   }

   if((node = ezxml_child(doc,"lock_dir")) != NULL) {
      config->lockdir = apr_pstrdup(ctx->pool, node->txt);
   } else {
      config->lockdir = apr_pstrdup(ctx->pool,"/tmp");
   }

   if((node = ezxml_child(doc,"lock_retry")) != NULL) {
      char *endptr;
      config->lock_retry_interval = (unsigned int)strtol(node->txt,&endptr,10);
      if(*endptr != 0 || config->lock_retry_interval < 0) {
         ctx->set_error(ctx, 400, "failed to parse lock_retry microseconds \"%s\". Expecting a positive integer",
               node->txt);
         return;
      }
   }
   
   if((node = ezxml_child(doc,"threaded_fetching")) != NULL) {
      if(!strcasecmp(node->txt,"true")) {
         config->threaded_fetching = 1;
      } else if(strcasecmp(node->txt,"false")) {
         ctx->set_error(ctx, 400, "failed to parse threaded_fetching \"%s\". Expecting true or false",node->txt);
         return;
      }
   }

   if((node = ezxml_child(doc,"log_level")) != NULL) {
      if(!strcasecmp(node->txt,"debug")) {
         config->loglevel = MAPCACHE_DEBUG;
      } else if(!strcasecmp(node->txt,"info")) {
         config->loglevel = MAPCACHE_INFO;
      } else if(!strcasecmp(node->txt,"notice")) {
         config->loglevel = MAPCACHE_NOTICE;
      } else if(!strcasecmp(node->txt,"warn")) {
         config->loglevel = MAPCACHE_WARN;
      } else if(!strcasecmp(node->txt,"error")) {
         config->loglevel = MAPCACHE_ERROR;
      } else if(!strcasecmp(node->txt,"crit")) {
         config->loglevel = MAPCACHE_CRIT;
      } else if(!strcasecmp(node->txt,"alert")) {
         config->loglevel = MAPCACHE_ALERT;
      } else if(!strcasecmp(node->txt,"emerg")) {
         config->loglevel = MAPCACHE_EMERG;
      } else {
         ctx->set_error(ctx,500,"failed to parse <log_level> \"%s\". Expecting debug, info, notice, warn, error, crit, alert or emerg",node->txt);
         return;
      }
   }
   if((node = ezxml_child(doc,"auto_reload")) != NULL) {
      if(!strcasecmp(node->txt,"true")) {
         config->autoreload = 1;
      } else if(!strcasecmp(node->txt,"false")) {
         config->autoreload = 0;
      } else {
         ctx->set_error(ctx,500,"failed to parse <auto_reload> \"%s\". Expecting true or false",node->txt);
         return;
      }
   }


cleanup:
   ezxml_free(doc);
   return;
}
Пример #10
0
FormatSpec::FormatSpec(const char* format_): format(format_) {
	assert(format_);
	parseFormat(strlen(format));
}
Пример #11
0
 Format fmt(const char *p)
 {
     return parseFormat(p);
 }
Пример #12
0
 Format fmt(const std::string& s)
 {
     const char *p = s.c_str();
     return parseFormat(p);
 }
Пример #13
0
status WAVEFile::readInit(AFfilesetup setup)
{
	Tag type, formtype;
	uint32_t size;
	uint32_t index = 0;

	bool hasFormat = false;
	bool hasData = false;
	bool hasCue = false;
	bool hasList = false;
	bool hasPlayList = false;
	bool hasFrameCount = false;
	bool hasINST = false;

	Track *track = allocateTrack();

	fh->seek(0, File::SeekFromBeginning);

	readTag(&type);
	readU32(&size);
	readTag(&formtype);

	assert(type == "RIFF");
	assert(formtype == "WAVE");

#ifdef DEBUG
	printf("size: %d\n", size);
#endif

	/* Include the offset of the form type. */
	index += 4;

	while (index < size)
	{
		Tag chunkid;
		uint32_t chunksize = 0;
		status result;

#ifdef DEBUG
		printf("index: %d\n", index);
#endif
		readTag(&chunkid);
		readU32(&chunksize);

#ifdef DEBUG
		printf("%s size: %d\n", chunkid.name().c_str(), chunksize);
#endif

		if (chunkid == "fmt ")
		{
			result = parseFormat(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;

			hasFormat = true;
		}
		else if (chunkid == "data")
		{
			/* The format chunk must precede the data chunk. */
			if (!hasFormat)
			{
				_af_error(AF_BAD_HEADER, "missing format chunk in WAVE file");
				return AF_FAIL;
			}

			result = parseData(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;

			hasData = true;
		}
		else if (chunkid == "inst")
		{
			result = parseInstrument(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;
		}
		else if (chunkid == "fact")
		{
			hasFrameCount = true;
			result = parseFrameCount(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;
		}
		else if (chunkid == "cue ")
		{
			hasCue = true;
			result = parseCues(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;
		}
		else if (chunkid == "LIST" || chunkid == "list")
		{
			hasList = true;
			result = parseList(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;
		}
		else if (chunkid == "INST")
		{
			hasINST = true;
			result = parseInstrument(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;
		}
		else if (chunkid == "plst")
		{
			hasPlayList = true;
			result = parsePlayList(chunkid, chunksize);
			if (result == AF_FAIL)
				return AF_FAIL;
		}

		index += chunksize + 8;

		/* All chunks must be aligned on an even number of bytes */
		if ((index % 2) != 0)
			index++;

		fh->seek(index + 8, File::SeekFromBeginning);
	}

	/* The format chunk and the data chunk are required. */
	if (!hasFormat || !hasData)
	{
		return AF_FAIL;
	}

	/*
		At this point we know that the file has a format chunk
		and a data chunk, so we can assume that track->f and
		track->data_size have been initialized.
	*/
	if (!hasFrameCount)
	{
		track->totalfframes = track->data_size /
			(int) _af_format_frame_size(&track->f, false);
	}

	if (track->f.compressionType != AF_COMPRESSION_NONE &&
		(track->f.compressionType == AF_COMPRESSION_G711_ULAW ||
		track->f.compressionType == AF_COMPRESSION_G711_ALAW))
	{
		track->totalfframes = track->data_size / track->f.channelCount;
	}

	/*
		A return value of AF_SUCCEED indicates successful parsing.
	*/
	return AF_SUCCEED;
}
Пример #14
0
// Parse one line of text, create fragments, end line when overflow width.
void PaintText::parseFragmentsWithCharBreak(
    TextLine& line,             // Line descriptor.
    int startPos,               // Location of beginning of string to examine.
    int endPos,                 // Location of one past the last character to examine.
    float maxWidth,             // Can't go beyond this width.
    bool ellipsis,              // True = if line doesn't fit, append ellipsis.
    int* resultPos              // OUT: Ptr to string past the format string.
) {
    int curPos = startPos;          // Beginning of current part of the string we are working on.
    double curWidth = maxWidth;     // The width left to work with.

    bool forceEndLine = false;      // True = end-of-line through format.  False = char width.

    while(curPos < endPos) {
        // Is there a format char left in this string?
        const string::size_type formatPos = m_text.find(DT_FORMAT_CHAR, curPos);
        if(formatPos == std::string::npos || formatPos >= endPos) {
            // No format char.
            addFragment(line, endPos, curPos, curWidth);
            break;
        }

        // Create fragment for characters before the format char.
        addFragment(line, formatPos, curPos, curWidth);
        if(curPos < formatPos) {
            // Format is past the max width.  We're done with this line.
            break;
        }

        // Interpret the format command.
        assert(m_text[curPos] == DT_FORMAT_CHAR);
        curPos++;       // Look at the command char.
        if(curPos >= endPos) {
            // No command char.  String ends with single "#".  Ignore it.
            curPos = endPos - 1;
            break;
        }
        if(m_text[curPos] == DT_FORMAT_CHAR) {
            // Double format char.  Equals one format char.
            const int oldPos = curPos;
            addFragment(line, curPos+1, curPos, curWidth);
            if(curPos == oldPos) {
                // No room in the line for the one char.  Leave it for next line.
                curPos--;           // Put chars back in string.
                break;              // End of this line.
            }
        } else {
            parseFormat(curPos, &curPos, &forceEndLine);
            if(forceEndLine) {
                break;
            }
        }
    }

    if(!forceEndLine && curPos < endPos) {
        if(ellipsis) {
            // We need to append an ellipsis. We didn't use the whole string, and we didn't end
            //  the line because of a format command.
            // We use the font at the end of the line.  This is a hack, but it seems like a
            //  reasonable compromise.  If we use the font from the beginning of the line, suppose the
            //  line starts out with bold, followed by a non-bold explanation?
            // We use the color of the last fragment before the ellipsis.

            const Font& font = m_layout.fontStack.back();
            const double ellipsisWidth = font.stringWidth(ELLIPSIS_STRING);
            // If ellipsis doesn't fit in the original width, just ship the truncated string.
            if(ellipsisWidth < maxWidth) {
                while(line.fragments.size() > 0) { 
                    TextFragment& frag = line.fragments.back();
                    // Remove enough space in the last fragment to be able to append the ellipsis.
                    int i;
                    for(i=frag.end; i>=frag.start; i--) {
                        curWidth -= frag.font.charWidth(m_text[i]);
                        if(curWidth+ellipsisWidth <= maxWidth) {
                            // If we back up this far, the ellipsis will fit in the max width.
                            frag.end = i;
                            break;
                        }
                    }
                    if(i < frag.start) {
                        // Used up the whole fragment and still didn't find enough space.
                        line.fragments.pop_back();
                    } else {
                        // Create an ellipsis fragment and append it to the line.
                        TextFragment newFrag = frag;
                        newFrag.start = ELLIPSIS_FRAGMENT;
                        line.fragments.push_back(newFrag);
                        curWidth += ellipsisWidth;
                        break;
                    }
                }
            }
        } else {
            // Get rid of word break chars at the end of this line.
            // First, make sure to skip over any white space.
            while(curPos < endPos && isWordBreak(m_text[curPos])) {
                curPos++;
            }

            // Now, get rid of any word break chars at the tail end of our fragment list.
            while(line.fragments.size() > 0) { 
                TextFragment& frag = line.fragments.back();
                int i;
                for(i=frag.end; i>=frag.start; i--) {
                    if(!isWordBreak(m_text[i])) {
                        break;
                    }
                    curWidth -= frag.font.charWidth(m_text[i]);
                }
                if(i >= frag.start) {
                    // Found something besides a word break in this fragment.
                    break;
                }
                // Used up the whole fragment.  Start on the next one.
                line.fragments.pop_back();
            }
        }
    }

    // Set the width of this line.
    line.width = maxWidth - curWidth;

    // And make sure we know how far we got in the string.
    *resultPos = curPos;
}
Пример #15
0
// Parse one line of text, create fragments, end line on word break when width overflows.
void PaintText::parseFragmentsWithWordBreak(
    TextLine& line,             // Line descriptor.
    int startPos,               // Location of beginning of string to examine.
    float maxWidth,             // Can't go beyond this width.
    int* resultPos              // OUT: Ptr to string past the format string.
) {
    int curPos = startPos;          // Beginning of current part of the string we are working on.
    double curWidth = maxWidth;     // The width left to work with.
    const int endPos = m_text.size();// One past the end of the string.

    bool forceEndLine = false;      // True = end-of-line through format.  False = char width.
    LayoutState origLayout = m_layout;// The original layout state before we start the line.

    int wordBreakPos = endPos;      // Previous word break location in text.

    // In this loop we just measure the width.  We find the end of the current line in m_text,
    //  then call parseFragmentsWithCharBreak once we know how far to go.
    while(curPos < endPos) {
        // Is there a format char left in this string?
        const string::size_type formatPos = m_text.find(DT_FORMAT_CHAR, curPos);
        int endFragPos = formatPos;
        if(formatPos == std::string::npos || formatPos >= endPos) {
            // No format char.
            endFragPos = endPos;
        }

        // Loop through the characters until we run out of room.
        const Font& font = m_layout.fontStack.back();
        while(curPos < endFragPos) {
            double charWidth = font.charWidth(m_text[curPos]);
            if(isWordBreak(m_text[curPos])) {
                wordBreakPos = curPos;
            }
            if(curWidth - charWidth < 0.0) {
                // The current character goes past the specified width.
                break;
            }
            curWidth -= charWidth;
            curPos++;
        }

        if(curPos == endPos) {
            // The rest of the text is not as wide as the max.  We are done with this pass.
            wordBreakPos = endPos;
            break;
        } else if(curPos < endFragPos) {
            // We found a last character. Go back to the last word break.
            break;
        }
        assert(curPos == formatPos);    // Other other case: we ran into a format command.

        // Interpret the format command.
        assert(m_text[curPos] == DT_FORMAT_CHAR);
        curPos++;       // Look at the command char.
        if(curPos >= endPos) {
            // No command char.  String ends with single "#".  Ignore it.
            curPos = endPos - 1;
            break;
        }
        if(m_text[curPos] == DT_FORMAT_CHAR) {
            // Double format char.  Equals one format char.
            curWidth -= font.charWidth(DT_FORMAT_CHAR);
            if(curWidth < 0.0) {
                // No room in the line for the one char.  Leave it for next line.
                curPos--;           // Put chars back in string.
                break;              // End of this line.
            }
        } else {
            parseFormat(curPos, &curPos, &forceEndLine);
            if(forceEndLine) {
                wordBreakPos = endPos;
                break;
            }
        }
    }

    // Now we need to generate the fragments.
    // NOTE:  If the text contains a word that is too long for a line, we get a special case
    //  where we never find a word break.  That ends up calling parseFragmentsWithCharBreak with
    //  the end of the string as the limit, so the word is broken on a char boundary, which is 
    //  exactly what we want.
    int endLinePos = wordBreakPos + 1;
    // Include all extra word break characters.
    while(endLinePos+1 < endPos && isWordBreak(m_text[endLinePos])) {
        endLinePos++;
    }
    m_layout = origLayout;                 // Undo any format changes.
    parseFragmentsWithCharBreak(line, startPos, endLinePos, maxWidth, false, resultPos);
}
Пример #16
0
  static bool loadZum1(std::string const& dataIn)
  {
    // Remove the header data
    const std::string data = dataIn.substr(5);

    createDefaultEmpty();
    currentDoc().width_ = 0;
    currentDoc().height_ = 0;

    ini_t * ini = ini_load(data.c_str(), nullptr);

    { // Load columns section
      const int columnsSection = ini_find_section(ini, "columns", 0);
      if (columnsSection != INI_NOT_FOUND)
      {
        const int columnsCount = ini_property_count(ini, columnsSection);
        for (int i = 0; i < columnsCount; ++i)
        {
          const int col = Index::strToColumn(std::string(ini_property_name(ini, columnsSection, i)));
          const int width = std::atoi(ini_property_value(ini, columnsSection, i));

          currentDoc().columnWidth_[col] = width;
        }
      }      
    }

    { // Load data section
      const int dataSection = ini_find_section(ini, "data", 0);
      if (dataSection == INI_NOT_FOUND)
      {
        logError("Could not locate the data section in the document");
        ini_destroy(ini);
        return false;
      }

      const int dataCount = ini_property_count(ini, dataSection);
      
      for (int i = 0; i < dataCount; ++i)
      {
        const Index idx = Index::fromStr(std::string(ini_property_name(ini, dataSection, i)));
        const std::string value = ini_property_value(ini, dataSection, i);

        setText(idx, value);
      }
    }

    { // Load format section
      const int formatSection = ini_find_section(ini, "format", 0);
      if (formatSection != INI_NOT_FOUND)
      {
        const int formatCount = ini_property_count(ini, formatSection);
        for (int i = 0; i < formatCount; ++i)
        {
          const Index idx = Index::fromStr(std::string(ini_property_name(ini, formatSection, i)));
          const std::string value = ini_property_value(ini, formatSection, i);

          getCell(idx).format = parseFormat(value);
        }
      }
    }

    ini_destroy(ini);

    evaluateDocument();
    return true;
  }
Пример #17
0
int main(int argc, char ** argv) {
  int iline=0, i, iarg=1, nfields=1, jmax=0, writetxt=0, writemat=0, grpsize=1;
  int membuf=1048576;
  char * here, *linebuf, *readbuf;
  string ifname = "", ofname = "", mfname = "", ffname = "", matfname = "", fdelim="\t", suffix="";
  if (argc < 2) {
    printf("%s", usage);
    return 1;
  }
  while (iarg < argc) {
    if (strncmp(argv[iarg], "-d", 2) == 0) {
      fdelim = argv[++iarg];
    } else if (strncmp(argv[iarg], "-c", 2) == 0) {
      suffix=".gz";
    } else if (strncmp(argv[iarg], "-f", 2) == 0) {
      ffname = argv[++iarg];
    } else if (strncmp(argv[iarg], "-i", 2) == 0) {
      ifname = argv[++iarg];
    } else if (strncmp(argv[iarg], "-m", 2) == 0) {
      mfname = argv[++iarg];
    } else if (strncmp(argv[iarg], "-o", 2) == 0) {
      ofname = argv[++iarg];
    } else if (strncmp(argv[iarg], "-s", 2) == 0) {
      membuf = strtol(argv[++iarg],NULL,10);
    } else if (strncmp(argv[iarg], "-?", 2) == 0) {
      printf("%s", usage);
      return 1;
    } else if (strncmp(argv[iarg], "-h", 2) == 0) {
      printf("%s", usage);
      return 1;
    } else {
      cout << "Unknown option " << argv[iarg] << endl;
      exit(1);
    }
    iarg++;
  }
  if (mfname.size() == 0) mfname = ofname;
  ivector tvec(0);
  svector delims(0);
  svector dnames(0);
  nfields = parseFormat(ffname, tvec, dnames, delims, &grpsize);
  srivector srv(nfields);
  ftvector ftv(nfields);

  istream * ifstr;
  linebuf = new char[membuf];
  readbuf = new char[membuf];

  ifstr = open_in_buf(ifname, readbuf, membuf);

  while (!ifstr->bad() && !ifstr->eof()) {
    ifstr->getline(linebuf, membuf-1);
    linebuf[membuf-1] = 0;
    if (ifstr->fail()) {
      ifstr->clear();
      ifstr->ignore(LONG_MAX,'\n');
    }
    if (strlen(linebuf) > 0) {
      jmax++;
      try {
        parseLine(linebuf, membuf, ++iline, fdelim.c_str(), tvec, delims, srv, ftv, grpsize);
      } catch (int e) {
        cerr << "Continuing" << endl;
      }
    }
    if ((jmax % 100000) == 0) {
      cout<<"\r"<<jmax<<" lines processed";
      cout.flush();
    }
  }
  if (ifstr) delete ifstr;
  cout<<"\r"<<jmax<<" lines processed";
  cout.flush();

  for (i = 0; i < nfields; i++) {
    switch (tvec[i]) {
    case ftype_int: case ftype_dt: case ftype_mdt: case ftype_date: case ftype_mdate: case ftype_cmdate:
      ftv[i].writeInts(ofname + dnames[i] + ".imat" + suffix);
      break;
    case ftype_dint:
      ftv[i].writeDInts(ofname + dnames[i] + ".dimat" + suffix);
      break;
    case ftype_qhex:
      ftv[i].writeQInts(ofname + dnames[i] + ".imat" + suffix);
      break;
    case ftype_float:
      ftv[i].writeFloats(ofname + dnames[i] + ".fmat" + suffix);
      break;
    case ftype_double:
      ftv[i].writeDoubles(ofname + dnames[i] + ".dmat" + suffix);
      break;
    case ftype_word:
      ftv[i].writeInts(ofname + dnames[i] + ".imat" + suffix);
      srv[i].writeMap(mfname + dnames[i], suffix);
      break;
    case ftype_string: case ftype_group: 
      ftv[i].writeIVecs(ofname + dnames[i] + ".imat" + suffix);
      srv[i].writeMap(mfname + dnames[i], suffix);
      break;
    case ftype_igroup:
      ftv[i].writeIVecs(ofname + dnames[i] + ".imat" + suffix);
      break;
    case ftype_digroup:
      ftv[i].writeDIVecs(ofname + dnames[i]);
      break;
    default:
      break;
    }    
  }
  printf("\n");
  if (linebuf) delete [] linebuf;
  return 0;
}