MythSocket *RemoteFile::openSocket(bool control) { QUrl qurl(path); QString dir; QString host = qurl.host(); int port = qurl.port(); dir = qurl.path(); if (qurl.hasQuery()) #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) dir += "?" + QUrl::fromPercentEncoding( qurl.query(QUrl::FullyEncoded).toLocal8Bit()); #else dir += "?" + QUrl::fromPercentEncoding(qurl.encodedQuery()); #endif if (qurl.hasFragment()) dir += "#" + qurl.fragment(); QString sgroup = qurl.userName(); MythSocket *lsock = new MythSocket(); QString stype = (control) ? "control socket" : "file data socket"; QString loc = QString("RemoteFile::openSocket(%1): ").arg(stype); if (port <= 0) { port = gCoreContext->GetBackendServerPort(host); } if (!lsock->ConnectToHost(host, port)) { LOG(VB_GENERAL, LOG_ERR, loc + QString("Could not connect to server %1:%2") .arg(host).arg(port)); lsock->DecrRef(); return NULL; } QString hostname = GetMythDB()->GetHostName(); QStringList strlist; #ifndef IGNORE_PROTO_VER_MISMATCH if (!gCoreContext->CheckProtoVersion(lsock, 5000)) { LOG(VB_GENERAL, LOG_ERR, loc + QString("Failed validation to server %1:%2").arg(host).arg(port)); lsock->DecrRef(); return NULL; } #endif if (control) { strlist.append(QString("ANN Playback %1 %2").arg(hostname).arg(false)); if (!lsock->SendReceiveStringList(strlist)) { LOG(VB_GENERAL, LOG_ERR, loc + QString("Could not read string list from server %1:%2") .arg(host).arg(port)); lsock->DecrRef(); return NULL; } } else { strlist.push_back(QString("ANN FileTransfer %1 %2 %3 %4") .arg(hostname).arg(writemode) .arg(usereadahead).arg(timeout_ms)); strlist << QString("%1").arg(dir); strlist << sgroup; QStringList::const_iterator it = possibleauxfiles.begin(); for (; it != possibleauxfiles.end(); ++it) strlist << *it; if (!lsock->SendReceiveStringList(strlist)) { LOG(VB_GENERAL, LOG_ERR, loc + QString("Did not get proper response from %1:%2") .arg(host).arg(port)); strlist.clear(); strlist.push_back("ERROR"); strlist.push_back("invalid response"); } if (strlist.size() >= 3) { it = strlist.begin(); ++it; recordernum = (*it).toInt(); ++it; filesize = (*(it)).toLongLong(); ++it; for (; it != strlist.end(); ++it) auxfiles << *it; } else if (!strlist.isEmpty() && strlist.size() < 3 && strlist[0] != "ERROR") { LOG(VB_GENERAL, LOG_ERR, loc + QString("Did not get proper response from %1:%2") .arg(host).arg(port)); strlist.clear(); strlist.push_back("ERROR"); strlist.push_back("invalid response"); } } if (strlist.isEmpty() || strlist[0] == "ERROR") { lsock->DecrRef(); lsock = NULL; if (strlist.isEmpty()) { LOG(VB_GENERAL, LOG_ERR, loc + "Failed to open socket, timeout"); } else { LOG(VB_GENERAL, LOG_ERR, loc + "Failed to open socket" + ((strlist.size() >= 2) ? QString(", error was %1").arg(strlist[1]) : QString(", remote error"))); } } return lsock; }
// // Thesaurus // void Thesaurus::findTermThesaurus(const QString &searchTerm) { if (!QFile::exists(m_dataFile)) { KMessageBox::error(0, i18n("The thesaurus file '%1' was not found. " "Please use 'Change Language...' to select a thesaurus file.", m_dataFile)); return; } // Find only whole words. Looks clumsy, but this way we don't have to rely on // features that might only be in certain versions of grep: QString searchTermTmp = ';' + searchTerm.trimmed() + ';'; m_thesProc->setOutputChannelMode(KProcess::SeparateChannels); m_thesProc->clearProgram(); m_thesProc->setReadChannel(QProcess::StandardOutput); *m_thesProc << "grep" << "-i" << searchTermTmp; *m_thesProc << m_dataFile; QStringList syn; QStringList hyper; QStringList hypo; m_thesProc->start(); if (!m_thesProc->waitForFinished()) { KMessageBox::error(0, i18n("<b>Error:</b> Failed to execute grep.")); return; } if (!m_thesProc->waitForReadyRead()) { } QByteArray byteArray = m_thesProc->readAllStandardOutput(); QString stdoutString(byteArray); QStringList lines = stdoutString.split(QChar('\n')); for (QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) { QString line = (*it); if (line.startsWith(" ")) { // ignore license (two spaces) continue; } int sep_pos = line.indexOf('#'); QString synPart = line.left(sep_pos); QString hyperPart = line.right(line.length() - sep_pos - 1); QStringList synTmp = synPart.split(QChar(';')); QStringList hyperTmp = hyperPart.split(QChar(';')); if (synTmp.filter(searchTerm, Qt::CaseInsensitive).size() > 0) { // match on the left side of the '#' -- synonyms for (QStringList::Iterator it2 = synTmp.begin(); it2 != synTmp.end(); ++it2) { // add if it's not the searchTerm itself and if it's not yet in the list QString term = (*it2); if (term.toLower() != searchTerm.toLower() && syn.contains(term) == 0 && !term.isEmpty()) { syn.append(term); } } for (QStringList::Iterator it2 = hyperTmp.begin(); it2 != hyperTmp.end(); ++it2) { QString term = (*it2); if (term.toLower() != searchTerm.toLower() && hyper.contains(term) == 0 && !term.isEmpty()) { hyper.append(term); } } } if (hyperTmp.filter(searchTerm, Qt::CaseInsensitive).size() > 0) { // match on the right side of the '#' -- hypernyms for (QStringList::Iterator it2 = synTmp.begin(); it2 != synTmp.end(); ++it2) { QString term = (*it2); if (term.toLower() != searchTerm && hypo.contains(term) == 0 && !term.isEmpty()) { hypo.append(term); } } } } m_synListWidget->clear(); if (syn.size() > 0) { syn.sort(); m_synListWidget->addItems(syn); m_synListWidget->setEnabled(true); } else { m_synListWidget->addItem(m_noMatch); m_synListWidget->setEnabled(false); } m_hyperListWidget->clear(); if (hyper.size() > 0) { hyper.sort(); m_hyperListWidget->addItems(hyper); m_hyperListWidget->setEnabled(true); } else { m_hyperListWidget->addItem(m_noMatch); m_hyperListWidget->setEnabled(false); } m_hypoListWidget->clear(); if (hypo.size() > 0) { hypo.sort(); m_hypoListWidget->addItems(hypo); m_hypoListWidget->setEnabled(true); } else { m_hypoListWidget->addItem(m_noMatch); m_hypoListWidget->setEnabled(false); } }
// Format lines using Qt's simple richtext. QString Thesaurus::formatLine(const QString &line) const { QString l = line; if (l == "--------------") return QString("<hr>"); QRegExp re; re.setPattern("^(\\d+\\.)(.*)$"); if (re.indexIn(l) != -1) { l = "<b>" +re.cap(1)+ "</b>" +re.cap(2); return l; } re.setPattern("^.* of (noun|verb|adj|adv) .*"); if (re.indexIn(l) != -1) { l = "<font size=\"5\">" +re.cap()+ "</font>\n\n"; return l; } if (m_mode == grep) { l = l.trimmed(); return QString("<a href=\"" +l+ "\">" +l+ "</a>"); } re.setPattern("^(Sense \\d+)"); if (re.indexIn(l) != -1) { l = "<b>" +re.cap()+ "</b>\n"; return l; } re.setPattern("(.*)(Also See->)(.*)"); // Example: first sense of verb "keep" if (re.indexIn(l) != -1) { l = re.cap(1); l += re.cap(2); QStringList links = re.cap(3).split(QChar(';'), QString::SkipEmptyParts); for (QStringList::Iterator it = links.begin(); it != links.end(); ++it) { QString link = (*it); if (it != links.begin()) { l += ", "; } link = link.trimmed(); link.remove(QRegExp("#\\d+")); l += "<a href=\"" + link + "\">" + link + "</a>"; } l.prepend (' '); // indent in table } re.setPattern("(.*)(=>|HAS \\w+:|PART OF:)(.*) --"); re.setMinimal(true); // non-greedy if (re.indexIn(l) != -1) { int dash_pos = l.indexOf("--"); QString line_end = l.mid(dash_pos+2, l.length()-dash_pos); l = re.cap(1); l += re.cap(2) + ' '; QStringList links = re.cap(3).split(QChar(','), QString::SkipEmptyParts); for (QStringList::Iterator it = links.begin(); it != links.end(); ++it) { QString link = (*it); if (it != links.begin()) { l += ", "; } link = link.trimmed(); l += "<a href=\"" +link+ "\">" +link+ "</a>"; } l += "<font color=\"#777777\">" +line_end+ "</font>"; l.prepend(' '); // indent in table return l; } re.setMinimal(false); // greedy again return l; }
MythSocket *RemoteFile::openSocket(bool control) { QUrl qurl(path); QString dir; QString host = qurl.host(); int port = qurl.port(); dir = qurl.path(); if (qurl.hasQuery()) dir += "?" + QUrl::fromPercentEncoding(qurl.encodedQuery()); if (qurl.hasFragment()) dir += "#" + qurl.fragment(); QString sgroup = qurl.userName(); MythSocket *lsock = new MythSocket(); QString stype = (control) ? "control socket" : "file data socket"; QString loc_err = QString("RemoteFile::openSocket(%1), Error: ").arg(stype); if (port <= 0) { port = GetMythDB()->GetSettingOnHost("BackendServerPort", host).toInt(); // if we still have no port use the default if (port <= 0) port = 6543; } if (!lsock->connect(host, port)) { VERBOSE(VB_IMPORTANT, loc_err + QString("\n\t\t\tCould not connect to server %1:%2") .arg(host).arg(port)); lsock->DownRef(); return NULL; } QString hostname = GetMythDB()->GetHostName(); QStringList strlist; if (control) { strlist.append( QString("ANN Playback %1 %2").arg(hostname).arg(false) ); lsock->writeStringList(strlist); if (!lsock->readStringList(strlist, true)) { VERBOSE(VB_IMPORTANT, loc_err + QString("\n\t\t\tCould not read string list from server " "%1:%2").arg(host).arg(port)); lsock->DownRef(); return NULL; } } else { strlist.push_back(QString("ANN FileTransfer %1 %2 %3 %4") .arg(hostname).arg(writemode) .arg(usereadahead).arg(timeout_ms)); strlist << QString("%1").arg(dir); strlist << sgroup; QStringList::const_iterator it = possibleauxfiles.begin(); for (; it != possibleauxfiles.end(); ++it) strlist << *it; if (!lsock->writeStringList(strlist) || !lsock->readStringList(strlist, true)) { VERBOSE(VB_IMPORTANT, loc_err + QString("Did not get proper response from %1:%2") .arg(host).arg(port)); strlist.clear(); strlist.push_back("ERROR"); strlist.push_back("invalid response"); } if (strlist.size() >= 4) { it = strlist.begin(); ++it; recordernum = (*it).toInt(); ++it; filesize = decodeLongLong(strlist, it); for (; it != strlist.end(); ++it) auxfiles << *it; } else if (0 < strlist.size() && strlist.size() < 4 && strlist[0] != "ERROR") { VERBOSE(VB_IMPORTANT, loc_err + QString("Did not get proper response from %1:%2") .arg(host).arg(port)); strlist.clear(); strlist.push_back("ERROR"); strlist.push_back("invalid response"); } } if (strlist.empty() || strlist[0] == "ERROR") { lsock->DownRef(); lsock = NULL; if (strlist.empty()) { VERBOSE(VB_IMPORTANT, loc_err + "Failed to open socket, timeout"); } else { VERBOSE(VB_IMPORTANT, loc_err + "Failed to open socket" + ((strlist.size() >= 2) ? QString(", error was %1").arg(strlist[1]) : QString(", remote error"))); } } return lsock; }
GVSpectrogramWDialogSettings::GVSpectrogramWDialogSettings(GVSpectrogram *parent) : QDialog((QWidget*)parent) , m_lastimgsize(-1) , ui(new Ui::GVSpectrogramWDialogSettings) { ui->setupUi(this); m_spectrogram = parent; gMW->m_settings.add(ui->cbSpectrogramWindowSizeForcedOdd); gMW->m_settings.add(ui->cbSpectrogramWindowType); gMW->m_settings.add(ui->spSpectrogramWindowNormPower); gMW->m_settings.add(ui->spSpectrogramWindowNormSigma); gMW->m_settings.add(ui->spSpectrogramWindowExpDecay); ui->lblWindowNormSigma->hide(); ui->spSpectrogramWindowNormSigma->hide(); ui->lblWindowNormPower->hide(); ui->spSpectrogramWindowNormPower->hide(); ui->lblWindowExpDecay->hide(); ui->spSpectrogramWindowExpDecay->hide(); gMW->m_settings.add(ui->sbSpectrogramStepSize); gMW->m_settings.add(ui->sbSpectrogramWindowSize); gMW->m_settings.add(ui->sbSpectrogramDFTSize); gMW->m_settings.add(ui->sbSpectrogramOversamplingFactor); gMW->m_settings.add(ui->cbSpectrogramDFTSizeType); if(ui->cbSpectrogramDFTSizeType->currentIndex()==0){ ui->sbSpectrogramOversamplingFactor->hide(); ui->sbSpectrogramDFTSize->show(); DFTSizeChanged(ui->sbSpectrogramDFTSize->value()); } else if(ui->cbSpectrogramDFTSizeType->currentIndex()==1){ ui->sbSpectrogramOversamplingFactor->show(); ui->sbSpectrogramDFTSize->hide(); DFTSizeChanged(ui->sbSpectrogramOversamplingFactor->value()); } connect(ui->cbSpectrogramDFTSizeType, SIGNAL(currentIndexChanged(int)), this, SLOT(DFTSizeTypeChanged(int))); connect(ui->sbSpectrogramDFTSize, SIGNAL(valueChanged(int)), this, SLOT(DFTSizeChanged(int))); connect(ui->sbSpectrogramOversamplingFactor, SIGNAL(valueChanged(int)), this, SLOT(DFTSizeChanged(int))); gMW->m_settings.add(ui->cbSpectrogramTransform); gMW->m_settings.add(ui->gbSpectrogramCepstralLiftering); gMW->m_settings.add(ui->sbSpectrogramCepstralLifteringOrder); gMW->m_settings.add(ui->cbSpectrogramCepstralLifteringPreserveDC); QStringList colormaps = QAEColorMap::getAvailableColorMaps(); for(QStringList::Iterator it=colormaps.begin(); it!=colormaps.end(); ++it) ui->cbSpectrogramColorMaps->addItem(*it); ui->cbSpectrogramColorMaps->setCurrentIndex(1); gMW->m_settings.add(ui->cbSpectrogramColorMaps); gMW->m_settings.add(ui->cbSpectrogramColorMapReversed); gMW->m_settings.add(ui->cbSpectrogramLoudnessWeighting); gMW->m_settings.add(ui->cbSpectrogramColorRangeMode); colorRangeModeCurrentIndexChanged(ui->cbSpectrogramColorRangeMode->currentIndex()); gMW->m_qxtSpectrogramSpanSlider->setLowerValue(gMW->m_settings.value("m_qxtSpectrogramSpanSlider_lower", gMW->m_qxtSpectrogramSpanSlider->lowerValue()).toInt()); gMW->m_qxtSpectrogramSpanSlider->setUpperValue(gMW->m_settings.value("m_qxtSpectrogramSpanSlider_upper", gMW->m_qxtSpectrogramSpanSlider->upperValue()).toInt()); checkImageSize(); adjustSize(); connect(ui->cbSpectrogramWindowType, SIGNAL(currentIndexChanged(QString)), this, SLOT(windowTypeCurrentIndexChanged(QString))); connect(ui->cbSpectrogramColorRangeMode, SIGNAL(currentIndexChanged(int)), this, SLOT(colorRangeModeCurrentIndexChanged(int))); }
QT_BEGIN_NAMESPACE int runUic3(int argc, char * argv[]) { bool impl = false; bool wrap = false; bool subcl = false; bool extract = false; bool imagecollection = false; bool imagecollection_tmpfile = false; bool convert = false; QStringList images; const char *error = 0; const char* fileName = 0; const char* className = 0; const char* headerFile = 0; const char* convertedUiFile = 0; QByteArray outputFile; QString qrcOutputFile; QByteArray image_tmpfile; const char* projectName = 0; const char* trmacro = 0; bool nofwd = false; bool fix = false; bool deps = false; bool implicitIncludes = true; QByteArray pchFile; QApplication app(argc, argv, false); for (int n = 1; n < argc && error == 0; n++) { QByteArray arg = argv[n]; if (arg[0] == '-') { // option QByteArray opt = arg.data() + 1; if (opt[0] == 'o') { // output redirection if (opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing output-file name"; break; } outputFile = argv[++n]; } else outputFile = opt.data() + 1; } else if (opt[0] == 'i' || opt == "impl") { impl = true; if (opt == "impl" || opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing name of header file"; break; } headerFile = argv[++n]; } else headerFile = opt.data() + 1; } else if (opt[0] == 'w' || opt == "wrap") { wrap = true; if (opt == "wrap" || opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing name of converted ui file"; break; } convertedUiFile = argv[++n]; } else convertedUiFile = opt.data() + 1; } else if (opt == "extract") { // output redirection extract = true; if (!(n < argc-1)) { error = "Missing output qrc-file name"; break; } qrcOutputFile = QFile::decodeName(argv[++n]); } else if ( opt[0] == 'e' || opt == "embed" ) { imagecollection = true; if ( opt == "embed" || opt[1] == '\0' ) { if ( !(n < argc-1) ) { error = "Missing name of project"; break; } projectName = argv[++n]; } else { projectName = opt.data() + 1; } if ( argc > n+1 && qstrcmp( argv[n+1], "-f" ) == 0 ) { imagecollection_tmpfile = true; image_tmpfile = argv[n+2]; n += 2; } } else if (opt == "d") { deps = true; } else if (opt == "no-implicit-includes") { implicitIncludes = false; } else if (opt == "nofwd") { nofwd = true; } else if (opt == "nounload") { // skip } else if (opt == "convert") { convert = true; } else if (opt == "subdecl") { subcl = true; if (!(n < argc-2)) { error = "Missing arguments"; break; } className = argv[++n]; headerFile = argv[++n]; } else if (opt == "subimpl") { subcl = true; impl = true; if (!(n < argc-2)) { error = "Missing arguments"; break; } className = argv[++n]; headerFile = argv[++n]; } else if (opt == "tr") { if (opt == "tr" || opt[1] == '\0') { if (!(n < argc-1)) { error = "Missing tr macro."; break; } trmacro = argv[++n]; } else { trmacro = opt.data() + 1; } } else if (opt == "L") { if (!(n < argc-1)) { error = "Missing plugin path."; break; } ++n; // ignore the next argument } else if (opt == "version") { fprintf(stderr, "Qt User Interface Compiler version %s\n", QT_VERSION_STR); return 1; } else if (opt == "help") { break; } else if (opt == "fix") { fix = true; } else if (opt == "pch") { if (!(n < argc-1)) { error = "Missing name of PCH file"; break; } pchFile = argv[++n]; } else { error = "Unrecognized option"; } } else { if (imagecollection && !imagecollection_tmpfile) images << QLatin1String(argv[n]); else if (fileName) // can handle only one file error = "Too many input files specified"; else fileName = argv[n]; } } if (argc < 2 || error || (!fileName && !imagecollection)) { fprintf(stderr, "Qt User Interface Compiler version %s\n", QT_VERSION_STR); if (error) fprintf(stderr, "uic: %s\n", error); fprintf(stderr, "Usage: %s [options] [mode] <uifile>\n\n" "Convert a UI file to version 4:\n" " %s [options] -convert <uifile>\n" "Generate declaration:\n" " %s [options] <uifile>\n" "\t<uiheaderfile> name of the data file\n" " %s [options] -decl <uiheaderfile> <uifile>\n" "\t<uiheaderfile> name of the data file\n" " %s [options] -wrap <converteduifile> <uifile>\n" "\t<converteduifile> name of the converted ui file\n" "Generate implementation:\n" " %s [options] -impl <headerfile> <uifile>\n" "\t<headerfile> name of the declaration file\n" "Generate image collection:\n" " %s [options] -embed <project> <image1> <image2> <image3> ...\n" "or\n" " %s [options] -embed <project> -f <temporary file containing image names>\n" "\t<project> project name\n" "\t<image[1-N]> image files\n" "Generate subclass declaration:\n" " %s [options] -subdecl <subclassname> <baseclassheaderfile> <uifile>\n" "\t<subclassname> name of the subclass to generate\n" "\t<baseclassheaderfile> declaration file of the baseclass\n" "Generate subclass implementation:\n" " %s [options] -subimpl <subclassname> <subclassheaderfile> <uifile>\n" "\t<subclassname> name of the subclass to generate\n" "\t<subclassheaderfile> declaration file of the subclass\n" "Options:\n" "\t-o file Write output to file rather than stdout\n" "\t-extract qrcFile Create resource file and extract embedded images into \"image\" dir\n" "\t-pch file Add #include \"file\" as the first statement in implementation\n" "\t-nofwd Omit forward declarations of custom classes\n" "\t-no-implicit-includes Do not generate #include-directives for custom classes\n" "\t-nounload Don't unload plugins after processing\n" "\t-tr func Use func() instead of tr() for i18n\n" "\t-L path Additional plugin search path\n" "\t-version Display version of uic\n" "\t-help Display this information\n" , argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0], argv[0] ); return 1; } if (imagecollection_tmpfile) { QFile ifile(QFile::decodeName(image_tmpfile)); if (ifile.open(QIODevice::ReadOnly)) { QTextStream ts(&ifile); QString s = ts.read(); s = s.simplified(); images = s.split(QLatin1Char(' ')); for (QStringList::Iterator it = images.begin(); it != images.end(); ++it) *it = (*it).simplified(); } } QFile fileOut; if (!outputFile.isEmpty()) { fileOut.setFileName(QFile::decodeName(outputFile)); if (!fileOut.open(QIODevice::WriteOnly)) { fprintf(stderr, "%s: Could not open output file '%s'\n", argv[0], outputFile.data()); return 1; } } else { fileOut.open(QIODevice::WriteOnly, stdout); } QTextStream out(&fileOut); Ui3Reader ui3(out); ui3.setExtractImages(extract, qrcOutputFile); if (projectName && imagecollection) { out.setEncoding(QTextStream::Latin1); ui3.embed(projectName, images); return 0; } out.setEncoding(QTextStream::UnicodeUTF8); QFile file(QFile::decodeName(fileName)); if (!file.open(QIODevice::ReadOnly)) { fprintf(stderr, "%s: Could not open file '%s'\n", argv[0], fileName); return 1; } QDomDocument doc; QString errMsg; int errLine; if (!doc.setContent(&file, &errMsg, &errLine)) { fprintf(stderr, "%s: Failed to parse %s: %s in line %d\n", argv[0], fileName, errMsg.latin1(), errLine); return 1; } QDomElement e = doc.firstChild().toElement(); double version = e.attribute(QLatin1String("version"), QLatin1String("3.0")).toDouble(); if (version > 3.3) { fprintf(stderr, "%s: File generated with too recent version of Qt Designer (%s vs. %s)\n", argv[0], e.attribute(QLatin1String("version")).latin1(), "3.3"); return 1; } DomTool::fixDocument(doc); if (fix) { out << doc.toString(); return 0; } if (imagecollection) { out.setEncoding(QTextStream::Latin1); ui3.embed(projectName, images); return 0; } else if (deps) { QStringList globalIncludes, localIncludes; ui3.computeDeps(e, globalIncludes, localIncludes, impl); foreach (QString i, globalIncludes) printf("%s\n", i.toLatin1().constData()); foreach (QString i, localIncludes) printf("%s\n", i.toLatin1().constData()); if (impl) printf("%s\n", headerFile); return 0; } else if (convert) { ui3.generateUi4(QFile::decodeName(fileName), QFile::decodeName(outputFile), doc, implicitIncludes); return 0; } QString protector; if (subcl && className && !impl) protector = QString::fromUtf8(className).toUpper() + QLatin1String("_H"); if (!protector.isEmpty()) { out << "#ifndef " << protector << endl; out << "#define " << protector << endl; } if (!pchFile.isEmpty() && impl) { out << "#include \"" << pchFile << "\" // PCH include" << endl; } if (headerFile) { out << "#include \"" << headerFile << "\"" << endl << endl; } QString convertedUi; if (wrap) { convertedUi = QFile::decodeName(convertedUiFile); int pos = convertedUi.lastIndexOf(QLatin1String(".ui")); if (pos > 0) { convertedUi = convertedUi.mid(0, pos); convertedUi += QLatin1String(".h"); } convertedUi = QLatin1String("ui_") + convertedUi; } ui3.generate(QFile::decodeName(fileName), QFile::decodeName(outputFile), doc, !impl, subcl, QString::fromUtf8(trmacro), QString::fromUtf8(className), nofwd, implicitIncludes, convertedUi); if (!protector.isEmpty()) { out << endl; out << "#endif // " << protector << endl; } if (fileOut.error() != QFile::NoError) { fprintf(stderr, "%s: Error writing to file\n", argv[0]); if (!outputFile.isEmpty()) remove(outputFile); } return 0; }
char Filters::BT_ThMLHTML::processText(sword::SWBuf& buf, const sword::SWKey* key, const sword::SWModule* module) { sword::ThMLHTML::processText(buf, key, module); CSwordModuleInfo* m = CPointers::backend()->findModuleByName( module->Name() ); if (m && !(m->has(CSwordModuleInfo::lemmas) || m->has(CSwordModuleInfo::strongNumbers))) { //only parse if the module has strongs or lemmas return 1; } QString result; QString t = QString::fromUtf8(buf.c_str()); QRegExp tag("([.,;]?<sync[^>]+(type|value)=\"([^\"]+)\"[^>]+(type|value)=\"([^\"]+)\"([^<]*)>)+"); QStringList list; int lastMatchEnd = 0; int pos = tag.indexIn(t, 0); if (pos == -1) { //no strong or morph code found in this text return 1; //WARNING: Return alread here } while (pos != -1) { list.append(t.mid(lastMatchEnd, pos + tag.matchedLength() - lastMatchEnd)); lastMatchEnd = pos + tag.matchedLength(); pos = tag.indexIn(t, pos + tag.matchedLength()); } if (!t.right(t.length() - lastMatchEnd).isEmpty()) { list.append(t.right(t.length() - lastMatchEnd)); } tag = QRegExp("<sync[^>]+(type|value|class)=\"([^\"]+)\"[^>]+(type|value|class)=\"([^\"]+)\"[^>]+((type|value|class)=\"([^\"]+)\")*([^<]*)>"); for (QStringList::iterator it = list.begin(); it != list.end(); ++it) { QString e( *it ); const bool textPresent = (e.trimmed().remove(QRegExp("[.,;:]")).left(1) != "<"); if (!textPresent) { continue; } bool hasLemmaAttr = false; bool hasMorphAttr = false; int pos = tag.indexIn(e, 0); bool insertedTag = false; QString value; QString valueClass; while (pos != -1) { bool isMorph = false; bool isStrongs = false; value = QString::null; valueClass = QString::null; // check 3 attribute/value pairs for (int i = 1; i < 6; i += 2) { if (i > 4) i++; if (tag.cap(i) == "type") { isMorph = (tag.cap(i + 1) == "morph"); isStrongs = (tag.cap(i + 1) == "Strongs"); } else if (tag.cap(i) == "value") { value = tag.cap(i + 1); } else if (tag.cap(i) == "class") { valueClass = tag.cap(i + 1); } } // prepend the class qualifier to the value if (!valueClass.isEmpty()) { value = valueClass + ":" + value; // value.append(":").append(value); } if (value.isEmpty()) { break; } //insert the span if (!insertedTag) { e.replace(pos, tag.matchedLength(), "</span>"); pos += 7; QString rep = QString("<span lemma=\"").append(value).append("\">"); int startPos = 0; QChar c = e[startPos]; while ((startPos < pos) && (c.isSpace() || c.isPunct())) { ++startPos; c = e[startPos]; } hasLemmaAttr = isStrongs; hasMorphAttr = isMorph; e.insert( startPos, rep ); pos += rep.length(); } else { //add the attribute to the existing tag e.remove(pos, tag.matchedLength()); if ((!isMorph && hasLemmaAttr) || (isMorph && hasMorphAttr)) { //we append another attribute value, e.g. 3000 gets 3000|5000 //search the existing attribute start QRegExp attrRegExp( isMorph ? "morph=\".+(?=\")" : "lemma=\".+(?=\")" ); attrRegExp.setMinimal(true); const int foundAttrPos = e.indexOf(attrRegExp, pos); if (foundAttrPos != -1) { e.insert(foundAttrPos + attrRegExp.matchedLength(), QString("|").append(value)); pos += value.length() + 1; hasLemmaAttr = !isMorph; hasMorphAttr = isMorph; } } else { //attribute was not yet inserted const int attrPos = e.indexOf(QRegExp("morph=|lemma="), 0); if (attrPos >= 0) { QString attr; attr.append(isMorph ? "morph" : "lemma").append("=\"").append(value).append("\" "); e.insert(attrPos, attr); hasMorphAttr = isMorph; hasLemmaAttr = !isMorph; pos += attr.length(); } } } insertedTag = true; pos = tag.indexIn(e, pos); } result.append( e ); } if (list.count()) { buf = (const char*)result.toUtf8(); } return 1; }
ElementCollection::ElementCollection(const QStringList &strings, QObject *parent) : QAbstractListModel(parent) { for(QStringList::const_iterator it = strings.begin(); it != strings.end(); ++it) { addElement(*it); } }
void LogViewWindow::createLog(LogFile * pLog, int iId, QString * pszFile) { if(!pLog) return; QRegExp rx; QString szLog, szLogDir, szInputBuffer, szOutputBuffer, szLine, szTmp; QString szDate = pLog->date().toString("yyyy.MM.dd"); /* Fetching previous export path and concatenating with generated filename * adjustFilePath is for file paths not directory paths */ szLog = KVI_OPTION_STRING(KviOption_stringLogsExportPath).trimmed(); if (!szLog.isEmpty()) szLog += KVI_PATH_SEPARATOR_CHAR; szLog += QString("%1_%2.%3_%4").arg(pLog->typeString(),pLog->name(),pLog->network(),szDate); KviFileUtils::adjustFilePath(szLog); // Getting output file path from the user, with overwrite confirmation if(!KviFileDialog::askForSaveFileName( szLog, __tr2qs_ctx("Export Log - KVIrc","log"), szLog, QString(), false, true, true, this)) return; /* Save export directory - this directory path is also used in the HTML export * and info is used when working with pszFile */ QFileInfo info(szLog); szLogDir = info.absoluteDir().absolutePath(); KVI_OPTION_STRING(KviOption_stringLogsExportPath) = szLogDir; /* Reading in log file - LogFiles are read in as bytes, so '\r' isn't * sanitised by default */ pLog->getText(szInputBuffer); QStringList lines = szInputBuffer.replace('\r', "").split('\n'); switch(iId) { case LogFile::PlainText: { /* Only append extension if it isn't there already (e.g. a specific * file is to be overwritten) */ if(!szLog.endsWith(".txt")) szLog += ".txt"; // Scan the file for(QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) { szTmp = (*it); szLine = KviControlCodes::stripControlBytes(szTmp); // Remove icons' code rx.setPattern("^\\d{1,3}\\s"); szLine.replace(rx,""); // Remove link from a user speaking, deal with (and keep) various ranks // e.g.: <!ncHelLViS69> --> <HelLViS69> rx.setPattern("\\s<([+%@&~!]?)!nc"); szLine.replace(rx," <\\1"); // Remove link from a nick in a mask // e.g.: !nFoo [~bar@!hfoo.bar] --> Foo [~bar@!hfoo.bar] rx.setPattern("\\s!n"); szLine.replace(rx," "); // Remove link from a host in a mask // e.g.: Foo [~bar@!hfoo.bar] --> Foo [[email protected]] rx.setPattern("@!h"); szLine.replace(rx,"@"); // Remove link from a channel // e.g.: !c#KVIrc --> #KVIrc rx.setPattern("!c#"); szLine.replace(rx,"#"); szOutputBuffer += szLine; szOutputBuffer += "\n"; } break; } case LogFile::HTML: { /* Only append extension if it isn't there already (e.g. a specific * file is to be overwritten) */ if(!szLog.endsWith(".html")) szLog += ".html"; szTmp = QString("KVIrc %1 %2").arg(KVI_VERSION).arg(KVI_RELEASE_NAME); QString szNick = ""; bool bFirstLine = true; QString szTitle; switch(pLog->type()) { case LogFile::Channel: szTitle = __tr2qs_ctx("Channel %1 on %2","log").arg(pLog->name(),pLog->network()); break; case LogFile::Console: szTitle = __tr2qs_ctx("Console on %1","log").arg(pLog->network()); break; case LogFile::Query: szTitle = __tr2qs_ctx("Query with %1 on %2","log").arg(pLog->name(),pLog->network()); break; case LogFile::DccChat: szTitle = __tr2qs_ctx("DCC Chat with %1","log").arg(pLog->name()); break; case LogFile::Other: szTitle = __tr2qs_ctx("Something on %1","log").arg(pLog->network()); break; } // Prepare HTML document szOutputBuffer += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"; szOutputBuffer += "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n"; szOutputBuffer += "<head>\n"; szOutputBuffer += "\t<meta http-equiv=\"content-type\" content=\"application/xhtml+xml; charset=utf-8\" />\n"; szOutputBuffer += "\t<meta name=\"author\" content=\"" + szTmp + "\" />\n"; szOutputBuffer += "\t<title>" + szTitle + "</title>\n"; szOutputBuffer += "</head>\n<body>\n"; szOutputBuffer += "<h2>" + szTitle + "</h2>\n<h3>Date: " + szDate + "</h3>\n"; // Scan the file for(QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) { szTmp = (*it); // Find who has talked QString szTmpNick = szTmp.section(" ",2,2); if((szTmpNick.left(1) != "<") && (szTmpNick.right(1) != ">")) szTmpNick = ""; // locate msgtype QString szNum = szTmp.section(' ',0,0); bool bOk; int iMsgType = szNum.toInt(&bOk); // only human text for now... if(iMsgType != 24 && iMsgType != 25 && iMsgType != 26) continue; // remove msgtype tag szTmp = szTmp.remove(0,szNum.length()+1); szTmp = KviHtmlGenerator::convertToHtml(szTmp,true); // insert msgtype icon at start of the current text line KviMessageTypeSettings msg(KVI_OPTION_MSGTYPE(iMsgType)); QString szIcon = g_pIconManager->getSmallIconResourceName((KviIconManager::SmallIcon)msg.pixId()); szTmp.prepend("<img src=\"" + szIcon + "\" alt=\"\" /> "); /* * Check if the nick who has talked is the same of the above line. * If so, we have to put the line as it is, otherwise we have to * open a new paragraph */ if(szTmpNick != szNick) { /* * People is not the same, close the paragraph opened * before and open a new one */ if(!bFirstLine) szOutputBuffer += "</p>\n"; szTmp.prepend("<p>"); szNick = szTmpNick; } else { // Break the line szTmp.prepend("<br />\n"); } szOutputBuffer += szTmp; bFirstLine = false; } // Close the last paragraph szOutputBuffer += "</p>\n"; // regexp to search all embedded icons rx.setPattern("<img src=\"smallicons:([^\"]+)"); int iIndex = szOutputBuffer.indexOf(rx); QStringList szImagesList; // search for icons while (iIndex >= 0) { int iLength = rx.matchedLength(); QString szCap = rx.cap(1); // if the icon isn't in the images list then add if(szImagesList.indexOf(szCap) == -1) szImagesList.append(szCap); iIndex = szOutputBuffer.indexOf(rx, iIndex + iLength); } // get current theme path QString szCurrentThemePath; g_pApp->getLocalKvircDirectory(szCurrentThemePath,KviApplication::Themes,KVI_OPTION_STRING(KviOption_stringIconThemeSubdir)); szCurrentThemePath += KVI_PATH_SEPARATOR_CHAR; // current coresmall path szCurrentThemePath += "coresmall"; szCurrentThemePath += KVI_PATH_SEPARATOR_CHAR; // check if coresmall exists in current theme if(!KviFileUtils::directoryExists(szCurrentThemePath)) { // get global coresmall path g_pApp->getGlobalKvircDirectory(szCurrentThemePath,KviApplication::Pics,"coresmall"); KviQString::ensureLastCharIs(szCurrentThemePath,QChar(KVI_PATH_SEPARATOR_CHAR)); } // copy all icons to the log destination folder for(int i=0; i < szImagesList.count(); i++) { QString szSourceFile = szCurrentThemePath + szImagesList.at(i); QString szDestFile = szLogDir + szImagesList.at(i); KviFileUtils::copyFile(szSourceFile,szDestFile); } // remove internal tags rx.setPattern("<qt>|</qt>|smallicons:"); szOutputBuffer.replace(rx,""); szOutputBuffer.replace(">!nc",">"); szOutputBuffer.replace("@!nc","@"); szOutputBuffer.replace("%!nc","%"); // Close the document szOutputBuffer += "</body>\n</html>\n"; break; } } // File overwriting already dealt with when file path was obtained QFile log(szLog); if(!log.open(QIODevice::WriteOnly | QIODevice::Text)) return; if(pszFile) { *pszFile = ""; *pszFile = info.filePath(); } // Ensure we're writing in UTF-8 QTextStream output(&log); output.setCodec("UTF-8"); output << szOutputBuffer; // Close file descriptors log.close(); }
QStringList ScribusQApp::getLang(QString lang) { QStringList langs; // read the locales if (!lang.isEmpty()) langs.push_back(lang); //add in user preferences lang, only overridden by lang command line option QString Pff = QDir::convertSeparators(ScPaths::getApplicationDataDir()); QFileInfo Pffi = QFileInfo(Pff); if (Pffi.exists()) { QString PrefsPfad; if (Pffi.isDir()) PrefsPfad = Pff; else PrefsPfad = QDir::homePath(); QString prefsXMLFile=QDir::convertSeparators(PrefsPfad + "/prefs150.xml"); QFileInfo infoPrefsFile(prefsXMLFile); if (infoPrefsFile.exists()) { PrefsFile* prefsFile = new PrefsFile(prefsXMLFile); if (prefsFile) { PrefsContext* userprefsContext = prefsFile->getContext("user_preferences"); if (userprefsContext) { QString prefslang = userprefsContext->get("gui_language",""); if (!prefslang.isEmpty()) langs.push_back(prefslang); } } delete prefsFile; } } if (!(lang = ::getenv("LC_ALL")).isEmpty()) langs.push_back(lang); if (!(lang = ::getenv("LC_MESSAGES")).isEmpty()) langs.push_back(lang); if (!(lang = ::getenv("LANG")).isEmpty()) langs.push_back(lang); #if defined(_WIN32) wchar_t out[256]; QString language, sublanguage; LCID lcIdo = GetUserDefaultLCID(); WORD sortId = SORTIDFROMLCID(lcIdo); LANGID langId = GetUserDefaultUILanguage(); LCID lcIdn = MAKELCID(langId, sortId); if ( GetLocaleInfoW(lcIdn, LOCALE_SISO639LANGNAME , out, 255) ) { language = QString::fromUtf16( (ushort*)out ); if ( GetLocaleInfoW(lcIdn, LOCALE_SISO3166CTRYNAME, out, 255) ) { sublanguage = QString::fromUtf16( (ushort*)out ).toLower(); lang = language; if ( sublanguage != language && !sublanguage.isEmpty() ) lang += "_" + sublanguage.toUpper(); langs.push_back(lang); } } #endif langs.push_back(QString(QLocale::system().name())); // remove duplicate entries... QStringList::Iterator it = langs.end(); while (it != langs.begin()) { --it; if (langs.count(*it) > 1) it = langs.erase(it); } return langs; }
//==================================== // exportData //------------------------------------ bool SCCKeyboard::exportData ( void ) { //==================================== // create Manipulator //------------------------------------ SaXManipulateKeyboard saxKeyboard ( mSection["Keyboard"] ); //==================================== // retrieve dialog data //------------------------------------ QString type = mKeyboardLayout -> getType(); QString layout = mKeyboardLayout -> getLayout(); QString variant = mKeyboardLayout -> getVariant(); QString option = mKeyboardOptions -> getOptions(); //==================================== // save keyboard model/type //------------------------------------ saxKeyboard.setXKBModel ( type ); int count = 0; int kbcnt = 0; //==================================== // save keyboard layout(s) //------------------------------------ QStringList variants = QStringList::split ( ",",variant,true ); QStringList layouts = QStringList::split ( ",",layout ); for (QStringList::Iterator it=layouts.begin();it!=layouts.end();++it) { QString layout (*it); QString variant (variants[count]); if (count == 0) { saxKeyboard.setXKBLayout ( layout ); saxKeyboard.setXKBVariant (layout,variant); } else { saxKeyboard.addXKBLayout ( layout ); if (variant.isEmpty()) { variant = ","; } saxKeyboard.setXKBVariant (layout,variant); } count++; } kbcnt = count; count = 0; //==================================== // save keyboard options //------------------------------------ QStringList options = QStringList::split ( ",",option ); for (QStringList::Iterator it=options.begin();it!=options.end();++it) { QString option (*it); if (count == 0) { saxKeyboard.setXKBOption ( option ); } else { saxKeyboard.addXKBOption ( option ); } count++; } //==================================== // add keyboard toggle key //------------------------------------ if (kbcnt == 1) { saxKeyboard.removeXKBOption ("grp:alt_shift_toggle"); } if ((kbcnt > 1) && (option.isEmpty())) { saxKeyboard.setXKBOption ( "grp:alt_shift_toggle" ); } return true; }
QString HelpPreProcessor::parse(const QString& filename) { QFile f( filename ); if ( !f.exists() ) { QStringList helpPaths = Qtopia::helpPaths(); QStringList::Iterator it; for ( it = helpPaths.begin(); it != helpPaths.end(); it++ ) { QString file = (*it) + "/" + filename; f.setFileName( file ); if ( f.exists() ) break; } if ( it == helpPaths.end() ) return tr("Could not locate %1", "%1 - file").arg( filename ); } qLog(Help) << "Loading help file: " << filename << "(" << f.fileName() << ")" ; f.open( QIODevice::ReadOnly ); QByteArray data = f.readAll(); QTextStream ts( data, QIODevice::ReadOnly ); ts.setCodec( QTextCodec::codecForName("UTF-8") ); QString text; QString line; QRegExp tagAny( "<!--#" ); QRegExp tagIf( "<!--#if\\s+expr=\"\\$([^\"]*)\"\\s*-->" ); QRegExp tagElif( "<!--#elif\\s+expr=\"\\$([^\"]*)\"\\s*-->" ); // not supported QRegExp tagElse( "<!--#else\\s*-->" ); QRegExp tagEndif( "<!--#endif\\s*-->" ); QRegExp tagSet( "<!--#set\\s+var=\"([^\"]*)\"\\s*value=\"([^\"]*)\"\\s*-->" ); QRegExp tagEcho( "<!--#echo\\s+var=\"([^\"]*)\"\\s*-->" ); QRegExp tagInclude( "<!--#include\\s+file=\"([^\"]*)\"\\s*-->" ); bool skip = false; int lnum=0; do { line = ts.readLine(); lnum++; if ( tagAny.indexIn(line) != -1 ) { int offset; int matchLen; offset = 0; matchLen = 0; while ( (offset = tagIf.indexIn( line, offset + matchLen )) != -1 ) { matchLen = tagIf.matchedLength(); tests.push(tagIf.capturedTexts().at(1).split(QRegExp("\\s*\\|\\|\\s*\\$"))); inverts.push(false); QStringList t = tagIf.capturedTexts().at(1).split(QRegExp("\\s*\\|\\|\\s*\\$")); //text+="TEST("+t.join(" or ")+")"; } offset = 0; matchLen = 0; while ( (offset = tagElse.indexIn( line, offset + matchLen )) != -1 ) { matchLen = tagEndif.matchedLength(); inverts.push(!inverts.pop()); } offset = 0; matchLen = 0; bool err=false; while ( (offset = tagEndif.indexIn( line, offset + matchLen )) != -1 ) { matchLen = tagEndif.matchedLength(); if (!tests.isEmpty()) tests.pop(); else err=true; if (!inverts.isEmpty()) inverts.pop(); else err=true; } if (err) qWarning("%s:%d:Unexpected #endif",filename.toLatin1().data(),lnum); QStack<QStringList>::ConstIterator it; QStack<bool>::ConstIterator bit; // recalculate skip skip = false; for ( it = tests.begin(),bit=inverts.begin(); it != tests.end() && !skip; ++it,++bit ) { skip = true; foreach (QString t, *it) if ( !replace[t].isEmpty() ) skip = false; if (*bit) skip = !skip; } if ( !skip ) { offset = 0; matchLen = 0; while ( (offset = tagSet.indexIn( line, offset + matchLen )) != -1 ) { matchLen = tagSet.matchedLength(); QString key = tagSet.capturedTexts().at(1); QString value = tagSet.capturedTexts().at(2); replace[key] = value; } while ( (offset = tagEcho.indexIn( line )) != -1 ) { QString key = tagEcho.capturedTexts().at(1); line.replace( offset, tagEcho.matchedLength(), replace[key] ); } if ( levels ) { while ( (offset = tagInclude.indexIn( line )) != -1 ) { QString file = tagInclude.capturedTexts().at(1); // Recurse. levels--; line.replace( offset, tagInclude.matchedLength(), parse(file) ); levels++; } } } } if ( !skip ) text += line + "\n"; } while (!ts.atEnd());
bool KatePrinter::print (KateDocument *doc) { QPrinter printer; readSettings(printer); // docname is now always there, including the right Untitled name printer.setDocName(doc->documentName()); KatePrintTextSettings *kpts = new KatePrintTextSettings; KatePrintHeaderFooter *kphf = new KatePrintHeaderFooter; KatePrintLayout *kpl = new KatePrintLayout; QList<QWidget*> tabs; tabs << kpts; tabs << kphf; tabs << kpl; QWidget *parentWidget=doc->widget(); if ( !parentWidget ) parentWidget=QApplication::activeWindow(); QScopedPointer<QPrintDialog> printDialog(KdePrint::createPrintDialog(&printer, KdePrint::SystemSelectsPages, tabs, parentWidget)); if ( doc->activeView()->selection() ) { printer.setPrintRange(QPrinter::Selection); printDialog->setOption(QAbstractPrintDialog::PrintSelection, true); } if ( printDialog->exec() ) { writeSettings(printer); KateRenderer renderer(doc, doc->activeKateView()); renderer.config()->setSchema (kpl->colorScheme()); renderer.setPrinterFriendly(true); QPainter paint( &printer ); /* * We work in tree cycles: * 1) initialize variables and retrieve print settings * 2) prepare data according to those settings * 3) draw to the printer */ uint pdmWidth = printer.width(); uint pdmHeight = printer.height(); int y = 0; uint xstart = 0; // beginning point for painting lines uint lineCount = 0; uint maxWidth = pdmWidth; int headerWidth = pdmWidth; int startCol = 0; int endCol = 0; bool pageStarted = true; int remainder = 0; // remaining sublines from a wrapped line (for the top of a new page) // Text Settings Page bool selectionOnly = (printDialog->printRange() == QAbstractPrintDialog::Selection); bool useGuide = kpts->printGuide(); bool printLineNumbers = kpts->printLineNumbers(); uint lineNumberWidth( 0 ); // Header/Footer Page QFont headerFont(kphf->font()); // used for header/footer bool useHeader = kphf->useHeader(); QColor headerBgColor(kphf->headerBackground()); QColor headerFgColor(kphf->headerForeground()); uint headerHeight( 0 ); // further init only if needed QStringList headerTagList; // do bool headerDrawBg = false; // do bool useFooter = kphf->useFooter(); QColor footerBgColor(kphf->footerBackground()); QColor footerFgColor(kphf->footerForeground()); uint footerHeight( 0 ); // further init only if needed QStringList footerTagList; // do bool footerDrawBg = false; // do // Layout Page renderer.config()->setSchema( kpl->colorScheme() ); bool useBackground = kpl->useBackground(); bool useBox = kpl->useBox(); int boxWidth(kpl->boxWidth()); QColor boxColor(kpl->boxColor()); int innerMargin = useBox ? kpl->boxMargin() : 6; // Post initialization int maxHeight = (useBox ? pdmHeight-innerMargin : pdmHeight); uint currentPage( 1 ); uint lastline = doc->lastLine(); // necessary to print selection only uint firstline( 0 ); const int fontHeight = renderer.fontHeight(); KTextEditor::Range selectionRange; /* * Now on for preparations... * during preparations, variable names starting with a "_" means * those variables are local to the enclosing block. */ { if ( selectionOnly ) { // set a line range from the first selected line to the last selectionRange = doc->activeView()->selectionRange(); firstline = selectionRange.start().line(); lastline = selectionRange.end().line(); lineCount = firstline; } if ( printLineNumbers ) { // figure out the horiizontal space required QString s( QString("%1 ").arg( doc->lines() ) ); s.fill('5', -1); // some non-fixed fonts haven't equally wide numbers // FIXME calculate which is actually the widest... lineNumberWidth = renderer.currentFontMetrics().width( s ); // a small space between the line numbers and the text int _adj = renderer.currentFontMetrics().width( "5" ); // adjust available width and set horizontal start point for data maxWidth -= (lineNumberWidth + _adj); xstart += lineNumberWidth + _adj; } if ( useHeader || useFooter ) { // Set up a tag map // This retrieves all tags, ued or not, but // none of theese operations should be expensive, // and searcing each tag in the format strings is avoided. QDateTime dt = QDateTime::currentDateTime(); QMap<QString,QString> tags; KUser u (KUser::UseRealUserID); tags["u"] = u.loginName(); tags["d"] = KGlobal::locale()->formatDateTime(dt, KLocale::ShortDate); tags["D"] = KGlobal::locale()->formatDateTime(dt, KLocale::LongDate); tags["h"] = KGlobal::locale()->formatTime(dt.time(), false); tags["y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::ShortDate); tags["Y"] = KGlobal::locale()->formatDate(dt.date(), KLocale::LongDate); tags["f"] = doc->url().fileName(); tags["U"] = doc->url().prettyUrl(); if ( selectionOnly ) { QString s( i18n("(Selection of) ") ); tags["f"].prepend( s ); tags["U"].prepend( s ); } QRegExp reTags( "%([dDfUhuyY])" ); // TODO tjeck for "%%<TAG>" if (useHeader) { headerDrawBg = kphf->useHeaderBackground(); headerHeight = QFontMetrics( headerFont ).height(); if ( useBox || headerDrawBg ) headerHeight += innerMargin * 2; else headerHeight += 1 + QFontMetrics( headerFont ).leading(); headerTagList = kphf->headerFormat(); QMutableStringListIterator it(headerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!headerBgColor.isValid()) headerBgColor = Qt::lightGray; if (!headerFgColor.isValid()) headerFgColor = Qt::black; } if (useFooter) { footerDrawBg = kphf->useFooterBackground(); footerHeight = QFontMetrics( headerFont ).height(); if ( useBox || footerDrawBg ) footerHeight += 2*innerMargin; else footerHeight += 1; // line only footerTagList = kphf->footerFormat(); QMutableStringListIterator it(footerTagList); while ( it.hasNext() ) { QString tag = it.next(); int pos = reTags.indexIn( tag ); QString rep; while ( pos > -1 ) { rep = tags[reTags.cap( 1 )]; tag.replace( (uint)pos, 2, rep ); pos += rep.length(); pos = reTags.indexIn( tag, pos ); } it.setValue( tag ); } if (!footerBgColor.isValid()) footerBgColor = Qt::lightGray; if (!footerFgColor.isValid()) footerFgColor = Qt::black; // adjust maxheight, so we can know when/where to print footer maxHeight -= footerHeight; } } // if ( useHeader || useFooter ) if ( useBackground ) { if ( ! useBox ) { xstart += innerMargin; maxWidth -= innerMargin * 2; } } if ( useBox ) { if (!boxColor.isValid()) boxColor = Qt::black; if (boxWidth < 1) // shouldn't be pssible no more! boxWidth = 1; // set maxwidth to something sensible maxWidth -= ( ( boxWidth + innerMargin ) * 2 ); xstart += boxWidth + innerMargin; // maxheight too.. maxHeight -= boxWidth; } else boxWidth = 0; // now that we know the vertical amount of space needed, // it is possible to calculate the total number of pages // if needed, that is if any header/footer tag contains "%P". if ( !headerTagList.filter("%P").isEmpty() || !footerTagList.filter("%P").isEmpty() ) { kDebug(13020)<<"'%P' found! calculating number of pages..."; int pageHeight = maxHeight; if ( useHeader ) pageHeight -= ( headerHeight + innerMargin ); if ( useFooter ) pageHeight -= innerMargin; const int linesPerPage = pageHeight / fontHeight; // kDebug() << "Lines per page:" << linesPerPage; // calculate total layouted lines in the document int totalLines = 0; // TODO: right now ignores selection printing for (int i = firstline; i <= lastline; ++i) { KateLineLayoutPtr rangeptr(new KateLineLayout(doc)); rangeptr->setLine(i); renderer.layoutLine(rangeptr, (int)maxWidth, false); totalLines += rangeptr->viewLineCount(); } int totalPages = (totalLines / linesPerPage) + ((totalLines % linesPerPage) > 0 ? 1 : 0); // kDebug() << "_______ pages:" << (totalLines / linesPerPage); // kDebug() << "________ rest:" << (totalLines % linesPerPage); // TODO: add space for guide if required // if ( useGuide ) // _lt += (guideHeight + (fontHeight /2)) / fontHeight; // substitute both tag lists QString re("%P"); QStringList::Iterator it; for ( it=headerTagList.begin(); it!=headerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); for ( it=footerTagList.begin(); it!=footerTagList.end(); ++it ) (*it).replace( re, QString( "%1" ).arg( totalPages ) ); } } // end prepare block /* On to draw something :-) */ while ( lineCount <= lastline ) { startCol = 0; endCol = 0; if ( y + fontHeight > maxHeight ) { kDebug(13020)<<"Starting new page,"<<lineCount<<"lines up to now."; printer.newPage(); paint.resetTransform(); currentPage++; pageStarted = true; y=0; } if ( pageStarted ) { if ( useHeader ) { paint.setPen(headerFgColor); paint.setFont(headerFont); if ( headerDrawBg ) paint.fillRect(0, 0, headerWidth, headerHeight, headerBgColor); if (headerTagList.count() == 3) { int valign = ( (useBox||headerDrawBg||useBackground) ? Qt::AlignVCenter : Qt::AlignTop ); int align = valign|Qt::AlignLeft; int marg = ( useBox || headerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = headerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, 0, headerWidth-(marg*2), headerHeight, align, s); align = valign|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } if ( ! ( headerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate header from contents { paint.drawLine( 0, headerHeight-1, headerWidth, headerHeight-1 ); //y += 1; now included in headerHeight } y += headerHeight + innerMargin; } if ( useFooter ) { paint.setPen(footerFgColor); if ( ! ( footerDrawBg || useBox || useBackground ) ) // draw a 1 px (!?) line to separate footer from contents paint.drawLine( 0, maxHeight + innerMargin - 1, headerWidth, maxHeight + innerMargin - 1 ); if ( footerDrawBg ) paint.fillRect(0, maxHeight+innerMargin+boxWidth, headerWidth, footerHeight, footerBgColor); if (footerTagList.count() == 3) { int align = Qt::AlignVCenter|Qt::AlignLeft; int marg = ( useBox || footerDrawBg ) ? innerMargin : 0; if ( useBox ) marg += boxWidth; QString s; for (int i=0; i<3; i++) { s = footerTagList[i]; if (s.indexOf("%p") != -1) s.replace("%p", QString::number(currentPage)); paint.drawText(marg, maxHeight+innerMargin, headerWidth-(marg*2), footerHeight, align, s); align = Qt::AlignVCenter|(i == 0 ? Qt::AlignHCenter : Qt::AlignRight); } } } // done footer if ( useBackground ) { // If we have a box, or the header/footer has backgrounds, we want to paint // to the border of those. Otherwise just the contents area. int _y = y, _h = maxHeight - y; if ( useBox ) { _y -= innerMargin; _h += 2 * innerMargin; } else { if ( headerDrawBg ) { _y -= innerMargin; _h += innerMargin; } if ( footerDrawBg ) { _h += innerMargin; } } paint.fillRect( 0, _y, pdmWidth, _h, renderer.config()->backgroundColor()); } if ( useBox ) { paint.setPen(QPen(boxColor, boxWidth)); paint.drawRect(0, 0, pdmWidth, pdmHeight); if (useHeader) paint.drawLine(0, headerHeight, headerWidth, headerHeight); else y += innerMargin; if ( useFooter ) // drawline is not trustable, grr. paint.fillRect( 0, maxHeight+innerMargin, headerWidth, boxWidth, boxColor ); } if ( useGuide && currentPage == 1 ) { // FIXME - this may span more pages... // draw a box unless we have boxes, in which case we end with a box line int _ystart = y; QString _hlName = doc->highlight()->name(); QList<KateExtendedAttribute::Ptr> _attributes; // list of highlight attributes for the legend doc->highlight()->getKateExtendedAttributeList(kpl->colorScheme(), _attributes); KateAttributeList _defaultAttributes; KateHlManager::self()->getDefaults ( renderer.config()->schema(), _defaultAttributes ); QColor _defaultPen = _defaultAttributes.at(0)->foreground().color(); paint.setPen(_defaultPen); int _marg = 0; if ( useBox ) _marg += (2*boxWidth) + (2*innerMargin); else { if ( useBackground ) _marg += 2*innerMargin; _marg += 1; y += 1 + innerMargin; } // draw a title string QFont _titleFont = renderer.config()->font(); _titleFont.setBold(true); paint.setFont( _titleFont ); QRect _r; paint.drawText( QRect(_marg, y, pdmWidth-(2*_marg), maxHeight - y), Qt::AlignTop|Qt::AlignHCenter, i18n("Typographical Conventions for %1", _hlName ), &_r ); int _w = pdmWidth - (_marg*2) - (innerMargin*2); int _x = _marg + innerMargin; y += _r.height() + innerMargin; paint.drawLine( _x, y, _x + _w, y ); y += 1 + innerMargin; int _widest( 0 ); foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) _widest = qMax(QFontMetrics(attribute->font()).width(attribute->name().section(':',1,1)), _widest); int _guideCols = _w/( _widest + innerMargin ); // draw attrib names using their styles int _cw = _w/_guideCols; int _i(0); _titleFont.setUnderline(true); QString _currentHlName; foreach (const KateExtendedAttribute::Ptr &attribute, _attributes) { QString _hl = attribute->name().section(':',0,0); QString _name = attribute->name().section(':',1,1); if ( _hl != _hlName && _hl != _currentHlName ) { _currentHlName = _hl; if ( _i%_guideCols ) y += fontHeight; y += innerMargin; paint.setFont(_titleFont); paint.setPen(_defaultPen); paint.drawText( _x, y, _w, fontHeight, Qt::AlignTop, _hl + ' ' + i18n("text") ); y += fontHeight; _i = 0; } KTextEditor::Attribute _attr = *_defaultAttributes[attribute->defaultStyleIndex()]; _attr += *attribute; paint.setPen( _attr.foreground().color() ); paint.setFont( _attr.font() ); if (_attr.hasProperty(QTextFormat::BackgroundBrush) ) { QRect _rect = QFontMetrics(_attr.font()).boundingRect(_name); _rect.moveTo(_x + ((_i%_guideCols)*_cw), y); paint.fillRect(_rect, _attr.background() ); } paint.drawText(( _x + ((_i%_guideCols)*_cw)), y, _cw, fontHeight, Qt::AlignTop, _name ); _i++; if ( _i && ! ( _i%_guideCols ) ) y += fontHeight; } if ( _i%_guideCols ) y += fontHeight;// last row not full // draw a box around the legend paint.setPen ( _defaultPen ); if ( useBox ) paint.fillRect( 0, y+innerMargin, headerWidth, boxWidth, boxColor ); else { _marg -=1; paint.drawRect( _marg, _ystart, pdmWidth-(2*_marg), y-_ystart+innerMargin ); } y += ( useBox ? boxWidth : 1 ) + (innerMargin*2); } // useGuide paint.translate(xstart,y); pageStarted = false; } // pageStarted; move on to contents:)
bool UserPlugin::onIq(gloox::Stanza* s) { QString xmlns=QString::fromStdString(s->xmlns()); AsyncRequest* req=bot()->asyncRequests()->byStanza(s); if (s->subtype()==gloox::StanzaIqGet) { if (s->subtype()!=gloox::StanzaIqResult && xmlns=="jabber:iq:version") { //We should send our version sendVersion(s); return true; } if (xmlns=="http://jabber.org/protocol/disco#items") { //Disco items request. Report error; gloox::Stanza *st=gloox::Stanza::createIqStanza(s->from(), s->findAttribute("id"), gloox::StanzaIqError, xmlns.toStdString()); bot()->client()->send(st); } if (s->subtype() != gloox::StanzaIqResult && xmlns=="jabber:iq:time" ) { //We should send our time (XEP-0090) sendTime(s); return true; } if (req) bot()->asyncRequests()->removeAll(req); return true; } if (!req) return false; if (req->plugin()!=this) return false; gloox::Tag* query=s->findChild("query", "xmlns", xmlns.toStdString()); if (!query) { reply(req->stanza(), "Error"); bot()->asyncRequests()->removeAll(req); delete req; return true; } if (xmlns=="jabber:iq:time") { QString msg, time; QString src = bot()->JIDtoNick(QString::fromStdString(s->from().full())); gloox::Tag *display = query->findChild("display"); if(display) { assert(display); time = QString::fromStdString(display->cdata()); } if( time.isEmpty() ) { gloox::Tag *tz = query->findChild("tz"); if(tz) { assert(tz); time = QString::fromStdString(tz->cdata()); } } if( time.isEmpty() ) { gloox::Tag *utc = query->findChild("utc"); if(utc) { assert(utc); QString time = utcToString( QString::fromStdString(utc->cdata()).trimmed(), "ddd, dd MMM yyyy HH:mm:ss"); msg=QString("at %1 there is %2 +0000") .arg(QString::fromStdString(s->from().full())) .arg(time); } } else { if ( msg.isEmpty() && src.isEmpty() ) msg=QString("It's %1 on your watch").arg(time); else if( msg.isEmpty() ) msg=QString("It's %1 on %2's watch").arg(time).arg(src); if( time.isEmpty() ) msg="responce with no data."; } if( s->subtype()==gloox::StanzaIqResult && s->error() == gloox::StanzaErrorUndefined ) reply( req->stanza(), msg ); else if( s->error() == gloox::StanzaErrorRemoteServerNotFound ) reply( req->stanza(), "Recipient is not in the conference room" ); else if( s->error() == gloox::StanzaErrorFeatureNotImplemented ) reply( req->stanza(), "Feature Not Implemented" ); else reply( req->stanza(), "Unable to get time" ); } if (xmlns=="jabber:iq:version") { if (req->name()=="PING") { QString msg; QString src=bot()->JIDtoNick(QString::fromStdString(s->from().full())); double delay=(double)req->time().time().msecsTo(QTime::currentTime()); delay/=1000.0; if (s->subtype()==gloox::StanzaIqResult) msg=QString("Pong from %1 after %2 secs.").arg(src).arg(delay); else msg=QString("Pong from %1's server after %2 secs.").arg(src).arg(delay); reply(req->stanza(), msg); } else if (s->subtype()==gloox::StanzaIqResult) { QString name; QString version; QString os; gloox::Tag* t; t=query->findChild("name"); if (t) name=QString::fromStdString(t->cdata()); t=query->findChild("version"); if (t) version=QString::fromStdString(t->cdata()); t=query->findChild("os"); if (t) os=QString::fromStdString(t->cdata()); QString res=name; if (!version.isEmpty()) res+=QString(" %1").arg(version); if (!os.isEmpty()) res+=QString(" // %1").arg(os); QString src=bot()->JIDtoNick(QString::fromStdString(s->from().full())); if (!src.isEmpty()) src+=" uses "; src+=res; reply(req->stanza(), src); } else { //TODO: Error handling reply(req->stanza(), "Unable to get version"); } } if (xmlns=="http://jabber.org/protocol/disco#items") { if (s->subtype()==gloox::StanzaIqError) reply(req->stanza(), "Unable to query"); else { QList<gloox::Tag*> lst= QList<gloox::Tag*>::fromStdList(query->children()); QStringList strings; bool safeJid=req->name().indexOf('@')<0; int noval=0; for (int i=0; i<lst.count(); i++) { QString name= QString::fromStdString(lst[i]->findAttribute("name")); QString jid= QString::fromStdString(lst[i]->findAttribute("jid")); if (name.isEmpty()) name=jid; if (name.isEmpty()) continue; QString cnt=getValue(name, "^.*\\(([^\\)]+)\\)$"); if (cnt.isEmpty()) { cnt="0"; noval++; } else name=getValue(name,"^(.*)\\([^\\)]+\\)$").trimmed(); bool ok=true; cnt.toInt(&ok); if (!ok) cnt="0"; cnt=cnt.rightJustified(8, '0', true); if (name!=jid && safeJid) name+=QString(" [%1]").arg(jid); strings.append(QString("%1 %2").arg(cnt).arg(name)); } strings.sort(); QStringList replyList; bool haveValues; if (lst.count()) { double perc=((double)noval)/((double)(lst.count())); haveValues=perc<0.2; } int idx=strings.count()-1; for (int i=0; i<strings.count(); i++) { int curIdx=haveValues ? idx : i; int value=strings[curIdx].section(' ',0,0).toInt(); QString name=strings[curIdx].section(' ', 1); idx--; QString item=QString("%1) %2").arg(i+1).arg(name); if (haveValues) item+=QString(": %1").arg(value); replyList.append(item); if (replyList.count()>=100) { replyList.append("..."); break; } } reply(req->stanza(), "Disco items:\n"+replyList.join("\n")); } } if (xmlns=="http://jabber.org/protocol/stats") { // Got statistic to display? if (s->subtype()==gloox::StanzaIqError) reply(req->stanza(), "Unable to query"); else { std::list<gloox::Tag*> childList=query->children(); QStringList statItemList; bool haveValues=true; for (std::list<gloox::Tag*>::iterator it=childList.begin(); it!=childList.end(); ++it) { gloox::Tag* child=*it; if (child->name()!="stat") continue; QString item=QString::fromStdString(child->findAttribute("name")); QString value=QString::fromStdString(child->findAttribute("value")); if (!value.isEmpty()) { item+=QString(": %1").arg(value); QString units=QString::fromStdString(child->findAttribute("units")); if (!units.isEmpty()) item+=QString(" %1").arg(units); } else { gloox::Tag* err=child->findChild("error"); if (err) { value=QString::fromStdString(err->cdata()); if (value.isEmpty()) value=QString::fromStdString(err->xml()); item+=QString(": %1").arg(value); } } if (value.isEmpty()) haveValues=false; statItemList.append(item); } if (req->name()=="STAT" && !haveValues) { // Resubmit query with values information std::string id=bot()->client()->getID(); gloox::Stanza *st2=gloox::Stanza::createIqStanza(s->from(), id, gloox::StanzaIqGet, xmlns.toStdString()); gloox::Tag* query2=st2->findChild("query", "xmlns", xmlns.toStdString()); assert(query2); for (QStringList::iterator it=statItemList.begin(); it!=statItemList.end(); ++it) { QString statItem=*it; query2->addChild(new gloox::Tag("stat","name",statItem.toStdString())); } st2->finalize(); gloox::Stanza *sf=new gloox::Stanza(req->stanza()); sf->addAttribute("id", id); AsyncRequest *req=new AsyncRequest(-1, this, sf, 3600); req->setName("STAT2"); bot()->asyncRequests()->append(req); bot()->client()->send(st2); } else { reply(req->stanza(), QString("Statistic:\n%1").arg(statItemList.join("\n"))); } } } if (xmlns=="jabber:iq:last") { QString value=QString::fromStdString(query->findAttribute("seconds")); bool ok=true; int res=value.toInt(&ok); if (ok==false || value.isEmpty()) reply(req->stanza(),"Unable to query"); else reply(req->stanza(), secsToString(res)); } if (xmlns=="http://jabber.org/protocol/muc#admin") { if (s->subtype()==gloox::StanzaIqError) reply(req->stanza(), "Unable to query"); else { QList<gloox::Tag*> lst = QList<gloox::Tag*>::fromStdList(query->children()); QStringList strings; QString affil, str, reason; for (int i = 0; i < lst.count(); i++) { QString jid = QString::fromStdString( lst[i]->findAttribute("jid")); gloox::Tag *tag = lst[i]->findChild("reason"); if (tag) { tag->cdata(); reason = QString::fromStdString( tag->cdata()).trimmed(); } QString nick = QString::fromStdString( lst[i]->findAttribute("nick")); if (nick.isEmpty()) str = jid; else str = QString("%1 (%2)").arg(nick).arg(jid); if (!reason.isEmpty()) str.append(" // ").append(reason.trimmed()); strings.append(str); } if (strings.count() <= 0) { reply(req->stanza(), affil += "list empty!"); } else { affil = QString::fromStdString(lst[0]->findAttribute("role")); if (affil.isEmpty()) affil = QString::fromStdString(lst[0]->findAttribute("affiliation")); strings.sort(); QStringList list; for (int i = 0; i < strings.count(); i++) { list.append(QString("%1) %2") .arg(i+1).arg(strings[i])); } int cnt = list.count(); reply(req->stanza(), QString("%1 %2%3 here:\n%4") .arg(cnt).arg(affil) .arg((cnt > 1) ? "s":"") .arg(list.join("\n").trimmed())); } } } bot()->asyncRequests()->removeAll(req); delete req; return true; }
/*! Load, parse, and process a qdoc configuration file. This function is only called by the other load() function, but this one is recursive, i.e., it calls itself when it sees an \c{include} statement in the qdog configuration file. */ void Config::load(Location location, const QString& fileName) { QRegExp keySyntax("\\w+(?:\\.\\w+)*"); #define SKIP_CHAR() \ do { \ location.advance(c); \ ++i; \ c = text.at(i); \ cc = c.unicode(); \ } while (0) #define SKIP_SPACES() \ while (c.isSpace() && cc != '\n') \ SKIP_CHAR() #define PUT_CHAR() \ word += c; \ SKIP_CHAR(); if (location.depth() > 16) location.fatal(tr("Too many nested includes")); QFile fin(fileName); if (!fin.open(QFile::ReadOnly | QFile::Text)) { fin.setFileName(fileName + ".qdoc"); if (!fin.open(QFile::ReadOnly | QFile::Text)) location.fatal(tr("Cannot open file '%1': %2").arg(fileName).arg(fin.errorString())); } QTextStream stream(&fin); stream.setCodec("UTF-8"); QString text = stream.readAll(); text += QLatin1String("\n\n"); text += QChar('\0'); fin.close(); location.push(fileName); location.start(); int i = 0; QChar c = text.at(0); uint cc = c.unicode(); while (i < (int) text.length()) { if (cc == 0) ++i; else if (c.isSpace()) { SKIP_CHAR(); } else if (cc == '#') { do { SKIP_CHAR(); } while (cc != '\n'); } else if (isMetaKeyChar(c)) { Location keyLoc = location; bool plus = false; QString stringValue; QStringList stringListValue; QString word; bool inQuote = false; bool prevWordQuoted = true; bool metWord = false; MetaStack stack; do { stack.process(c, location); SKIP_CHAR(); } while (isMetaKeyChar(c)); QStringList keys = stack.getExpanded(location); //qDebug() << "KEYS:" << keys; SKIP_SPACES(); if (keys.count() == 1 && keys.first() == "include") { QString includeFile; if (cc != '(') location.fatal(tr("Bad include syntax")); SKIP_CHAR(); SKIP_SPACES(); while (!c.isSpace() && cc != '#' && cc != ')') { includeFile += c; SKIP_CHAR(); } SKIP_SPACES(); if (cc != ')') location.fatal(tr("Bad include syntax")); SKIP_CHAR(); SKIP_SPACES(); if (cc != '#' && cc != '\n') location.fatal(tr("Trailing garbage")); /* Here is the recursive call. */ load(location, QFileInfo(QFileInfo(fileName).dir(), includeFile) .filePath()); } else { /* It wasn't an include statement, so it;s something else. */ if (cc == '+') { plus = true; SKIP_CHAR(); } if (cc != '=') location.fatal(tr("Expected '=' or '+=' after key")); SKIP_CHAR(); SKIP_SPACES(); for (;;) { if (cc == '\\') { int metaCharPos; SKIP_CHAR(); if (cc == '\n') { SKIP_CHAR(); } else if (cc > '0' && cc < '8') { word += QChar(c.digitValue()); SKIP_CHAR(); } else if ((metaCharPos = QString::fromLatin1("abfnrtv").indexOf(c)) != -1) { word += "\a\b\f\n\r\t\v"[metaCharPos]; SKIP_CHAR(); } else { PUT_CHAR(); } } else if (c.isSpace() || cc == '#') { if (inQuote) { if (cc == '\n') location.fatal(tr("Unterminated string")); PUT_CHAR(); } else { if (!word.isEmpty()) { if (metWord) stringValue += QLatin1Char(' '); stringValue += word; stringListValue << word; metWord = true; word.clear(); prevWordQuoted = false; } if (cc == '\n' || cc == '#') break; SKIP_SPACES(); } } else if (cc == '"') { if (inQuote) { if (!prevWordQuoted) stringValue += QLatin1Char(' '); stringValue += word; if (!word.isEmpty()) stringListValue << word; metWord = true; word.clear(); prevWordQuoted = true; } inQuote = !inQuote; SKIP_CHAR(); } else if (cc == '$') { QString var; SKIP_CHAR(); while (c.isLetterOrNumber() || cc == '_') { var += c; SKIP_CHAR(); } if (!var.isEmpty()) { char *val = getenv(var.toLatin1().data()); if (val == 0) { location.fatal(tr("Environment variable '%1' undefined").arg(var)); } else { word += QString(val); } } } else { if (!inQuote && cc == '=') location.fatal(tr("Unexpected '='")); PUT_CHAR(); } } QStringList::ConstIterator key = keys.begin(); while (key != keys.end()) { if (!keySyntax.exactMatch(*key)) keyLoc.fatal(tr("Invalid key '%1'").arg(*key)); if (plus) { if (locMap[*key].isEmpty()) { locMap[*key] = keyLoc; } else { locMap[*key].setEtc(true); } if (stringValueMap[*key].isEmpty()) { stringValueMap[*key] = stringValue; } else { stringValueMap[*key] += QLatin1Char(' ') + stringValue; } stringListValueMap[*key] += stringListValue; } else { locMap[*key] = keyLoc; stringValueMap[*key] = stringValue; stringListValueMap[*key] = stringListValue; } ++key; } } } else { location.fatal(tr("Unexpected character '%1' at beginning of line") .arg(c)); } } }
// Function which displays a info box and restarts networking void Utils::restartNetworking() { QMessageBox infoBox; infoBox.setWindowModality(Qt::ApplicationModal); infoBox.setWindowTitle(QObject::tr("Restarting network...")); infoBox.setInformativeText(QObject::tr("Network is restarting, please wait...")); infoBox.setStandardButtons(QMessageBox::NoButton); infoBox.show(); QProcess cmd; cmd.start(QString("/etc/rc.d/netif"), QStringList() << "restart" ); while ( cmd.state() != QProcess::NotRunning ) { cmd.waitForFinished(100); QCoreApplication::processEvents(); } // Set the gateway device name QString route = getConfFileValue("/etc/rc.conf", "defaultrouter=", 1); if ( ! route.isEmpty() ) { infoBox.setInformativeText(QObject::tr("Setting default route...")); cmd.start(QString("route"), QStringList() << "delete" << "default" ); while ( cmd.state() != QProcess::NotRunning ) { cmd.waitForFinished(100); QCoreApplication::processEvents(); } cmd.start(QString("route"), QStringList() << "add" << "default" << route ); while ( cmd.state() != QProcess::NotRunning ) { cmd.waitForFinished(100); QCoreApplication::processEvents(); } } // Check for any devices to run DHCP on QStringList ifs = NetworkInterface::getInterfaces(); for ( QStringList::Iterator it = ifs.begin(); it != ifs.end(); ++it ) { QString dev = *it; // Devices we can safely skip if (dev.indexOf("lo") == 0 || dev.indexOf("fwe") == 0 || dev.indexOf("ipfw") == 0 || dev.indexOf("plip") == 0 || dev.indexOf("pfsync") == 0 || dev.indexOf("pflog") == 0 || dev.indexOf("usbus") == 0 || dev.indexOf("vboxnet") == 0 || dev.indexOf("tun") == 0) continue; // Check if this device has DHCP enabled if ( Utils::getConfFileValue( "/etc/rc.conf", "ifconfig_" + dev + "=", 1 ).indexOf("DHCP") != -1 ) { qDebug() << "Running DHCP on " << dev; infoBox.setInformativeText(QObject::tr("Running DHCP...")); cmd.start(QString("/etc/rc.d/dhclient"), QStringList() << "start" << dev ); while ( cmd.state() != QProcess::NotRunning ) { cmd.waitForFinished(100); QCoreApplication::processEvents(); } } } infoBox.close(); }
void EditFile::showFiles() { QString s = edtFile->text(); #ifdef WIN32 s.replace(QRegExp("\\\\"), "/"); #endif if (bDirMode){ s = QFileDialog::getExistingDirectory(s, topLevelWidget(), title); }else if (bMultiplyMode){ QStringList lst = QFileDialog::getOpenFileNames(filter, QString::null, topLevelWidget()); if ((lst.count() > 1) || ((lst.count() > 0) && (lst[0].find(' ') >= 0))){ for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it){ *it = QString("\"") + *it + QString("\""); } } s = lst.join(" "); }else{ if (s.isEmpty()){ s = startDir; if (!s.isEmpty()){ string d; d = QFile::encodeName(s); makedir((char*)d.c_str()); } } if (createPreview){ FileDialog *dlg = new FileDialog( s, filter, topLevelWidget(), title.isEmpty() ? i18n("Open") : title); if ( topLevelWidget()->icon() && !topLevelWidget()->icon()->isNull()){ dlg->setIcon( *topLevelWidget()->icon() ); }else if (qApp->mainWidget() && qApp->mainWidget()->icon() && !qApp->mainWidget()->icon()->isNull()){ dlg->setIcon( *qApp->mainWidget()->icon() ); } FilePreview *preview = createPreview(dlg); #ifdef USE_KDE dlg->setOperationMode( KFileDialog::Opening); if (preview) dlg->setPreviewWidget(preview); #else dlg->setMode( QFileDialog::ExistingFile ); if (preview){ dlg->setContentsPreview(preview, preview); dlg->setContentsPreviewEnabled(true); dlg->setPreviewMode(QFileDialog::Contents); } #endif dlg->setFilter(filter); QString result; s = ""; if (dlg->exec() == QDialog::Accepted){ s = dlg->selectedFile(); } delete preview; delete dlg; }else{ #ifdef USE_KDE if (title.isEmpty()){ s = QFileDialog::getOpenFileName(s, filter, topLevelWidget()); }else{ s = QFileDialog::getOpenFileName(s, filter, topLevelWidget(), title); } #else s = QFileDialog::getOpenFileName(s, filter, topLevelWidget(), "filedialog", title); #endif } } #ifdef WIN32 s.replace(QRegExp("/"), "\\"); #endif if (s.length()) edtFile->setText(s); }
void OContact::insertEmails( const QStringList &v ) { for ( QStringList::ConstIterator it = v.begin(); it != v.end(); ++it ) insertEmail( *it ); }
bool Filters::BT_ThMLHTML::handleToken(sword::SWBuf &buf, const char *token, sword::BasicFilterUserData *userData) { if (!substituteToken(buf, token) && !substituteEscapeString(buf, token)) { sword::XMLTag tag(token); BT_UserData* myUserData = dynamic_cast<BT_UserData*>(userData); sword::SWModule* myModule = const_cast<sword::SWModule*>(myUserData->module); //hack to be able to call stuff like Lang() if ( tag.getName() && !sword::stricmp(tag.getName(), "foreign") ) { // a text part in another language, we have to set the right font if (tag.getAttribute("lang")) { const char* abbrev = tag.getAttribute("lang"); //const CLanguageMgr::Language* const language = CPointers::languageMgr()->languageForAbbrev( QString::fromLatin1(abbrev) ); buf.append("<span class=\"foreign\" lang=\""); buf.append(abbrev); buf.append("\">"); } } else if (tag.getName() && !sword::stricmp(tag.getName(), "sync")) { //lemmas, morph codes or strongs if (tag.getAttribute("type") && (!sword::stricmp(tag.getAttribute("type"), "morph") || !sword::stricmp(tag.getAttribute("type"), "Strongs") || !sword::stricmp(tag.getAttribute("type"), "lemma"))) { // Morph or Strong buf.append('<'); buf.append(token); buf.append('>'); } } else if (tag.getName() && !sword::stricmp(tag.getName(), "note")) { // <note> tag if (!tag.isEndTag() && !tag.isEmpty()) { //appending is faster than appendFormatted buf.append(" <span class=\"footnote\" note=\""); buf.append(myModule->Name()); buf.append('/'); buf.append(myUserData->key->getShortText()); buf.append('/'); buf.append( QString::number(myUserData->swordFootnote++).toUtf8().constData() ); buf.append("\">*</span> "); myUserData->suspendTextPassThru = true; myUserData->inFootnoteTag = true; } else if (tag.isEndTag() && !tag.isEmpty()) { //end tag //buf += ")</span>"; myUserData->suspendTextPassThru = false; myUserData->inFootnoteTag = false; } } else if (tag.getName() && !sword::stricmp(tag.getName(), "scripRef")) { // a scripRef //scrip refs which are embeded in footnotes may not be displayed! if (!myUserData->inFootnoteTag) { if (tag.isEndTag()) { if (myUserData->inscriptRef) { // like "<scripRef passage="John 3:16">See John 3:16</scripRef>" buf.append("</a></span>"); myUserData->inscriptRef = false; myUserData->suspendTextPassThru = false; } else { // like "<scripRef>John 3:16</scripRef>" CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible); //Q_ASSERT(mod); tested later if (mod) { ReferenceManager::ParseOptions options; options.refBase = QString::fromUtf8(myUserData->key->getText()); //current module key options.refDestinationModule = QString(mod->name()); options.sourceLanguage = QString(myModule->Lang()); options.destinationLanguage = QString("en"); //it's ok to split the reference, because to descriptive text is given bool insertSemicolon = false; buf.append("<span class=\"crossreference\">"); QStringList refs = QString::fromUtf8(myUserData->lastTextNode.c_str()).split(";"); QString oldRef; //the previous reference to use as a base for the next refs for (QStringList::iterator it(refs.begin()); it != refs.end(); ++it) { if (! oldRef.isEmpty() ) { options.refBase = oldRef; //use the last ref as a base, e.g. Rom 1,2-3, when the next ref is only 3:3-10 } const QString completeRef( ReferenceManager::parseVerseReference((*it), options) ); oldRef = completeRef; //use the parsed result as the base for the next ref. if (insertSemicolon) { //prepend a ref divider if we're after the first one buf.append("; "); } buf.append("<a href=\""); buf.append( ReferenceManager::encodeHyperlink( mod->name(), completeRef, ReferenceManager::typeFromModule(mod->type()) ).toUtf8().constData() ); buf.append("\" crossrefs=\""); buf.append((const char*)completeRef.toUtf8()); buf.append("\">"); buf.append((const char*)(*it).toUtf8()); buf.append("</a>"); insertSemicolon = true; } buf.append("</span>"); //crossref end } myUserData->suspendTextPassThru = false; } } else if (tag.getAttribute("passage") ) { //the passage was given as a parameter value myUserData->inscriptRef = true; myUserData->suspendTextPassThru = false; const char* ref = tag.getAttribute("passage"); Q_ASSERT(ref); CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible); //Q_ASSERT(mod); tested later ReferenceManager::ParseOptions options; options.refBase = QString::fromUtf8(myUserData->key->getText()); options.sourceLanguage = myModule->Lang(); options.destinationLanguage = QString("en"); const QString completeRef = ReferenceManager::parseVerseReference(QString::fromUtf8(ref), options); if (mod) { options.refDestinationModule = QString(mod->name()); buf.append("<span class=\"crossreference\">"); buf.append("<a href=\""); buf.append( ReferenceManager::encodeHyperlink( mod->name(), completeRef, ReferenceManager::typeFromModule(mod->type()) ).toUtf8().constData() ); buf.append("\" crossrefs=\""); buf.append((const char*)completeRef.toUtf8()); buf.append("\">"); } else { buf.append("<span><a>"); } } else if ( !tag.getAttribute("passage") ) { // we're starting a scripRef like "<scripRef>John 3:16</scripRef>" myUserData->inscriptRef = false; // let's stop text from going to output, the text get's added in the -tag handler myUserData->suspendTextPassThru = true; } } } else if (tag.getName() && !sword::stricmp(tag.getName(), "div")) { if (tag.isEndTag()) { buf.append("</div>"); } else if ( tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "sechead") ) { buf.append("<div class=\"sectiontitle\">"); } else if (tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "title")) { buf.append("<div class=\"booktitle\">"); } } else if (tag.getName() && !sword::stricmp(tag.getName(), "img") && tag.getAttribute("src")) { const char* value = tag.getAttribute("src"); if (value[0] == '/') { value++; //strip the first / } buf.append("<img src=\""); QString absPath(QTextCodec::codecForLocale()->toUnicode(myUserData->module->getConfigEntry("AbsoluteDataPath"))); QString relPath(QString::fromUtf8(value)); QString url(QUrl::fromLocalFile(absPath.append('/').append(relPath)).toString()); buf.append(url.toUtf8().data()); buf.append("\" />"); } else { // let unknown token pass thru return sword::ThMLHTML::handleToken(buf, token, userData); } } return true; }
XmlSettingsEntry XmlSettingsEntry::makeBranch( const QStringList &xpath ) { QStringList::ConstIterator itXPath; AbstractNode *node = NULL; XmlSettingsEntry entry( find(xpath, itXPath, node) ); if( itXPath != xpath.end() ) { JQ_ASSERT(node); m_master->clearErrors(); AbstractNode::Type nodeType = node->type(); // Error if( nodeType == AbstractNode::Scalar ) return XmlSettingsEntry( entry.m_master ); QStringList::ConstIterator itXPathEnd = xpath.end(); for(; itXPath != itXPathEnd; itXPath++ ) { QString elem(*itXPath); switch( nodeType ) { case AbstractNode::Map: { MapNode *mapNode = (MapNode*)node; if( itXPath + 1 == itXPathEnd ) { // Last element, must be a scalar (*mapNode)[elem] = (node = new ScalarNode()); } else { (*mapNode)[elem] = (node = new VectorNode()); } } nodeType = AbstractNode::Vector; break; case AbstractNode::Vector: if( elem.startsWith("[") ) { JQ_ASSERT( elem.endsWith("]") && elem.size() > 2 ); VectorNode *vectorNode = (VectorNode*)node; bool ok; int index = elem.mid(1, elem.size()-2).toUInt(&ok); JQ_ASSERT(ok == true); if( index >= vectorNode->size() ) { vectorNode->resize(index+1); } int sz = vectorNode->size(); for( int i = 0; i < sz; i++ ) { if( !(*vectorNode)[i] ) (*vectorNode)[i] = (node = new MapNode() ); } if( itXPath + 1 == itXPathEnd ) { // Last element, must be a scalar MapNode *mapNode = dynamic_cast<MapNode*>((*vectorNode)[index]); (*mapNode)[__TEXT_PSEUDO_ELEMENT] = (node = new ScalarNode()); } } else { return XmlSettingsEntry(m_master); } nodeType = AbstractNode::Map; break; default: //AbstractNode::Scalar: return XmlSettingsEntry(m_master); } } } return XmlSettingsEntry(m_master, node); }
void ZOptionItem::selected(ZSettingItem* item) { if ( (ZOptionItem*)item != this ) return; switch ( type ) { case EDIT_TEXT: case EDIT_TEXT_NUM: case EDIT_FILE: { ZSingleCaptureDlg* zscd = new ZSingleCaptureDlg(title, "", ZSingleCaptureDlg::TypeLineEdit, this, "", true, 0, 0); ZLineEdit* zle = (ZLineEdit*)zscd->getLineEdit(); #ifndef WITHOUT_EDIT_TEXT_NUM if ( type==EDIT_TEXT_NUM ) ((ZApplication*)qApp)->setInputMethod(zle, ZKB_INPUT_NUMERIC, ZKbInputField::FIELD_TYPE_NUMERIC, ""); #endif zle->setText(text); if ( zscd->exec() == QDialog::Accepted ) setText(zle->text()); delete zle; delete zscd; } break; case EDIT_BOOL_YESNO: case EDIT_BOOL_ONOFF: { QStringList itemList; if ( type==EDIT_BOOL_ONOFF ) { itemList.append(LNG_ON); itemList.append(LNG_OFF); } else { itemList.append(LNG_YES); itemList.append(LNG_NO); } ZSingleSelectDlg *dlg = new ZSingleSelectDlg(title, "", this); dlg->addItemsList(itemList); dlg->getListBox()->checkItem(!n, true); if ( dlg->exec() == QDialog::Accepted ) setNum(!dlg->getCheckedItemIndex()); delete dlg; } break; case EDIT_NUM: { ZNumPickerDlg * dlg = new ZNumPickerDlg(2, this); ZNumModule* num = dlg->getNumModule(); num->setMaxValue(max); num->setMinValue(min); num->setValue(n); if ( dlg->exec() == QDialog::Accepted ) setNum( num->getValue() ); delete num; delete dlg; } break; #ifndef WITHOUT_GAIN_VOL case EDIT_GAIN_VOLUME: { ZNumPickerDlg * dlg = new ZNumPickerDlg(2, this); ZNumModule* num = dlg->getNumModule(); num->setMaxValue( GAIN_DEVICE_VOL_MAX ); num->setMinValue( GAIN_DEVICE_VOL_MIN); num->setValue( gainTable[n] ); if ( dlg->exec() == QDialog::Accepted ) { gainTable[n] = num->getValue(); setSubItem(0, 1, QString::number( gainTable[n] ) ); } delete num; delete dlg; } break; case EDIT_GAIN_EQUALOSER: { ZSingleCaptureDlg* zscd = new ZSingleCaptureDlg(title, "", ZSingleCaptureDlg::TypeLineEdit, this, "", true, 0, 0); ZLineEdit* zle = (ZLineEdit*)zscd->getLineEdit(); ((ZApplication*)qApp)->setInputMethod(zle, ZKB_INPUT_NUMERIC, ZKbInputField::FIELD_TYPE_NUMERIC, ""); zle->setText(QString::number(u2n.num-GAIN_EQUALASER_MIN)); if ( zscd->exec() == QDialog::Accepted ) { int num = zle->text().toInt(); if ( num<0 ) num=0; if ( num>GAIN_EQUALASER_MAX-GAIN_EQUALASER_MIN ) num=GAIN_EQUALASER_MAX-GAIN_EQUALASER_MIN; u2n.num = num+GAIN_EQUALASER_MIN; memcpy(&gainTable[n], u2n.data, 2); setSubItem(0, 1, QString::number( u2n.num-GAIN_EQUALASER_MIN ) ); } delete zle; delete zscd; } break; #endif case EDIT_ONE_OF_LIST: { if ( list == NULL ) return; ZSingleSelectDlg *dlg = new ZSingleSelectDlg(title, "", this); dlg->addItemsList(*list); dlg->getListBox()->checkItem(n, true); if ( dlg->exec() == QDialog::Accepted ) setNum(dlg->getCheckedItemIndex()); delete dlg; } break; case EDIT_INTERNET_PROFILE: #ifndef WITHOUT_EDIT_INTERNET_PROFILE { UINT32 profiles = NAPI_GetMaxProfiles(); QStringList list; list.append(LNG_ASK); if(profiles != -1) { char *buf = new char[NAPI_MAX_PROFILE_NAME_LENGTH * profiles]; if(NAPI_ListAllProfile((INT8*)buf, &profiles) != -1) { char *prof_ptr = buf; for(uint i = 0; i < profiles; i++, prof_ptr = buf + i * NAPI_MAX_PROFILE_NAME_LENGTH) list.append(QString::fromUtf8(prof_ptr)); } delete buf; } ZSingleSelectDlg *dlg = new ZSingleSelectDlg(title, "", this); dlg->addItemsList(list); int sel=0, i=0; for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) if ( *it == text ) { sel=i; break; } else i++; if ( sel >= 0 ) dlg->getListBox()->checkItem(sel, true); if ( dlg->exec() == QDialog::Accepted ) { n=dlg->getCheckedItemIndex(); setText( (n>0)?(*(list.at(n))):"" ); } delete dlg; } #endif break; } }
// FIXME: this currently does not work if the user has changed his date format, // since . is hardcoded as date parts separator. void KviQueryWindow::pasteLastLog() { QString szQuery = target().toLower(); QString szNetwork = console()->currentNetworkName().toLower(); QDate date = QDate::currentDate(); // Create the filter for the dir // Format: query__<nick>.<network>_*.*.*.log* QString szLogFilter = "query_"; szLogFilter += szQuery; szLogFilter += "."; szLogFilter += szNetwork; szLogFilter += "_*.*.*.log*"; // Get the logs QString szLogPath; g_pApp->getLocalKvircDirectory(szLogPath,KviApplication::Log); QDir logDir(szLogPath); QStringList filter = QStringList(szLogFilter); QStringList logList = logDir.entryList(filter,QDir::Files,QDir::Name | QDir::Reversed); // Scan log files // Format: query_nick.networkName_year.month.day.log // Format: query_nick.networkName_year.month.day.log.gz bool bGzip; QString szFileName; for(QStringList::Iterator it = logList.begin(); it != logList.end(); ++it) { int iLogYear, iLogMonth, iLogDay; szFileName = (*it); QString szTmpName = (*it); QFileInfo fi(szTmpName); bGzip = false; // Skip the log just created on join if(fi.suffix() == "tmp") continue; // Remove trailing dot and extension .gz if(fi.suffix() == "gz") { bGzip = true; szTmpName.chop(3); } // Ok, we have the right nick/network log. Get date QString szLogDate = szTmpName.section('.',-4,-1).section('_',1,1); iLogYear = szLogDate.section('.',0,0).toInt(); iLogMonth = szLogDate.section('.',1,1).toInt(); iLogDay = szLogDate.section('.',2,2).toInt(); // Check log validity int iInterval = -KVI_OPTION_UINT(KviOption_uintDaysIntervalToPasteOnQueryJoin); QDate logDate(iLogYear,iLogMonth,iLogDay); QDate checkDate = date.addDays(iInterval); if(logDate < checkDate) return; else break; } // Get the right log name szFileName.prepend("/"); szFileName.prepend(szLogPath); // Load the log QByteArray log = loadLogFile(szFileName,bGzip); if(log.size() > 0) { QList<QByteArray> list = log.split('\n'); unsigned int uCount = list.size(); unsigned int uLines = KVI_OPTION_UINT(KviOption_uintLinesToPasteOnQueryJoin); unsigned int uStart = uCount - uLines - 1; /* // Check if the log is smaller than the lines to print if(uStart < 0) uStart = 0; */ QString szDummy = __tr2qs("Starting last log"); output(KVI_OUT_QUERYPRIVMSG,szDummy); // Scan the log file for(unsigned int i = uStart; i < uCount; i++) { QString szLine = QString(list.at(i)); szLine = szLine.section(' ',1); #ifdef COMPILE_ON_WINDOWS // Remove the \r char at the szEnd of line szLine.chop(1); #endif // Print the line in the channel buffer output(KVI_OUT_QUERYPRIVMSG,szLine); } szDummy = __tr2qs("End of log"); output(KVI_OUT_QUERYPRIVMSG,szDummy); } }
QSize GLDMaskBox::sizeHint() const { QSize sz; int textWidth = m_labelTextBody->fontMetrics().width(m_oTipBoxParam.m_strBody); // int textHeight = m_labelTextBody->fontMetrics().ascent() + m_labelTextBody->fontMetrics().descent(); int singalTextHeight = m_oTipBoxParam.m_nRowHeight; if (textWidth <= m_oTipBoxParam.m_nMaxWidth - 87) { sz.setWidth(87 + textWidth); sz.setHeight(64 + singalTextHeight); } else { QStringList list = m_oTipBoxParam.m_strBody.split("\n"); if (list.count() == 1) { sz.setWidth(m_oTipBoxParam.m_nMaxWidth); if (textWidth % (m_oTipBoxParam.m_nMaxWidth - 87) == 0) { sz.setHeight(64 + singalTextHeight * (textWidth / (m_oTipBoxParam.m_nMaxWidth - 87))); } else { sz.setHeight(/*64 + */singalTextHeight * (textWidth / (m_oTipBoxParam.m_nMaxWidth/* - 87*/)/* + 1*/)); } } else { QStringList::iterator iter = list.begin(); int rowCount = 0; int maxWidth = 0; while (iter != list.end()) { int subTextWidth = m_labelTextBody->fontMetrics().width(*iter); if (subTextWidth % (m_oTipBoxParam.m_nMaxWidth - 87) != 0) { ++rowCount; } rowCount += subTextWidth / (m_oTipBoxParam.m_nMaxWidth - 87); if (subTextWidth >= (m_oTipBoxParam.m_nMaxWidth - 87)) { maxWidth = m_oTipBoxParam.m_nMaxWidth - 87; } else { if (maxWidth < subTextWidth) { maxWidth = subTextWidth; } } iter++; } sz.setWidth(maxWidth + 87); sz.setHeight(64 + singalTextHeight * rowCount); } } return sz; }
void doTests() { // the data file to use. // first determine the path used to call this program, // and then prepend that to the data file name. QString path = myName.section('/', 0, -3); QString datafile = path; datafile.append("/healpix_example_sm.fits"); // create a temporary config file to use QString cfgfile = "testhealpix.temp"; KConfig *cfg = new KConfig(cfgfile, false, false); cfg->setGroup("Healpix General"); cfg->setGroup(datafile); cfg->writeEntry("Matrix X Dimension", XDIM); cfg->writeEntry("Matrix Y Dimension", YDIM); cfg->writeEntry("Theta Autoscale", true); cfg->writeEntry("Theta Units", 0); cfg->writeEntry("Theta Min", 0.0); cfg->writeEntry("Theta Max", 1.0); cfg->writeEntry("Phi Autoscale", true); cfg->writeEntry("Phi Units", 0); cfg->writeEntry("Phi Min", 0.0); cfg->writeEntry("Phi Max", 1.0); cfg->writeEntry("Vector Theta", 1); cfg->writeEntry("Vector Phi", 2); cfg->writeEntry("Vector Degrade Factor", DEGRADE); cfg->writeEntry("Vector Magnitude Autoscale", true); cfg->writeEntry("Vector Max Magnitude", 1.0); cfg->writeEntry("Vector is QU", true); // use the C functions to test for healpix support int verstehen = understands_healpix(cfg, datafile); if (verstehen) { kstdDebug() << "Data file " << datafile << " is supported" << endl; QString suggestion; bool complete; QStringList matrices = matrixList_healpix(cfg, datafile, "HEALPIX", &suggestion, &complete); kstdDebug() << "Available matrices are:" << endl; for ( QStringList::Iterator it = matrices.begin(); it != matrices.end(); ++it ) { kstdDebug() << " " << *it << endl; } kstdDebug() << " suggestion = " << suggestion << endl; kstdDebug() << " complete = " << complete << endl; QStringList fields = fieldList_healpix(cfg, datafile, "HEALPIX", &suggestion, &complete); kstdDebug() << "Available fields are:" << endl; for ( QStringList::Iterator it = fields.begin(); it != fields.end(); ++it ) { kstdDebug() << " " << *it << endl; } kstdDebug() << " suggestion = " << suggestion << endl; kstdDebug() << " complete = " << complete << endl; // actually create HealpixSource HealpixSource *hpx = new HealpixSource(cfg, datafile, "HEALPIX"); // test that saveConfig produces the same as the // original input configuration QString cfgfile2 = "testhealpix.temp2"; KConfig *chk = new KConfig(cfgfile2, false, false); hpx->saveConfig(chk); StringMap cfgmap = cfg->entryMap(datafile); StringMap chkmap = chk->entryMap(datafile); /* kstdDebug() << cfgmap["Matrix X Dimension"] << " " << chkmap["Matrix X Dimension"] << endl; kstdDebug() << cfgmap["Matrix Y Dimension"] << " " << chkmap["Matrix Y Dimension"] << endl; kstdDebug() << cfgmap["Theta Autoscale"] << " " << chkmap["Theta Autoscale"] << endl; kstdDebug() << cfgmap["Theta Units"] << " " << chkmap["Theta Units"] << endl; kstdDebug() << cfgmap["Theta Min"] << " " << chkmap["Theta Min"] << endl; kstdDebug() << cfgmap["Theta Max"] << " " << chkmap["Theta Max"] << endl; kstdDebug() << cfgmap["Phi Autoscale"] << " " << chkmap["Phi Autoscale"] << endl; kstdDebug() << cfgmap["Phi Units"] << " " << chkmap["Phi Units"] << endl; kstdDebug() << cfgmap["Phi Min"] << " " << chkmap["Phi Min"] << endl; kstdDebug() << cfgmap["Phi Max"] << " " << chkmap["Phi Max"] << endl; kstdDebug() << cfgmap["Vector Theta"] << " " << chkmap["Vector Theta"] << endl; kstdDebug() << cfgmap["Vector Phi"] << " " << chkmap["Vector Phi"] << endl; kstdDebug() << cfgmap["Vector Degrade Factor"] << " " << chkmap["Vector Degrade Factor"] << endl; kstdDebug() << cfgmap["Vector Magnitude Autoscale"] << " " << chkmap["Vector Magnitude Autoscale"] << endl; kstdDebug() << cfgmap["Vector Max Magnitude"] << " " << chkmap["Vector Max Magnitude"] << endl; kstdDebug() << cfgmap["Vector is QU"] << " " << chkmap["Vector is QU"] << endl; */ if (cfgmap["Matrix X Dimension"] != chkmap["Matrix X Dimension"]) { QString msg = "Matrix X Dimension integrity"; testAssert(false, msg); } if (cfgmap["Matrix Y Dimension"] != chkmap["Matrix Y Dimension"]) { QString msg = "Matrix Y Dimension integrity"; testAssert(false, msg); } if (cfgmap["Theta Autoscale"] != chkmap["Theta Autoscale"]) { QString msg = "Theta Autoscale integrity"; testAssert(false, msg); } if (cfgmap["Theta Units"] != chkmap["Theta Units"]) { QString msg = "Theta Units integrity"; testAssert(false, msg); } if (cfgmap["Theta Min"] != chkmap["Theta Min"]) { QString msg = "Theta Min integrity"; testAssert(false, msg); } if (cfgmap["Theta Max"] != chkmap["Theta Max"]) { QString msg = "Theta Max integrity"; testAssert(false, msg); } if (cfgmap["Phi Autoscale"] != chkmap["Phi Autoscale"]) { QString msg = "Phi Autoscale integrity"; testAssert(false, msg); } if (cfgmap["Phi Units"] != chkmap["Phi Units"]) { QString msg = "Phi Units integrity"; testAssert(false, msg); } if (cfgmap["Phi Min"] != chkmap["Phi Min"]) { QString msg = "Phi Min integrity"; testAssert(false, msg); } if (cfgmap["Phi Max"] != chkmap["Phi Max"]) { QString msg = "Phi Max integrity"; testAssert(false, msg); } if (cfgmap["Vector Theta"] != chkmap["Vector Theta"]) { QString msg = "Vector Theta integrity"; testAssert(false, msg); } if (cfgmap["Vector Phi"] != chkmap["Vector Phi"]) { QString msg = "Vector Phi integrity"; testAssert(false, msg); } if (cfgmap["Vector Degrade Factor"] != chkmap["Vector Degrade Factor"]) { QString msg = "Vector Degrade Factor integrity"; testAssert(false, msg); } if (cfgmap["Vector Magnitude Autoscale"] != chkmap["Vector Magnitude Autoscale"]) { QString msg = "Vector Magnitude Autoscale integrity"; testAssert(false, msg); } if (cfgmap["Vector Max Magnitude"] != chkmap["Vector Max Magnitude"]) { QString msg = "Vector Max Magnitude integrity"; testAssert(false, msg); } if (cfgmap["Vector is QU"] != chkmap["Vector is QU"]) { QString msg = "Vector is QU integrity"; testAssert(false, msg); } kstdDebug() << "Save/Load config is consistent." << endl; // print _metaData and compute NSIDE and number // of samples in the vectors int nside = 0; int nvec; QString key; KstString *data; kstdDebug() << "Checking metaData:" << endl; QDict<KstString> metamap = hpx->metaData(); QDictIterator<KstString> it(metamap); for ( ; it.current(); ++it ) { key = it.currentKey(); data = it.current(); if (data) { kstdDebug() << " " << key.latin1() << " = " << data->value().latin1() << endl; if (key == "NSIDE") { nside = data->value().toInt(); } } } kstdDebug() << "Data file has nside = " << nside << endl; testAssert(nside != 0, "data file NSIDE"); for (int i = 0; i < DEGRADE; i++) { nside = (int)(nside/2); } nvec = 12*nside*nside; kstdDebug() << "Degraded vectorfield has nside = " << nside << " and " << nvec << " full-sphere pixels" << endl; // check that all returned fields are valid, and that // optionally field number names are valid. kstdDebug() << "Checking matrix validity:" << endl; int num = 1; int xdim, ydim, nframe, sampframe; for ( QStringList::Iterator it = matrices.begin(); it != matrices.end(); ++it ) { if (hpx->isValidMatrix(*it)) { kstdDebug() << " \"" << *it << "\" is VALID" << endl; hpx->matrixDimensions(*it, &xdim, &ydim); kstdDebug() << " and has dimensions " << xdim << "x" << ydim << endl; testAssert((xdim == XDIM)&&(ydim == YDIM), "dimension integrity"); } else { QString msg = (*it); msg.append(" validity"); testAssert(false, msg); } QString numfield = QString("%1").arg(num); if (hpx->isValidMatrix(numfield)) { kstdDebug() << " \"" << numfield << "\" is VALID" << endl; hpx->matrixDimensions(numfield, &xdim, &ydim); kstdDebug() << " and has dimensions " << xdim << "x" << ydim << endl; testAssert((xdim == XDIM)&&(ydim == YDIM), "dimension integrity"); } else { QString msg = numfield; msg.append(" validity"); testAssert(false, msg); } num++; } kstdDebug() << "Checking field validity:" << endl; num = 1; for ( QStringList::Iterator it = fields.begin(); it != fields.end(); ++it ) { if (hpx->isValidField(*it)) { kstdDebug() << " \"" << *it << "\" is VALID" << endl; nframe = hpx->frameCount(*it); sampframe = hpx->samplesPerFrame(*it); kstdDebug() << " and has " << nframe << " frames of " << sampframe << " sample(s) each" << endl; testAssert(sampframe == 1, "samples per frame"); testAssert(nframe == nvec, "number of frames"); } else { QString msg = (*it); msg.append(" validity"); testAssert(false, msg); } QString numfield = QString("%1").arg(num); if (hpx->isValidField(numfield)) { kstdDebug() << " \"" << numfield << "\" is VALID" << endl; nframe = hpx->frameCount(numfield); sampframe = hpx->samplesPerFrame(numfield); kstdDebug() << " and has " << nframe << " frames of " << sampframe << " sample(s) each" << endl; testAssert(sampframe == 1, "samples per frame"); testAssert(nframe == nvec, "number of frames"); } else { QString msg = numfield; msg.append(" validity"); testAssert(false, msg); } num++; } // check reset function if (hpx->reset()) { kstdDebug() << "Reset function is implemented." << endl; } else { testAssert(false, "reset"); } } else { testAssert(false, "understanding"); } }
MixxxLibraryFeature::MixxxLibraryFeature(QObject* parent, TrackCollection* pTrackCollection, ConfigObject<ConfigValue>* pConfig) : LibraryFeature(parent), kMissingTitle(tr("Missing Tracks")), kHiddenTitle(tr("Hidden Tracks")), m_pMissingView(NULL), m_pHiddenView(NULL), m_trackDao(pTrackCollection->getTrackDAO()), m_pConfig(pConfig), m_pTrackCollection(pTrackCollection) { QStringList columns; columns << "library." + LIBRARYTABLE_ID << "library." + LIBRARYTABLE_PLAYED << "library." + LIBRARYTABLE_TIMESPLAYED //has to be up here otherwise Played and TimesPlayed are not show << "library." + LIBRARYTABLE_ARTIST << "library." + LIBRARYTABLE_TITLE << "library." + LIBRARYTABLE_ALBUM << "library." + LIBRARYTABLE_YEAR << "library." + LIBRARYTABLE_DURATION << "library." + LIBRARYTABLE_RATING << "library." + LIBRARYTABLE_GENRE << "library." + LIBRARYTABLE_COMPOSER << "library." + LIBRARYTABLE_FILETYPE << "library." + LIBRARYTABLE_TRACKNUMBER << "library." + LIBRARYTABLE_KEY << "library." + LIBRARYTABLE_DATETIMEADDED << "library." + LIBRARYTABLE_BPM << "library." + LIBRARYTABLE_BPM_LOCK << "library." + LIBRARYTABLE_BITRATE << "track_locations.location" << "track_locations.fs_deleted" << "library." + LIBRARYTABLE_COMMENT << "library." + LIBRARYTABLE_MIXXXDELETED; QSqlQuery query(pTrackCollection->getDatabase()); QString tableName = "library_cache_view"; QString queryString = QString( "CREATE TEMPORARY VIEW IF NOT EXISTS %1 AS " "SELECT %2 FROM library " "INNER JOIN track_locations ON library.location = track_locations.id") .arg(tableName, columns.join(",")); query.prepare(queryString); if (!query.exec()) { LOG_FAILED_QUERY(query); } // Strip out library. and track_locations. for (QStringList::iterator it = columns.begin(); it != columns.end(); ++it) { if (it->startsWith("library.")) { *it = it->replace("library.", ""); } else if (it->startsWith("track_locations.")) { *it = it->replace("track_locations.", ""); } } BaseTrackCache* pBaseTrackCache = new BaseTrackCache( pTrackCollection, tableName, LIBRARYTABLE_ID, columns, true); connect(&m_trackDao, SIGNAL(trackDirty(int)), pBaseTrackCache, SLOT(slotTrackDirty(int))); connect(&m_trackDao, SIGNAL(trackClean(int)), pBaseTrackCache, SLOT(slotTrackClean(int))); connect(&m_trackDao, SIGNAL(trackChanged(int)), pBaseTrackCache, SLOT(slotTrackChanged(int))); connect(&m_trackDao, SIGNAL(tracksAdded(QSet<int>)), pBaseTrackCache, SLOT(slotTracksAdded(QSet<int>))); connect(&m_trackDao, SIGNAL(tracksRemoved(QSet<int>)), pBaseTrackCache, SLOT(slotTracksRemoved(QSet<int>))); connect(&m_trackDao, SIGNAL(dbTrackAdded(TrackPointer)), pBaseTrackCache, SLOT(slotDbTrackAdded(TrackPointer))); m_pBaseTrackCache = QSharedPointer<BaseTrackCache>(pBaseTrackCache); pTrackCollection->addTrackSource(QString("default"), m_pBaseTrackCache); // These rely on the 'default' track source being present. m_pLibraryTableModel = new LibraryTableModel(this, pTrackCollection); TreeItem* pRootItem = new TreeItem(); TreeItem* pmissingChildItem = new TreeItem(kMissingTitle, kMissingTitle, this, pRootItem); TreeItem* phiddenChildItem = new TreeItem(kHiddenTitle, kHiddenTitle, this, pRootItem); pRootItem->appendChild(pmissingChildItem); pRootItem->appendChild(phiddenChildItem); m_childModel.setRootItem(pRootItem); }
int QgsWFSServer::getFeature( QgsRequestHandler& request, const QString& format ) { QgsDebugMsg( "Info format is:" + format ); //read TYPENAME QMap<QString, QString>::const_iterator type_name_it = mParameterMap.find( "TYPENAME" ); if ( type_name_it != mParameterMap.end() ) { mTypeName = type_name_it.value(); } else { return 1; } QStringList wfsLayersId = mConfigParser->wfsLayers(); QMap< QString, QMap< int, QString > > aliasInfo = mConfigParser->layerAliasInfo(); QMap< QString, QSet<QString> > hiddenAttributes = mConfigParser->hiddenAttributes(); QList<QgsMapLayer*> layerList; QgsMapLayer* currentLayer = 0; layerList = mConfigParser->mapLayerFromStyle( mTypeName, "" ); currentLayer = layerList.at( 0 ); QgsVectorLayer* layer = dynamic_cast<QgsVectorLayer*>( currentLayer ); if ( layer && wfsLayersId.contains( layer->id() ) ) { //is there alias info for this vector layer? QMap< int, QString > layerAliasInfo; QMap< QString, QMap< int, QString > >::const_iterator aliasIt = aliasInfo.find( currentLayer->id() ); if ( aliasIt != aliasInfo.constEnd() ) { layerAliasInfo = aliasIt.value(); } //hidden attributes for this layer QSet<QString> layerHiddenAttributes; QMap< QString, QSet<QString> >::const_iterator hiddenIt = hiddenAttributes.find( currentLayer->id() ); if ( hiddenIt != hiddenAttributes.constEnd() ) { layerHiddenAttributes = hiddenIt.value(); } //do a select with searchRect and go through all the features QgsVectorDataProvider* provider = layer->dataProvider(); if ( !provider ) { return 2; } QgsFeature feature; QgsAttributeMap featureAttributes; const QgsFieldMap& fields = provider->fields(); //map extent QgsRectangle searchRect = layer->extent(); //read FEATUREDID bool fidOk = false; QString fid; QMap<QString, QString>::const_iterator fidIt = mParameterMap.find( "FEATUREID" ); if ( fidIt != mParameterMap.end() ) { fidOk = true; fid = fidIt.value(); } //read FILTER bool filterOk = false; QDomDocument filter; QMap<QString, QString>::const_iterator filterIt = mParameterMap.find( "FILTER" ); if ( filterIt != mParameterMap.end() ) { try { QString errorMsg; if ( !filter.setContent( filterIt.value(), true, &errorMsg ) ) { QgsDebugMsg( "soap request parse error" ); QgsDebugMsg( "error message: " + errorMsg ); QgsDebugMsg( "the xml string was:" ); QgsDebugMsg( filterIt.value() ); } else { filterOk = true; } } catch ( QgsMapServiceException& e ) { Q_UNUSED( e ); filterOk = false; } } bool conversionSuccess; double minx, miny, maxx, maxy; bool bboxOk = false; //read BBOX QMap<QString, QString>::const_iterator bbIt = mParameterMap.find( "BBOX" ); if ( bbIt == mParameterMap.end() ) { minx = 0; miny = 0; maxx = 0; maxy = 0; } else { bboxOk = true; QString bbString = bbIt.value(); minx = bbString.section( ",", 0, 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} miny = bbString.section( ",", 1, 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} maxx = bbString.section( ",", 2, 2 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} maxy = bbString.section( ",", 3, 3 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} } //read MAXFEATURES long maxFeat = layer->featureCount(); long featureCounter = 0; QMap<QString, QString>::const_iterator mfIt = mParameterMap.find( "MAXFEATURES" ); if ( mfIt != mParameterMap.end() ) { QString mfString = mfIt.value(); bool mfOk; maxFeat = mfString.toLong( &mfOk, 10 ); if ( !mfOk ) { maxFeat = layer->featureCount(); } } //read PROPERTYNAME mWithGeom = true; QgsAttributeList attrIndexes = provider->attributeIndexes(); QMap<QString, QString>::const_iterator pnIt = mParameterMap.find( "PROPERTYNAME" ); if ( pnIt != mParameterMap.end() ) { QStringList attrList = pnIt.value().split( "," ); if ( attrList.size() > 0 ) { mWithGeom = false; QStringList::const_iterator alstIt; QList<int> idxList; QMap<QString, int> fieldMap = provider->fieldNameMap(); QMap<QString, int>::const_iterator fieldIt; QString fieldName; for ( alstIt = attrList.begin(); alstIt != attrList.end(); ++alstIt ) { fieldName = *alstIt; fieldIt = fieldMap.find( fieldName ); if ( fieldIt != fieldMap.end() ) { idxList.append( fieldIt.value() ); } else if ( fieldName == "geometry" ) { mWithGeom = true; } } if ( idxList.size() > 0 || mWithGeom ) { attrIndexes = idxList; } else { mWithGeom = true; } } } QgsCoordinateReferenceSystem layerCrs = layer->crs(); startGetFeature( request, format ); if ( fidOk ) { provider->featureAtId( fid.toInt(), feature, mWithGeom, attrIndexes ); sendGetFeature( request, format, &feature, 0, layerCrs, fields, layerHiddenAttributes ); } else if ( filterOk ) { provider->select( attrIndexes, searchRect, mWithGeom, true ); try { QgsFilter* mFilter = QgsFilter::createFilterFromXml( filter.firstChild().toElement().firstChild().toElement(), layer ); while ( provider->nextFeature( feature ) && featureCounter < maxFeat ) { if ( mFilter ) { if ( mFilter->evaluate( feature ) ) { sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes ); ++featureCounter; } } else { sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes ); ++featureCounter; } } delete mFilter; } catch ( QgsMapServiceException& e ) { Q_UNUSED( e ); while ( provider->nextFeature( feature ) && featureCounter < maxFeat ) { sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes ); ++featureCounter; } } } else { if ( bboxOk ) searchRect.set( minx, miny, maxx, maxy ); provider->select( attrIndexes, searchRect, mWithGeom, true ); while ( provider->nextFeature( feature ) && featureCounter < maxFeat ) { sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes ); ++featureCounter; } } endGetFeature( request, format ); } else { return 2; } return 0; }
// // WordNet // void Thesaurus::findTermWordnet(const QString &term) { m_wnProc->setOutputChannelMode(KProcess::SeparateChannels); m_wnProc->clearProgram(); *m_wnProc << "wn"; *m_wnProc << term; // get all results: nouns, verbs, adjectives, adverbs (see below for order): if (m_wnComboBox->currentIndex() == -1 || m_wnComboBox->currentIndex() == 0) { *m_wnProc << "-synsn" << "-synsv" << "-synsa" << "-synsr"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 1) { *m_wnProc << "-simsv"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 2) { *m_wnProc << "-antsn" << "-antsv" << "-antsa" << "-antsr"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 3) { *m_wnProc << "-hypon" << "-hypov"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 4) { *m_wnProc << "-meron"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 5) { *m_wnProc << "-holon"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 6) { // e.g. "size -> large/small" *m_wnProc << "-attrn" << "-attra"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 7) { // e.g. "kill -> die" *m_wnProc << "-causv"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 8) { // e.g. "walk -> step" *m_wnProc << "-entav"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 9) { *m_wnProc << "-famln" << "-famlv" << "-famla" << "-famlr"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 10) { *m_wnProc << "-framv"; m_mode = other; } else if (m_wnComboBox->currentIndex() == 11) { *m_wnProc << "-grepn" << "-grepv" << "-grepa" << "-grepr"; m_mode = grep; } else if (m_wnComboBox->currentIndex() == 12) { *m_wnProc << "-over"; m_mode = other; } *m_wnProc << "-g"; // "Display gloss" int current = m_wnComboBox->currentIndex() != -1 ? m_wnComboBox->currentIndex() : 0; // remember current position m_wnComboBox->clear(); // warning: order matters! // 0: m_wnComboBox->insertItem(-1, i18n("Synonyms/Hypernyms - Ordered by Frequency")); m_wnComboBox->insertItem(-1, i18n("Synonyms - Ordered by Similarity of Meaning (verbs only)")); m_wnComboBox->insertItem(-1, i18n("Antonyms - Words with Opposite Meanings")); m_wnComboBox->insertItem(-1, i18n("Hyponyms - ... is a (kind of) %1", m_edit->currentText())); m_wnComboBox->insertItem(-1, i18n("Meronyms - %1 has a ...", m_edit->currentText())); // 5: m_wnComboBox->insertItem(-1, i18n("Holonyms - ... has a %1", m_edit->currentText())); m_wnComboBox->insertItem(-1, i18n("Attributes")); m_wnComboBox->insertItem(-1, i18n("Cause To (for some verbs only)")); m_wnComboBox->insertItem(-1, i18n("Verb Entailment (for some verbs only)")); m_wnComboBox->insertItem(-1, i18n("Familiarity & Polysemy Count")); // 10: m_wnComboBox->insertItem(-1, i18n("Verb Frames (examples of use)")); m_wnComboBox->insertItem(-1, i18n("List of Compound Words")); m_wnComboBox->insertItem(-1, i18n("Overview of Senses")); /** NOT todo: * -Hypernym tree: layout is difficult, you can get the same information * by following links * -Coordinate terms (sisters): just go to synset and then use hyponyms * -Has Part Meronyms, Has Substance Meronyms, Has Member Meronyms, * Member of Holonyms, Substance of Holonyms, Part of Holonyms: * these are just subsets of Meronyms/Holonyms * -hmern, hholn: these are just compact versions, you can get the * same information by following some links */ /** TODO?: * -pert (e.g. nuclear -> nuclues, but "=>" are nested, difficult to display) * -nomn(n|v), e.g. deny -> denial, but this doesn't seem to work? */ m_wnComboBox->setCurrentIndex(current); // reset previous position if (m_wnProc->state() == QProcess::Running) { // should never happen kDebug(31000) <<"Warning: findTerm(): process is already running?!"; return; } m_wnProc->start(); if (!m_wnProc->waitForFinished()) { m_resultTextBrowser->setHtml(i18n("<b>Error:</b> Failed to execute WordNet program 'wn'. " "WordNet has to be installed on your computer if you want to use it, " "and 'wn' has to be in your PATH. " "You can get WordNet at <a href=\"http://wordnet.princeton.edu/\">" "http://wordnet.princeton.edu/</a>. Note that WordNet only supports " "the English language.")); m_wnComboBox->setEnabled(false); return; } QString stdoutString = m_wnProc->readAllStandardOutput(); if (stdoutString.isEmpty()) { m_resultTextBrowser->setHtml(i18n("No match for '%1'.", m_edit->currentText())); } else { // render in a table, each line one row: QStringList lines = stdoutString.split(QChar('\n'), QString::SkipEmptyParts); QString result = "<qt><table>\n"; // TODO in Qt > 3.01: try without the following line (it's necessary to ensure the // first column is really always quite small): result += "<tr><td width=\"10%\"></td><td width=\"90%\"></td></tr>\n"; uint ct = 0; for (QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) { QString l = (*it); // Remove some lines: QRegExp re("^\\d+( of \\d+)? senses? of \\w+"); if (re.indexIn(l) != -1) { continue; } // Escape XML: l.replace('&', "&"); l.replace('<', "<"); l.replace('>', ">"); // TODO?: // move "=>" in own column? l = formatLine(l); // Table layout: result += "<tr>"; if (l.startsWith(' ')) { result += "\t<td width=\"15\"></td>"; l = l.trimmed(); result += "\t<td>" + l + "</td>"; } else { l = l.trimmed(); result += "<td colspan=\"2\">" + l + "</td>"; } result += "</tr>\n"; ct++; } result += "\n</table></qt>\n"; m_resultTextBrowser->setHtml(result); //kDebug() << result; } }
/*! \a fileName is the path of the file to find. \a files and \a dirs are the lists where we must find the components of \a fileName. \a location is used for obtaining the file and line numbers for report qdoc errors. */ QString Config::findFile(const Location& location, const QStringList& files, const QStringList& dirs, const QString& fileName, QString& userFriendlyFilePath) { if (fileName.isEmpty() || fileName.startsWith(QLatin1Char('/'))) { userFriendlyFilePath = fileName; return fileName; } QFileInfo fileInfo; QStringList components = fileName.split(QLatin1Char('?')); QString firstComponent = components.first(); QStringList::ConstIterator f = files.begin(); while (f != files.end()) { if (*f == firstComponent || (*f).endsWith(QLatin1Char('/') + firstComponent)) { fileInfo.setFile(*f); if (!fileInfo.exists()) location.fatal(tr("File '%1' does not exist").arg(*f)); break; } ++f; } if (fileInfo.fileName().isEmpty()) { QStringList::ConstIterator d = dirs.begin(); while (d != dirs.end()) { fileInfo.setFile(QDir(*d), firstComponent); if (fileInfo.exists()) { break; } ++d; } } userFriendlyFilePath = QString(); if (!fileInfo.exists()) return QString(); QStringList::ConstIterator c = components.begin(); for (;;) { bool isArchive = (c != components.end() - 1); QString userFriendly = *c; userFriendlyFilePath += userFriendly; if (isArchive) { QString extracted = extractedDirs[fileInfo.filePath()]; ++c; fileInfo.setFile(QDir(extracted), *c); } else break; userFriendlyFilePath += "?"; } return fileInfo.filePath(); }
void SetLyricsCommand::execute() { // This and LyricEditDialog::unparse() are opposites that will // need to be kept in sync with any changes to one another. (They // should really both be in a common lyric management class.) // first remove old lyric events Segment::iterator i = m_segment->begin(); while (i != m_segment->end()) { Segment::iterator j = i; ++j; if ((*i)->isa(Text::EventType)) { std::string textType; if ((*i)->get<String>(Text::TextTypePropertyName, textType) && textType == Text::Lyric) { long verse = 0; (*i)->get<Int>(Text::LyricVersePropertyName, verse); if (verse == m_verse) { m_oldLyricEvents.push_back(new Event(**i)); m_segment->erase(i); } } } i = j; } // now parse the new string QStringList barStrings = m_newLyricData.split("/", QString::KeepEmptyParts); // empties ok Composition *comp = m_segment->getComposition(); int barNo = comp->getBarNumber(m_segment->getStartTime()); QStringList::Iterator bsi = barStrings.begin(); while ( bsi != barStrings.end() ) { NOTATION_DEBUG << "Parsing lyrics for bar number " << barNo << ": \"" << *bsi << "\"" << endl; std::pair<timeT, timeT> barRange = comp->getBarRange(barNo++); QString syllables = *bsi; syllables.replace(QRegExp("\\[\\d+\\] "), " "); syllables.replace(QRegExp("\n"), " "); QStringList syllableList = syllables.split(" ", QString::SkipEmptyParts); // no empties i = m_segment->findTime(barRange.first); timeT laterThan = barRange.first - 1; ++bsi; // update here in order to check whether we are in the last bar string bool isLastBSI = (bsi == barStrings.end()); for (QStringList::Iterator ssi = syllableList.begin(); ssi != syllableList.end(); ++ssi) { // As a rule, syllables belong to a certain bar. However, from the // last barString list syllables may flow to the following bars. // As a result, one may copy&paste the full syllable list of a verse. while (m_segment->isBeforeEndMarker(i) && (isLastBSI || (*i)->getAbsoluteTime() < barRange.second) && (!(*i)->isa(Note::EventType) || (*i)->getNotationAbsoluteTime() <= laterThan || ((*i)->has(TIED_BACKWARD) && (*i)->get <Bool>(TIED_BACKWARD)))) ++i; timeT time = m_segment->getEndMarkerTime(); timeT notationTime = time; if (m_segment->isBeforeEndMarker(i)) { time = (*i)->getAbsoluteTime(); notationTime = (*i)->getNotationAbsoluteTime(); } QString syllable = *ssi; syllable.replace(QRegExp("~"), " "); syllable = syllable.simplified(); if (syllable == "") continue; laterThan = notationTime + 1; if (syllable == ".") continue; NOTATION_DEBUG << "Syllable \"" << syllable << "\" at time " << time << endl; Text text(qstrtostr(syllable), Text::Lyric); Event *event = text.getAsEvent(time); event->set<Int>(Text::LyricVersePropertyName, m_verse); m_segment->insert(event); } } }
void TagComparator::mergeNames(Tags& t1, Tags& t2, Tags& result) { set<QString> altNames, nonAltNames; set<QString> toRemove; toRemove.insert("alt_name"); for (Tags::const_iterator it1 = t1.begin(); it1 != t1.end(); it1++) { if (it1.key() == "alt_name") { QStringList sl = Tags::split(it1.value()); altNames.insert(sl.begin(), sl.end()); } else { if (OsmSchema::getInstance().isAncestor(it1.key(), "abstract_name")) { result[it1.key()] = it1.value(); QStringList sl = Tags::split(it1.value()); // keep track of all the names we've used nonAltNames.insert(sl.begin(), sl.end()); toRemove.insert(it1.key()); } } } for (Tags::const_iterator it2 = t2.begin(); it2 != t2.end(); it2++) { if (it2.key() == "alt_name") { QStringList sl = Tags::split(it2.value()); altNames.insert(sl.begin(), sl.end()); } else if (result.contains(it2.key())) { const Qt::CaseSensitivity caseSensitivity = _caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive; if (result[it2.key()].compare(it2.value(), caseSensitivity) != 0) { QStringList sl = Tags::split(it2.value()); altNames.insert(sl.begin(), sl.end()); } } else { if (OsmSchema::getInstance().isAncestor(it2.key(), "abstract_name")) { result[it2.key()] = it2.value(); QStringList sl = Tags::split(it2.value()); nonAltNames.insert(sl.begin(), sl.end()); toRemove.insert(it2.key()); } } } for (set<QString>::const_iterator it = toRemove.begin(); it != toRemove.end(); it++) { t1.remove(*it); t2.remove(*it); } // add all the altNames that don't exist in nonAltNames QStringList l; for (set<QString>::const_iterator it = altNames.begin(); it != altNames.end(); it++) { if (nonAltNames.find(*it) == nonAltNames.end()) { l.append(*it); } } if (l.size() > 0) { result.setList("alt_name", l); } }