Exemple #1
0
inline CharAcceptor const& shell_quote_chars_iter(CharAcceptor const& chars, CharForwardIter i, CharForwardIter end, bool quote_empty=true)
{
  if (i==end) {
    if (quote_empty) {
      chars('"');
      chars('"');
    }
  } else if (std::find_if(i, end, is_shell_special<char>)==end) {
    for(;i!=end;++i)
      chars(*i);
  } else {
    chars('"');
    for(;i!=end;++i) {
      char c=*i;
      if (needs_shell_escape_in_quotes(c))
        chars('\\');
      chars(c);
    }
    chars('"');
  }
  return chars;
}
Exemple #2
0
void alignedNormalizeUnicodeString(icu::UnicodeString const& u, IcuNormalizer2Ptr normalizer,
                                   ITakeAlignedChars& out) {
    // TODO: test
    Position start = 0;
    int32 len = u.length(), pos;
    UErrorCode err = U_ZERO_ERROR;
    int nfcPrefixLen = normalizer->spanQuickCheckYes(u, err);
    assert(U_SUCCESS(err));
    assert(len >= 0 && nfcPrefixLen >= 0);
    TokenSpan span;
    span.first = 0;
    icu::StringCharacterIterator it(u);
    while ((pos = it.getIndex()) < nfcPrefixLen) {
        assert(it.hasNext());
        Unicode c = it.next32PostInc();
        span.second = span.first + 1;
        out.takeWithSpan(c, span);
        ++span.first;
    }
    icu::UnicodeString remainder(u.tempSubString(nfcPrefixLen)), normalized;
    CharsFromUnicodeStringImpl chars(remainder);  // TODO: docs say normalizeSecondAndAppend
    IcuNormalizeByChunks<CharsFromUnicodeStringImpl> norm(chars, normalizer);
    norm.takeAllWithSpan(out);
}
Exemple #3
0
// write XPM image data
static bool write_xpm_image(const QImage &sourceImage, QIODevice *device, const QString &fileName)
{
    if (!device->isWritable())
        return false;

    QImage image;
    if (sourceImage.depth() != 32)
        image = sourceImage.convertToFormat(QImage::Format_RGB32);
    else
        image = sourceImage;

    QMap<QRgb, int> colorMap;

    int w = image.width(), h = image.height(), ncolors = 0;
    int x, y;

    // build color table
    for(y=0; y<h; y++) {
        QRgb * yp = (QRgb *)image.scanLine(y);
        for(x=0; x<w; x++) {
            QRgb color = *(yp + x);
            if (!colorMap.contains(color))
                colorMap.insert(color, ncolors++);
        }
    }

    // number of 64-bit characters per pixel needed to encode all colors
    int cpp = 1;
    for (int k = 64; ncolors > k; k *= 64) {
        ++cpp;
        // limit to 4 characters per pixel
        // 64^4 colors is enough for a 4096x4096 image
         if (cpp > 4)
            break;
    }

    QString line;

    // write header
    QTextStream s(device);
    s << "/* XPM */" << endl
      << "static char *" << fbname(fileName) << "[]={" << endl
      << '\"' << w << ' ' << h << ' ' << ncolors << ' ' << cpp << '\"';

    // write palette
    QMap<QRgb, int>::Iterator c = colorMap.begin();
    while (c != colorMap.end()) {
        QRgb color = c.key();
        if (image.format() != QImage::Format_RGB32 && !qAlpha(color))
            line.sprintf("\"%s c None\"",
                          xpm_color_name(cpp, *c));
        else
            line.sprintf("\"%s c #%02x%02x%02x\"",
                          xpm_color_name(cpp, *c),
                          qRed(color),
                          qGreen(color),
                          qBlue(color));
        ++c;
        s << ',' << endl << line;
    }

    // write pixels, limit to 4 characters per pixel
    line.truncate(cpp*w);
    for(y=0; y<h; y++) {
        QRgb * yp = (QRgb *) image.scanLine(y);
        int cc = 0;
        for(x=0; x<w; x++) {
            int color = (int)(*(yp + x));
            QByteArray chars(xpm_color_name(cpp, colorMap[color]));
            line[cc++] = QLatin1Char(chars[0]);
            if (cpp > 1) {
                line[cc++] = QLatin1Char(chars[1]);
                if (cpp > 2) {
                    line[cc++] = QLatin1Char(chars[2]);
                    if (cpp > 3) {
                        line[cc++] = QLatin1Char(chars[3]);
                    }
                }
            }
        }
        s << ',' << endl << '\"' << line << '\"';
    }
    s << "};" << endl;
    return (s.status() == QTextStream::Ok);
}
Exemple #4
0
MyOstream & GBString::InstanceToOStream(MyOstream & os) const {
  os << chars();
  return os;
};
Exemple #5
0
		result_t ParseJsonNumber(v8::Local<v8::Value> &retVal)
		{
			bool negative = false;
			int32_t beg_pos = position_;

			if (c0_ == '-') {
				Advance();
				negative = true;
			}

			if (c0_ == '0') {
				Advance();
				if (IsDecimalDigit(c0_))
					return ReportUnexpectedCharacter();
			} else
			{
				int32_t i = 0;
				int32_t digits = 0;
				if (c0_ < '1' || c0_ > '9')
					return ReportUnexpectedCharacter();

				do {
					i = i * 10 + c0_ - '0';
					digits++;
					Advance();
				} while (IsDecimalDigit(c0_));

				if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) {
					SkipWhitespace();
					retVal = v8::Int32::New(isolate->m_isolate, negative ? -i : i);
					return 0;
				}
			}

			if (c0_ == '.') {
				Advance();
				if (!IsDecimalDigit(c0_))
					return ReportUnexpectedCharacter();

				do {
					Advance();
				} while (IsDecimalDigit(c0_));
			}

			if (AsciiAlphaToLower(c0_) == 'e') {
				Advance();
				if (c0_ == '-' || c0_ == '+') Advance();
				if (!IsDecimalDigit(c0_))
					return ReportUnexpectedCharacter();

				do {
					Advance();
				} while (IsDecimalDigit(c0_));
			}

			int32_t length = position_ - beg_pos;
			double number;
			std::string chars(source_ + beg_pos, length);

			number = atof(chars.c_str());
			SkipWhitespace();
			retVal = v8::Number::New(isolate->m_isolate, number);
			return 0;
		}
