// return the absolute path from a filename read from project file QString QgsProject::readPath( QString src ) const { if ( readBoolEntry( "Paths", "/Absolute", false ) ) { return src; } // relative path should always start with ./ or ../ if ( !src.startsWith( "./" ) && !src.startsWith( "../" ) ) { #if defined(Q_OS_WIN) if ( src.startsWith( "\\\\" ) || src.startsWith( "//" ) || ( src[0].isLetter() && src[1] == ':' ) ) { // UNC or absolute path return src; } #else if ( src[0] == '/' ) { // absolute path return src; } #endif // so this one isn't absolute, but also doesn't start // with ./ or ../. // That means that it was saved with an earlier version of "relative path support", // where the source file had to exist and only the project directory was stripped // from the filename. QFileInfo pfi( fileName() ); if ( !pfi.exists() ) return src; QFileInfo fi( pfi.canonicalPath() + "/" + src ); if ( !fi.exists() ) { return src; } else { return fi.canonicalFilePath(); } } QString srcPath = src; QString projPath = fileName(); if ( projPath.isEmpty() ) { return src; } #if defined(Q_OS_WIN) srcPath.replace( "\\", "/" ); projPath.replace( "\\", "/" ); bool uncPath = projPath.startsWith( "//" ); #endif QStringList srcElems = srcPath.split( "/", QString::SkipEmptyParts ); QStringList projElems = projPath.split( "/", QString::SkipEmptyParts ); #if defined(Q_OS_WIN) if ( uncPath ) { projElems.insert( 0, "" ); projElems.insert( 0, "" ); } #endif // remove project file element projElems.removeLast(); // append source path elements projElems << srcElems; projElems.removeAll( "." ); // resolve .. int pos; while (( pos = projElems.indexOf( ".." ) ) > 0 ) { // remove preceding element and .. projElems.removeAt( pos - 1 ); projElems.removeAt( pos - 1 ); } #if !defined(Q_OS_WIN) // make path absolute projElems.prepend( "" ); #endif return projElems.join( "/" ); }
Installer::Installer(QWidget *parent) : QMainWindow(parent, Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnBottomHint) { setupUi(this); //Setup the window if(!DEBUG){ this->setGeometry( QApplication::primaryScreen()->geometry() ); }//full screen else{ this->setWindowFlags(Qt::Window); } //don't keep on bottom/frameless for testing translator = new QTranslator(); connect(backButton, SIGNAL(clicked()), this, SLOT(slotBack())); connect(nextButton, SIGNAL(clicked()), this, SLOT(slotNext())); connect(helpButton, SIGNAL(clicked()), this, SLOT(slotHelp())); connect(pushTouchKeyboard, SIGNAL(clicked()), this, SLOT(slotPushVirtKeyboard())); connect(pushChangeKeyLayout, SIGNAL(clicked()), this, SLOT(slotPushKeyLayout())); connect(lineHostname,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckHost())); connect(lineDomainName, SIGNAL(textChanged(const QString &)), this, SLOT(slotCheckDomainName()) ); connect(lineRootPW, SIGNAL(textChanged ( const QString &)), this, SLOT(slotCheckRootPW())); connect(lineRootPW2, SIGNAL(textChanged ( const QString &)), this, SLOT(slotCheckRootPW())); connect(lineName,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser())); connect(lineName,SIGNAL(editingFinished()),this,SLOT(slotSuggestUsername())); connect(lineUsername,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser())); connect(linePW,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser())); connect(linePW2,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser())); connect(line_PCpass, SIGNAL(textChanged(const QString)), this, SLOT(slotCheckUser())) ; connect(line_PCpass_repeat, SIGNAL(textChanged(const QString)), this, SLOT(slotCheckUser())) ; connect(group_usePC, SIGNAL(toggled(bool)), this, SLOT(slotCheckUser()) ); connect(push_PC_device, SIGNAL(clicked()), this, SLOT(slotGetPCDevice()) ); connect(tool_testAudio, SIGNAL(clicked()), this, SLOT(slotPlayAudioTest()) ); connect(slider_volume, SIGNAL(valueChanged(int)), this, SLOT(slotAudioVolumeChanged()) ); connect(combo_audiodevice, SIGNAL(currentIndexChanged(int)), this, SLOT(slotSetAudioDev()) ); backButton->setText(tr("&Back")); nextButton->setText(tr("&Next")); // Load the keyboard info keyModels = Scripts::Backend::keyModels(); keyLayouts = Scripts::Backend::keyLayouts(); // If we have a saved keyboard layout from installation, use it first QString kD; if ( QFile::exists("/var/.wizardKeyboard") ) { QFile kFile("/var/.wizardKeyboard"); if ( kFile.open(QIODevice::ReadOnly | QIODevice::Text) ) { kD = kFile.readLine().simplified(); kFile.close(); kbMod = kD.section(" ", 0, 0); kbLay = kD.section(" ", 1, 1); kbVar = kD.section(" ", 2, 2); Scripts::Backend::changeKbMap(kbMod, kbLay, kbVar); } } // Load the timezones comboBoxTimezone->clear(); QString curZone = Scripts::Backend::guessTimezone(); comboBoxTimezone->addItems(Scripts::Backend::timezones()); if ( ! curZone.isEmpty() ) { int index = comboBoxTimezone->findText(curZone, Qt::MatchStartsWith); if (index != -1) { comboBoxTimezone->setCurrentIndex(index); } else { // Set America/New_York to default index = comboBoxTimezone->findText("America/New_York", Qt::MatchStartsWith); if (index != -1) comboBoxTimezone->setCurrentIndex(index); } } else { // Set America/New_York to default int index = comboBoxTimezone->findText("America/New_York", Qt::MatchStartsWith); if (index != -1) comboBoxTimezone->setCurrentIndex(index); } // Load the hostname lineHostname->setText(Utils::getConfFileValue("/etc/rc.conf", "hostname=", 1).section(".",0,0)); // Load the domain name lineDomainName->setText(Utils::getConfFileValue("/etc/rc.conf", "hostname=",1).section(".",1,100)); //Load the available Services into the UI LoadServices(); // Start on the first screen installStackWidget->setCurrentIndex(0); backButton->setVisible(false); // Update the status bar // This makes the status text more "visible" instead of using the blue background //statusBar()->setStyleSheet("background: white"); //Load the audio settings values combo_audiodevice->clear(); QStringList devs = Utils::runShellCommand("cat /dev/sndstat"); //qDebug() << "Sound Devices:" <<devs; int def = -1; for(int i=0; i<devs.length(); i++){ if(!devs[i].startsWith("pcm")){ devs.removeAt(i); i--; continue; } combo_audiodevice->addItem(devs[i], devs[i].section(":",0,0)); //<full text>, <pcmID> if(devs[i].contains(" default")){ def = i; } } if(def<0 && !devs.isEmpty()){ def=0; } if(def<0){ //No audio devices found - disable this functionality Page_Audio->setEnabled(false); //just do the whole page - nothing will work }else{ combo_audiodevice->setCurrentIndex(def); //make sure this item is initially selected slotSetAudioDev(); //make sure to run the setup command initially } slider_volume->setValue(100); slotAudioVolumeChanged(); //update the volume % label // If we have wireless, UP it so we can scan if ( system("ifconfig wlan0") == 0 ) { system("ifconfig wlan0 up"); } }
/*! Creates a declaration (header file) for the form given in \a e \sa createFormImpl() */ void Ui3Reader::createFormDecl(const QDomElement &e) { QDomElement body = e; QDomElement n; QDomNodeList nl; int i; QString objClass = getClassName(e); if (objClass.isEmpty()) return; QString objName = getObjectName(e); QStringList typeDefs; QMap<QString, CustomInclude> customWidgetIncludes; /* We are generating a few QImage members that are not strictly necessary in some cases. Ideally, we would use requiredImage, which is computed elsewhere, to keep the generated .h and .cpp files synchronized. */ // at first the images QMap<QString, int> customWidgets; QStringList forwardDecl; QStringList forwardDecl2; for (n = e; !n.isNull(); n = n.nextSibling().toElement()) { if (n.tagName().toLower() == QLatin1String("customwidgets")) { QDomElement n2 = n.firstChild().toElement(); while (!n2.isNull()) { if (n2.tagName().toLower() == QLatin1String("customwidget")) { QDomElement n3 = n2.firstChild().toElement(); QString cl; while (!n3.isNull()) { QString tagName = n3.tagName().toLower(); if (tagName == QLatin1String("class")) { cl = n3.firstChild().toText().data(); if (m_options & CustomWidgetForwardDeclarations) forwardDecl << cl; customWidgets.insert(cl, 0); } else if (tagName == QLatin1String("header")) { CustomInclude ci; ci.header = n3.firstChild().toText().data(); ci.location = n3.attribute(QLatin1String("location"), QLatin1String("global")); if (!ci.header.isEmpty()) forwardDecl.removeAll(cl); customWidgetIncludes.insert(cl, ci); } n3 = n3.nextSibling().toElement(); } } n2 = n2.nextSibling().toElement(); } } } // register the object and unify its name objName = registerObject(objName); QString protector = objName.toUpper() + QLatin1String("_H"); protector.replace(QLatin1String("::"), QLatin1String("_")); out << "#ifndef " << protector << endl; out << "#define " << protector << endl; out << endl; out << "#include <qvariant.h>" << endl; // for broken HP-UX compilers QStringList globalIncludes, localIncludes; { QMap<QString, CustomInclude>::Iterator it = customWidgetIncludes.find(objClass); if (it != customWidgetIncludes.end()) { if ((*it).location == QLatin1String("global")) globalIncludes += (*it).header; else localIncludes += (*it).header; } } QStringList::ConstIterator it; globalIncludes = unique(globalIncludes); for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include <" << header << '>' << endl; } } localIncludes = unique(localIncludes); for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include \"" << header << '\"' << endl; } } out << endl; bool dbForm = false; registerDatabases(e); dbConnections = unique(dbConnections); if (dbForms[QLatin1String("(default)")].count()) dbForm = true; bool subDbForms = false; for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) { if (dbForms[(*it)].count()) { subDbForms = true; break; } } } // some typedefs, maybe typeDefs = unique(typeDefs); for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) { if (!(*it).isEmpty()) out << "typedef " << *it << ';' << endl; } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward")); for (i = 0; i < (int) nl.length(); i++) forwardDecl2 << fixDeclaration(nl.item(i).toElement().firstChild().toText().data()); forwardDecl = unique(forwardDecl); for (it = forwardDecl.constBegin(); it != forwardDecl.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != objClass) { QString forwardName = *it; QStringList forwardNamespaces = forwardName.split(QLatin1String("::")); forwardName = forwardNamespaces.last(); forwardNamespaces.removeAt(forwardNamespaces.size()-1); QStringList::ConstIterator ns = forwardNamespaces.constBegin(); while (ns != forwardNamespaces.constEnd()) { out << "namespace " << *ns << " {" << endl; ++ns; } out << "class " << forwardName << ';' << endl; for (int i = 0; i < (int) forwardNamespaces.count(); i++) out << '}' << endl; } } for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) { QString fd = *it; fd = fd.trimmed(); if (!fd.endsWith(QLatin1Char(';'))) fd += QLatin1Char(';'); out << fd << endl; } out << endl; Driver d; d.option().headerProtection = false; d.option().copyrightHeader = false; d.option().extractImages = m_extractImages; d.option().limitXPM_LineLength = (m_options & LimitXPM_LineLength) ? 1 : 0; d.option().qrcOutputFile = m_qrcOutputFile; d.option().implicitIncludes = (m_options & ImplicitIncludes) ? 1 : 0; if (trmacro.size()) d.option().translateFunction = trmacro; DomUI *ui = generateUi4(e); d.uic(fileName, ui, &out); delete ui; createWrapperDeclContents(e); out << "#endif // " << protector << endl; }
bool ZInstrument::loadSfz(const QString& s) { _program = 0; QFileInfo fi(s); QString path = fi.absolutePath(); QStringList fileContents = readFile(s); if (fileContents.empty()) { return false; } SfzControl c; c.init(); c.defines.clear(); for (int i = 0;i < 128; i++) c.set_cc[i] = -1; int idx = 0; bool inBlockComment = false; // preprocessor while(idx < fileContents.size()) { QRegularExpression findWithSpaces("\"(.+)\""); QRegularExpression comment("//.*$"); QRegularExpression trailingSpacesOrTab("^[\\s\\t]*"); QRegularExpressionMatch foundWithSpaces; QString curLine = fileContents[idx]; QString curLineCopy = curLine; bool nextIsImportant = false; int idxBlockComment = 0; int from = 0; for (QChar chr : curLineCopy) { bool terminated = false; if (nextIsImportant) { nextIsImportant = false; if (inBlockComment && chr == '/') { // found block end inBlockComment = false; terminated = true; curLine.remove(from, idxBlockComment - from + 1); idxBlockComment = from - 1; } else if (!inBlockComment && chr == '*') { // found block start inBlockComment = true; terminated = true; from = idxBlockComment - 1; } } if (!terminated && inBlockComment && chr == '*') nextIsImportant = true; else if (!terminated && !inBlockComment && chr == '/') nextIsImportant = true; idxBlockComment++; } if (inBlockComment) curLine.remove(from, curLine.size() - from); curLine = curLine.remove(comment); curLine.remove(trailingSpacesOrTab); fileContents[idx] = curLine; if (curLine.startsWith("#define")) { QStringList define = curLine.split(" "); foundWithSpaces = findWithSpaces.match(curLine); if (define.size() == 3) c.defines.insert(std::pair<QString, QString>(define[1], define[2])); else if(foundWithSpaces.hasMatch()) c.defines.insert(std::pair<QString, QString>(define[1], foundWithSpaces.captured(1))); fileContents.removeAt(idx); } else if (curLine.startsWith("#include")) { foundWithSpaces = findWithSpaces.match(curLine); if (foundWithSpaces.hasMatch()) { QString newFilename = foundWithSpaces.captured(1); for(auto define : c.defines) { newFilename.replace(define.first, define.second); } QStringList newFileContents = readFile(path + "/" + newFilename); if (newFileContents.empty()) return false; int offset = 1; for (QString newFileLine : newFileContents) { fileContents.insert(idx+offset, newFileLine); offset++; } fileContents.removeAt(idx); } } else if (curLine.isEmpty()) fileContents.removeAt(idx); else idx++; } int total = fileContents.size(); SfzRegion r; SfzRegion g; // group SfzRegion glob; r.init(path); g.init(path); glob.init(path); bool groupMode = false; bool globMode = false; zerberus->setLoadProgress(0); for (int idx = 0; idx < fileContents.size(); idx++) { QString curLine = fileContents[idx]; zerberus->setLoadProgress(((qreal) idx * 100) / (qreal) total); if (zerberus->loadWasCanceled()) return false; if (curLine.startsWith("<global>")) { if (!globMode && !groupMode && !r.isEmpty()) addRegion(r); glob.init(path); g.init(path); // global also resets group r.init(path); globMode = true; } if (curLine.startsWith("<group>")) { if (!groupMode && !globMode && !r.isEmpty()) addRegion(r); g.init(path); if (globMode) { glob = r; globMode = false; } else { r = glob; // initialize group with global values } groupMode = true; curLine = curLine.mid(7); } else if (curLine.startsWith("<region>")) { if (groupMode) { g = r; groupMode = false; } else if (globMode) { glob = r; g = glob; globMode = false; } else { if (!r.isEmpty()) addRegion(r); r = g; // initialize next region with group values } curLine = curLine.mid(8); } else if (curLine.startsWith("<control>")) c.init(); QRegularExpression re("\\s?([\\w\\$]+)="); // defines often use the $-sign QRegularExpressionMatchIterator i = re.globalMatch(curLine); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); int si = match.capturedEnd(); int ei; if (i.hasNext()) { QRegularExpressionMatch nextMatch = i.peekNext(); ei = nextMatch.capturedStart(); } else ei = curLine.size(); QString s = curLine.mid(si, ei-si); r.readOp(match.captured(1), s, c); } } for (int i = 0; i < 128; i++) _setcc[i] = c.set_cc[i]; zerberus->setLoadProgress(100); if (!groupMode && !globMode && !r.isEmpty()) addRegion(r); return true; }
int Gui::drawPage( LGraphicsView *view, QGraphicsScene *scene, Steps *steps, int stepNum, QString const &addLine, Where ¤t, QStringList &csiParts, QStringList &pliParts, bool isMirrored, QHash<QString, QStringList> &bfx, bool printing, bool bfxStore2, QStringList &bfxParts, bool calledOut) { bool global = true; QString line; Callout *callout = NULL; Range *range = NULL; Step *step = NULL; bool pliIgnore = false; bool partIgnore = false; bool synthBegin = false; bool multiStep = false; bool partsAdded = false; bool coverPage = false; bool bfxStore1 = false; bool bfxLoad = false; int numLines = ldrawFile.size(current.modelName); bool firstStep = true; steps->isMirrored = isMirrored; QList<InsertMeta> inserts; Where topOfStep = current; Rc gprc = OkRc; Rc rc; statusBar()->showMessage("Processing " + current.modelName); page.coverPage = false; QStringList calloutParts; /* * do until end of page */ for ( ; current <= numLines; current++) { Meta &curMeta = callout ? callout->meta : steps->meta; QStringList tokens; // If we hit end of file we've got to note end of step if (current >= numLines) { line.clear(); gprc = EndOfFileRc; tokens << "0"; // not end of file, so get the next LDraw line } else { line = ldrawFile.readLine(current.modelName,current.lineNumber); split(line,tokens); } if (tokens.size() == 15 && tokens[0] == "1") { QString color = tokens[1]; QString type = tokens[tokens.size()-1]; csiParts << line; partsAdded = true; /* since we have a part usage, we have a valid step */ if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } /* addition of ldraw parts */ if (curMeta.LPub.pli.show.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { QString colorType = color+type; if (! isSubmodel(type) || curMeta.LPub.pli.includeSubs.value()) { if (bfxStore2 && bfxLoad) { bool removed = false; for (int i = 0; i < bfxParts.size(); i++) { if (bfxParts[i] == colorType) { bfxParts.removeAt(i); removed = true; break; } } if ( ! removed) { pliParts << Pli::partLine(line,current,steps->meta); } } else { pliParts << Pli::partLine(line,current,steps->meta); } } if (bfxStore1) { bfxParts << colorType; } } /* if it is a sub-model, then process it */ if (ldrawFile.contains(type) && callout) { /* we are a callout, so gather all the steps within the callout */ /* start with new meta, but no rotation step */ if (callout->bottom.modelName != type) { Where current2(type,0); skipHeader(current2); callout->meta.rotStep.clear(); SubmodelStack tos(current.modelName,current.lineNumber,stepNum); callout->meta.submodelStack << tos; Meta saveMeta = callout->meta; callout->meta.LPub.pli.constrain.resetToDefault(); step->append(callout); calloutParts.clear(); QStringList csiParts2; QHash<QString, QStringList> calloutBfx; int rc; rc = drawPage( view, scene, callout, 1, line, current2, csiParts2, calloutParts, ldrawFile.mirrored(tokens), calloutBfx, printing, bfxStore2, bfxParts, true); callout->meta = saveMeta; if (callout->meta.LPub.pli.show.value() && ! callout->meta.LPub.callout.pli.perStep.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { pliParts += calloutParts; } if (rc != 0) { steps->placement = steps->meta.LPub.assem.placement; return rc; } } else { callout->instances++; pliParts += calloutParts; } /* remind user what file we're working on */ statusBar()->showMessage("Processing " + current.modelName); } } else if (tokens.size() > 0 && (tokens[0] == "2" || tokens[0] == "3" || tokens[0] == "4" || tokens[0] == "5")) { csiParts << line; partsAdded = true; /* we've got a line, triangle or polygon, so add it to the list */ /* and make sure we know we have a step */ if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, steps->meta, calledOut, multiStep); range->append(step); } } else if (tokens.size() > 0 && tokens[0] == "0" || gprc == EndOfFileRc) { /* must be meta-command (or comment) */ if (global && tokens.contains("!LPUB") && tokens.contains("GLOBAL")) { topOfStep = current; } else { global = false; } QString part; if (gprc == EndOfFileRc) { rc = gprc; } else { rc = curMeta.parse(line,current,true); } /* handle specific meta-commands */ switch (rc) { /* toss it all out the window, per James' original plan */ case ClearRc: pliParts.clear(); csiParts.clear(); steps->freeSteps(); break; /* Buffer exchange */ case BufferStoreRc: bfx[curMeta.bfx.value()] = csiParts; bfxStore1 = true; bfxParts.clear(); break; case BufferLoadRc: csiParts = bfx[curMeta.bfx.value()]; bfxLoad = true; break; case MLCadGroupRc: csiParts << line; break; case IncludeRc: include(curMeta); break; /* substitute part/parts with this */ case PliBeginSub1Rc: if (pliIgnore) { parseError("Nested PLI BEGIN/ENDS not allowed\n",current); } if (steps->meta.LPub.pli.show.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { SubData subData = curMeta.LPub.pli.begin.sub.value(); QString addPart = QString("1 0 0 0 0 0 0 0 0 0 0 0 0 0 %1") .arg(subData.part); pliParts << Pli::partLine(addPart,current,curMeta); } if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } pliIgnore = true; break; /* substitute part/parts with this */ case PliBeginSub2Rc: if (pliIgnore) { parseError("Nested BEGIN/ENDS not allowed\n",current); } if (steps->meta.LPub.pli.show.value() && ! pliIgnore && ! partIgnore && ! synthBegin) { SubData subData = curMeta.LPub.pli.begin.sub.value(); QString addPart = QString("1 %1 0 0 0 0 0 0 0 0 0 0 0 0 %2") .arg(subData.color) .arg(subData.part); pliParts << Pli::partLine(addPart,current,curMeta); } if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } pliIgnore = true; break; /* do not put subsequent parts into PLI */ case PliBeginIgnRc: if (pliIgnore) { parseError("Nested BEGIN/ENDS not allowed\n",current); } pliIgnore = true; break; case PliEndRc: if ( ! pliIgnore) { parseError("PLI END with no PLI BEGIN",current); } pliIgnore = false; break; /* discard subsequent parts, and don't create CSI's for them */ case PartBeginIgnRc: case MLCadSkipBeginRc: if (partIgnore) { parseError("Nested BEGIN/ENDS not allowed\n",current); } partIgnore = true; break; case PartEndRc: case MLCadSkipEndRc: if (partIgnore) { parseError("Ignore ending with no ignore begin",current); } partIgnore = false; break; case SynthBeginRc: if (synthBegin) { parseError("Nested BEGIN/ENDS not allowed\n",current); } synthBegin = true; break; case SynthEndRc: if ( ! synthBegin) { parseError("Ignore ending with no ignore begin",current); } synthBegin = false; break; /* remove a group or all instances of a part type */ case GroupRemoveRc: case RemoveGroupRc: case RemovePartRc: case RemoveNameRc: { QStringList newCSIParts; if (rc == RemoveGroupRc) { remove_group(csiParts,steps->meta.LPub.remove.group.value(),newCSIParts); } else if (rc == RemovePartRc) { remove_parttype(csiParts, steps->meta.LPub.remove.parttype.value(),newCSIParts); } else { remove_partname(csiParts, steps->meta.LPub.remove.partname.value(),newCSIParts); } csiParts = newCSIParts; if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } } break; case ReserveSpaceRc: /* since we have a part usage, we have a valid step */ if (calledOut || multiStep) { step = NULL; Reserve *reserve = new Reserve(current,steps->meta.LPub); if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } range->append(reserve); } break; case InsertCoverPageRc: coverPage = true; page.coverPage = true; case InsertPageRc: partsAdded = true; break; case InsertRc: inserts.append(curMeta.LPub.insert); // these are always placed before any parts in step break; case CalloutBeginRc: if (callout) { parseError("Nested CALLOUT not allowed within the same file",current); } else { callout = new Callout(curMeta,view); callout->setTopOfCallout(current); } break; case CalloutDividerRc: if (range) { range->sepMeta = curMeta.LPub.callout.sep; range = NULL; step = NULL; } break; case CalloutPointerRc: if (callout) { callout->appendPointer(current,curMeta.LPub.callout); } break; case CalloutEndRc: if ( ! callout) { parseError("CALLOUT END without a CALLOUT BEGIN",current); } else { callout->parentStep = step; callout->parentRelativeType = step->relativeType; callout->pli.clear(); callout->placement = curMeta.LPub.callout.placement; callout->setBottomOfCallout(current); callout = NULL; } break; case StepGroupBeginRc: if (calledOut) { parseError("MULTI_STEP not allowed inside callout models",current); } else { if (multiStep) { parseError("Nested MULTI_STEP not allowed",current); } multiStep = true; } steps->relativeType = StepGroupType; break; case StepGroupDividerRc: if (range) { range->sepMeta = steps->meta.LPub.multiStep.sep; range = NULL; step = NULL; } break; /* finished off a multiStep */ case StepGroupEndRc: if (multiStep) { // save the current meta as the meta for step group // PLI for non-pli-per-step if (partsAdded) { parseError("Expected STEP before MULTI_STEP END", current); } multiStep = false; if (pliParts.size() && steps->meta.LPub.multiStep.pli.perStep.value() == false) { steps->pli.bom = false; steps->pli.setParts(pliParts,steps->stepGroupMeta); steps->pli.sizePli(&steps->stepGroupMeta, StepGroupType, false); } pliParts.clear(); /* this is a page we're supposed to process */ steps->placement = steps->meta.LPub.multiStep.placement; showLine(steps->topOfSteps()); bool endOfSubmodel = stepNum == ldrawFile.numSteps(current.modelName); int instances = ldrawFile.instances(current.modelName,isMirrored); addGraphicsPageItems(steps, coverPage, endOfSubmodel,instances, view, scene,printing); return HitEndOfPage; } break; /* we're hit some kind of step, or implied step and end of file */ case EndOfFileRc: case RotStepRc: case StepRc: if ( ! partsAdded && bfxLoad) { // special case of no parts added, but BFX load if (step == NULL) { if (range == NULL) { range = newRange(steps,calledOut); steps->append(range); } step = new Step(topOfStep, range, stepNum, curMeta, calledOut, multiStep); range->append(step); } int rc = step->createCsi( isMirrored ? addLine : "1 color 0 0 0 1 0 0 0 1 0 0 0 1 foo.ldr", csiParts, &step->csiPixmap, steps->meta); partsAdded = true; // OK, so this is a lie, but it works } if (partsAdded) { if (firstStep) { steps->stepGroupMeta = curMeta; firstStep = false; } if (pliIgnore) { parseError("PLI BEGIN then STEP. Expected PLI END",current); pliIgnore = false; } if (partIgnore) { parseError("PART BEGIN then STEP. Expected PART END",current); partIgnore = false; } if (synthBegin) { parseError("SYNTH BEGIN then STEP. Expected SYNTH_END",current); synthBegin = false; } bool pliPerStep; if (multiStep && steps->meta.LPub.multiStep.pli.perStep.value()) { pliPerStep = true; } else if (calledOut && steps->meta.LPub.callout.pli.perStep.value()) { pliPerStep = true; } else if ( ! multiStep && ! calledOut) { pliPerStep = true; } else { pliPerStep = false; } if (step) { Page *page = dynamic_cast<Page *>(steps); if (page) { page->inserts = inserts; } if (pliPerStep) { PlacementType relativeType; if (multiStep) { relativeType = StepGroupType; } else if (calledOut) { relativeType = CalloutType; } else { relativeType = SingleStepType; } step->pli.setParts(pliParts,steps->meta); pliParts.clear(); step->pli.sizePli(&steps->meta,relativeType,pliPerStep); } int rc = step->createCsi( isMirrored ? addLine : "1 color 0 0 0 1 0 0 0 1 0 0 0 1 foo.ldr", csiParts, &step->csiPixmap, steps->meta); statusBar()->showMessage("Processing " + current.modelName); if (rc) { return rc; } } else { if (pliPerStep) { pliParts.clear(); } /* * Only pages or step can have inserts.... no callouts */ if ( ! multiStep && ! calledOut) { Page *page = dynamic_cast<Page *>(steps); if (page) { page->inserts = inserts; } } } if ( ! multiStep && ! calledOut) { /* * Simple step */ if (steps->list.size() == 0) { steps->relativeType = PageType; } steps->placement = steps->meta.LPub.assem.placement; showLine(topOfStep); int numSteps = ldrawFile.numSteps(current.modelName); bool endOfSubmodel = numSteps == 0 || stepNum == numSteps; int instances = ldrawFile.instances(current.modelName,isMirrored); addGraphicsPageItems(steps,coverPage,endOfSubmodel,instances,view,scene,printing); stepPageNum += ! coverPage; steps->setBottomOfSteps(current); return HitEndOfPage; } steps->meta.pop(); stepNum += partsAdded; topOfStep = current; partsAdded = false; coverPage = false; step = NULL; bfxStore2 = bfxStore1; bfxStore1 = false; bfxLoad = false; } inserts.clear(); steps->setBottomOfSteps(current); break; case RangeErrorRc: showLine(current); QMessageBox::critical(NULL, QMessageBox::tr("LPub"), QMessageBox::tr("Parameter(s) out of range: %1:%2\n%3") .arg(current.modelName) .arg(current.lineNumber) .arg(line)); return RangeErrorRc; break; default: break; } } else if (line != "") { showLine(current); QMessageBox::critical(NULL, QMessageBox::tr("LPub"), QMessageBox::tr("Invalid LDraw Line Type: %1:%2\n %3") .arg(current.modelName) .arg(current.lineNumber) .arg(line)); return InvalidLDrawLineRc; } } steps->meta.rotStep.clear(); return 0; }
FileList *Phone::getStaticFileList(QString path, QString sdk, bool hiddenFiles) { QTextCodec *codec = QTextCodec::codecForLocale(); FileList *fileList = new FileList; QProcess *phone=new QProcess; phone->setProcessChannelMode(QProcess::MergedChannels); QString command; qDebug()<<QDateTime::currentDateTime().toString("hh:mm:ss"); qDebug()<<"Phone::getFileList() - "<<path; if (hiddenFiles) command="\""+sdk+"\""+"adb shell \"busybox ls -l -a \'"+codec->toUnicode(path.toAscii())+"\'\""; else command="\""+sdk+"\""+"adb shell \"busybox ls -l \'"+codec->toUnicode(path.toAscii())+"\'\""; qDebug()<<"Phone::getFileList() - "<<command; phone->start(command); QString outputLine="1"; QStringList outputLines; while (!outputLine.isEmpty()) { phone->waitForReadyRead(-1); outputLine = phone->readLine(); qDebug()<<"Phone::getFileList() - "<<outputLine; outputLines.append(outputLine); } if (outputLines.first().contains("No such file or directory")||outputLines.first().contains("cannot")||outputLines.first().contains("Not a directory")) { fileList->name.append("error"); phone->terminate(); delete phone; return fileList; } outputLines.removeLast(); // pusty QStringList lineParts; QString name; while (outputLines.length()>0) { lineParts.clear(); name.clear(); lineParts=outputLines.first().split(QRegExp("\\s+")); outputLines.removeFirst(); if (lineParts.length()>8) { if (lineParts[4].contains(",")) { fileList->size.append(lineParts.at(4)+lineParts.at(5)); lineParts.removeAt(5); } else fileList->size.append(lineParts.at(4)); fileList->date.append(lineParts[5]+" "+lineParts[6]+" "+lineParts[7]); for (int i=8;i<lineParts.length()-1;i++) name.append(lineParts.at(i)+" "); name.chop(1); fileList->name.append(name); qDebug()<<"Phone::getFileList() - plik: "<<name<< " - " <<lineParts.first(); if (lineParts.first()[0]=='d') fileList->type.append("dir"); else if (lineParts.first()[0]=='-'||lineParts.first()[0]=='s') fileList->type.append("file"); else if (lineParts.first()[0]=='l') fileList->type.append("link"); else if (lineParts.first()[0]=='c'||lineParts.first()[0]=='b'||lineParts.first()[0]=='p') fileList->type.append("device"); } } phone->close(); qDebug()<<"Phone::getFileList() - skonczylem analizowac pliki"; if (fileList->name.count()>0) { // if (fileList->name.first()==".") // { int x=fileList->name.indexOf("."); if (x!=-1) { qDebug("deleting ."); fileList->date.removeAt(x); fileList->name.removeAt(x); fileList->size.removeAt(x); fileList->type.removeAt(x); } x=fileList->name.indexOf(".."); if (x!=-1) { qDebug("deleting .."); fileList->date.removeAt(x); fileList->name.removeAt(x); fileList->size.removeAt(x); fileList->type.removeAt(x); } } qDebug()<<"Phone::getFileList() - . i .. usuniete, koncze funkcje"; phone->terminate(); delete phone; return fileList; }
void radeon_profile::on_list_variables_itemClicked(QListWidgetItem *item) { ui->list_vaules->clear(); if (item->text().contains("----")) // the separator return; if (envVars.isEmpty()) return; // read variable possible values from file QStringList values = envVars.filter(ui->list_variables->currentItem()->text())[0].remove(ui->list_variables->currentItem()->text()+"|").split("#",QString::SkipEmptyParts); // if value for this variable is 'user_input' display a window for input if (values[0] == "user_input") { bool ok; QString input = QInputDialog::getText(this, tr("Enter value"), tr("Enter valid value for ") + ui->list_variables->currentItem()->text(), QLineEdit::Normal,"",&ok); // look for this variable in list int varIndex = selectedVariableVaules.indexOf(QRegExp(ui->list_variables->currentItem()->text()+".+",Qt::CaseInsensitive),0); if (!input.isEmpty() && ok) { // if value was ok if (varIndex == -1) // add it to list selectedVariableVaules.append(ui->list_variables->currentItem()->text()+"="+input); else // replace if already exists selectedVariableVaules[varIndex] = ui->list_variables->currentItem()->text()+"=\""+input+"\""; } else { // hehe, looks weird but check ok status is for, when input was empty, and whether user click ok or cancel, dispaly quesion if ((varIndex != -1) || ok) { if (QMessageBox::question(this, tr("Question"), tr("Remove this item?"), QMessageBox::Yes | QMessageBox::No,QMessageBox::Yes) == QMessageBox::Yes) selectedVariableVaules.removeAt(varIndex); } } ui->txt_summary->setText(selectedVariableVaules.join(" ")); return; } // go through list from file and check if it is selected (exists in summary) for (int i= 0 ; i< values.count(); i++ ) { // look for selected variable in list with variables and its values int varIndex = selectedVariableVaules.indexOf(QRegExp(ui->list_variables->currentItem()->text()+".+",Qt::CaseInsensitive),0); QListWidgetItem *valItem = new QListWidgetItem(); valItem->setText(values[i]); // if not, add to list where from user can choose, add unchecked if (varIndex == -1) { valItem->setFlags(item->flags() | Qt::ItemIsUserCheckable); valItem->setCheckState(Qt::Unchecked); } else { // if it is on list, add checked if (selectedVariableVaules[varIndex].contains(valItem->text())) valItem->setCheckState(Qt::Checked); else { // other, unchecked valItem->setFlags(item->flags() | Qt::ItemIsUserCheckable); valItem->setCheckState(Qt::Unchecked); } } ui->list_vaules->addItem(valItem); } }
Player::Player(QWidget *parent) : QWidget(parent) , videoWidget(0) , coverLabel(0) , slider(0) #ifndef PLAYER_NO_COLOROPTIONS , colorDialog(0) #endif { //! [create-objs] player = new QMediaPlayer(this); // owned by PlaylistModel playlist = new QMediaPlaylist(); player->setPlaylist(playlist); //! [create-objs] connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64))); connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64))); connect(player, SIGNAL(metaDataChanged()), SLOT(metaDataChanged())); connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(playlistPositionChanged(int))); connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), this, SLOT(statusChanged(QMediaPlayer::MediaStatus))); connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int))); connect(player, SIGNAL(videoAvailableChanged(bool)), this, SLOT(videoAvailableChanged(bool))); connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(displayErrorMessage())); //! [2] videoWidget = new VideoWidget(this); player->setVideoOutput(videoWidget); playlistModel = new PlaylistModel(this); playlistModel->setPlaylist(playlist); //! [2] playlistView = new QListView(this); playlistView->setModel(playlistModel); playlistView->setCurrentIndex(playlistModel->index(playlist->currentIndex(), 0)); connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex))); slider = new QSlider(Qt::Horizontal, this); slider->setRange(0, player->duration() / 1000); labelDuration = new QLabel(this); connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int))); QPushButton *openButton = new QPushButton(tr("Open"), this); connect(openButton, SIGNAL(clicked()), this, SLOT(open())); PlayerControls *controls = new PlayerControls(this, player); controls->setState(player->state()); controls->setVolume(player->volume()); controls->setMuted(controls->isMuted()); connect(controls, SIGNAL(play()), player, SLOT(play())); connect(controls, SIGNAL(pause()), player, SLOT(pause())); connect(controls, SIGNAL(stop()), player, SLOT(stop())); connect(controls, SIGNAL(next()), playlist, SLOT(next())); connect(controls, SIGNAL(previous()), this, SLOT(previousClicked())); connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int))); connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool))); connect(controls, SIGNAL(changeRate(qreal)), player, SLOT(setPlaybackRate(qreal))); connect(controls, SIGNAL(stop()), videoWidget, SLOT(update())); connect(player, SIGNAL(stateChanged(QMediaPlayer::State)), controls, SLOT(setState(QMediaPlayer::State))); connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int))); connect(player, SIGNAL(mutedChanged(bool)), controls, SLOT(setMuted(bool))); fullScreenButton = new QPushButton(tr("FullScreen"), this); fullScreenButton->setCheckable(true); #ifndef PLAYER_NO_COLOROPTIONS colorButton = new QPushButton(tr("Color Options..."), this); colorButton->setEnabled(false); connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog())); #endif QBoxLayout *displayLayout = new QHBoxLayout; displayLayout->addWidget(videoWidget, 2); displayLayout->addWidget(playlistView); QBoxLayout *controlLayout = new QHBoxLayout; controlLayout->setMargin(0); controlLayout->addWidget(openButton); controlLayout->addStretch(1); controlLayout->addWidget(controls); controlLayout->addStretch(1); controlLayout->addWidget(fullScreenButton); #ifndef PLAYER_NO_COLOROPTIONS controlLayout->addWidget(colorButton); #endif QBoxLayout *layout = new QVBoxLayout; layout->addLayout(displayLayout); QHBoxLayout *hLayout = new QHBoxLayout; hLayout->addWidget(slider); hLayout->addWidget(labelDuration); layout->addLayout(hLayout); layout->addLayout(controlLayout); setLayout(layout); if (!player->isAvailable()) { QMessageBox::warning(this, tr("Service not available"), tr("The QMediaPlayer object does not have a valid service.\n"\ "Please check the media service plugins are installed.")); controls->setEnabled(false); playlistView->setEnabled(false); openButton->setEnabled(false); #ifndef PLAYER_NO_COLOROPTIONS colorButton->setEnabled(false); #endif fullScreenButton->setEnabled(false); } metaDataChanged(); QStringList arguments = qApp->arguments(); arguments.removeAt(0); addToPlaylist(arguments); }
QMailTimeStampPrivate::QMailTimeStampPrivate(const QString& timeText) : utcOffset(0) { int month = -1, day = -1, year = -1; bool ok; QString timeStr, offsetStr; // Remove any comments from the text QString uncommented; uncommented.reserve( timeText.length() ); int commentDepth = 0; bool escaped = false; const QChar* it = timeText.constData(); const QChar* end = it + timeText.length(); for ( ; it != end; ++it ) { if ( !escaped && ( *it == '\\' ) ) { escaped = true; continue; } if ( *it == '(' && !escaped ) commentDepth += 1; else if ( *it == ')' && !escaped && ( commentDepth > 0 ) ) commentDepth -= 1; else if ( commentDepth == 0 ) { // Remove characters we don't want if ( *it != ',' && *it != '\n' && *it != '\r' ) uncommented.append( *it ); } escaped = false; } // Extract the date/time elements uncommented = uncommented.trimmed(); QStringList tokens = uncommented.split(' ', QString::SkipEmptyParts); int tokenCount = tokens.count(); if ( tokenCount > 0 ) { static const QString Days("sunmontuewedthufrisat"); if (Days.indexOf(tokens[0].left(3).toLower()) != -1) { tokens.removeAt(0); tokenCount -= 1; } if (tokenCount > 0) { int value = tokens[0].toInt(&ok); if ( ok ) day = value; } } if ( tokenCount > 1 ) { static const QString Months("janfebmaraprmayjunjulaugsepoctnovdec"); int value = Months.indexOf( tokens[1].left( 3 ).toLower() ); if ( value != -1 ) month = (value + 3) / 3; } if ( tokenCount > 2 ) { int value = tokens[2].toInt(&ok); if ( ok ) { // Interpret year according to RFC2822 year = value; if ( year < 100 ) { year += ( year <= 49 ? 2000 : 1900 ); } else if ( year < 1000 ) { year += 1900; } } } if ( tokenCount > 3 ) { timeStr = tokens[3].trimmed(); } if ( tokenCount > 4 ) { offsetStr = tokens[4].trimmed(); } // Parse the text into UTC-adjusted time part and UTC-offset indicator if ( (day != -1) && (month != -1) && (year != -1) ) { QDate dateComponent(year, month, day); QTime timeComponent; QTime parsedTime; if ( timeStr.length() == 8 ) { parsedTime = QTime::fromString( timeStr, "hh:mm:ss" ); } else if ( timeStr.length() == 5 ) { // Is this legal? Either way, it seems desirable for robustness... parsedTime = QTime::fromString( timeStr, "hh:mm" ); } if ( parsedTime.isValid() ) timeComponent = parsedTime; time = QDateTime( dateComponent, timeComponent, Qt::UTC ); if ( offsetStr.length() == 5 ) { int h = offsetStr.left(3).toInt(&ok); if ( ok ) { int m = offsetStr.right(2).toInt(&ok); if ( ok ) { utcOffset = ( h * 3600 ) + ( m * 60 * ( h < 0 ? -1 : 1 ) ); time = time.addSecs( -utcOffset ); } } } } }
//Methodes publiques QStringList ParserExpr::getMonomes() const { QStringList monomes = splitExpr(_formatedExpr); monomes.removeAt(0); return monomes; }
void tableSelectParaDialog::on_removeOutputButton_clicked() { int currentIndex = ui->outputList->currentIndex().row(); outputModel->removeRows(currentIndex,1); outputEntries.removeAt(currentIndex); }
int Option::parseCommandLine(QStringList &args) { QStringList user_configs; bool before = true; args << QString(); // Avoid bounds checking for options which take an argument for (int x = 0; x < args.size() - 1; ) { QString arg = args.at(x); if (arg.size() > 1 && arg.startsWith('-')) { /* options */ QString opt = arg.mid(1); if(opt == "o" || opt == "output") { Option::output.setFileName(args.at(x + 1)); args.erase(args.begin() + x, args.begin() + x + 2); continue; } else if(opt == "after") { before = false; } else if(opt == "t" || opt == "template") { Option::user_template = args.at(++x); } else if(opt == "tp" || opt == "template_prefix") { Option::user_template_prefix = args.at(++x); } else if(opt == "unix") { Option::dir_sep = "/"; } else if(opt == "win32") { Option::dir_sep = "\\"; } else if(opt == "d") { Option::debug_level++; } else if(opt == "version" || opt == "v" || opt == "-version") { fprintf(stdout, "QMake version %s\n" "Using Qt version %s in %s\n", qmake_version(), QT_VERSION_STR, QLibraryInfo::location(QLibraryInfo::LibrariesPath).toLatin1().constData()); #ifdef QMAKE_OPENSOURCE_VERSION fprintf(stdout, "QMake is Open Source software from Nokia Corporation and/or its subsidiary(-ies).\n"); #endif return Option::QMAKE_CMDLINE_BAIL; } else if(opt == "h" || opt == "help") { return Option::QMAKE_CMDLINE_SHOW_USAGE; } else if(opt == "Wall") { Option::warn_level |= WarnAll; } else if(opt == "Wparser") { Option::warn_level |= WarnParser; } else if(opt == "Wlogic") { Option::warn_level |= WarnLogic; } else if(opt == "Wdeprecated") { Option::warn_level |= WarnDeprecated; } else if(opt == "Wnone") { Option::warn_level = WarnNone; } else if(opt == "r" || opt == "recursive") { Option::recursive = true; args.removeAt(x); continue; } else if(opt == "nr" || opt == "norecursive") { Option::recursive = false; args.removeAt(x); continue; } else if(opt == "config") { user_configs += args.at(++x); } else { if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(opt == "nodepend" || opt == "nodepends") { Option::mkfile::do_deps = false; } else if(opt == "nomoc") { Option::mkfile::do_mocs = false; } else if(opt == "nocache") { Option::mkfile::do_cache = false; } else if(opt == "createstub") { Option::mkfile::do_stub_makefile = true; } else if(opt == "nodependheuristics") { Option::mkfile::do_dep_heuristics = false; } else if(opt == "E") { Option::mkfile::do_preprocess = true; } else if(opt == "cache") { Option::mkfile::cachefile = args.at(++x); } else if(opt == "platform" || opt == "spec") { Option::mkfile::qmakespec = args[x] = cleanSpec(args.at(++x)); } else if (opt == "xplatform" || opt == "xspec") { Option::mkfile::xqmakespec = args[x] = cleanSpec(args.at(x)); } else { fprintf(stderr, "***Unknown option -%s\n", opt.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } else if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { if(opt == "nopwd") { Option::projfile::do_pwd = false; } else { fprintf(stderr, "***Unknown option -%s\n", opt.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } } } else { if(arg.indexOf('=') != -1) { if(before) Option::before_user_vars.append(arg); else Option::after_user_vars.append(arg); } else { bool handled = true; if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY || Option::qmake_mode == Option::QMAKE_SET_PROPERTY || Option::qmake_mode == Option::QMAKE_UNSET_PROPERTY) { Option::prop::properties.append(arg); } else { QFileInfo fi(arg); if(!fi.makeAbsolute()) //strange arg = fi.filePath(); if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(fi.isDir()) { QString proj = detectProjectFile(arg); if (!proj.isNull()) arg = proj; } Option::mkfile::project_files.append(arg); } else if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { Option::projfile::project_dirs.append(arg); } else { handled = false; } } if(!handled) { return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } args.removeAt(x); continue; } } x++; } if (!user_configs.isEmpty()) Option::before_user_vars += "CONFIG += " + user_configs.join(" "); if (Option::mkfile::xqmakespec.isEmpty()) Option::mkfile::xqmakespec = Option::mkfile::qmakespec; args.takeLast(); return Option::QMAKE_CMDLINE_SUCCESS; }
bool TScriptInternalFunctions::runFunction(QString function, QStringList param, QString &result) { QString fn = function.toUpper(); if (fn == "ACOS") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(acos(v)); return true; } if (fn == "ASIN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(asin(v)); return true; } if (fn == "ATAN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(atan(v)); return true; } if (fn == "BUILDTYPE") { #ifdef STANDALONE result = "STANDALONE"; #endif #ifdef PACKAGED result = "PACKAGED"; #endif return true; } if (fn == "CALC") { // Calculate an expression (e.g. 5+5) if (param.length() == 0) return false; QString expr = param[0]; result = calc(expr); return true; } if (fn == "COS") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(cos(v)); return true; } if (fn == "COLORAT") { // $ColorAt(@window, layer, x, y) if (param.length() < 3) return false; QString layer = "main"; if (param.length() > 3) { layer = param[1]; param.removeAt(1); } subwindow_t sw = getCustomWindow(param[0]); if (sw.type == WT_NOTHING) return false; int x = floor( param[1].toFloat() ); int y = floor( param[2].toFloat() ); result = sw.widget->picwinPtr()->colorAt(layer, x, y); return true; } if (fn == "CURWINTYPE") { // Returns the current target type (msg or channel) subwindow_t sw = winList->value(*activeWid); if (sw.type == WT_CHANNEL) result = "CHANNEL"; else if (sw.type == WT_GRAPHIC) result = "GRAPHIC"; else if (sw.type == WT_GWINPUT) result = "GRAPHICINPUT"; else if (sw.type == WT_NOTHING) result = "NOTHIG"; else if (sw.type == WT_PRIVMSG) result = "PRIVMSG"; else if (sw.type == WT_STATUS) result = "STATUS"; else if (sw.type == WT_TXTONLY) result = "TXTONLY"; else result = "UNKNOWN"; return true; } if (fn == "DLG") { // Returns information of a dialog or its objects // $dlg(dialog,object) if (param.count() == 2) { QString dlg = param[0]; QString object = param[1]; QHashIterator<QString,TCustomScriptDialog*> i(*dialogs); while (i.hasNext()) { i.next(); if (i.key().toUpper() == dlg.toUpper()) { result = i.value()->getLabel(object); return true; } } } // $dlg(dialog,object,index) if (param.count() == 3) { QString dlg = param[0]; QString object = param[1]; QString index = param[2]; QHashIterator<QString,TCustomScriptDialog*> i(*dialogs); while (i.hasNext()) { i.next(); if (i.key().toUpper() == dlg.toUpper()) { result = i.value()->getItem(object, index.toInt()); return true; } } } // Default return false; } if (fn == "FILE") { // Returns a file descriptor by opening a file for read and|or write // $file(file.name, rwb) // result: 0 cannot open, -1 not existing if (param.count() < 2) { result = "0"; return true; } QString mode = param[1]; bool read = false; bool write = false; bool binary = false; bool append = false; bool switchfail = false; for (int i = 0; i <= mode.length()-1; i++) { char c = mode[i].toLatin1(); switch (c) { case 'a': append = true; continue; case 'r': read = true; continue; case 'w': write = true; continue; case 'b': binary = true; continue; default: switchfail = true; break; } } if (switchfail == true) { result = "0"; return true; } if ((read || write) == false) read = true; QIODevice::OpenMode om = 0; if (read) om |= QIODevice::ReadOnly; if (write) om |= QIODevice::WriteOnly; if (! binary) om |= QIODevice::Text; if (append) om |= QIODevice::Append; if (om == 0) { result = "0"; return true; } QFile *f = new QFile(param[0]); if (! f->open(om)) { result = "0"; return true; } t_sfile ts; ts.binary = binary; ts.read = read; ts.write = write; ts.fd = fdc; ts.file = f; files->insert(fdc, ts); result = QString::number(fdc++); return true; } if (fn == "FNEXIST") { // Checks if an actual function exists; This will NOT work on "internal" functions (these in here) if (param.count() != 1) return false; int idx = fnindex->value(param[0].toUpper(), -1); if (idx > -1) result = "1"; else result = "0"; return true; } if (fn == "GLUE") { // "glue" texts together. // $glue(hello,big,world) will return hellobigworld QString r; for (int i = 0; i <= param.length()-1; i++) r += param[i]; result = r; return true; } if (fn == "HOSTMASK") { // Returns hostmask *!*@host.name of nickname if IAL got it. // Otherwise, if IAL doesn't, it returns nickname!*@* as hostmask. if (param.count() != 1) { result.clear(); return false; } QString nickname = param[0]; IConnection *con = conList->value(*activeConn); QString host = con->ial.getHost(nickname); if (host.isEmpty()) { host = nickname; host.append("!*@*"); } else host.prepend("*!*@"); result = host; return true; } if (fn == "IALHOSTMASK") { // Returns hostname of nickname if IAL got it, otherwise empty text. // Better off using $hostmask() instead. if (param.count() != 1) { result.clear(); return false; } QString nickname = param[0]; IConnection *con = conList->value(*activeConn); QString host = con->ial.getHost(nickname); if (! host.isEmpty()) host.prepend("*!*@"); result = host; return true; } if (fn == "LEN") { // Counts amount of letters in a given text if (param.count() == 0) { result = "0"; return true; } result = QString::number( param.at(0).length() ); return true; } if (fn == "NULL") { // Returns empty result.clear(); return true; } if (fn == "PATH") { // $path(type) // Returns a file path to the given type. if (param.count() != 1) return false; QString type = param[0].toUpper(); if (type == "CONFIG") result = CONF_PATH; if (type == "COMMON") result = COMMON_PATH; if (type == "EXEC") result = QApplication::applicationDirPath(); if (type == "SKEL") result = SKEL_PATH; return true; } if (fn == "RAND") { // Pseudo-random number generator if (param.length() < 2) return false; int lo = param[0].toInt(); int hi = param[1].toInt(); result = rand(lo, hi); return true; } if (fn == "SIN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(sin(v)); return true; } if (fn == "SOCKBUFLEN") { // Returns amount of bytes left in sockread buffer if (param.length() < 1) return false; result = sockfactory->sockBufLen(param[0]); return true; } if (fn == "SOCKLIST") { // Find socket names. // $socklist(patt_*, pos) // If pos is zero, that will return amount of socket names the pattern matches. // If pos > 0, this will return an actual socket name it matches. if (param.length() < 2) return false; result = sockfactory->socklist(param[0], param[1].toInt()); return true; } if (fn == "SSTR") { // Substring, returns text by given positions inside the text. // $SSTR(The text, start, end) end is optional. if (param.length() < 2) return false; int start = param[1].toInt(); int stop = -1; if (param.length() >= 3) stop = param[2].toInt(); QString text = param[0]; result = sstr(text, start, stop); return true; } if (fn == "TAN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(tan(v)); return true; } if (fn == "TARGET") { // Returns the current target to send messages to (msg or channel) subwindow_t sw = winList->value(*activeWid); result.clear(); if ((sw.type == WT_CHANNEL) || (sw.type == WT_PRIVMSG)) result = sw.widget->getTarget(); return true; } if (fn == "TEXTWIDTH") { // Return text width in pixles by given font name and size // $textwidth(font, size, text) if (param.count() != 3) return false; QFont font(param[0]); font.setPixelSize(param[1].toInt()); QFontMetrics fm(font); result = QString::number( fm.width(param[2]) ); return true; } if (fn == "TOKEN") { // Get a text by tokens // $token(text here, position, token) the token is in ascii number. // If the position is zero, this will count amount of text items separated by the given token if (param.length() < 3) return false; bool ok = false; QString tcnum = param[2]; // token character (ascii num) QChar tc = tcnum.toInt(&ok); // converted from string-number to actual number, into a character. if (ok == false) return false; int p = param[1].toInt(&ok); // Which position to use if (ok == false) return false; result = token(param[0], p, tc); return true; } if (fn == "VERSION") { // IIRC version. result = VERSION_STRING; return true; } // No functions were matching, return false as error. return false; }
QString AFormatter::normalizeBody (const QString& body, const QString& nick) { QString data = body; // отбрасываем "[tagline]" и "[moderator]" QRegExp tagline("\\[tagline\\](.+)\\[/tagline\\]", Qt::CaseInsensitive); QRegExp moderator("\\[moderator\\](.+)\\[/moderator\\]", Qt::CaseInsensitive); tagline.setMinimal(true); moderator.setMinimal(true); data.replace(tagline, ""); data.replace(moderator, ""); // удаляем img с даными вместо ссылки (например, см. http://www.rsdn.ru/forum/flame.comp/4077971.1.aspx) QRegExp img1("\\[img\\]data:(\\S+)\\[/img\\]", Qt::CaseInsensitive); img1.setMinimal(true); data.replace(img1, ""); // заменяем [img]...[/img] на ссылку QRegExp img2("\\[img\\](\\S+)\\[/img\\]", Qt::CaseInsensitive); img2.setMinimal(true); data.replace(img2, QString::fromUtf8("[url=\\1]\\1[/url]")); // укорачивание длинных ссылок (например, см. http://www.rsdn.ru/forum/web/4086359.1.aspx) QRegExp url1("\\[url=data:(\\S+)\\](.+)\\[/url\\]", Qt::CaseInsensitive); url1.setMinimal(true); data.replace(url1, "[url=bad%20link]\\2[/url]"); // удаление тэга цитирования QRegExp q1("(^|[^\\[])\\[q\\]", Qt::CaseInsensitive); q1.setMinimal(true); data.replace(q1, "\\1"); QRegExp q2("(^|[^\\[])\\[/q\\]", Qt::CaseInsensitive); q2.setMinimal(true); data.replace(q2, "\\1"); // удаление таблиц из цитирования QRegExp table("(^|[^\\[])\\[t\\](.+)\\[/t\\]", Qt::CaseInsensitive); table.setMinimal(true); data.replace(table, "\\1"); // удаление тэгов [h1]..[h6] из цитирования for (int i = 1; i < 7; i++) { QRegExp h1("(^|[^\\[])\\[h" + QString::number(i) + "\\]", Qt::CaseInsensitive); h1.setMinimal(true); data.replace(h1, "\\1"); QRegExp h2("(^|[^\\[])\\[/h" + QString::number(i) + "\\]", Qt::CaseInsensitive); h2.setMinimal(true); data.replace(h2, "\\1"); } data = data.trimmed(); // разбиение QStringList source = data.split("\n"); QString nick_3 = AFormatter::nick3(nick); // добавление квотинга к строкам for (int i = 0; i < source.size(); i++) if (source[i].trimmed().length()) source[i] = nick_3 + "> " + source[i]; // удаление дублирующихся пустых строк int index = 0; // регексп для приветствий в квотинге QRegExp hello(QString::fromUtf8(">\\s{0,}Здравствуйте,\\s.+,\\sВы писали:")); while (index < source.size() - 1) { if (source.at(index).trimmed().length() == 0 && source.at(index + 1).trimmed().length() == 0) { source.removeAt(index); continue; } else if (source.at(index).indexOf(hello) != -1) { source.removeAt(index); if (index > 0) index--; continue; } index++; } // вычисление уровня квотинга QList<int> quoting_level; int size = source.size(); for (int i = 0; i < size; i++) { QString temp = source.at(i).trimmed(); int level = 0; for (int j = 0; j < temp.length() - 3; j++) { if (temp[j] == ' ' && !(temp[j + 1] == '&' || temp[j + 2] == '&' || temp[j + 3] == '&')) break; else if (temp[j] == '&' && temp[j + 1] == 'g' && temp[j + 2] == 't' && temp[j + 3] == ';') { level++; j += 3; } else if (temp[j] == '&' && temp[j + 1] == 'l' && temp[j + 2] == 't' && temp[j + 3] == ';') break; } quoting_level.append(level); source[i] = temp; } // вставка пустых строк между разными уровнями квотинга for (int i = 0; i < size - 1; i++) { if (source[i].length() == 0) continue; if (quoting_level.at(i) != quoting_level.at(i + 1) && source[i + 1].length() /*&& (quoting_level.at(i) == 0 || quoting_level.at(i + 1) == 0)*/) source[i] = source[i] + "\r\n"; } data = source.join("\r\n").trimmed(); // замена HTML спец-символов data.replace(">", ">"); data.replace("<", "<"); data.replace("&", "&"); return data; }
void QrcEditor::resolveLocationIssues(QStringList &files) { const QDir dir = QFileInfo(m_treeview->fileName()).absoluteDir(); const QString dotdotSlash = QLatin1String("../"); int i = 0; int count = files.count(); // Find first troublesome file for (; i < count; i++) { QString const &file = files.at(i); const QString relativePath = dir.relativeFilePath(file); if (relativePath.startsWith(dotdotSlash)) break; } // All paths fine -> no interaction needed if (i == count) { return; } // Interact with user from now on bool abort = false; for (; i < count; i++) { // Path fine -> skip file QString const &file = files.at(i); QString const relativePath = dir.relativeFilePath(file); if (!relativePath.startsWith(dotdotSlash)) { continue; } // Path troublesome and aborted -> remove file if (abort) { files.removeAt(i); count--; i--; continue; } else { // Path troublesome -> query user QMessageBox message(this); message.setWindowTitle(tr("Invalid file")); message.setIcon(QMessageBox::Warning); QPushButton * const copyButton = message.addButton(tr("Copy"), QMessageBox::ActionRole); QPushButton * const skipButton = message.addButton(tr("Don't add"), QMessageBox::DestructiveRole); QPushButton * const abortButton = message.addButton(tr("Abort"), QMessageBox::RejectRole); message.setDefaultButton(copyButton); message.setEscapeButton(skipButton); message.setText(tr("The file %1 is not in a subdirectory of the resource file. Continuing will result in an invalid resource file.") .arg(QDir::toNativeSeparators(file))); message.exec(); if (message.clickedButton() == skipButton) { files.removeAt(i); count--; i--; // Compensate i++ } else if (message.clickedButton() == copyButton) { const QFileInfo fi(file); const QFileInfo suggestion(dir, fi.fileName()); const QString copyName = QFileDialog::getSaveFileName(this, tr("Choose copy location"), suggestion.absoluteFilePath()); if (!copyName.isEmpty()) { QString relPath = dir.relativeFilePath(copyName); if (relPath.startsWith(dotdotSlash)) { // directory is still invalid i--; // Compensate i++ and try again continue; } if (QFile::exists(copyName)) { if (!QFile::remove(copyName)) { QMessageBox::critical(this, tr("Overwrite failed"), tr("Could not overwrite file %1.") .arg(QDir::toNativeSeparators(copyName))); // Remove file files.removeAt(i); count--; i--; // Compensate i++ continue; } } if (!QFile::copy(file, copyName)) { QMessageBox::critical(this, tr("Copying failed"), tr("Could not copy the file to %1.") .arg(QDir::toNativeSeparators(copyName))); // Remove file files.removeAt(i); count--; i--; // Compensate i++ continue; } files[i] = copyName; } else { // Remove file files.removeAt(i); count--; i--; // Compensate i++ } } else if (message.clickedButton() == abortButton) { abort = true; files.removeAt(i); count--; i--; // Compensate i++ } } } }
void Test::finished(QNetworkReply * reply) { finish = true; if(!s){ char buf[1024]; QStringList allBug; QStringList singleBug; QStringList head; bool isBug = false; bool isHead = false; bool headBegin = false; while(reply->readLine(buf,sizeof(buf)) > 0){ QString b(buf); if(b.contains("bz_buglist")){ isHead = true; } if(isHead){ if(b.contains("<tr")){ headBegin = true; } if(headBegin) head << b; if(b.contains("</tr>")){ isHead = false; QStringList list = XMLHelper::getValueFromString(head.join("")); ui->tableWidget->setColumnCount(8); ui->tableWidget->setHorizontalHeaderLabels(list); ui->tableWidget->setEnabled(true); //qDebug() << list.join(" "); head = list; continue; } } if(b.contains("<td class=\"first-child\">")){ isBug = true; Bug *bug = Bug::getEmpty(); bug->head = head; bugs->append(bug); } if(isBug){ if(b.contains("</tr>")){ isBug = false; singleBug.insert(0,"<tr>"); singleBug.append("</tr>"); allBug << singleBug.join(""); QStringList list = XMLHelper::getValueFromString(singleBug.join(" ")); list.removeAt(1); //qDebug() << list.join(" "); bugs->last()->value = list; singleBug.clear(); continue; }else if(b.contains("</table>")){ break; } singleBug << b.trimmed(); } } qDebug() << bugs->size() << "bugs size"; ui->tableWidget->setRowCount(bugs->size()); for(int i = 0;i < bugs->size();i++){ Bug *bug = bugs->at(i); if(bug->value.size()!=bug->head.size()){ bug->value.insert(6,""); } for(int j=0;j<bug->value.size();j++){ QTableWidgetItem *item = new QTableWidgetItem(bug->value.at(j)); //item-> ui->tableWidget->setItem(i,j,item); } } qDebug() << "load end"; } if(s){ s= false; char buf[1024]; bool BREAK = false; QStringList tt; while(reply->readLine(buf,sizeof(buf)) > 0){ if(QString(buf).contains("href=\"http://bugzilla.tcl-ta.com/\"")){ while(reply->readLine(buf,sizeof(buf)) > 0){ QString b(buf); if(b.trimmed().length() >0){ if(b.contains("Administration")){ BREAK = true; break; } if(b.contains("title") || b.contains("href")){ QStringList tmp = b.split("="); QString key = ((QString)tmp.at(0)).trimmed(); tmp.removeAt(0); QString value = tmp.join("=").trimmed(); int value_length = value.length(); if(value_length>2){ value = value.right(value_length-1).left(value_length-2); } if(key == "title"){ search_title->append(value); }else if(key == "href"){ search_href->append(value.left(value.length()-1)); } } tt << b; } } if(BREAK) break; } } //qDebug() << tt.join(""); if(search_href->length()>1){ search_title->insert(0,"My Bugs"); if(search_href->length() == search_title->length()){ for(int i=0;i<search_href->length();i++){ ui->comboBox->insertItem(i,search_title->at(i)); } } } } }
QList<File> *Phone::getFileList(QString filter) { QList<File> *fileList = new QList<File>; File tmpFile; if ((this->getConnectionState() != RECOVERY) && (this->getConnectionState() != DEVICE)) { return NULL; } QProcess *phone=new QProcess(this); phone->setProcessChannelMode(QProcess::MergedChannels); QString command; qDebug()<<QDateTime::currentDateTime().toString("hh:mm:ss"); qDebug()<<"Phone::getFileList() - "<<this->getPath(); if (this->hiddenFiles) command="\""+this->sdk+"\""+"adb shell \"busybox ls -l -a \'"+this->codec->toUnicode(this->getPath().toUtf8())+"\' | grep \'" + filter + "\'\""; else command="\""+this->sdk+"\""+"adb shell \"busybox ls -l \'"+this->codec->toUnicode(this->getPath().toUtf8())+"\' | grep \'" + filter + "\'\""; qDebug()<<"Phone::getFileList() - "<<command; phone->start(command); QString outputLine="1"; QStringList outputLines; while (!outputLine.isEmpty()) { qApp->processEvents(); phone->waitForReadyRead(-1); outputLine = phone->readLine(); qDebug()<<"Phone::getFileList() - "<<outputLine; outputLines.append(outputLine); } if (outputLines.first().contains("No such file or directory")||outputLines.first().contains("cannot")||outputLines.first().contains("Not a directory")) { phone->terminate(); delete phone; return NULL; } outputLines.removeLast(); // pusty QStringList lineParts; QString name; QFile plik; // QFileIconProvider *provider = new QFileIconProvider; QString tmp; while (outputLines.length()>0) { qApp->processEvents(); lineParts.clear(); name.clear(); tmp.clear(); tmp = outputLines.takeFirst(); tmp.remove(QRegExp("\\s+$")); lineParts=tmp.split(QRegExp("\\s+")); // outputLines.removeFirst(); if (lineParts.length()>8) { if (lineParts[4].contains(",")) { tmpFile.fileSize = lineParts.at(4)+lineParts.at(5); lineParts.removeAt(5); } else tmpFile.fileSize = lineParts.at(4); tmpFile.fileDate = lineParts[5]+" "+lineParts[6]+" "+lineParts[7]; for (int i=8;i<lineParts.length();i++) name.append(lineParts.at(i)+" "); name.chop(1); name.remove(QString("%1[0m").arg( QChar( 0x1b ))); name.remove(QChar( 0x1b ), Qt::CaseInsensitive); if (name.contains("0;30"))//black { tmpFile.fileColor = QColor(Qt::black); } else if (name.contains("0;34"))//blue { tmpFile.fileColor = QColor(Qt::blue); } else if (name.contains("0;32"))//green { tmpFile.fileColor = QColor(Qt::green); } else if (name.contains("0;36"))//cyan { tmpFile.fileColor = QColor(Qt::cyan); } else if (name.contains("0;31"))//red { tmpFile.fileColor = QColor(Qt::red); } else if (name.contains("0;35"))//purple { tmpFile.fileColor = QColor(0, 0, 0); } else if (name.contains("0;33"))//brown { tmpFile.fileColor = QColor(0, 0, 0); } else if (name.contains("0;37"))//light gray { tmpFile.fileColor = QColor(Qt::lightGray); } else if (name.contains("1;30"))//dark gray { tmpFile.fileColor = QColor(Qt::darkGray); } else if (name.contains("1;34"))//dark gray { tmpFile.fileColor = QColor(Qt::blue); } else if (name.contains("1;32"))//light green { tmpFile.fileColor = QColor(Qt::green); } else if (name.contains("1;36"))//light cyan { tmpFile.fileColor = QColor(Qt::cyan); } else if (name.contains("1;31"))//light red { tmpFile.fileColor = QColor(Qt::red); } else if (name.contains("1;35"))//light purple { tmpFile.fileColor = QColor(0, 0, 0); } else if (name.contains("1;33"))//yellow { tmpFile.fileColor = QColor(Qt::yellow); } else if (name.contains("1;37"))//white { tmpFile.fileColor = QColor(Qt::white); } else tmpFile.fileColor = QColor(Qt::black); name.remove(QRegExp("\\[\\d;\\d+m")); tmpFile.fileName = QString::fromUtf8(name.toAscii()); tmpFile.filePath = this->getPath() + tmpFile.fileName; qDebug()<<"Phone::getFileList() - plik: "<<name<< " - " <<lineParts.first(); if (lineParts.first()[0]=='d') tmpFile.fileType = "dir"; else if (lineParts.first()[0]=='-'||lineParts.first()[0]=='s') tmpFile.fileType = "file"; else if (lineParts.first()[0]=='l') tmpFile.fileType = "link"; else if (lineParts.first()[0]=='c'||lineParts.first()[0]=='b'||lineParts.first()[0]=='p') tmpFile.fileType = "device"; name = tmpFile.fileName; name.remove(QString("%1[0m").arg( QChar( 0x1b ))); name.remove(QChar( 0x1b ), Qt::CaseInsensitive); name.remove(QRegExp("\\[\\d;\\d+m")); // if (tmpFile.fileType == "file" || tmpFile.fileType == "device") // { // plik.setFileName(QDir::currentPath()+"/tmp/"+name); // plik.open(QFile::WriteOnly); // tmpFile.fileIcon = provider->icon(QFileInfo(plik)); // plik.remove(); // } // else if (tmpFile.fileType == "link") // { // tmpFile.fileIcon = QApplication::style()->standardIcon(QStyle::SP_FileLinkIcon); // } // else // tmpFile.fileIcon = QApplication::style()->standardIcon(QStyle::SP_DirIcon); if (tmpFile.fileName == "." || tmpFile.fileName == "..") continue; else fileList->append(tmpFile); } } phone->close(); qDebug()<<"Phone::getFileList() - skonczylem analizowac pliki"; phone->terminate(); // delete provider; delete phone; return fileList; }
QString LXDG::findDefaultAppForMime(QString mime){ //First get the priority-ordered list of default file locations QStringList dirs; dirs << QString(getenv("XDG_CONFIG_HOME"))+"/lumina-mimeapps.list" \ << QString(getenv("XDG_CONFIG_HOME"))+"/mimeapps.list"; QStringList tmp = QString(getenv("XDG_CONFIG_DIRS")).split(":"); for(int i=0; i<tmp.length(); i++){ dirs << tmp[i]+"/lumina-mimeapps.list"; } for(int i=0; i<tmp.length(); i++){ dirs << tmp[i]+"/mimeapps.list"; } dirs << QString(getenv("XDG_DATA_HOME"))+"/applications/lumina-mimeapps.list" \ << QString(getenv("XDG_DATA_HOME"))+"/applications/mimeapps.list"; tmp = QString(getenv("XDG_DATA_DIRS")).split(":"); for(int i=0; i<tmp.length(); i++){ dirs << tmp[i]+"/applications/lumina-mimeapps.list"; } for(int i=0; i<tmp.length(); i++){ dirs << tmp[i]+"/applications/mimeapps.list"; } //Now go through all the files in order of priority until a default is found QString cdefault; QStringList white; //lists to keep track of during the search (black unused at the moment) for(int i=0; i<dirs.length() && cdefault.isEmpty(); i++){ if(!QFile::exists(dirs[i])){ continue; } QStringList info = LUtils::readFile(dirs[i]); if(info.isEmpty()){ continue; } QString workdir = dirs[i].section("/",0,-1); //just the directory int def = info.indexOf("[Default Applications]"); //find this line to start on if(def>=0){ for(int d=def+1; d<info.length(); d++){ if(info[d].startsWith("[")){ break; } //starting a new section now - finished with defaults if(info[d].contains(mime+"=")){ white << info[d].section("=",1,50).split(";"); break; } } } // Now check for any white-listed files in this work dir // find the full path to the file (should run even if nothing in this file) for(int w=0; w<white.length(); w++){ //First check for absolute paths to *.desktop file if( white[w].startsWith("/") ){ if( QFile::exists(white[w]) ){ cdefault=white[w]; break; } else{ white.removeAt(w); w--; } //invalid file path - remove it from the list } //Now check for relative paths to file (in current priority-ordered work dir) else if( QFile::exists(workdir+"/"+white[w]) ){ cdefault=workdir+"/"+white[w]; break; } } /* WRITTEN BUT UNUSED CODE FOR MIMETYPE ASSOCIATIONS //Skip using this because it is simply an alternate/unsupported standard that conflicts with the current mimetype database standards. It is better/faster to parse 1 or 2 database glob files rather than have to iterate through hundreds of *.desktop files *every* time you need to find an application if(addI<0 && remI<0){ //Simple Format: <mimetype>=<*.desktop file>;<*.desktop file>;..... // (usually only one desktop file listed) info = info.filter(mimetype+"="); //Load the listed default(s) for(int w=0; w<info.length(); w++){ white << info[w].section("=",1,50).split(";"); } }else{ //Non-desktop specific mimetypes file: has a *very* convoluted/inefficient algorithm (required by spec) if(addI<0){ addI = info.length(); } //no add section if(remI<0){ remI = info.length(); } // no remove section: //Whitelist items for(int a=addI+1; a!=remI && a<info.length(); a++){ if(info[a].contains(mimetype+"=")){ QStringList tmp = info[a].section("=",1,50).split(";"); for(int t=0; t<tmp.length(); t++){ if(!black.contains(tmp[t])){ white << tmp[t]; } //make sure this item is not on the black list } break; } } //Blacklist items for(int a=remI+1; a!=addI && a<info.length(); a++){ if(info[a].contains(mimetype+"=")){ black << info[a].section("=",1,50).split(";"); break;} } //STEPS 3/4 not written yet } //End of non-DE mimetypes file */ } //End loop over files return cdefault; }
bool Loader_obj::load_model_data(Model& mdl, QString path){ qDebug("Parsing obj file..."); QStringList pathlist = path.split("/",QString::KeepEmptyParts); //KeepEmptyParts QString model_name = pathlist.last(); qDebug("Model name: " + model_name.toUtf8()); //LOAD MESH DATA QFile file(path); if (!file.open (QIODevice::ReadOnly)) { qDebug("Model import: Error 1: Model file could not be loaded..."); return false; } QTextStream stream ( &file ); QString line; QString mtllib; QString current_mesh; QMap<QString,QVector<int> >mesh_faces; QMap<QString,QString> mesh_mtl; QMap<QString,Material* > mtln_mtl; QVector<Vector3> model_vertices; QVector<Vector3> model_vertex_normals; QVector<Vector3> model_vertex_texture_coordinates; while( !stream.atEnd() ) { line = stream.readLine(); QStringList list = line.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts if(!list.empty()){ if(list.first() == "mtllib"){ mtllib = list.last(); } else if(list.first() == "v"){ model_vertices.append(Vector3( list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat())); } else if(list.first() == "vn"){ model_vertex_normals.append(Vector3( list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat())); } else if(list.first() == "vt"){ model_vertex_texture_coordinates.append(Vector3( list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat())); } else if(list.first() == "g"){ current_mesh = list.value(1); } else if(list.first() == "usemtl"){ mesh_mtl[current_mesh] = list.value(1); } else if(list.first() == "f"){ QStringList face_part_1_list = list.value(1).split("/",QString::SkipEmptyParts); //SkipEmptyParts QStringList face_part_2_list = list.value(2).split("/",QString::SkipEmptyParts); //SkipEmptyParts QStringList face_part_3_list = list.value(3).split("/",QString::SkipEmptyParts); //SkipEmptyParts mesh_faces[current_mesh].append(face_part_1_list.value(0).toInt()); mesh_faces[current_mesh].append(face_part_1_list.value(1).toInt()); mesh_faces[current_mesh].append(face_part_1_list.value(2).toInt()); mesh_faces[current_mesh].append(face_part_2_list.value(0).toInt()); mesh_faces[current_mesh].append(face_part_2_list.value(1).toInt()); mesh_faces[current_mesh].append(face_part_2_list.value(2).toInt()); mesh_faces[current_mesh].append(face_part_3_list.value(0).toInt()); mesh_faces[current_mesh].append(face_part_3_list.value(1).toInt()); mesh_faces[current_mesh].append(face_part_3_list.value(2).toInt()); } } } file.close(); //LOAD MTL DATA pathlist.removeAt(pathlist.length()-1); QString mtl_path = pathlist.join("/") + "/" + mtllib; QString tex_path = pathlist.join("/") + "/"; QFile mtlfile(mtl_path); if (!mtlfile.open (QIODevice::ReadOnly)) { qDebug("Model import: Error 2: Model material file could not be loaded..."); return false; } QTextStream mtlstream ( &mtlfile ); QString mtlline; QString current_mtl; QMap<QString,Vector3> mtl_ambient_c; //Ka QMap<QString,Vector3> mtl_diffuse_c; //Kd QMap<QString,Vector3> mtl_specular_c; //Ks QMap<QString,float> mtl_specular_ns; //Ns QMap<QString,float> mtl_transparency_d; //d QMap<QString,float> mtl_transparency_tr; //Tr QMap<QString,Vector3> mtl_transparency_tf; //Tf QMap<QString,QString> mtl_ambient_map; //map_Ka QMap<QString,QString> mtl_diffuse_map; //map_Kd QMap<QString,QString> mtl_specular_map; //map_Ks QMap<QString,QString> mtl_bump_map; //map_bump QMap<QString,int> mtl_illumination; //illum while( !mtlstream.atEnd() ) { mtlline = mtlstream.readLine(); QStringList list = mtlline.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts if(!list.empty()){ if(list.first() == "newmtl"){ current_mtl = list.last(); } else if(list.first() == "Ka"){ mtl_ambient_c[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "Kd"){ mtl_diffuse_c[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "Ks"){ mtl_specular_c[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "Ns"){ mtl_specular_ns[current_mtl] = list.value(1).toFloat(); } else if(list.first() == "d"){ mtl_transparency_d[current_mtl] = list.value(1).toFloat(); } else if(list.first() == "Tr"){ mtl_transparency_tr[current_mtl] = list.value(1).toFloat(); } else if(list.first() == "Tf"){ mtl_transparency_tf[current_mtl] = Vector3(list.value(1).toFloat(), list.value(2).toFloat(), list.value(3).toFloat()); } else if(list.first() == "map_Ka"){ mtl_ambient_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if(list.first() == "map_Kd"){ mtl_diffuse_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if(list.first() == "map_Ks"){ mtl_specular_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if((list.first() == "map_bump") || (list.first() == "bump")){ mtl_bump_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8(); } else if(list.first() == "illum"){ mtl_illumination[current_mtl] = list.value(1).toInt(); } } } return true; }
/** * @brief creating new transfer * * @param m_strURIs transfers urls * @param downloadTrueUploadFalse boolean value for download or upload * @param m_nClass download type default -1 * @param m_strDestination destination fo transfer * @param m_nDownLimit down limit of transfer * @param m_nUpLimit up limit of transfer * @param m_bPaused boolean true if transfer is paused */ void TransfersMethods::createTransfer(QString m_strURIs,bool downloadTrueUploadFalse,int m_nClass,QString m_strDestination, int m_nDownLimit,int m_nUpLimit,bool m_bPaused) { Queue* queue = 0; QList<Transfer*> listTransfers; try { QStringList uris; uris = m_strURIs.split('\n', QString::SkipEmptyParts); if(uris.isEmpty()) throw RuntimeException(); for(int i=0;i<uris.size();i++) { QString trm = uris[i].trimmed(); if(trm.isEmpty()) { uris.removeAt(i); i--; } else uris[i] = trm; } int detectedClass = m_nClass; for(int i=0;i<uris.size();i++) { Transfer* d; int classID; if(m_nClass == -1) { Transfer::BestEngine eng; if(downloadTrueUploadFalse) eng = Transfer::bestEngine(uris[i], Transfer::Download); else eng = Transfer::bestEngine(m_strDestination, Transfer::Upload); if(eng.nClass < 0) throw RuntimeException(tr("Couldn't autodetect transfer type for \"%1\"").arg(uris[i])); else classID = eng.nClass; if(detectedClass == -1) detectedClass = classID; else if(detectedClass >= 0 && detectedClass != classID) detectedClass = -2; } else classID = m_nClass; Transfer::Mode myMode = downloadTrueUploadFalse ? Transfer::Download : Transfer::Upload;; d = Transfer::createInstance(myMode, classID); if(d == 0) throw RuntimeException(tr("Failed to create a class instance.")); listTransfers << d; QString source, destination; source = uris[i].trimmed(); destination = m_strDestination; d->setUrl( (myMode == Transfer::Download) ? source : destination); if(!m_auth.strUser.isEmpty()) { QString& obj = (myMode == Transfer::Download) ? source : destination; QUrl url = obj; if(url.userInfo().isEmpty()) { url.setUserName(m_auth.strUser); url.setPassword(m_auth.strPassword); } obj = url.toString(); } d->init(source, destination); d->setUserSpeedLimits(m_nDownLimit,m_nUpLimit); } if(m_bPaused) { foreach(Transfer* d, listTransfers) d->setState(Transfer::Waiting); } else { foreach(Transfer* d, listTransfers) d->setState(Transfer::Active); } g_queuesLock.lockForWrite(); queue = g_queues[0]; if(!queue) throw RuntimeException(tr("Internal error.")); queue->add(listTransfers); g_queuesLock.unlock(); } catch(const RuntimeException& e) { qDeleteAll(listTransfers); listTransfers.clear(); if(!e.what().isEmpty()) { qDebug() <<"Error: " + e.what(); } } Queue::saveQueuesAsync(); }
MainWindow::MainWindow() : MainWindowBase(0, "main window"), editPalette(palette()), previewPalette(palette()), previewstyle(0) { modified = true; desktopThemeName = tr("Desktop Settings (Default)"); QStringList gstyles = QStyleFactory::keys(); gstyles.sort(); gstylecombo->addItem(desktopThemeName); gstylecombo->setItemData(gstylecombo->findText(desktopThemeName), tr("Choose style and palette based on your desktop settings."), Qt::ToolTipRole); gstylecombo->insertStringList(gstyles); QSettings settings(QLatin1String("Trolltech")); settings.beginGroup(QLatin1String("Qt")); QString currentstyle = settings.value(QLatin1String("style")).toString(); if (currentstyle.isEmpty()) { gstylecombo->setCurrentItem(gstylecombo->findText(desktopThemeName)); currentstyle = QLatin1String(QApplication::style()->name()); } else { int index = gstylecombo->findText(currentstyle, Qt::MatchFixedString); if (index != -1) { gstylecombo->setCurrentItem(index); } else { // we give up gstylecombo->insertItem(QLatin1String("Unknown")); gstylecombo->setCurrentItem(gstylecombo->count() - 1); } } buttonMainColor->setColor(palette().color(QPalette::Active, QColorGroup::Button)); buttonMainColor2->setColor(palette().color(QPalette::Active, QColorGroup::Window)); connect(buttonMainColor, SIGNAL(colorChanged(QColor)), this, SLOT(buildPalette())); connect(buttonMainColor2, SIGNAL(colorChanged(QColor)), this, SLOT(buildPalette())); if (X11->desktopEnvironment == DE_KDE) colorConfig->hide(); else labelKDENote->hide(); QFontDatabase db; QStringList families = db.families(); familycombo->insertStringList(families); QStringList fs = families; QStringList fs2 = QFont::substitutions(); QStringList::Iterator fsit = fs2.begin(); while (fsit != fs2.end()) { if (! fs.contains(*fsit)) fs += *fsit; fsit++; } fs.sort(); familysubcombo->insertStringList(fs); choosesubcombo->insertStringList(families); Q3ValueList<int> sizes = db.standardSizes(); Q3ValueList<int>::Iterator it = sizes.begin(); while (it != sizes.end()) psizecombo->insertItem(QString::number(*it++)); dcispin->setValue(QApplication::doubleClickInterval()); cfispin->setValue(QApplication::cursorFlashTime()); wslspin->setValue(QApplication::wheelScrollLines()); // ############# // resolvelinks->setChecked(qt_resolve_symlinks); effectcheckbox->setChecked(QApplication::isEffectEnabled(Qt::UI_General)); effectbase->setEnabled(effectcheckbox->isChecked()); if (QApplication::isEffectEnabled(Qt::UI_FadeMenu)) menueffect->setCurrentItem(2); else if (QApplication::isEffectEnabled(Qt::UI_AnimateMenu)) menueffect->setCurrentItem(1); if (QApplication::isEffectEnabled(Qt::UI_AnimateCombo)) comboeffect->setCurrentItem(1); if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip)) tooltipeffect->setCurrentItem(2); else if (QApplication::isEffectEnabled(Qt::UI_AnimateTooltip)) tooltipeffect->setCurrentItem(1); if ( QApplication::isEffectEnabled( Qt::UI_AnimateToolBox ) ) toolboxeffect->setCurrentItem( 1 ); QSize globalStrut = QApplication::globalStrut(); strutwidth->setValue(globalStrut.width()); strutheight->setValue(globalStrut.height()); // find the default family QStringList::Iterator sit = families.begin(); int i = 0, possible = -1; while (sit != families.end()) { if (*sit == QApplication::font().family()) break; if ((*sit).contains(QApplication::font().family())) possible = i; i++; sit++; } if (sit == families.end()) i = possible; if (i == -1) // no clue about the current font i = 0; familycombo->setCurrentItem(i); QStringList styles = db.styles(familycombo->currentText()); stylecombo->insertStringList(styles); QString stylestring = db.styleString(QApplication::font()); sit = styles.begin(); i = 0; possible = -1; while (sit != styles.end()) { if (*sit == stylestring) break; if ((*sit).contains(stylestring)) possible = i; i++; sit++; } if (sit == styles.end()) i = possible; if (i == -1) // no clue about the current font i = 0; stylecombo->setCurrentItem(i); i = 0; for (int psize = QApplication::font().pointSize(); i < psizecombo->count(); ++i) { const int sz = psizecombo->text(i).toInt(); if (sz == psize) { psizecombo->setCurrentItem(i); break; } else if(sz > psize) { psizecombo->insertItem(i, QString::number(psize)); psizecombo->setCurrentItem(i); break; } } QStringList subs = QFont::substitutes(familysubcombo->currentText()); sublistbox->clear(); sublistbox->insertStringList(subs); rtlExtensions->setChecked(settings.value(QLatin1String("useRtlExtensions"), false).toBool()); #ifdef Q_WS_X11 inputStyle->setCurrentText(settings.value(QLatin1String("XIMInputStyle"), trUtf8("On The Spot")).toString()); #else inputStyle->hide(); inputStyleLabel->hide(); #endif #if defined(Q_WS_X11) && !defined(QT_NO_XIM) QStringList inputMethods = QInputContextFactory::keys(); int inputMethodIndex = -1; QString defaultInputMethod = settings.value(QLatin1String("DefaultInputMethod"), QLatin1String("xim")).toString(); for (int i = inputMethods.size()-1; i >= 0; --i) { const QString &im = inputMethods.at(i); if (im.contains(QLatin1String("imsw"))) { inputMethods.removeAt(i); if (inputMethodIndex > i) --inputMethodIndex; } else if (im == defaultInputMethod) { inputMethodIndex = i; } } if (inputMethodIndex == -1 && !inputMethods.isEmpty()) inputMethodIndex = 0; inputMethod->addItems(inputMethods); inputMethod->setCurrentIndex(inputMethodIndex); #else inputMethod->hide(); inputMethodLabel->hide(); #endif fontembeddingcheckbox->setChecked(settings.value(QLatin1String("embedFonts"), true).toBool()); fontpaths = settings.value(QLatin1String("fontPath")).toStringList(); fontpathlistbox->insertStringList(fontpaths); audiosinkCombo->addItem(tr("Auto (default)"), QLatin1String("Auto")); audiosinkCombo->setItemData(audiosinkCombo->findText(tr("Auto (default)")), tr("Choose audio output automatically."), Qt::ToolTipRole); audiosinkCombo->addItem(tr("aRts"), QLatin1String("artssink")); audiosinkCombo->setItemData(audiosinkCombo->findText(tr("aRts")), tr("Experimental aRts support for GStreamer."), Qt::ToolTipRole); #ifndef QT_NO_GSTREAMER phononVersionLabel->setText(QLatin1String(Phonon::phononVersion())); if (gst_init_check(0, 0, 0)) { gchar *versionString = gst_version_string(); gstversionLabel->setText(QLatin1String(versionString)); g_free(versionString); GList* factoryList = gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY); QString name, klass, description; for (GList* iter = g_list_first(factoryList) ; iter != NULL ; iter = g_list_next(iter)) { GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data); klass = QLatin1String(gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature))); if (klass == QLatin1String("Sink/Audio")) { name = QLatin1String(GST_PLUGIN_FEATURE_NAME(feature)); if (name == QLatin1String("sfsink")) continue; //useless to output audio to file when you cannot set the file path else if (name == QLatin1String("autoaudiosink")) continue; //This is used implicitly from the auto setting GstElement *sink = gst_element_factory_make (qPrintable(name), NULL); if (sink) { description = QLatin1String(gst_element_factory_get_description (GST_ELEMENT_FACTORY(feature))); audiosinkCombo->addItem(name, name); audiosinkCombo->setItemData(audiosinkCombo->findText(name), description, Qt::ToolTipRole); gst_object_unref (sink); } } } g_list_free(factoryList); } #else tab4->setEnabled(false); phononLabel->setText(tr("Phonon GStreamer backend not available.")); #endif videomodeCombo->addItem(tr("Auto (default)"), QLatin1String("Auto")); videomodeCombo->setItemData(videomodeCombo->findText(tr("Auto (default)")), tr("Choose render method automatically"), Qt::ToolTipRole); #ifdef Q_WS_X11 videomodeCombo->addItem(tr("X11"), QLatin1String("X11")); videomodeCombo->setItemData(videomodeCombo->findText(tr("X11")), tr("Use X11 Overlays"), Qt::ToolTipRole); #endif #ifndef QT_NO_OPENGL videomodeCombo->addItem(tr("OpenGL"), QLatin1String("OpenGL")); videomodeCombo->setItemData(videomodeCombo->findText(tr("OpenGL")), tr("Use OpenGL if avaiable"), Qt::ToolTipRole); #endif videomodeCombo->addItem(tr("Software"), QLatin1String("Software")); videomodeCombo->setItemData(videomodeCombo->findText(tr("Software")), tr("Use simple software rendering"), Qt::ToolTipRole); QString audioSink = settings.value(QLatin1String("audiosink"), QLatin1String("Auto")).toString(); QString videoMode = settings.value(QLatin1String("videomode"), QLatin1String("Auto")).toString(); audiosinkCombo->setCurrentItem(audiosinkCombo->findData(audioSink)); videomodeCombo->setCurrentItem(videomodeCombo->findData(videoMode)); settings.endGroup(); // Qt helpview->setText(tr(appearance_text)); setModified(false); updateStyleLayout(); }
void ContTblPlugin::tblResult(DataBox *data, QString nameGene) // nameGene: "name-name" { data->dataClear(); QList<Gene> curGenes; QStringList lst = nameGene.split("-"); for (int i = 0; i < data->numGenes(); ++i) { for (int j = 0; j < lst.size(); ++j) { if (lst.at(j) == data->nameGene(i)) { curGenes.push_back(data->getGene(i)); lst.removeAt(j); break; } } } QHash<QString, int> uniqHAlleles; QHash<QString, int> uniqIAlleles; int allH = 0, allI = 0; int minAlleles = curGenes.at(0).alleles.size(); for (int i = 1; i < curGenes.size(); ++i) if (curGenes.at(i).alleles.size() < minAlleles) minAlleles = curGenes.at(i).alleles.size(); for (int i = 0; i < minAlleles; ++i) { if (!zeroAlleles(curGenes, i)) { QString al11, al22; for (int k = 0; k < curGenes.size(); ++k) { QStringList strlst; strlst = curGenes[k].alleles[i].allele.split(","); al11 += strlst[0] + ","; al22 += strlst[1] + ","; } al11.chop(1); al22.chop(1); if (uniqHAlleles.contains(al11)) { int numH = uniqHAlleles.value(al11); numH += curGenes[0].alleles[i].numHealthy.toInt(); // значения кол-ва здоровых у гена1 и гена2 одинаково uniqHAlleles.insert(al11, numH); } else { uniqHAlleles.insert(al11, curGenes[0].alleles[i].numHealthy.toInt()); } if (uniqHAlleles.contains(al22)) { int numH = uniqHAlleles.value(al22); numH += curGenes[0].alleles[i].numHealthy.toInt(); uniqHAlleles.insert(al22, numH); } else { uniqHAlleles.insert(al22, curGenes[0].alleles[i].numHealthy.toInt()); } if (uniqIAlleles.contains(al11)) { int numI = uniqIAlleles.value(al11); numI += curGenes[0].alleles[i].numIll.toInt(); uniqIAlleles.insert(al11, numI); } else { uniqIAlleles.insert(al11, curGenes[0].alleles[i].numIll.toInt()); } if (uniqIAlleles.contains(al22)) { int numI = uniqIAlleles.value(al22); numI += curGenes[0].alleles[i].numIll.toInt(); uniqIAlleles.insert(al22, numI); } else { uniqIAlleles.insert(al22, curGenes[0].alleles[i].numIll.toInt()); } } } QVector<QString> alleles; QVector<int> numH; QVector<int> numI; alleles = uniqHAlleles.keys().toVector(); qSort(alleles.begin(), alleles.end()); allH = 0; allI = 0; for (int i = 0; i < alleles.size(); ++i) { numH.push_back(uniqHAlleles.value(alleles[i])); numI.push_back(uniqIAlleles.value(alleles[i])); allH += numH.at(i); allI += numI.at(i); } data->setColumnCount(8); data->setRowCount(uniqHAlleles.size()); for (int i = 0; i < data->getRowCount(); ++i) { DataForAlleles var; for (int j = 0; j < data->getColumnCount(); ++j) { switch (j) { case 0: // наименование var.name = alleles[i]; break; case 1: // группа var.group = 1; break; case 2: // здоровые кол-во var.numHealthy = numH[i]; break; case 3: // больные кол-во var.numIll = numI[i]; break; case 4: // здоровые частота var.freakHealthy = (double)numH[i] / allH; break; case 5: // больные частота var.freakIll = (double)numI[i] / allI; break; case 6: // относ риск processRR(alleles[i], curGenes); var.RR = RR; break; case 7: // 95% интервал var.RRInt = confInt; break; default: qDebug() << "no columns to show"; } var.geneName = nameGene; } data->setDataToModel(var); } data->resetModel(); }
int Gui::getBOMParts( Where current, QStringList &pliParts) { bool partIgnore = false; bool pliIgnore = false; bool synthBegin = false; bool bfxStore1 = false; bool bfxStore2 = false; bool bfxLoad = false; bool partsAdded = false; QStringList bfxParts; Meta meta; skipHeader(current); QHash<QString, QStringList> bfx; int numLines = ldrawFile.size(current.modelName); Rc rc; for ( ; current.lineNumber < numLines; current.lineNumber++) { // scan through the rest of the model counting pages // if we've already hit the display page, then do as little as possible QString line = ldrawFile.readLine(current.modelName,current.lineNumber).trimmed(); if (line.startsWith("0 GHOST ")) { line = line.mid(8).trimmed(); } switch (line.toAscii()[0]) { case '1': if ( ! partIgnore && ! pliIgnore && ! synthBegin) { QStringList token; split(line,token); QString type = token[token.size()-1]; /* * Automatically ignore parts added twice due to buffer exchange */ bool removed = false; QString colorPart = token[1] + type; if (bfxStore2 && bfxLoad) { int i; for (i = 0; i < bfxParts.size(); i++) { if (bfxParts[i] == colorPart) { bfxParts.removeAt(i); removed = true; break; } } } if ( ! removed) { if (ldrawFile.contains(type)) { Where current2(type,0); getBOMParts(current2,pliParts); } else { pliParts << Pli::partLine(line,current,meta); } } if (bfxStore1) { bfxParts << colorPart; } partsAdded = true; } break; case '0': rc = meta.parse(line,current); /* substitute part/parts with this */ switch (rc) { case PliBeginSub1Rc: if (! pliIgnore && ! partIgnore && ! synthBegin) { QString line = QString("1 0 0 0 0 0 0 0 0 0 0 0 0 0 %1") .arg(meta.LPub.pli.begin.sub.value().part); pliParts << Pli::partLine(line,current,meta); pliIgnore = true; } break; /* substitute part/parts with this */ case PliBeginSub2Rc: if (! pliIgnore && ! partIgnore && ! synthBegin) { QString line = QString("1 %1 0 0 0 0 0 0 0 0 0 0 0 0 %2") .arg(meta.LPub.pli.begin.sub.value().color) .arg(meta.LPub.pli.begin.sub.value().part); pliParts << Pli::partLine(line,current,meta); pliIgnore = true; } break; case PliBeginIgnRc: pliIgnore = true; break; case PliEndRc: pliIgnore = false; break; case PartBeginIgnRc: partIgnore = true; break; case PartEndRc: partIgnore = false; break; case SynthBeginRc: synthBegin = true; break; case SynthEndRc: synthBegin = false; break; /* Buffer exchange */ case BufferStoreRc: bfxStore1 = true; bfxParts.clear(); break; case BufferLoadRc: bfxLoad = true; break; // Any of the metas that can change pliParts needs // to be processed here case ClearRc: pliParts.empty(); break; case MLCadGroupRc: pliParts << Pli::partLine(line,current,meta); break; /* remove a group or all instances of a part type */ case GroupRemoveRc: case RemoveGroupRc: case RemovePartRc: case RemoveNameRc: { QStringList newCSIParts; if (rc == RemoveGroupRc) { remove_group(pliParts,meta.LPub.remove.group.value(),newCSIParts); } else if (rc == RemovePartRc) { remove_parttype(pliParts, meta.LPub.remove.parttype.value(),newCSIParts); } else { remove_partname(pliParts, meta.LPub.remove.partname.value(),newCSIParts); } pliParts = newCSIParts; } break; case StepRc: if (partsAdded) { bfxStore2 = bfxStore1; bfxStore1 = false; bfxLoad = false; if ( ! bfxStore2) { bfxParts.clear(); } } partsAdded = false; break; default: break; } // switch break; } } // for every line return 0; }
int OpenAipPoiLoader::load( QList<Airfield>& airfieldList ) { // Set a global lock during execution to avoid calls in parallel. QMutexLocker locker( &m_mutexAf ); QTime t; t.start(); int loadCounter = 0; // number of successfully loaded files QString mapDir = MapContents::instance()->getMapRootDirectory() + "/points"; QStringList preselect; // Setup a filter for the desired file extensions. QString filter = "*_wpt.aip"; MapContents::addDir( preselect, mapDir, filter ); if( preselect.count() == 0 ) { qWarning( "OAIP: No airfield files found in the map directory!" ); return loadCounter; } // Check, which files shall be loaded. QStringList files = _settings.value( "/Points/FileList", QStringList(QString("All"))).toStringList(); if( files.isEmpty() ) { // No files shall be loaded qWarning() << "OAIP: No airfield files defined for loading by the user!"; return loadCounter; } if( files.first() != "All" ) { // Tidy up the preselection list, if not all found files shall be loaded. for( int i = preselect.size() - 1; i >= 0; i-- ) { QString file = QFileInfo(preselect.at(i)).fileName(); if( files.contains( file ) == false ) { preselect.removeAt(i); } } } while( ! preselect.isEmpty() ) { QString srcName; OpenAip openAip; QString errorInfo; srcName = preselect.first(); // Remove source file to be read from the list. preselect.removeAt(0); bool ok = openAip.readAirfields( srcName, airfieldList, errorInfo, true ); if( ok ) { loadCounter++; } } qDebug( "OAIP: %d airfield file(s) with %d items loaded in %dms", loadCounter, airfieldList.size(), t.elapsed() ); return loadCounter; }
QVariant QSystemLocale::query(QueryType type, QVariant in) const { QSystemLocaleData *d = qSystemLocaleData(); #if defined(Q_OS_QNX) QBBLocaleData *bbd = qbbLocaleData(); #endif const QLocale &lc_numeric = d->lc_numeric; const QLocale &lc_time = d->lc_time; const QLocale &lc_monetary = d->lc_monetary; const QLocale &lc_messages = d->lc_messages; switch (type) { case DecimalPoint: return lc_numeric.decimalPoint(); case GroupSeparator: return lc_numeric.groupSeparator(); case ZeroDigit: return lc_numeric.zeroDigit(); case NegativeSign: return lc_numeric.negativeSign(); case DateFormatLong: return lc_time.dateFormat(QLocale::LongFormat); case DateFormatShort: return lc_time.dateFormat(QLocale::ShortFormat); case TimeFormatLong: return lc_time.timeFormat(QLocale::LongFormat); case TimeFormatShort: return lc_time.timeFormat(QLocale::ShortFormat); case DayNameLong: return lc_time.dayName(in.toInt(), QLocale::LongFormat); case DayNameShort: return lc_time.dayName(in.toInt(), QLocale::ShortFormat); case MonthNameLong: return lc_time.monthName(in.toInt(), QLocale::LongFormat); case MonthNameShort: return lc_time.monthName(in.toInt(), QLocale::ShortFormat); case DateToStringLong: return lc_time.toString(in.toDate(), QLocale::LongFormat); case DateToStringShort: return lc_time.toString(in.toDate(), QLocale::ShortFormat); case TimeToStringLong: return lc_time.toString(in.toTime(), QLocale::LongFormat); case TimeToStringShort: return lc_time.toString(in.toTime(), QLocale::ShortFormat); case DateTimeFormatLong: return lc_time.dateTimeFormat(QLocale::LongFormat); case DateTimeFormatShort: return lc_time.dateTimeFormat(QLocale::ShortFormat); case DateTimeToStringLong: return lc_time.toString(in.toDateTime(), QLocale::LongFormat); case DateTimeToStringShort: return lc_time.toString(in.toDateTime(), QLocale::ShortFormat); case PositiveSign: return lc_numeric.positiveSign(); case AMText: return lc_time.amText(); case PMText: return lc_time.pmText(); case FirstDayOfWeek: return lc_time.firstDayOfWeek(); case CurrencySymbol: return lc_monetary.currencySymbol(QLocale::CurrencySymbolFormat(in.toUInt())); case CurrencyToString: { switch (in.type()) { case QVariant::Int: return lc_monetary.toCurrencyString(in.toInt()); case QVariant::UInt: return lc_monetary.toCurrencyString(in.toUInt()); case QVariant::Double: return lc_monetary.toCurrencyString(in.toDouble()); case QVariant::LongLong: return lc_monetary.toCurrencyString(in.toLongLong()); case QVariant::ULongLong: return lc_monetary.toCurrencyString(in.toULongLong()); default: break; } return QString(); } case MeasurementSystem: { const QString meas_locale = QString::fromLatin1(d->lc_measurement_var.constData(), d->lc_measurement_var.size()); if (meas_locale.compare(QLatin1String("Metric"), Qt::CaseInsensitive) == 0) return QLocale::MetricSystem; if (meas_locale.compare(QLatin1String("Other"), Qt::CaseInsensitive) == 0) return QLocale::MetricSystem; #if defined(Q_OS_QNX) return bbd->ppsMeasurement; #endif return QVariant((int)QLocale(meas_locale).measurementSystem()); } case UILanguages: { static QString languages = QString::fromLatin1(qgetenv("LANGUAGE")); if (!languages.isEmpty()) { QStringList lst = languages.split(QLatin1Char(':')); for (int i = 0; i < lst.size();) { const QString &name = lst.at(i); QString lang, script, cntry; if (name.isEmpty() || !qt_splitLocaleName(name, lang, script, cntry)) lst.removeAt(i); else ++i; } return lst; } if (!d->lc_messages_var.isEmpty()) { QString lang, script, cntry; if (qt_splitLocaleName(QString::fromLatin1(d->lc_messages_var.constData(), d->lc_messages_var.size()), lang, script, cntry)) { if (!cntry.length() && lang.length()) return QStringList(lang); return QStringList(lang % QLatin1Char('-') % cntry); } } return QVariant(); } case StringToStandardQuotation: return lc_messages.quoteString(in.value<QStringRef>()); case StringToAlternateQuotation: return lc_messages.quoteString(in.value<QStringRef>(), QLocale::AlternateQuotation); case ListToSeparatedString: return lc_messages.createSeparatedList(in.value<QStringList>()); case LocaleChanged: d->updateLocale(); break; default: break; } return QVariant(); }
void LDesktop::UpdateBackground(){ //Get the current Background if(bgupdating || bgWindow==0){ return; } //prevent multiple calls to this at the same time bgupdating = true; if(DEBUG){ qDebug() << " - Update Desktop Background for screen:" << desktopnumber; } //Get the list of background(s) to show QStringList bgL = settings->value(DPREFIX+"background/filelist", QStringList()).toStringList(); //qDebug() << " - List:" << bgL << CBG; //Remove any invalid files for(int i=0; i<bgL.length(); i++){ if( (!QFile::exists(bgL[i]) && bgL[i]!="default" && !bgL[i].startsWith("rgb(") ) || bgL[i].isEmpty()){ bgL.removeAt(i); i--; } } if(bgL.isEmpty()){ bgL << "default"; } //always fall back on the default //Determine if the background needs to be changed //qDebug() << "BG List:" << bgL << oldBGL << CBG << bgtimer->isActive(); if(bgL==oldBGL && !CBG.isEmpty() && bgtimer->isActive()){ //No background change scheduled - just update the widget bgWindow->update(); bgupdating=false; return; } oldBGL = bgL; //save this for later //Determine which background to use next int index; if(CBG.isEmpty()){ index = ( qrand() % bgL.length() ); } //random first wallpaper else{ //Go to the next in the list index = bgL.indexOf(CBG); if(index < 0 || index >= bgL.length()-1){ index = 0; } //if invalid or last item in the list - go to first else{ index++; } //go to next } QString bgFile = bgL[index]; //Save this file as the current background CBG = bgFile; //qDebug() << " - Set Background to:" << CBG << index << bgL; if( (bgFile.toLower()=="default")){ bgFile = LOS::LuminaShare()+"desktop-background.jpg"; } //Now set this file as the current background QString style; QString format = settings->value(DPREFIX+"background/format","stretch").toString(); if(bgFile.startsWith("rgb(")){ style = "QWidget#bgWindow{ border-image: none; background-color: %1;}"; }else if( format == "center"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: center; background-repeat: no-repeat; }"; }else if( format == "topleft"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: top left; background-repeat: no-repeat; }"; }else if( format == "topright"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: top right; background-repeat: no-repeat; }"; }else if( format == "bottomleft"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: bottom left; background-repeat: no-repeat; }"; }else if( format == "bottomright"){ style = "QWidget#bgWindow{ background: black url(%1); background-position: bottom right; background-repeat: no-repeat; }"; }else if( format == "tile"){ style = "QWidget#bgWindow{ background-color: black; border-image:url(%1) repeat;}"; }else{ /* STRETCH*/ style = "QWidget#bgWindow{ background-color: black; border-image:url(%1) stretch;}"; } style = style.arg(bgFile); bgWindow->setStyleSheet(style); bgWindow->show(); //Now reset the timer for the next change (if appropriate) if(bgtimer->isActive()){ bgtimer->stop(); } if(bgL.length() > 1){ //get the length of the timer (in minutes) int min = settings->value(DPREFIX+"background/minutesToChange",5).toInt(); //restart the internal timer if(min > 0){ bgtimer->start(min*60000); //convert from minutes to milliseconds } } //Now update the panel backgrounds for(int i=0; i<PANELS.length(); i++){ PANELS[i]->update(); PANELS[i]->show(); } bgupdating=false; }
//=========== // PUBLIC SLOTS //=========== void LPanel::UpdatePanel(){ //Create/Update the panel as designated in the Settings file settings->sync(); //make sure to catch external settings changes //First set the geometry of the panel and send the EWMH message to reserve that space if(DEBUG){ qDebug() << "Update Panel"; } hidden = settings->value(PPREFIX+"hidepanel",false).toBool(); //default to true for the moment QString loc = settings->value(PPREFIX+"location","").toString().toLower(); if(loc.isEmpty() && defaultpanel){ loc="top"; } if(loc=="top" || loc=="bottom"){ horizontal=true; layout->setAlignment(Qt::AlignLeft); layout->setDirection(QBoxLayout::LeftToRight); }else{ horizontal=false; layout->setAlignment(Qt::AlignTop); layout->setDirection(QBoxLayout::TopToBottom); } int ht = settings->value(PPREFIX+"height", 30).toInt(); //this is technically the distance into the screen from the edge int hidesize = qRound(ht*0.01); //use 1% of the panel size if(hidesize<2){ hidesize=2; } //minimum of 2 pixels (need space for the mouse to go over it) if(hidden){ viswidth = hidesize; } else{ viswidth = ht; } if(DEBUG){ qDebug() << "Hidden Panel size:" << hidesize << "pixels"; } //qDebug() << " - set Geometry"; int xwid = screen->screenGeometry(screennum).width(); int xhi = screen->screenGeometry(screennum).height(); int xloc = screen->screenGeometry(screennum).x(); double panelPercent = settings->value(PPREFIX+"lengthPercent",100).toInt(); if(panelPercent<1 || panelPercent>100){ panelPercent = 100; } panelPercent = panelPercent/100.0; QString panelPinLoc = settings->value(PPREFIX+"pinLocation","center").toString().toLower(); //[left/right/center] possible values (assume center otherwise) //xloc=xoffset; if(loc=="top"){ //top of screen QSize sz = QSize(xwid*panelPercent, ht); if(panelPinLoc=="left"){} // no change to xloc else if(panelPinLoc=="right"){ xloc = xloc+xwid-sz.width(); } else{ xloc = xloc+((xwid-sz.width())/2) ; } //centered this->setMinimumSize(sz); this->setMaximumSize(sz); this->setGeometry(xloc,0,sz.width(), sz.height()); if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc, 0, this->width(), ht, "top"); } else{ LX11::ReservePanelLocation(this->winId(), xloc, 0, this->width(), hidesize, "top"); hidepoint = QPoint(xloc, hidesize-ht); showpoint = QPoint(xloc, 0); this->move(hidepoint); //Could bleed over onto the screen above } }else if(loc=="bottom"){ //bottom of screen QSize sz = QSize(xwid*panelPercent, ht); if(panelPinLoc=="left"){} // no change to xloc else if(panelPinLoc=="right"){ xloc = xloc+xwid-sz.width(); } else{ xloc = xloc+((xwid-sz.width())/2) ; } //centered this->setMinimumSize(sz); this->setMaximumSize(sz); this->setGeometry(xloc,xhi-ht,sz.width(), ht ); if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc, xhi-ht, this->width(), ht, "bottom"); } else{ LX11::ReservePanelLocation(this->winId(), xloc, xhi-hidesize, this->width(), hidesize, "bottom"); hidepoint = QPoint(xloc, xhi-hidesize); showpoint = QPoint(xloc, xhi-ht); this->move(hidepoint); //Could bleed over onto the screen below } }else if(loc=="left"){ //left side of screen QSize sz = QSize(ht, xhi*panelPercent); int yloc = 0; if(panelPinLoc=="left"){} //this is actually the top (left of center in length dimension) else if(panelPinLoc=="right"){ yloc = yloc+xhi-sz.height(); } else{ yloc = yloc+((xhi-sz.height())/2) ; } //centered this->setMinimumSize(sz); this->setMaximumSize(sz); this->setGeometry(xloc,yloc, ht, sz.height()); if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc, yloc, ht, sz.height(), "left"); } else{ LX11::ReservePanelLocation(this->winId(), xloc, yloc, hidesize, sz.height(), "left"); hidepoint = QPoint(xloc-ht+hidesize, yloc); showpoint = QPoint(xloc, yloc); this->move(hidepoint); //Could bleed over onto the screen left } }else{ //right side of screen QSize sz = QSize(ht, xhi*panelPercent); int yloc = 0; if(panelPinLoc=="left"){} //this is actually the top (left of center in length dimension) else if(panelPinLoc=="right"){ yloc = yloc+xhi-sz.height(); } else{ yloc = yloc+((xhi-sz.height())/2) ; } //centered this->setMinimumSize(sz); this->setMaximumSize(sz); this->setGeometry(xloc+xwid-ht,yloc,ht, sz.height()); if(!hidden){ LX11::ReservePanelLocation(this->winId(), xloc+xwid-ht, yloc, ht, sz.height(), "right"); } else{ LX11::ReservePanelLocation(this->winId(), xloc+xwid-hidesize, yloc, hidesize, sz.height(), "right"); hidepoint = QPoint(xloc+xwid-hidesize, yloc); showpoint = QPoint(xloc+xwid-ht, yloc); this->move(hidepoint); //Could bleed over onto the screen right } } //With QT5, we need to make sure to reset window properties on occasion //LSession::handle()->XCB->SetAsSticky(this->winId()); //LX11::SetAsPanel(this->winId()); //First test/update all the window attributes as necessary //if(!this->testAttribute(Qt::WA_X11DoNotAcceptFocus)){ this->setAttribute(Qt::WA_X11DoNotAcceptFocus); } //if(!this->testAttribute(Qt::WA_X11NetWmWindowTypeDock)){ this->setAttribute(Qt::WA_X11NetWmWindowTypeDock); } //if(!this->testAttribute(Qt::WA_AlwaysShowToolTips)){ this->setAttribute(Qt::WA_AlwaysShowToolTips); } //Now update the appearance of the toolbar if(settings->value(PPREFIX+"customcolor", false).toBool()){ QString color = settings->value(PPREFIX+"color", "rgba(255,255,255,160)").toString(); QString style = "QWidget#LuminaPanelColor{ background: %1; border-radius: 3px; border: 1px solid %1; }"; style = style.arg(color); panelArea->setStyleSheet(style); }else{ panelArea->setStyleSheet(""); //clear it and use the one from the theme } //Then go through the plugins and create them as necessary QStringList plugins = settings->value(PPREFIX+"pluginlist", QStringList()).toStringList(); if(defaultpanel && plugins.isEmpty()){ plugins << "userbutton" << "taskmanager" << "spacer" << "systemtray" << "clock" << "systemdashboard"; } if(DEBUG){ qDebug() << " - Initialize Plugins: " << plugins; } for(int i=0; i<plugins.length(); i++){ //Ensure this plugin has a unique ID (NOTE: this numbering does not persist between sessions) if(!plugins[i].contains("---")){ int num=1; while( plugins.contains(plugins[i]+"---"+QString::number(screennum)+"."+QString::number(this->number())+"."+QString::number(num)) ){ num++; } plugins[i] = plugins[i]+"---"+QString::number(screennum)+"."+QString::number(this->number())+"."+QString::number(num); //qDebug() << "Adjust Plugin ID:" << plugins[i]; } //See if this plugin is already there or in a different spot bool found = false; for(int p=0; p<PLUGINS.length(); p++){ if(PLUGINS[p]->type()==plugins[i]){ found = true; //already exists //Make sure the plugin layout has the correct orientation if(horizontal){PLUGINS[p]->layout()->setDirection(QBoxLayout::LeftToRight); } else{ PLUGINS[p]->layout()->setDirection(QBoxLayout::TopToBottom); } QTimer::singleShot(0,PLUGINS[p], SLOT( OrientationChange() ) ); //Now check the location of the plugin in the panel if(p!=i){ //wrong place in the panel layout->takeAt(p); //remove the item from the current location layout->insertWidget(i, PLUGINS[p]); //add the item into the correct location PLUGINS.move(p,i); //move the identifier in the list to match } break; } } if(!found){ //New Plugin if(DEBUG){ qDebug() << " -- New Plugin:" << plugins[i] << i; } LPPlugin *plug = NewPP::createPlugin(plugins[i], panelArea, horizontal); if(plug != 0){ PLUGINS.insert(i, plug); layout->insertWidget(i, PLUGINS[i]); }else{ //invalid plugin type plugins.removeAt(i); //remove this invalid plugin from the list i--; //make sure we don't miss the next item with the re-order } } LSession::processEvents(); } //Now remove any extra plugins from the end //qDebug() << "plugins:" << plugins; //qDebug() << "PLUGINS length:" << PLUGINS.length(); for(int i=0; i<PLUGINS.length(); i++){ if(plugins.contains(PLUGINS[i]->type())){ continue; } //good plugin - skip it if(DEBUG){ qDebug() << " -- Remove Plugin: " << PLUGINS[i]->type(); } //If this is the system tray - stop it first if( PLUGINS[i]->type().startsWith("systemtray---") ){ static_cast<LSysTray*>(PLUGINS[i])->stop(); } layout->takeAt(i); //remove from the layout delete PLUGINS.takeAt(i); //delete the actual widget LSession::processEvents(); i--; //need to back up one space to not miss another plugin } this->update(); this->show(); //make sure the panel is visible now if(hidden){ this->move(hidepoint); } //Now go through and send the orientation update signal to each plugin for(int i=0; i<PLUGINS.length(); i++){ QTimer::singleShot(0,PLUGINS[i], SLOT(OrientationChange())); } LSession::processEvents(); }
//=========== // PUBLIC SLOTS //=========== void LPanel::UpdatePanel(){ //Create/Update the panel as designated in the Settings file settings->sync(); //make sure to catch external settings changes //First set the geometry of the panel and send the EWMH message to reserve that space qDebug() << "Update Panel"; QString loc = settings->value(PPREFIX+"location","").toString(); if(loc.isEmpty() && defaultpanel){ loc="top"; } int ht = settings->value(PPREFIX+"height", 22).toInt(); int xoffset=0; for(int i=0; i<screennum; i++){ xoffset = xoffset + screen->screenGeometry(i).width(); } qDebug() << " - set Geometry"; if(loc=="top"){ this->setGeometry(xoffset,0,screen->screenGeometry(screennum).width(), ht ); LX11::ReservePanelLocation(this->winId(), xoffset, 0, this->width(), ht+2); }else{ this->setGeometry(xoffset,screen->screenGeometry(screennum).height()-ht,screen->screenGeometry(screennum).width(), ht ); LX11::ReservePanelLocation(this->winId(), xoffset, screen->screenGeometry(screennum).height()-ht, this->width(), ht+2); } //Now update the appearance of the toolbar QString color = settings->value(PPREFIX+"color", "rgb(255,250,250)").toString(); QString style = "QWidget#LuminaPanelWidget{ background: %1; }"; style = style.arg(color); this->setStyleSheet(style); //Then go through the plugins and create them as necessary QStringList plugins = settings->value(PPREFIX+"pluginlist", QStringList()).toStringList(); if(defaultpanel && plugins.isEmpty()){ plugins << "userbutton" << "desktopbar" << "spacer" << "clock"; }else if(defaultpanel && !plugins.contains("userbutton") ){ plugins.prepend("userbutton"); //make sure we have this button since that lets the user logout } qDebug() << " - Initialize Plugins: " << plugins; for(int i=0; i<plugins.length(); i++){ //See if this plugin is already there or in a different spot bool found = false; for(int p=0; p<PLUGINS.length(); p++){ if(PLUGINS[p]->type()==plugins[i]){ found = true; //already exists if(p!=i){ //wrong place in the panel layout->takeAt(p); //remove the item from the current location layout->insertWidget(i, PLUGINS[p]); //add the item into the correct location PLUGINS.move(p,i); //move the identifier in the list to match } break; } } if(!found){ //New Plugin qDebug() << " -- New Plugin:" << plugins[i]; LPPlugin *plug = NewPP::createPlugin(plugins[i]); if(plug != 0){ PLUGINS.insert(i, plug); layout->insertWidget(i, PLUGINS[i]); }else{ //invalid plugin type plugins.removeAt(i); //remove this invalid plugin from the list i--; //make sure we don't miss the next item with the re-order } } } //Now remove any extra plugins from the end for(int i=plugins.length(); i<PLUGINS.length(); i++){ qDebug() << " -- Remove Plugin: " << i; layout->takeAt(i); //remove from the layout delete PLUGINS.takeAt(i); //delete the actual widget } this->move(0,0); //this will trigger the move event and ensire that it is put in the proper spot this->show(); //make sure the panel is visible now }
int Option::parseCommandLine(QStringList &args, QMakeCmdLineParserState &state) { enum { ArgNone, ArgOutput } argState = ArgNone; int x = 0; while (x < args.count()) { switch (argState) { case ArgOutput: Option::output.setFileName(args.at(x--)); args.erase(args.begin() + x, args.begin() + x + 2); argState = ArgNone; continue; default: QMakeGlobals::ArgumentReturn cmdRet = globals->addCommandLineArguments(state, args, &x); if (cmdRet == QMakeGlobals::ArgumentsOk) break; if (cmdRet == QMakeGlobals::ArgumentMalformed) { fprintf(stderr, "***Option %s requires a parameter\n", qPrintable(args.at(x - 1))); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } Q_ASSERT(cmdRet == QMakeGlobals::ArgumentUnknown); QString arg = args.at(x); if (arg.startsWith(QLatin1Char('-'))) { if (arg == "-d") { Option::debug_level++; } else if (arg == "-v" || arg == "-version" || arg == "--version") { fprintf(stdout, "QMake version %s\n" "Using Qt version %s in %s\n", QMAKE_VERSION_STR, QT_VERSION_STR, QLibraryInfo::location(QLibraryInfo::LibrariesPath).toLatin1().constData()); #ifdef QMAKE_OPENSOURCE_VERSION fprintf(stdout, "QMake is Open Source software from Digia Plc and/or its subsidiary(-ies).\n"); #endif return Option::QMAKE_CMDLINE_BAIL; } else if (arg == "-h" || arg == "-help" || arg == "--help") { return Option::QMAKE_CMDLINE_SHOW_USAGE; } else if (arg == "-Wall") { Option::warn_level |= WarnAll; } else if (arg == "-Wparser") { Option::warn_level |= WarnParser; } else if (arg == "-Wlogic") { Option::warn_level |= WarnLogic; } else if (arg == "-Wdeprecated") { Option::warn_level |= WarnDeprecated; } else if (arg == "-Wnone") { Option::warn_level = WarnNone; } else if (arg == "-r" || arg == "-recursive") { Option::recursive = true; args.removeAt(x); continue; } else if (arg == "-nr" || arg == "-norecursive") { Option::recursive = false; args.removeAt(x); continue; } else if (arg == "-o" || arg == "-output") { argState = ArgOutput; } else { if (Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if (arg == "-nodepend" || arg == "-nodepends") { Option::mkfile::do_deps = false; } else if (arg == "-nomoc") { Option::mkfile::do_mocs = false; } else if (arg == "-createstub") { Option::mkfile::do_stub_makefile = true; } else if (arg == "-nodependheuristics") { Option::mkfile::do_dep_heuristics = false; } else if (arg == "-E") { Option::mkfile::do_preprocess = true; } else { fprintf(stderr, "***Unknown option %s\n", arg.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } else if (Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { if (arg == "-nopwd") { Option::projfile::do_pwd = false; } else { fprintf(stderr, "***Unknown option %s\n", arg.toLatin1().constData()); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } } } } else { bool handled = true; if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY || Option::qmake_mode == Option::QMAKE_SET_PROPERTY || Option::qmake_mode == Option::QMAKE_UNSET_PROPERTY) { Option::prop::properties.append(arg); } else { QFileInfo fi(arg); if(!fi.makeAbsolute()) //strange arg = fi.filePath(); if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(fi.isDir()) { QString proj = detectProjectFile(arg); if (!proj.isNull()) arg = proj; } Option::mkfile::project_files.append(arg); } else if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) { Option::projfile::project_dirs.append(arg); } else { handled = false; } } if(!handled) { return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } args.removeAt(x); continue; } } x++; } if (argState != ArgNone) { fprintf(stderr, "***Option %s requires a parameter\n", qPrintable(args.at(x - 1))); return Option::QMAKE_CMDLINE_SHOW_USAGE | Option::QMAKE_CMDLINE_ERROR; } return Option::QMAKE_CMDLINE_SUCCESS; }
void MusicLibrary::updateSongsInPath(QString path) { int pathid = -1; QSqlQuery query; QList<QString> *files = new QList<QString>(); QList<QString> dbFiles; QString fname; QStringList parts; QString title, artist; int x,pos; query.prepare("SELECT id FROM library_path WHERE path = ?"); query.addBindValue(path); query.exec(); while( query.next() ) { if( pathid != -1 ) { qDebug() << "Too many results for path!"; pathid = -1; break; } else { pathid = query.value("id").toInt(); } } if( pathid == -1 ) { qWarning() << "Directory" << path << "not found in database"; } qDebug() << "Working with path" << pathid; _scanFiles(files,path); qDebug() << "Found" << files->length() << "files"; query.prepare("SELECT file FROM song WHERE path = ?"); query.addBindValue(pathid); query.exec(); while( query.next() ) { dbFiles.append(query.value("file").toString()); } qDebug() << "Found" << dbFiles.length() << "songs in DB"; // ADD FILES THAT DON'T EXIST TO DATABASE for( x=0;x<files->length();x++ ) { fname = files->at(x); if( dbFiles.indexOf(fname) == -1 ) { if( fname.indexOf(" - ") == -1 ) { qWarning() << "Don't know how to parse" << fname; } else { parts = fname.split(" - "); artist = parts.at(0); pos = artist.lastIndexOf(QDir::separator()) + 1; artist = artist.right(artist.length() - pos); parts.removeAt(0); title = parts.join(" - "); title = title.replace(".mp3",""); title = title.replace(" [karaoke]",""); qDebug() << "Add" << fname << "(" << title << "by" << artist << "to database"; query.prepare("INSERT INTO song (path,artist,title,file) VALUES (?,?,?,?)"); query.addBindValue(pathid); query.addBindValue(artist); query.addBindValue(title); query.addBindValue(fname); if( !query.exec() ) { qWarning() << "Insert error:" << query.executedQuery(); } } } } }