Exemple #6
0
 Bytes(const void * source, size_t size) : m_data(size)
 {
     const auto * sourceChars = reinterpret_cast<const Byte *>(source);
     std::copy(sourceChars, sourceChars + size, chars());
 }
Exemple #7
0
 void copyTo(void * destination) const
 {
     std::copy(chars(), chars() + size(), static_cast<char*>(destination));
 }
Exemple #8
0
bool TeXCodes::contains(QString k) {
  return chars().contains(k);
}
Exemple #9
0
void SpellChecker::advanceToNextMisspelling(bool startBeforeSelection)
{
    // The basic approach is to search in two phases - from the selection end to the end of the doc, and
    // then we wrap and search from the doc start to (approximately) where we started.

    // Start at the end of the selection, search to edge of document. Starting at the selection end makes
    // repeated "check spelling" commands work.
    VisibleSelection selection(m_frame.selection().selection());
    RefPtr<Range> spellingSearchRange(rangeOfContents(m_frame.document()));

    bool startedWithSelection = false;
    if (selection.start().deprecatedNode()) {
        startedWithSelection = true;
        if (startBeforeSelection) {
            VisiblePosition start(selection.visibleStart());
            // We match AppKit's rule: Start 1 character before the selection.
            VisiblePosition oneBeforeStart = start.previous();
            setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
        } else {
            setStart(spellingSearchRange.get(), selection.visibleEnd());
        }
    }

    Position position = spellingSearchRange->startPosition();
    if (!isEditablePosition(position)) {
        // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
        // selection is editable.
        // This can happen in Mail for a mix of non-editable and editable content (like Stationary),
        // when spell checking the whole document before sending the message.
        // In that case the document might not be editable, but there are editable pockets that need to be spell checked.

        position = firstEditableVisiblePositionAfterPositionInRoot(position, m_frame.document()).deepEquivalent();
        if (position.isNull())
            return;

        Position rangeCompliantPosition = position.parentAnchoredEquivalent();
        spellingSearchRange->setStart(rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset(), IGNORE_EXCEPTION);
        startedWithSelection = false; // won't need to wrap
    }

    // topNode defines the whole range we want to operate on
    ContainerNode* topNode = highestEditableRoot(position);
    // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
    spellingSearchRange->setEnd(topNode, lastOffsetForEditing(topNode), IGNORE_EXCEPTION);

    // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
    // at a word boundary. Going back by one char and then forward by a word does the trick.
    if (startedWithSelection) {
        VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
        if (oneBeforeStart.isNotNull())
            setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
        // else we were already at the start of the editable node
    }

    if (spellingSearchRange->collapsed())
        return; // nothing to search in

    // We go to the end of our first range instead of the start of it, just to be sure
    // we don't get foiled by any word boundary problems at the start. It means we might
    // do a tiny bit more searching.
    Node* searchEndNodeAfterWrap = spellingSearchRange->endContainer();
    int searchEndOffsetAfterWrap = spellingSearchRange->endOffset();

    int misspellingOffset = 0;
    GrammarDetail grammarDetail;
    int grammarPhraseOffset = 0;
    RefPtr<Range> grammarSearchRange = nullptr;
    String badGrammarPhrase;
    String misspelledWord;

    bool isSpelling = true;
    int foundOffset = 0;
    String foundItem;
    RefPtr<Range> firstMisspellingRange = nullptr;
    if (unifiedTextCheckerEnabled()) {
        grammarSearchRange = spellingSearchRange->cloneRange();
        foundItem = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
        if (isSpelling) {
            misspelledWord = foundItem;
            misspellingOffset = foundOffset;
        } else {
            badGrammarPhrase = foundItem;
            grammarPhraseOffset = foundOffset;
        }
    } else {
        misspelledWord = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
        grammarSearchRange = spellingSearchRange->cloneRange();
        if (!misspelledWord.isEmpty()) {
            // Stop looking at start of next misspelled word
            CharacterIterator chars(grammarSearchRange.get());
            chars.advance(misspellingOffset);
            grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
        }

        if (isGrammarCheckingEnabled())
            badGrammarPhrase = TextCheckingHelper(spellCheckerClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
    }

    // If we found neither bad grammar nor a misspelled word, wrap and try again (but don't bother if we started at the beginning of the
    // block rather than at a selection).
    if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
        spellingSearchRange->setStart(topNode, 0, IGNORE_EXCEPTION);
        // going until the end of the very first chunk we tested is far enough
        spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, IGNORE_EXCEPTION);

        if (unifiedTextCheckerEnabled()) {
            grammarSearchRange = spellingSearchRange->cloneRange();
            foundItem = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
            if (isSpelling) {
                misspelledWord = foundItem;
                misspellingOffset = foundOffset;
            } else {
                badGrammarPhrase = foundItem;
                grammarPhraseOffset = foundOffset;
            }
        } else {
            misspelledWord = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
            grammarSearchRange = spellingSearchRange->cloneRange();
            if (!misspelledWord.isEmpty()) {
                // Stop looking at start of next misspelled word
                CharacterIterator chars(grammarSearchRange.get());
                chars.advance(misspellingOffset);
                grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
            }

            if (isGrammarCheckingEnabled())
                badGrammarPhrase = TextCheckingHelper(spellCheckerClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
        }
    }

    if (!badGrammarPhrase.isEmpty()) {
        // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
        // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
        // panel, and store a marker so we draw the green squiggle later.

        ASSERT(badGrammarPhrase.length() > 0);
        ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);

        // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
        RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
        m_frame.selection().setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
        m_frame.selection().revealSelection();

        m_frame.document()->markers().addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
    } else if (!misspelledWord.isEmpty()) {
        // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
        // a marker so we draw the red squiggle later.

        RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
        m_frame.selection().setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
        m_frame.selection().revealSelection();

        spellCheckerClient().updateSpellingUIWithMisspelledWord(misspelledWord);
        m_frame.document()->markers().addMarker(misspellingRange.get(), DocumentMarker::Spelling);
    }
}
Exemple #10
0
//credit for conversion function(with a minor tweak) http://stackoverflow.com/a/2687562
std::vector< bool > get_bits(unsigned long x, int numBits) {
	std::string chars(std::bitset< sizeof(long) * CHAR_BIT >(x)
		.to_string(char(0), char(1)));
	chars = chars.substr(chars.length()-numBits, chars.length());
	return std::vector< bool >(chars.begin(), chars.end());
}
Exemple #11
0
dInteger
dString::hash() const {
    return uALGO::hashFromByteSequence((dByte*)chars(), length() * sizeof(TCHAR));
}
Exemple #12
0
int String::endsWith(const char* szEnd) const
{
  if (szStr_ == 0) { return 0; }
  String sSuffix = subString(chars() - UTF8_CharLen(szEnd));
  return sSuffix == szEnd;
}
Exemple #13
0
void SnapshotLoader::load(ConcurrentTableSharedStore& s) {
  // This could share code with apc_load_impl_compressed, but that function
  // should go away together with the shared object format.
  {
    std::vector<KeyValuePair> ints(read32());
    for (auto& item : ints) {
      item.key = readString().begin();
      s.constructPrime(read64(), item);
    }
    s.prime(ints);
  }
  {
    std::vector<KeyValuePair> chars(read32());
    for (auto& item : chars) {
      item.key = readString().begin();
      switch (static_cast<SnapshotBuilder::CharBasedType>(read<char>())) {
        case SnapshotBuilder::kSnapFalse:
          s.constructPrime(false, item);
          break;
        case SnapshotBuilder::kSnapTrue:
          s.constructPrime(true, item);
          break;
        case SnapshotBuilder::kSnapNull:
          s.constructPrime(uninit_null(), item);
          break;
        default:
          assert(false);
          break;
      }
    }
    s.prime(chars);
  }
  auto numStringBased = read32();
  CHECK(numStringBased == SnapshotBuilder::kNumStringBased);
  for (int i = 0; i < numStringBased; ++i) {
    auto type = static_cast<SnapshotBuilder::StringBasedType>(i);
    std::vector<KeyValuePair> items(read32());
    for (auto& item : items) {
      item.key = readString().begin();
      auto data = readString();
      String value(data.begin(), data.size(), CopyString);
      switch (type) {
        case SnapshotBuilder::kSnapString:
          s.constructPrime(value, item, false);
          break;
        case SnapshotBuilder::kSnapObject:
          s.constructPrime(value, item, true);
          break;
        case SnapshotBuilder::kSnapThrift: {
          Variant success;
          Variant v = HHVM_FN(fb_unserialize)(value, ref(success));
          if (same(success, false)) {
            throw Exception("bad apc archive, fb_unserialize failed");
          }
          s.constructPrime(v, item);
          break;
        }
        case SnapshotBuilder::kSnapOther: {
          Variant v = unserialize_from_string(value);
          if (same(v, false)) {
            throw Exception("bad apc archive, unserialize_from_string failed");
          }
          s.constructPrime(v, item);
          break;
        }
        default:
          assert(false);
          break;
      }
    }
    s.prime(items);
  }
  {
    const char* disk = m_begin + header().diskOffset;
    std::vector<KeyValuePair> items(read32());
    for (auto& item : items) {
      item.key = readString().begin();
      item.sSize = read32();
      item.sAddr = const_cast<char*>(disk);
      disk += abs(item.sSize) + 1;  // \0
    }
    assert(disk == m_begin + m_size);
    s.prime(items);
  }
  assert(m_cur == m_begin + header().diskOffset);
  // Keys have been copied, so don't need that part any more.
  madvise(const_cast<char*>(m_begin), header().diskOffset, MADV_DONTNEED);
}
Exemple #14
0
Note* NoteFactory::dropNote(const QMimeData *source, Basket *parent, bool fromDrop, Qt::DropAction action, Note */*noteSource*/)
{
	Note *note = 0L;

	QStringList formats = source->formats();
	/* No data */
	if (formats.size() == 0) {
		// TODO: add a parameter to say if it's from a clipboard paste, a selection paste, or a drop
		//       To be able to say "The clipboard/selection/drop is empty".
//		KMessageBox::error(parent, i18n("There is no data to insert."), i18n("No Data"));
		return 0;
	}

	/* Debug */
	if (Global::debugWindow) {
		*Global::debugWindow << "<b>Drop :</b>";
		for (int i = 0; formats.size(); ++i)
			*Global::debugWindow << "\t[" + QString::number(i) + "] " + formats[i];
		switch (action) { // The source want that we:
			case Qt::CopyAction:       *Global::debugWindow << ">> Drop action: Copy";       break;
			case Qt::MoveAction:       *Global::debugWindow << ">> Drop action: Move";       break;
			case Qt::LinkAction:       *Global::debugWindow << ">> Drop action: Link";       break;
			default:                     *Global::debugWindow << ">> Drop action: Unknown";           //  supported by Qt!
		}
	}

	/* Copy or move a Note */
	if (NoteDrag::canDecode(source)) {
		bool moveFiles = fromDrop && action == Qt::MoveAction;
		bool moveNotes = moveFiles;
		return NoteDrag::decode(source, parent, moveFiles, moveNotes); // Filename will be kept
	}

	/* Else : Drop object to note */

	QImage image = qvariant_cast<QImage>(source->imageData()) ;
	if ( !image.isNull() )
		return createNoteImage(QPixmap::fromImage(image), parent);

	if (source->hasColor()){
		return createNoteColor(qvariant_cast<QColor>(source->colorData()), parent);
	}
	
	// And then the hack (if provide color MIME type or a text that contains color), using createNote Color RegExp:
	QString hack;
	QRegExp exp("^#(?:[a-fA-F\\d]{3}){1,4}$");
	hack = source->text();
	if (source->hasFormat("application/x-color") || (!hack.isNull() && exp.exactMatch(hack)) ) {
		QColor color = qvariant_cast<QColor>(source->colorData()) ;
		if (color.isValid())
			return createNoteColor(color, parent);
//			if ( (note = createNoteColor(color, parent)) )
//				return note;
//			// Theorically it should be returned. If not, continue by dropping other things
	}

	KUrl::List urls = KUrl::List::fromMimeData(source);
	if ( !urls.isEmpty() ){
		// If it's a Paste, we should know if files should be copied (copy&paste) or moved (cut&paste):
		if (!fromDrop && Tools::isAFileCut(source))
			action = Qt::MoveAction;
		return dropURLs(urls, parent, action, fromDrop);
	}

	// FIXME: use dropURLs() also from Mozilla?

	/*
	* Mozilla's stuff sometimes uses utf-16-le - little-endian UTF-16.
	*
	* This has the property that for the ASCII subset case (And indeed, the
	* ISO-8859-1 subset, I think), if you treat it as a C-style string,
	* it'll come out to one character long in most cases, since it looks
	 * like:
	*
	* "<\0H\0T\0M\0L\0>\0"
	*
	* A strlen() call on that will give you 1, which simply isn't correct.
	* That might, I suppose, be the answer, or something close.
	*
	* Also, Mozilla's drag/drop code predates the use of MIME types in XDnD
	* - hence it'll throw about STRING and UTF8_STRING quite happily, hence
	* the odd named types.
	*
	* Thanks to Dave Cridland for having said me that.
	*/
	if (source->hasFormat("text/x-moz-url")) { // FOR MOZILLA
		// Get the array and create a QChar array of 1/2 of the size
		QByteArray mozilla = source->data("text/x-moz-url");
		QVector<QChar> chars( mozilla.count() / 2 );
		// A small debug work to know the value of each bytes
		if (Global::debugWindow)
			for (int i = 0; i < mozilla.count(); i++)
				*Global::debugWindow << QString("'") + QChar(mozilla[i]) + "' " + QString::number(int(mozilla[i]));
		// text/x-moz-url give the URL followed by the link title and separed by OxOA (10 decimal: new line?)
		uint size   = 0;
		QChar *name = 0L;
		// For each little endian mozilla chars, copy it to the array of QChars
		for (int i = 0; i < mozilla.count(); i += 2) {
			chars[i/2] = QChar(mozilla[i], mozilla[i+1]);
			if (mozilla.at(i) == 0x0A) {
				size = i/2;
				name = &(chars[i/2+1]);
			}
		}
		// Create a QString that take the address of the first QChar and a length
		if (name == 0L) { // We haven't found name (FIXME: Is it possible ?)
			QString normalHtml(&(chars[0]), chars.size());
			return createNoteLink(normalHtml, parent);
		} else {
			QString normalHtml(  &(chars[0]), size               );
			QString normalTitle( name,        chars.size()-size-1);
			return createNoteLink(normalHtml, normalTitle, parent);
		}
	}

	if (source->hasFormat("text/html")) {
		QString html;
		QString subtype("html");
		// If the text/html comes from Mozilla or GNOME it can be UTF-16 encoded: we need ExtendedTextDrag to check that
		ExtendedTextDrag::decode(source, html, subtype);
		return createNoteHtml(html, parent);
	}

	QString text;
	// If the text/plain comes from GEdit or GNOME it can be empty: we need ExtendedTextDrag to check other MIME types
	if ( ExtendedTextDrag::decode(source, text) )
		return createNoteFromText(text, parent);

	/* Unsucceful drop */
	note = createNoteUnknown(source, parent);
	QString message = i18n("<p>%1 doesn't support the data you've dropped.<br>"
			"It however created a generic note, allowing you to drag or copy it to an application that understand it.</p>"
			"<p>If you want the support of these data, please contact developer or visit the "
			"<a href=\"http://basket.kde.org/dropdb.php\">BasKet Drop Database</a>.</p>",KGlobal::mainComponent().aboutData()->programName());
	KMessageBox::information(parent, message, i18n("Unsupported MIME Type(s)"),
							 "unsupportedDropInfo", KMessageBox::AllowLink);
	return note;
}
Exemple #15
0
bool LauncherProfile(const wchar_t *cf,LauncherStructure &config)
{
  std::wstring pfile;
  if(cf==nullptr){
    std::wstring folder;
    if(!GetProcessImageFileFolder(folder)){
      MessageBoxW(nullptr,
        L"GetModuleFileNameW Failed!",
        L"Internal System Error",
        MB_OK|MB_ICONERROR);
      return false;
    }
    pfile=folder+L"/launcher.toml";
    if(!PathFileExistsW(pfile.c_str())){
      pfile=folder+L"/launcher.exe.toml";
      if(!PathFileExistsW(pfile.c_str())){
        MessageBoxW(nullptr,
          folder.c_str(),
          L"Cannot open launcher.toml or launcher.exe.toml on this path",
          MB_OK|MB_ICONERROR);
        return false;
      }
    }
  }else{
    pfile=cf;
  }
  Characters chars(pfile.c_str());
  std::shared_ptr<cpptoml::table> g;
  try {
    g = cpptoml::parse_file(chars.Get());
    std::cout << (*g) << std::endl;
  } catch (const cpptoml::parse_exception &e) {
    (void)e;
    MessageBoxW(nullptr,
      pfile.c_str(),
      L"Cannot parser toml-format profile!",
      MB_OK|MB_ICONERROR);
    return false;
  }
  auto Strings = [&](const char *key, const wchar_t *v, std::wstring &sv) {
    if (g->contains_qualified(key)) {
      std::string astr = g->get_qualified(key)->as<std::string>()->get();
      WCharacters was(astr.c_str());
      sv=was.Get();
      return;
    }
    if(v){
        sv = v;
      }
  };
  auto Boolean = [&](const char *key, bool b) {
    if (g->contains_qualified(key)) {
      return g->get_qualified(key)->as<bool>()->get();
    }
    return b;
  };
  auto Vector = [&](const char *key, std::vector<std::wstring> &v) {
    if (g->contains_qualified(key) && g->get_qualified(key)->is_array()) {
      auto av = g->get_qualified(key)->as_array();
      for (auto &e : av->get()) {
        WCharacters was(e->as<std::string>()->get().c_str());
        v.push_back(was.Get());
      }
    }
  };
  Strings("Launcher.MSYSTEM",L"MINGW64",config.env);
  Strings("Launcher.Root",L"C:/MSYS2",config.root);
  Strings("Launcher.WD",L"C:/MSYS2/usr/bin",config.wd);
  Strings("Launcher.Mintty",L"C:/MSYS2/usr/bin/mintty.exe",config.mintty);
  Strings("Launcher.ICONPath",L"/msys2.ico",config.icon);
  Strings("Launcher.Shell",L"bash",config.otherShell);
  Strings("Launcher.AppendShellArgs",nullptr,config.shellArgs);
  Vector("Launcher.AppendPath",config.appendPath);
  config.enableZshell=Boolean("Launcher.EnableZshell",false);
  config.clearEnvironment=Boolean("Launcher.UseClearEnv",false);
  return true;
}
Exemple #16
0
QString TeXCodes::map(QString k) {
  if (contains(k))
    return chars()[k];
  else
    return "";
}
Exemple #17
0
    void walk(const TextRun& run, bool isVerticalText, const String& language, int from, int to)
    {
        // Should hold true for SVG text, otherwhise sth. is wrong
        ASSERT(to - from == run.length());

        Vector<SVGGlyphIdentifier::ArabicForm> chars(charactersWithArabicForm(String(run.data(from), run.length()), run.rtl()));

        SVGGlyphIdentifier identifier;
        bool foundGlyph = false;
        int characterLookupRange;
        int endOfScanRange = to + m_walkerData.extraCharsAvailable;

        bool haveAltGlyph = false;
        SVGGlyphIdentifier altGlyphIdentifier;
        if (RenderObject* renderObject = run.referencingRenderObject()) {
            if (renderObject->element() && renderObject->element()->hasTagName(SVGNames::altGlyphTag)) {
                SVGGlyphElement* glyphElement = static_cast<SVGAltGlyphElement*>(renderObject->element())->glyphElement();
                if (glyphElement) {
                    haveAltGlyph = true;
                    altGlyphIdentifier = glyphElement->buildGlyphIdentifier();
                    altGlyphIdentifier.isValid = true;
                    altGlyphIdentifier.nameLength = to - from;
                }
            }
        }

        for (int i = from; i < to; ++i) {
            // If characterLookupRange is > 0, then the font defined ligatures (length of unicode property value > 1).
            // We have to check wheter the current character & the next character define a ligature. This needs to be
            // extended to the n-th next character (where n is 'characterLookupRange'), to check for any possible ligature.
            characterLookupRange = endOfScanRange - i;

            String lookupString(run.data(i), characterLookupRange);
            Vector<SVGGlyphIdentifier> glyphs;
            if (haveAltGlyph)
                glyphs.append(altGlyphIdentifier);
            else
                m_fontElement->getGlyphIdentifiersForString(lookupString, glyphs);

            Vector<SVGGlyphIdentifier>::iterator it = glyphs.begin();
            Vector<SVGGlyphIdentifier>::iterator end = glyphs.end();
            
            for (; it != end; ++it) {
                identifier = *it;
                if (identifier.isValid && isCompatibleGlyph(identifier, isVerticalText, language, chars, i, i + identifier.nameLength)) {
                    ASSERT(characterLookupRange > 0);
                    i += identifier.nameLength - 1;
                    m_walkerData.charsConsumed += identifier.nameLength;
                    m_walkerData.glyphName = identifier.glyphName;

                    foundGlyph = true;
                    SVGGlyphElement::inheritUnspecifiedAttributes(identifier, m_fontData);
                    break;
                }
            }

            if (!foundGlyph) {
                ++m_walkerData.charsConsumed;
                if (SVGMissingGlyphElement* element = m_fontElement->firstMissingGlyphElement()) {
                    // <missing-glyph> element support
                    identifier = SVGGlyphElement::buildGenericGlyphIdentifier(element);
                    SVGGlyphElement::inheritUnspecifiedAttributes(identifier, m_fontData);
                    identifier.isValid = true;
                } else {
                    // Fallback to system font fallback
                    TextRun subRun(run);
                    subRun.setText(subRun.data(i), 1);

                    (*m_walkerMissingGlyphCallback)(subRun, m_walkerData);
                    continue;
                }
            }

            if (!(*m_walkerCallback)(identifier, m_walkerData))
                break;

            foundGlyph = false;
        }
    }
Exemple #18
0
inline std::basic_ostream<Ch, Tr> & out_shell_quote(std::basic_ostream<Ch, Tr> &out, const C& data, bool quote_empty=true) {
  out_stream<Ch, Tr> chars(out);
  shell_quote_chars(chars, to_string(data), quote_empty);
  return out;
}
String IndexInput::readModifiedUTF8String() {
    int32_t length = readVInt();
    CharArray chars(CharArray::newInstance(length));
    return String(chars.get(), readChars(chars.get(), 0, length));
}
TFiniteAutomaton TFiniteAutomaton::Minimized() const {
    // NOTE: automaton shoud be deterministic here

    TFiniteAutomaton result;

    vector<size_t> labels(Size());
    vector< vector<size_t> > classes(2);

    // basis: divide states into final / not final
    for (size_t i = 0, size = Size(); i != size; ++i)
        classes[labels[i] = static_cast<size_t>(States[i].IsFinal)].push_back(i);
    if (classes[1].empty())
        classes.pop_back();
    if (classes[0].empty())
        classes.erase(classes.begin());

    // unite alphabets
    set<TChar> charSet;
    for (size_t i = 0, size = Size(); i != size; ++i) {
        const TTransitions& tran = States[i].Transitions;
        for (TTransitions::const_iterator trIt = tran.begin(), trEnd = tran.end(); trIt != trEnd; ++trIt)
            charSet.insert(trIt->first);
    }
    vector<TChar> chars(charSet.begin(), charSet.end());
    charSet.clear();

    // find equivalence classes
    bool modified = true;
    TBucketTable<size_t> buckets(Size() + 1);
    while (modified) {
        vector< vector<size_t> > newClasses;
        modified = false;
        for (size_t i = 0, size = classes.size(); i != size; ++i) {
            const vector<size_t>& cls = classes[i];
            bool class_modified = false;
            for (size_t chInd = 0, chEnd = chars.size(); chInd != chEnd; ++chInd) {
                const TChar ch = chars[chInd];
                buckets.Clear();
                for (size_t j = 0, clsSize = cls.size(); j != clsSize; ++j) {
                    const TTransitions& tran = States[cls[j]].Transitions;
                    TTransitions::const_iterator it = tran.find(ch);
                    size_t bucket = (it != tran.end() ? labels[*it->second.begin()] + 1 : 0);
                    buckets.Push(cls[j], bucket);
                }
                if (buckets.UsedBuckets() != 1) {
                    const TBucketTable<size_t>::TBuckets& bucks = buckets.GetBuckets();
                    const vector<size_t>& used = buckets.GetUsedBuckets();
                    for (size_t b = 0, usedSize = used.size(); b != usedSize; ++b)
                        newClasses.push_back(bucks[used[b]]);
                    class_modified = true;
                    modified = true;
                    break;
                }
            }
            if (!class_modified)
                newClasses.push_back(cls);
        }
        classes.swap(newClasses);
        for (size_t i = 0, size = classes.size(); i != size; ++i) {
            const vector<size_t>& cls = classes[i];
            for (size_t j = 0, clsSize = cls.size(); j != clsSize; ++j)
                labels[cls[j]] = i;
        }
    }

    // construct resulting DFA using labels ang classes
    result.Resize(classes.size());
    for (size_t i = 0, size = classes.size(); i != size; ++i) {
        // NOTE: it is guaranteed that classes are not empty
        size_t state = classes[i].front();
        const TTransitions& tran = States[state].Transitions;
        for (TTransitions::const_iterator it = tran.begin(), end = tran.end(); it != end; ++it)
            result.AddTransition(labels[state], labels[*it->second.begin()], it->first); // NOTE: all labels by one char are equal
    }
    result.SetStartState(labels[StartState]);
    for (TStateIdSet::const_iterator it = FinalStates.begin(), end = FinalStates.end(); it != end; ++it)
        result.SetFinalState(labels[*it]);

    return result;
}