void Media::TextRecordingPrivate::insertNewMessage(const QMap<QString,QString>& message, ContactMethod* cm, Media::Media::Direction direction) { //Only create it if none was found on the disk if (!m_pCurrentGroup) { m_pCurrentGroup = new Serializable::Group(); auto cMethod = q_ptr->call() ? q_ptr->call()->peerContactMethod() : cm; Serializable::Peers* p = SerializableEntityManager::peer(cMethod); if (m_lAssociatedPeers.indexOf(p) == -1) { m_lAssociatedPeers << p; } p->groups << m_pCurrentGroup; } //Create the message time_t currentTime; ::time(¤tTime); Serializable::Message* m = new Serializable::Message(); m->timestamp = currentTime ; m->direction = direction ; m->type = Serializable::Message::Type::CHAT; m->authorSha1= cm->sha1() ; if (direction == Media::Media::Direction::OUT) m->isRead = true; // assume outgoing messages are read, since we're sending them QMapIterator<QString, QString> iter(message); while (iter.hasNext()) { iter.next(); if (iter.value() != QLatin1String("application/resource-lists+xml")) { //This one is useless const QString mimeType = iter.key(); Serializable::Payload* p = new Serializable::Payload(); p->mimeType = mimeType ; p->payload = iter.value(); m->payloads << p; if (p->mimeType == QLatin1String("text/plain")) { m->m_PlainText = p->payload; m->m_HasText = true; } else if (p->mimeType == QLatin1String("text/html")) { m->m_HTML = p->payload; m->m_HasText = true; } // Make the clients life easier and tell the payload type const int hasArgs = mimeType.indexOf(';'); const QString strippedMimeType = hasArgs != -1 ? mimeType.left(hasArgs) : mimeType; const int currentSize = m_hMimeTypes.size(); m_hMimeTypes[strippedMimeType] = true; if (currentSize != m_hMimeTypes.size()) m_lMimeTypes << strippedMimeType; } } m_pCurrentGroup->messages << m; //Make sure the model exist q_ptr->instantMessagingModel(); //Update the reconstructed conversation ::TextMessageNode* n = new ::TextMessageNode() ; n->m_pMessage = m ; n->m_pContactMethod = const_cast<ContactMethod*>(cm); m_pImModel->addRowBegin(); m_lNodes << n; m_pImModel->addRowEnd(); //Save the conversation q_ptr->save(); cm->setLastUsed(currentTime); emit q_ptr->messageInserted(message, const_cast<ContactMethod*>(cm), direction); if (!m->isRead) { m_UnreadCount += 1; emit q_ptr->unreadCountChange(1); emit cm->unreadTextMessageCountChanged(); emit cm->changed(); } }
// TODO: refactor this! void RuleParser::parsePropertyChange(QString const &stream, int &pos, QHash<Id, Id> const &mMatch) { QString const name = parseElemName(stream, pos); if (hasErrors()) { return; } QString const prop = parseElemProperty(stream, pos); if (hasErrors()) { return; } pos++; skip(stream, pos); if (!checkForEqual(stream, pos)) { return; } pos++; skip(stream, pos); if (stream.mid(pos, 5) == "cond(") { pos += 5; skip(stream, pos); QString const condName = parseElemName(stream, pos); if (hasErrors()) { return; } QString const condProperty = parseElemProperty(stream, pos); if (hasErrors()) { return; } checkForClosingBracketAndColon(stream, pos); Id const condId = elementByName(condName, mMatch); if (condId == Id::rootId()) { error(unknownElementName); return; } int position = 0; bool value = parseCondition(property(condId, condProperty).toString(), position, condId); Id const id = elementByName(name, mMatch); if (id == Id::rootId()) { error(unknownElementName); return; } setProperty(id, prop, QString(value ? "true" : "false")); mCurrentId = mRuleId; return; } if (stream.at(pos).toLatin1() == '"') { pos++; QString const value = stream.mid(pos, stream.indexOf("\"", pos) - pos); pos += value.length(); if (stream.at(pos).toLatin1() != '"') { error(unexpectedSymbol, QString::number(pos) , "\"", QString(stream.at(pos).toLatin1())); return; } Id const id = elementByName(name, mMatch); if (id == Id::rootId()) { error(unknownElementName); return; } setProperty(id, prop, value); pos++; skip(stream, pos); if (!checkForColon(stream, pos)) { return; } pos++; return; } if (checkForLogicalConst(stream, pos)) { int len = 0; QString value = ""; if (stream.mid(pos, 4) == "true") { len = 4; value = "true"; } if (stream.mid(pos, 5) == "false") { len = 5; value = "false"; } QChar c = stream.at(pos + len).toLatin1(); if (!isDigit(c) && !isLetter(c)) { pos += len; skip(stream, pos); if (!checkForColon(stream, pos)) { return; } pos++; Id const id = elementByName(name, mMatch); if (id == Id::rootId()) { error(unknownElementName); return; } setProperty(id, prop, value); return; } } if (stream.mid(pos, 4) == "null") { pos += 4; skip(stream, pos); if (!checkForColon(stream, pos)) { return; } pos++; Id const elem = elementByName(name, mMatch); if (elem == Id::rootId()) { error(unknownElementName); return; } setProperty(elem, prop, QVariant(property(elem, prop).type())); return; } if ((stream.indexOf("=", pos) > pos && stream.indexOf("=", pos) < stream.indexOf(";", pos)) || (stream.indexOf("<", pos) > pos && stream.indexOf("<", pos) < stream.indexOf(";", pos)) || (stream.indexOf(">", pos) > pos && stream.indexOf(">", pos) < stream.indexOf(";", pos))) { bool result = parseConditionHelper(stream, pos); if (hasErrors()) { return; } skip(stream, pos); if (!checkForColon(stream, pos)) { return; } pos++; Id const id = elementByName(name, mMatch); if (id == Id::rootId()) { error(unknownElementName); return; } setProperty(id, prop, QString(result ? "true" : "false")); } else { Number result = parseExpression(stream, pos); if (hasErrors()) { return; } skip(stream, pos); if (!checkForColon(stream, pos)) { return; } pos++; Id const id = elementByName(name, mMatch); if (id == Id::rootId()) { error(unknownElementName); return; } setProperty(id, prop, result.property("Number").toString()); } }
//MTL PARSER INSPIRED FROM KIXOR.NET "objloader" (http://www.kixor.net/dev/objloader/) bool ccMaterialSet::ParseMTL(QString path, const QString& filename, ccMaterialSet &materials, QStringList& errors) { //open mtl file QString fullPathFilename = path + QString('/') + filename; QFile file(fullPathFilename); if (!file.open(QFile::ReadOnly)) { errors << QString("Error reading file: %1").arg(filename); return false; } //update path (if the input filename has already a relative path) path = QFileInfo(fullPathFilename).absolutePath(); QTextStream stream(&file); QString currentLine = stream.readLine(); unsigned currentLineIndex = 0; ccMaterial::Shared currentMaterial(0); while( !currentLine.isNull() ) { ++currentLineIndex; QStringList tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts); //skip comments & empty lines if( tokens.empty() || tokens.front().startsWith('/',Qt::CaseInsensitive) || tokens.front().startsWith('#',Qt::CaseInsensitive) ) { currentLine = stream.readLine(); continue; } //start material if (tokens.front() == "newmtl") { //push the previous material (if any) if (currentMaterial) { materials.addMaterial(currentMaterial); currentMaterial = ccMaterial::Shared(0); } // get the name QString materialName = currentLine.mid(7).trimmed(); //we must take the whole line! (see OBJ filter) if (materialName.isEmpty()) materialName = "undefined"; currentMaterial = ccMaterial::Shared(new ccMaterial(materialName)); } else if (currentMaterial) //we already have a "current" material { //ambient if (tokens.front() == "Ka") { if (tokens.size() > 3) { ccColor::Rgbaf ambient( tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat(), 1.0f); currentMaterial->setAmbient(ambient); } } //diff else if (tokens.front() == "Kd") { if (tokens.size() > 3) { ccColor::Rgbaf diffuse( tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat(), 1.0f); currentMaterial->setDiffuse(diffuse); } } //specular else if (tokens.front() == "Ks") { if (tokens.size() > 3) { ccColor::Rgbaf specular(tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat(), 1.0f); currentMaterial->setSpecular(specular); } } //shiny else if (tokens.front() == "Ns") { if (tokens.size() > 1) currentMaterial->setShininess(tokens[1].toFloat()); } //transparent else if (tokens.front() == "d" || tokens.front() == "Tr") { if (tokens.size() > 1) currentMaterial->setTransparency(tokens[1].toFloat()); } //reflection else if (tokens.front() == "r") { //ignored //if (tokens.size() > 1) // currentMaterial->reflect = tokens[1].toFloat(); } //glossy else if (tokens.front() == "sharpness") { //ignored //if (tokens.size() > 1) // currentMaterial->glossy = tokens[1].toFloat(); } //refract index else if (tokens.front() == "Ni") { //ignored //if (tokens.size() > 1) // currentMaterial->refract_index = tokens[1].toFloat(); } // illumination type else if (tokens.front() == "illum") { //ignored } // texture map else if (tokens.front() == "map_Ka" || tokens.front() == "map_Kd" || tokens.front() == "map_Ks") { //DGM: in case there's hidden or space characters at the beginning of the line... int shift = currentLine.indexOf("map_K",0); QString textureFilename = (shift + 7 < currentLine.size() ? currentLine.mid(shift+7).trimmed() : QString()); QString fullTexName = path + QString('/') + textureFilename; if (!currentMaterial->loadAndSetTexture(fullTexName)) { errors << QString("Failed to load texture file: %1").arg(fullTexName); } } else { errors << QString("Unknown command '%1' at line %2").arg(tokens.front()).arg(currentLineIndex); } } currentLine = stream.readLine(); } file.close(); //don't forget to push the last material! if (currentMaterial) materials.addMaterial(currentMaterial); return true; }
QStringList CMakeProject::getCXXFlagsFor(const CMakeBuildTarget &buildTarget, QByteArray *cachedBuildNinja) { QString makeCommand = QDir::fromNativeSeparators(buildTarget.makeCommand); int startIndex = makeCommand.indexOf(QLatin1Char('\"')); int endIndex = makeCommand.indexOf(QLatin1Char('\"'), startIndex + 1); if (startIndex != -1 && endIndex != -1) { startIndex += 1; QString makefile = makeCommand.mid(startIndex, endIndex - startIndex); int slashIndex = makefile.lastIndexOf(QLatin1Char('/')); makefile.truncate(slashIndex); makefile.append(QLatin1String("/CMakeFiles/") + buildTarget.title + QLatin1String(".dir/flags.make")); QFile file(makefile); if (file.exists()) { file.open(QIODevice::ReadOnly | QIODevice::Text); QTextStream stream(&file); while (!stream.atEnd()) { QString line = stream.readLine().trimmed(); if (line.startsWith(QLatin1String("CXX_FLAGS ="))) { // Skip past = return line.mid(11).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts); } } } } // Attempt to find build.ninja file and obtain FLAGS (CXX_FLAGS) from there if no suitable flags.make were // found // Get "all" target's working directory if (!buildTargets().empty()) { if (cachedBuildNinja->isNull()) { QString buildNinjaFile = QDir::fromNativeSeparators(buildTargets().at(0).workingDirectory); buildNinjaFile += QLatin1String("/build.ninja"); QFile buildNinja(buildNinjaFile); if (buildNinja.exists()) { buildNinja.open(QIODevice::ReadOnly | QIODevice::Text); *cachedBuildNinja = buildNinja.readAll(); buildNinja.close(); } else { *cachedBuildNinja = QByteArray(); } } if (cachedBuildNinja->isEmpty()) return QStringList(); QTextStream stream(cachedBuildNinja); bool targetFound = false; bool cxxFound = false; QString targetSearchPattern = QString::fromLatin1("target %1").arg(buildTarget.title); while (!stream.atEnd()) { // 1. Look for a block that refers to the current target // 2. Look for a build rule which invokes CXX_COMPILER // 3. Return the FLAGS definition QString line = stream.readLine().trimmed(); if (line.startsWith(QLatin1String("#"))) { if (!line.startsWith(QLatin1String("# Object build statements for"))) continue; targetFound = line.endsWith(targetSearchPattern); } else if (targetFound && line.startsWith(QLatin1String("build"))) { cxxFound = line.indexOf(QLatin1String("CXX_COMPILER")) != -1; } else if (cxxFound && line.startsWith(QLatin1String("FLAGS ="))) { // Skip past = return line.mid(7).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts); } } } return QStringList(); }
void NumberSegmentIdentification::init() { qDebug() <<"NumberSegmentIdentification Init."; allNotingNumbers.clear(); records.clear(); if( QFile::exists(fileNameforNSI)) { QFile file(fileNameforNSI); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<< "PhoneNumberIdentification,open fileNameforPNI fail."; } QTextStream out(&file); QString dataLine ; QString startNumber; struct NumberSegmentInformation numberSegmentInformation; //两条相邻的记录的两个起始号码之间构成一个号码段 numberSegmentInformation.startNumber = 0; //初始为0,为了判断是否已经收集完第1条记录,此时不为0 struct NumberSegmentInformation numberSegmentInformationTmp; while((dataLine=out.readLine()) != NULL) { //起始号码 int firstPosition = dataLine.indexOf(" "); if(firstPosition>0) { startNumber = dataLine.mid(0,firstPosition); qDebug()<< "startNumber is:"+startNumber; numberSegmentInformationTmp.startNumber = startNumber.toULongLong(); } else { // //格式不对,删除该行,继续解析 qDebug()<<"firstPosition <=0"; // continue; goto FormatError; } //状态 int secondPosition = dataLine.indexOf(" ",firstPosition+1); if(secondPosition>0) { numberSegmentInformationTmp.state = (IdentificationState)dataLine.mid(firstPosition+1,secondPosition-(firstPosition+1)).toInt(); qDebug()<< "state is:"+QString::number(numberSegmentInformationTmp.state); } else { // //格式不对,删除该行,继续解析 qDebug()<<"secondPosition <=0"; // continue; goto FormatError; } //记录的号码个数 int thirdPosition = dataLine.indexOf(" ",secondPosition+1); if(thirdPosition>0) { numberSegmentInformationTmp.count = dataLine.mid(secondPosition+1,thirdPosition-(secondPosition+1)).toInt(); qDebug()<< "count is:"+QString::number(numberSegmentInformationTmp.count); } else { //格式不对,删除该行,继续解析 qDebug()<<"thirdPosition <=0"; goto FormatError; } //提取记录的号码 int position1 = thirdPosition ; int position2 ; int count =numberSegmentInformationTmp.count; numberSegmentInformationTmp.Numbers.clear(); while(count) { position2 = dataLine.indexOf(" ",position1+1); if(position2>0) { numberSegmentInformationTmp.Numbers.append(dataLine.mid(position1+1,position2-(position1+1)).toULongLong()); allNotingNumbers.append(dataLine.mid(position1+1,position2-(position1+1)).toULongLong()); position1 = position2; } else { //格式不对,删除该行,继续解析 qDebug()<<"position2 <=0"; goto FormatError; } count--; } //号码段的结束号码 if(numberSegmentInformation.startNumber >0) { numberSegmentInformation.endNumber = numberSegmentInformationTmp.startNumber-1; records.insert( numberSegmentInformation.startNumber, numberSegmentInformation ); numberSegmentInformation = numberSegmentInformationTmp; } else { qDebug()<<"read first record"; numberSegmentInformation = numberSegmentInformationTmp; // qDebug() << "records start number:" + QString::number(numberSegmentInformation.startNumber)+ // ",end number:" + QString::number(numberSegmentInformation.endNumber)+ // ",state:" + QString::number(numberSegmentInformation.state)+ // ",count:" + QString::number(numberSegmentInformation.count); } continue; FormatError: qDebug()<<"NumberSegmentIdentification init ,格式不对"; } file.close(); } else { //文件不存在时的处理方法 qDebug()<< "PhoneNumberIdentification, fileNameforPNI no exists."; createNewNumberSegment(); } //显示结果 qDebug()<<"NumberSegmentIdentification init result."; // showresult(); saveKeyNumberSegments(); // for(int i=0;i<allNotingNumbers.count();i++) // { // qDebug()<<"allNotingNumbers " +QString::number(i) + " is :" + // QString::number(allNotingNumbers[i]); // } // QMapIterator<qulonglong,NumberSegmentInformation> iterator(records); // while(iterator.hasNext()) // { // iterator.next(); // qDebug() << "records start number:" + QString::number(iterator.value().startNumber)+ // ",end number:" + QString::number(iterator.value().endNumber)+ // ",state:" + QString::number(iterator.value().state)+ // ",count:" + QString::number(iterator.value().count); // } }
/*! Returns a Qt version of the given \a sys_fmt Symbian locale format string. */ static QString s60ToQtFormat(const QString &sys_fmt) { TLocale *locale = _s60Locale.GetLocale(); QString result; QString other; QString qtformatchars = QString::fromLatin1("adhmsyzAHM"); QChar c; int i = 0; bool open_escape = false; bool abbrev_next = false; bool locale_indep_ordering = false; bool minus_mode = false; bool plus_mode = false; bool n_mode = false; TTimeFormat tf = locale->TimeFormat(); while (i < sys_fmt.size()) { c = sys_fmt.at(i); // let formatting thru if (c.unicode() == '%') { // if we have gathered string, concat it if (!other.isEmpty()) { result += other; other.clear(); } // if we have open escape, end it if (open_escape) { result += QLatin1Char('\''); open_escape = false; } ++i; if (i >= sys_fmt.size()) break; c = sys_fmt.at(i); // process specials abbrev_next = c.unicode() == '*'; plus_mode = c.unicode() == '+'; minus_mode = c.unicode() == '-'; if (abbrev_next || plus_mode || minus_mode) { ++i; if (i >= sys_fmt.size()) break; c = sys_fmt.at(i); if (plus_mode || minus_mode) { // break on undefined plus/minus mode if (c.unicode() != 'A' && c.unicode() != 'B') break; } } switch (c.unicode()) { case 'F': { // locale indep mode on locale_indep_ordering = true; break; } case '/': { // date sep 0-3 ++i; if (i >= sys_fmt.size()) break; c = sys_fmt.at(i); if (c.isDigit() && c.digitValue() <= 3) { TChar s = locale->DateSeparator(c.digitValue()); TUint val = s; // some indexes return zero for empty if (val > 0) result += QChar(val); } break; } case 'D': { if (!locale_indep_ordering) break; if (!abbrev_next) result += QLatin1String("dd"); else result += QLatin1Char('d'); break; } case 'M': { if (!locale_indep_ordering) break; if (!n_mode) { if (!abbrev_next) result += QLatin1String("MM"); else result += QLatin1String("M"); } else { if (!abbrev_next) result += QLatin1String("MMMM"); else result += QLatin1String("MMM"); } break; } case 'N': { n_mode = true; if (!locale_indep_ordering) break; if (!abbrev_next) result += QLatin1String("MMMM"); else result += QLatin1String("MMM"); break; } case 'Y': { if (!locale_indep_ordering) break; if (!abbrev_next) result += QLatin1String("yyyy"); else result += QLatin1String("yy"); break; } case 'E': { if (!abbrev_next) result += QLatin1String("dddd"); else result += QLatin1String("ddd"); break; } case ':': { // timesep 0-3 ++i; if (i >= sys_fmt.size()) break; c = sys_fmt.at(i); if (c.isDigit() && c.digitValue() <= 3) { TChar s = locale->TimeSeparator(c.digitValue()); TUint val = s; // some indexes return zero for empty if (val > 0) result += QChar(val); } break; } case 'J': { if (tf == ETime24 && !abbrev_next) result += QLatin1String("hh"); else result += QLatin1Char('h'); break; } case 'H': { if (!abbrev_next) result += QLatin1String("hh"); else result += QLatin1Char('h'); break; } case 'I': { result += QLatin1Char('h'); break; } case 'T': { if (!abbrev_next) result += QLatin1String("mm"); else result += QLatin1Char('m'); break; } case 'S': { if (!abbrev_next) result += QLatin1String("ss"); else result += QLatin1Char('s'); break; } case 'B': { // only done for 12h clock if (tf == ETime24) break; } // fallthru to A case 'A': { // quickie to get capitalization, can't use s60 string as is because Qt 'hh' format's am/pm logic TAmPmName ampm = TAmPmName(); TChar first(ampm[0]); QString qtampm = QString::fromLatin1(first.IsUpper() ? "AP" : "ap"); int pos = locale->AmPmSymbolPosition(); if ((minus_mode && pos != ELocaleBefore) || (plus_mode && pos != ELocaleAfter)) break; if (!abbrev_next && locale->AmPmSpaceBetween()) { if (pos == ELocaleBefore) qtampm.append(QLatin1Char(' ')); else qtampm.prepend(QLatin1Char(' ')); } result += qtampm; } break; case '.': { // decimal sep TChar s = locale->DecimalSeparator(); TUint val = s; if (val > 0) result += QChar(val); } break; case 'C': { // six digits in s60, three digits in qt if (!abbrev_next) { result += QLatin1String("zzz"); } else { // next char is number from 0-6, how many digits to display ++i; if (i >= sys_fmt.size()) break; c = sys_fmt.at(i); if (c.isDigit()) { // try to match wanted digits QChar val(c.digitValue()); if (val >= 3) { result += QLatin1String("zzz"); } else if (val > 0) { result += QLatin1Char('z'); } } } break; } // these cases fallthru case '1': case '2': case '3': case '4': case '5': { // shouldn't parse these with %F if (locale_indep_ordering) break; TDateFormat df = locale->DateFormat(); const char **locale_dep; switch (df) { default: // fallthru to american case EDateAmerican: locale_dep = us_locale_dep; break; case EDateEuropean: locale_dep = eu_locale_dep; break; case EDateJapanese: locale_dep = jp_locale_dep; break; } int offset = 0; if (abbrev_next) offset += 5; if (n_mode) offset += 10; result += QLatin1String(locale_dep[offset + (c.digitValue()-1)]); break; } case '%': // fallthru percent { // any junk gets copied as is } default: { result += c; break; } case 'Z': // Qt doesn't support these :( case 'X': case 'W': { break; } } } else { // double any single quotes, don't begin escape if (c.unicode() == '\'') { // end open escape if (open_escape) { result += other; other.clear(); result += QLatin1Char('\''); open_escape = false; } other += c; } // gather chars and escape them in one go if any format chars are found if (!open_escape && qtformatchars.indexOf(c) != -1) { result += QLatin1Char('\''); open_escape = true; } other += c; } ++i; } if (!other.isEmpty()) result += other; if (open_escape) result += QLatin1Char('\''); return result; }
void SelectPageAction::slotGoToPage(const QString &pageLabelText) { const int start = pageLabelText.indexOf(QLatin1Char('(')) + 1; // pageLabelText is of the form "iv (4 / 316)", so we extract the "4" const int pageNumber = pageLabelText.mid(start, pageLabelText.indexOf(QLatin1Char('/')) - start).toInt() - 1; Q_EMIT pageSelected(pageNumber); }
void MainWindow::checkForSaveFile() { QFile file2("autosave.dat"); QString fileInput = "autosave.dat"; if (!file2.exists() && !QFile(QString(".autosave.dat")).exists()) QString fileInput = QFileDialog::getSaveFileName(this, tr("Autosave File"), "", tr("Data File (*.dat)")); else if (!file2.exists() && QFile(QString(".autosave.dat")).exists()) QFile(QString(".autosave.dat")).copy(fileInput); QList<QString> asList; if (fileInput != "") { /** Load the last save into memory. Allows us to extract the serials/class members. **/ QFile file(fileInput); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; }//end if QTextStream in(&file); while (!in.atEnd()) { asList.push_back(in.readLine()); }//iterate through the file. All of it. Store. }//end if. for (int x = 0; x < asList.size(); x++) { /** Now, we segment the file. **/ QString current = asList.at(x); QString flipped = reverse(current); QList<QString> currentKid; int y = x; while (asList.at(y) != flipped) { y++; } for (int z = x; z < y; z++) { currentKid.push_back(asList.at(z)); x++; }//end for z. if (true) { QString last = currentKid.at(0); QString email = currentKid.at(1); int index = email.indexOf(":") + 1; email.remove(0, index); QString period = currentKid.at(2); index = period.indexOf(":") + 1; period.remove(0, index); QString balance = currentKid.at(3); KedighKid toPush(last, period, email); for (int i = 4; i < currentKid.size(); i++) { QString line = currentKid.at(i); QString tabLength = "\t\t"; line.remove(0, tabLength.length()); int index = line.indexOf(":"); QString serial = line; serial.remove(index, line.size()); QString denom = line; denom.remove(0, serial.size()); QString toSize = " $"; denom.remove(0, 3); int _denomination = denom.toInt(); KedighCash money(serial, "Today", _denomination); toPush.addMoney(money); } kids.push_back(toPush); x++; } } qSort(kids.begin(), kids.end()); for (int i = 0; i < kids.size(); i++) { ui->studentSelect->addItem(kids.at(i).name); } for (int y = 0; y < kids.size(); y++) { ui->fileDisplay->addItem(kids.at(y).name); } countCash(); displayInfo(); }//open last save.
void WindowsModernStyle::drawControl( ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget ) const { switch ( element ) { case CE_MenuBarEmptyArea: return; case CE_MenuBarItem: if ( option->state & QStyle::State_Sunken && option->state & QStyle::State_Enabled ) { painter->setPen( m_colorMenuBorder ); QLinearGradient gradient( option->rect.topLeft(), option->rect.bottomLeft() ); gradient.setColorAt( 0.0, m_colorMenuTitleBegin ); gradient.setColorAt( 1.0, m_colorMenuTitleEnd ); painter->setBrush( gradient ); painter->drawRect( option->rect.adjusted( 0, 0, -1, 0 ) ); } else if ( option->state & QStyle::State_Selected && option->state & QStyle::State_Enabled ) { painter->setPen( m_colorItemBorder ); QLinearGradient gradient( option->rect.topLeft(), option->rect.bottomLeft() ); gradient.setColorAt( 0.0, m_colorItemBackgroundBegin ); gradient.setColorAt( 1.0, m_colorItemBackgroundEnd ); painter->setBrush( gradient ); painter->drawRect( option->rect.adjusted( 0, 0, -1, -1 ) ); } if ( const QStyleOptionMenuItem* optionItem = qstyleoption_cast<const QStyleOptionMenuItem*>( option ) ) { int flags = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine; if ( !styleHint( SH_UnderlineShortcut, option, widget ) ) flags |= Qt::TextHideMnemonic; if ( !optionItem->icon.isNull() ) { QPixmap pixmap = optionItem->icon.pixmap( pixelMetric( PM_SmallIconSize, option, widget ), QIcon::Normal ); drawItemPixmap( painter, option->rect, flags, pixmap ); } else { drawItemText( painter, option->rect, flags, option->palette, true, optionItem->text, QPalette::Text ); } } return; case CE_MenuEmptyArea: painter->fillRect( option->rect, m_colorMenuBackground ); return; case CE_MenuItem: { if ( option->state & QStyle::State_Selected && option->state & QStyle::State_Enabled ) { painter->setPen( m_colorItemBorder ); painter->setBrush( m_colorItemBackgroundBegin ); painter->drawRect( option->rect.adjusted( 1, 0, -3, -1 ) ); } else { QLinearGradient gradient( QPoint( 0, 0 ), QPoint( 25, 0 ) ); gradient.setColorAt( 0.0, m_colorBarBegin ); gradient.setColorAt( 1.0, m_colorBarEnd ); QRect margin = option->rect; margin.setWidth( 25 ); painter->fillRect( margin, gradient ); QRect background = option->rect; background.setLeft( margin.right() + 1 ); painter->fillRect( background, m_colorMenuBackground ); } if ( const QStyleOptionMenuItem* optionItem = qstyleoption_cast<const QStyleOptionMenuItem*>( option ) ) { if ( optionItem->menuItemType == QStyleOptionMenuItem::Separator ) { painter->setPen( m_colorSeparator ); painter->drawLine( option->rect.left() + 32, ( option->rect.top() + option->rect.bottom() ) / 2, option->rect.right(), ( option->rect.top() + option->rect.bottom() ) / 2 ); return; } QRect checkRect = option->rect.adjusted( 2, 1, -2, -2 ); checkRect.setWidth( 20 ); if ( optionItem->checked && option->state & QStyle::State_Enabled ) { painter->setPen( m_colorItemBorder ); if ( option->state & QStyle::State_Selected && option->state & QStyle::State_Enabled ) painter->setBrush( m_colorItemSunkenBegin ); else painter->setBrush( m_colorItemCheckedBegin ); painter->drawRect( checkRect ); } if ( !optionItem->icon.isNull() ) { QIcon::Mode mode; if ( optionItem->state & State_Enabled ) mode = ( optionItem->state & State_Selected ) ? QIcon::Active : QIcon::Normal; else mode = QIcon::Disabled; QIcon::State state = optionItem->checked ? QIcon::On : QIcon::Off; QPixmap pixmap = optionItem->icon.pixmap( pixelMetric( PM_SmallIconSize, option, widget ), mode, state ); QRect rect = pixmap.rect(); rect.moveCenter( checkRect.center() ); painter->drawPixmap( rect.topLeft(), pixmap ); } else if ( optionItem->checked ) { QStyleOption optionCheckMark; optionCheckMark.initFrom( widget ); optionCheckMark.rect = checkRect; if ( !( option->state & State_Enabled ) ) optionCheckMark.palette.setBrush( QPalette::Text, optionCheckMark.palette.brush( QPalette::Disabled, QPalette::Text ) ); drawPrimitive( PE_IndicatorMenuCheckMark, &optionCheckMark, painter, widget ); } QRect textRect = option->rect.adjusted( 32, 1, -16, -1 ); int flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine; if ( !styleHint( SH_UnderlineShortcut, option, widget ) ) flags |= Qt::TextHideMnemonic; QString text = optionItem->text; int pos = text.indexOf( '\t' ); if ( pos >= 0 ) { drawItemText( painter, textRect, flags | Qt::AlignRight, option->palette, option->state & State_Enabled, text.mid( pos + 1 ), QPalette::Text ); text = text.left( pos ); } drawItemText( painter, textRect, flags, option->palette, option->state & State_Enabled, text, QPalette::Text ); if ( optionItem->menuItemType == QStyleOptionMenuItem::SubMenu ) { QStyleOption optionArrow; optionArrow.initFrom( widget ); optionArrow.rect = option->rect.adjusted( 0, 4, -4, -4 ); optionArrow.rect.setLeft( option->rect.right() - 12 ); optionArrow.state = option->state & State_Enabled; drawPrimitive( PE_IndicatorArrowRight, &optionArrow, painter, widget ); } } return; } case CE_ToolBar: { QRect rect = option->rect; bool vertical = false; if ( const QToolBar* toolBar = qobject_cast<const QToolBar*>( widget ) ) { vertical = ( toolBar->orientation() == Qt::Vertical ); if ( vertical ) rect.setBottom( toolBar->childrenRect().bottom() + 2 ); else rect.setRight( toolBar->childrenRect().right() + 2 ); } painter->save(); QRegion region = rect.adjusted( 2, 0, -2, 0 ); region += rect.adjusted( 0, 2, 0, -2 ); region += rect.adjusted( 1, 1, -1, -1 ); painter->setClipRegion( region ); QLinearGradient gradient; if ( vertical ) gradient = QLinearGradient( rect.topLeft(), rect.topRight() ); else gradient = QLinearGradient( rect.topLeft(), rect.bottomLeft() ); gradient.setColorAt( 0.0, m_colorBarBegin ); gradient.setColorAt( 0.4, m_colorBarMiddle ); gradient.setColorAt( 0.6, m_colorBarMiddle ); gradient.setColorAt( 1.0, m_colorBarEnd ); painter->fillRect( rect, gradient ); painter->setPen( vertical ? m_colorBorderLight : m_colorBorder ); painter->drawLine( rect.bottomLeft() + QPoint( 2, 0 ), rect.bottomRight() - QPoint( 2, 0 ) ); painter->setPen( vertical ? m_colorBorder : m_colorBorderLight ); painter->drawLine( rect.topRight() + QPoint( 0, 2 ), rect.bottomRight() - QPoint( 0, 2 ) ); painter->setPen( m_colorBorderLight ); painter->drawPoint( rect.bottomRight() - QPoint( 1, 1 ) ); painter->restore(); return; } case CE_DockWidgetTitle: { QLinearGradient gradient( option->rect.topLeft(), option->rect.bottomLeft() ); gradient.setColorAt( 0.0, m_colorBarBegin ); gradient.setColorAt( 1.0, m_colorBarEnd ); painter->fillRect( option->rect, gradient ); if ( const QStyleOptionDockWidget* optionDockWidget = qstyleoption_cast<const QStyleOptionDockWidget*>( option ) ) { QRect rect = option->rect.adjusted( 6, 0, -4, 0 ); if ( optionDockWidget->closable ) rect.adjust( 0, 0, -16, 0 ); if ( optionDockWidget->floatable ) rect.adjust( 0, 0, -16, 0 ); QString text = painter->fontMetrics().elidedText( optionDockWidget->title, Qt::ElideRight, rect.width() ); drawItemText( painter, rect, Qt::AlignLeft | Qt::AlignVCenter, option->palette, option->state & State_Enabled, text, QPalette::WindowText ); } return; } case CE_TabBarTabShape: if ( isStyledTabBar( widget ) ) { bool firstTab = false; bool lastTab = false; bool bottom = false; if ( const QStyleOptionTab* optionTab = qstyleoption_cast<const QStyleOptionTab*>( option ) ) { if ( optionTab->position == QStyleOptionTab::Beginning ) firstTab = true; else if ( optionTab->position == QStyleOptionTab::End ) lastTab = true; else if ( optionTab->position == QStyleOptionTab::OnlyOneTab ) firstTab = lastTab = true; if ( optionTab->shape == QTabBar::RoundedSouth ) bottom = true; } QRect rect = option->rect; painter->save(); if ( option->state & State_Selected ) { if ( bottom ) rect.adjust( firstTab ? 0 : -2, -1, lastTab ? -1 : 1, -1 ); else rect.adjust( firstTab ? 0 : -2, 0, lastTab ? -1 : 1, 1 ); } else { if ( bottom ) { rect.adjust( 0, -1, lastTab ? -1 : 0, -2 ); painter->setClipRect( rect.adjusted( 0, 1, 1, 1 ) ); } else { rect.adjust( 0, 1, lastTab ? -1 : 0, 0 ); painter->setClipRect( rect.adjusted( 0, 0, 1, 0 ) ); } } QLinearGradient gradient; if ( bottom ) gradient = QLinearGradient( rect.bottomLeft(), rect.topLeft() ); else gradient = QLinearGradient( rect.topLeft(), rect.bottomLeft() ); if ( option->state & State_Selected ) { gradient.setColorAt( 0.0, m_colorItemBackgroundBegin ); gradient.setColorAt( 1.0, option->palette.window().color() ); painter->setPen( m_colorBorder ); } else if ( option->state & State_MouseOver && option->state & State_Enabled ) { gradient.setColorAt( 0.0, m_colorItemBackgroundBegin ); gradient.setColorAt( 1.0, m_colorItemBackgroundEnd ); painter->setPen( m_colorBorderLight ); } else { gradient.setColorAt( 0.0, m_colorBarMiddle ); gradient.setColorAt( 1.0, m_colorBarEnd ); painter->setPen( m_colorBorderLight ); } painter->setBrush( gradient ); painter->drawRect( rect ); painter->restore(); return; } break; case CE_ToolBoxTabShape: { QRect rect = option->rect.adjusted( 0, 0, -1, -1 ); QLinearGradient gradient( rect.topLeft(), rect.bottomLeft() ); if ( option->state & QStyle::State_Sunken ) { gradient.setColorAt( 0.0, m_colorItemSunkenBegin ); gradient.setColorAt( 1.0, m_colorItemSunkenEnd ); painter->setPen( m_colorBorder ); } else if ( option->state & State_MouseOver && option->state & State_Enabled ) { gradient.setColorAt( 0.0, m_colorItemBackgroundBegin ); gradient.setColorAt( 1.0, m_colorItemBackgroundEnd ); painter->setPen( m_colorBorder ); } else { gradient.setColorAt( 0.0, m_colorBarMiddle ); gradient.setColorAt( 1.0, m_colorBarEnd ); painter->setPen( m_colorBorderLight ); } painter->setBrush( gradient ); painter->drawRect( rect ); return; } case CE_Splitter: if ( qobject_cast<const QMainWindow*>( widget->window() ) ) return; break; default: break; } if ( useVista() ) QWindowsVistaStyle::drawControl( element, option, painter, widget ); else QWindowsXPStyle::drawControl( element, option, painter, widget ); }
void MainWindow::checkForPasswordFile() { QString fileInput = "password.txt"; QString hidden = ".password.txt"; QList<QString> asList; QFile file(fileInput); if (!file.exists() && !QFile(hidden).exists()) { UserWindow * newUser = new UserWindow(0, false); connect(newUser, SIGNAL(createAccount(QString,QString)), this, SLOT(makeAccount(QString,QString))); newUser->show(); }//first run, or file cannot be found. else if (!file.exists() && QFile(hidden).exists()) { QFile file2(hidden); file2.copy(fileInput); /** Load the password into memory. **/ if (!file2.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; }//end if QTextStream in(&file2); while (!in.atEnd()) { asList.push_back(in.readLine()); }//iterate through the file. All of it. Store. if (asList.size() > 0) { QString current = asList.at(0); int index1 = current.indexOf("User:"******"password: "******"") { /** Load the password into memory. **/ if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; }//end if QTextStream in(&file); while (!in.atEnd()) { asList.push_back(in.readLine()); }//iterate through the file. All of it. Store. if (asList.size() > 0) { QString current = asList.at(0); int index1 = current.indexOf("User:"******"password: " current.remove(0, 10); m_password = current; }//end if countCash(); displayInfo(); }//open last save. }
void MainWindow::parseFile(QString fileInput) { if (fileInput != "") { QFile file(fileInput); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; }//end if QTextStream in(&file); QList<QString> asList; QList<QString> dataList; QString email, date; while (!in.atEnd()) { asList.push_back(in.readLine()); }//iterate through the file. All of it. Store. ui->fileDisplay->clear(); for (int x = 0; x < asList.size(); x++) { if (asList.at(x) == "" && x > 0) { asList.removeAt(x); x--; } //remove the blank lines }//end for x for (int z = 0; z < asList.size(); z++) { /** Order of the file here, lastname: period: version: denomination: serial: Submit: Submit HTTP_USER_AGENT: WOW64; REMOTE_ADDR: From: lastname [email] Sent: date **/ if (asList.at(z).contains("From")) { int index1, index2; QString current; current = asList.at(z); if (current.contains("[")) { index1 = current.indexOf("["); current.remove(0, index1 + 1); index2 = current.indexOf("]"); current.remove(index2, current.size() - 1); }//end if else { index1 = current.indexOf("<"); current.remove(0, index1 + 1); index2 = current.indexOf(">"); current.remove(index2, current.size() - 1); } email = current; z++; current = asList.at(z); index1 = current.indexOf(","); current.remove(0, index1 + 1); index2 = current.indexOf(":"); current.remove(index2 - 2, current.size() - 1); date = current; z++; } else if (asList.at(z).contains("lastname: ")) { QString lastname, period, version, denom, serial, remote; //we have a section to extract from. QString toSize; QString current; current = asList.at(z); int theSize = 0; toSize = "lastname: "; theSize = toSize.size(); current.remove(0, theSize); lastname = current; z++; //we can go to the next line now if (asList.at(z).contains("period: ")) { toSize = "period: "; current = asList.at(z); current.remove(0, toSize.size() - 1); period = current; z++; }//make sure it exists! else period = "invalid"; if (asList.at(z).contains("version")) { current = asList.at(z); toSize = "version: "; current.remove(0, toSize.size() - 1); version = current; z++; } if (asList.at(z).contains("denomination")) { toSize = "denomination: "; current = asList.at(z); current.remove(0, toSize.size() - 1); denom = current; z++; } if (asList.at(z).contains("serial")) { toSize = "serial: "; current = asList.at(z); current.remove(0, toSize.size() - 1); serial = current; z += 3; //go to remote line } if (asList.at(z).contains("REMOTE_ADDR")) { toSize = "REMOTE_ADDR: "; current = asList.at(z); current.remove(0, toSize.size() - 1); remote = current; } //get email bool exists = false; int index = -1; for (int k = 0; k < kids.size(); k++) { if (QString::compare(kids.at(k).name, lastname, Qt::CaseInsensitive) == 0) { exists = true; index = k; break; } } KedighKid toPush(lastname, period, email); if (!exists) { kids.push_back(toPush); KedighCash dolla(serial, date, lastname, remote, toInt(denom)); kids.last().addMoney(dolla); }//end if. else { KedighCash dolla(serial, date, lastname, remote, toInt(denom)); kids.last().addMoney(dolla); }//end else } else if (asList.at(z).contains("denomination")) { QString lastname, period, version, denom, serial, remote; //we have a section to extract from. QString toSize; QString current; current = asList.at(z); int theSize = 0; toSize = "denomination: "; current = asList.at(z); current.remove(0, toSize.size() - 1); denom = current; z++; if (asList.at(z).contains("serial")) { toSize = "serial: "; current = asList.at(z); current.remove(0, toSize.size() - 1); serial = current; z ++; //go to remote line } if (asList.at(z).contains("period")) { toSize = "period: "; current = asList.at(z); current.remove(0, toSize.size() - 1); period = current; z++; }//make sure it exists! else period = "invalid"; if (asList.at(z).contains("lastname")) { current = asList.at(z); toSize = "lastname: "; theSize = toSize.size(); current.remove(0, theSize); lastname = current; z += 3; //we can go to the next line now } if (asList.at(z).contains("REMOTE_ADDR")) { toSize = "REMOTE_ADDR: "; current = asList.at(z); current.remove(0, toSize.size() - 1); remote = current; } //get email bool exists = false; int index = -1; for (int k = 0; k < kids.size(); k++) { if (QString::compare(kids.at(k).name, lastname, Qt::CaseInsensitive) == 0) { exists = true; index = k; break; } } KedighKid toPush(lastname, period, email); if (!exists) { kids.push_back(toPush); KedighCash dolla(serial, date, lastname, remote, toInt(denom)); kids.last().addMoney(dolla); }//end if. else { KedighCash dolla(serial, date, lastname, remote, toInt(denom)); kids.last().addMoney(dolla); }//end else }//end else if. } qSort(kids.begin(), kids.end()); for (int i = 0; i < kids.size(); i++) { ui->studentSelect->addItem(kids.at(i).name); } for (int y = 0; y < kids.size(); y++) { ui->fileDisplay->addItem(kids.at(y).name); } file.close(); }//end if countCash(); }
void SysCacheDaemon::answerRequest(){ //curSock->waitForReadyRead(1000); //wait max 1 second for the request from the client static bool working = false; if(working || curSock==0){ return; } working = true; QStringList req, out, delim; delim << " " << "\"" << "\'"; //input string delimiters bool stopdaemon=false; QTextStream stream(curSock); bool done = false; bool nonCLI = false; while(!stream.atEnd()){ req.clear(); QString line = stream.readLine(); //qDebug() << "Found Request Line:" << line; if(!line.contains("[/]")){ usleep(600); QCoreApplication::processEvents(); line.append(stream.readLine()); } if(line.contains("[FINISHED]")){done = true; } if(line.contains("[NONCLI]")){ nonCLI = true; } if(line.contains("[")){ line = line.section("[",0,0); } if(line.isEmpty() || line == "[/]"){ continue; } //Be careful about quoted strings (only one input, even if multiple words) int index = 0; int dindex = 0; //start off with the space (lowest priority) while(index < line.length()){ //qDebug() << "Pass:"******" - new index:" << temp << ni << ndin; if( temp < ni && temp>0){ ni = temp; ndin = i; } } //NOTE: this delimiter routine will *NOT* work with nested delimiters (this is "some 'nested input'") if(ndin==dindex){ dindex = 0; } //found end tag, reset back to lowest priority else{ dindex = ndin; } //found the first tag, start with this next time around if(ni==line.length()-1){ ni++; } //need to add one on the last entry QString tmpreq = line.mid(index, ni-index); //qDebug() << "Found Argument:" << tmpreq << index << ni; if(!tmpreq.isEmpty()){ req << tmpreq; } index = ni+1; } //qDebug() << " - Request:" << req; //qDebug() << "Request Received:" << req; if(req.join("")=="shutdowndaemon"){ stopdaemon=true; done=true; break; } if(req.join("")=="[FINISHED]"){ done = true; break; } else{ QString res = DATA->fetchInfo(req, nonCLI); //For info not available, try once more time as it can error unexpectedly if it was // stuck waiting for a sync to finish if(res =="[ERROR] Information not available"){ res = DATA->fetchInfo(req); } out << "[INFOSTART]"+ res+"\n"; } } //Now write the output to the socket and disconnect it //qDebug() << " - Request replied:" << done; stream << out.join("\n"); //curSock->disconnectFromServer(); working = false; if(done){ stream << "\n[FINISHED]"; } else{ QTimer::singleShot(0,this, SLOT(answerRequest()) ); } if(stopdaemon){ QTimer::singleShot(10, this, SLOT(stopServer())); } }
void HuggleFeedProviderIRC::ParseEdit(QString line) { // skip edits if provider is disabled if (this->Paused) { return; } if (!line.contains(QString(QChar(003)) + "07")) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (no07):" + line); return; } line = line.mid(line.indexOf(QString(QChar(003)) + "07") + 3); if (!line.contains(QString(QChar(003)) + "14")) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (no14):" + line); return; } WikiEdit *edit = new WikiEdit(); edit->Page = new WikiPage(line.mid(0, line.indexOf(QString(QChar(003)) + "14"))); edit->IncRef(); if (!line.contains(QString(QChar(003)) + "4 ")) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (no:x4:" + line); edit->DecRef(); return; } line = line.mid(line.indexOf(QString(QChar(003)) + "4 ") + 2); QString flags = line.mid(0, line.indexOf(QChar(003))); edit->Bot = flags.contains("B"); edit->NewPage = flags.contains("N"); edit->Minor = flags.contains("M"); // this below looks like a nasty hack to filter out just what we need // but I will later use all of these actions for something too if (flags.contains("thank") || flags.contains("modify") || flags.contains("rights") || flags.contains("review") || flags.contains("block") || flags.contains("protect") || flags.contains("reblock") || flags.contains("unhelpful") || flags.contains("helpful") || flags.contains("approve") || flags.contains("resolve") || flags.contains("upload") || flags.contains("feature") || flags.contains("noaction") || flags.contains("selfadd") || flags.contains("overwrite") || flags.contains("create") || flags.contains("delete") || flags.contains("restore") || flags.contains("move") || flags.contains("tag") || /* abuse filter */flags.contains("hit") || flags.contains("patrol") || flags.contains("revision")) { edit->DecRef(); return; } if (!edit->NewPage) { if (!line.contains("?diff=")) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (flags: " + flags + ") (no diff):" + line); edit->DecRef(); return; } line = line.mid(line.indexOf("?diff=") + 6); if (!line.contains("&")) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (no &):" + line); edit->DecRef(); return; } edit->Diff = line.mid(0, line.indexOf("&")).toInt(); edit->RevID = line.mid(0, line.indexOf("&")).toInt(); } if (!line.contains("oldid=")) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (no oldid?):" + line); edit->DecRef(); return; } line = line.mid(line.indexOf("oldid=") + 6); if (!line.contains(QString(QChar(003)))) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (no termin):" + line); edit->DecRef(); return; } edit->OldID = line.mid(0, line.indexOf(QString(QChar(003)))).toInt(); if (!line.contains(QString(QChar(003)) + "03")) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line, no user: "******"03") + 3); if (!line.contains(QString(QChar(3)))) { Huggle::Syslog::HuggleLogs->DebugLog("Invalid line (no termin):" + line); edit->DecRef(); return; } QString name = line.mid(0, line.indexOf(QString(QChar(3)))); if (name.length() <= 0) { edit->DecRef(); return; } edit->User = new WikiUser(name); if (line.contains(QString(QChar(3)) + " (")) { line = line.mid(line.indexOf(QString(QChar(3)) + " (") + 3); if (line.contains(")")) { QString xx = line.mid(0, line.indexOf(")")); xx = xx.replace("\002", ""); int size = 0; if (xx.startsWith("+")) { xx = xx.mid(1); size = xx.toInt(); edit->Size = size; } else if (xx.startsWith("-")) { xx = xx.mid(1); size = xx.toInt() * -1; edit->Size = size; } else { Syslog::HuggleLogs->DebugLog("No size information for " + edit->Page->PageName); } }else { Syslog::HuggleLogs->DebugLog("No size information for " + edit->Page->PageName); } } else { Syslog::HuggleLogs->DebugLog("No size information for " + edit->Page->PageName); } if (line.contains(QString(QChar(3)) + "10")) { line = line.mid(line.indexOf(QString(QChar(3)) + "10") + 3); if (line.contains(QString(QChar(3)))) { edit->Summary = line.mid(0, line.indexOf(QString(QChar(3)))); } } this->InsertEdit(edit); }
void MiningPage::readProcessOutput() { QByteArray output; minerProcess->reset(); output = minerProcess->readAll(); QString outputString(output); if (!outputString.isEmpty()) { QStringList list = outputString.split("\n", QString::SkipEmptyParts); int i; for (i=0; i<list.size(); i++) { QString line = list.at(i); // Ignore protocol dump if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr")) continue; if (ui->debugCheckBox->isChecked()) { ui->list->addItem(line.trimmed()); ui->list->scrollToBottom(); } if (line.contains("(yay!!!)")) reportToList("Share accepted", SHARE_SUCCESS, getTime(line)); else if (line.contains("(booooo)")) reportToList("Share rejected", SHARE_FAIL, getTime(line)); else if (line.contains("LONGPOLL detected new block")) reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line)); else if (line.contains("Supported options:")) reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL); else if (line.contains("The requested URL returned error: 403")) reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL); else if (line.contains("HTTP request failed")) reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL); else if (line.contains("JSON-RPC call failed")) reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL); else if (line.contains("thread ") && line.contains("khash/s")) { QString threadIDstr = line.at(line.indexOf("thread ")+7); int threadID = threadIDstr.toInt(); int threadSpeedindx = line.indexOf(","); QString threadSpeedstr = line.mid(threadSpeedindx); threadSpeedstr.chop(8); threadSpeedstr.remove(", "); threadSpeedstr.remove(" "); threadSpeedstr.remove('\n'); double speed=0; speed = threadSpeedstr.toDouble(); threadSpeed[threadID] = speed; updateSpeed(); } } } }
/* * Convert an image url e.g. "asset:///images/Blue_20Nose_20Thumb.png" * into a full path that can be opened with routines that don't know asset:// */ QString PictureHelper::getImagePath(QString imageUrl) { /*QString resourceText = imageUrl.toString();*/ int index = imageUrl.indexOf("/images/"); return (index > 0)? getAssetDir() + imageUrl.mid(index) : imageUrl; }
void QgsBrowserDockWidget::itemClicked( const QModelIndex& index ) { QgsDataItem *item = mModel->dataItem( index ); if ( !item ) return; QgsLayerItem *layerItem = qobject_cast<QgsLayerItem*>( mModel->dataItem( index ) ); if ( layerItem == NULL ) return; QString uri = layerItem->uri(); if ( uri.isEmpty() ) return; QgsMapLayer::LayerType type = layerItem->mapLayerType(); QString providerKey = layerItem->providerKey(); QgsDebugMsg( providerKey + " : " + uri ); QgsMapLayer* layer = NULL; if ( type == QgsMapLayer::VectorLayer ) { layer = new QgsVectorLayer( uri, layerItem->name(), providerKey ); } if ( type == QgsMapLayer::RasterLayer ) { // This should go to WMS provider QStringList URIParts = uri.split( "|" ); QString rasterLayerPath = URIParts.at( 0 ); QStringList layers; QStringList styles; QString format; QString crs; for ( int i = 1 ; i < URIParts.size(); i++ ) { QString part = URIParts.at( i ); int pos = part.indexOf( "=" ); QString field = part.left( pos ); QString value = part.mid( pos + 1 ); if ( field == "layers" ) layers = value.split( "," ); if ( field == "styles" ) styles = value.split( "," ); if ( field == "format" ) format = value; if ( field == "crs" ) crs = value; } QgsDebugMsg( "rasterLayerPath = " + rasterLayerPath ); QgsDebugMsg( "layers = " + layers.join( " " ) ); layer = new QgsRasterLayer( 0, rasterLayerPath, layerItem->name(), providerKey, layers, styles, format, crs ); } if ( !layer || !layer->isValid() ) { qDebug( "No layer" ); delete layer; return; } // add layer to the application QgsMapLayerRegistry::instance()->addMapLayer( layer ); }
CMakeEditorWidget::Link CMakeEditorWidget::findLinkAt(const QTextCursor &cursor, bool/* resolveTarget*/, bool /*inNextSplit*/) { Link link; int lineNumber = 0, positionInBlock = 0; convertPosition(cursor.position(), &lineNumber, &positionInBlock); const QString block = cursor.block().text(); // check if the current position is commented out const int hashPos = block.indexOf(QLatin1Char('#')); if (hashPos >= 0 && hashPos < positionInBlock) return link; // find the beginning of a filename QString buffer; int beginPos = positionInBlock - 1; while (beginPos >= 0) { QChar c = block.at(beginPos); if (isValidFileNameChar(c)) { buffer.prepend(c); beginPos--; } else { break; } } // find the end of a filename int endPos = positionInBlock; while (endPos < block.count()) { QChar c = block.at(endPos); if (isValidFileNameChar(c)) { buffer.append(c); endPos++; } else { break; } } if (buffer.isEmpty()) return link; // TODO: Resolve variables QDir dir(textDocument()->filePath().toFileInfo().absolutePath()); QString fileName = dir.filePath(buffer); QFileInfo fi(fileName); if (fi.exists()) { if (fi.isDir()) { QDir subDir(fi.absoluteFilePath()); QString subProject = subDir.filePath(QLatin1String("CMakeLists.txt")); if (QFileInfo::exists(subProject)) fileName = subProject; else return link; } link.targetFileName = fileName; link.linkTextStart = cursor.position() - positionInBlock + beginPos + 1; link.linkTextEnd = cursor.position() - positionInBlock + endPos; } return link; }
void TcpServer::KnxDataHandler(QString incomingData, QString & response) { int startPos = 0; int endPos = 0; if ( incomingData.contains("POST") ) { startPos = 0; endPos = incomingData.length(); startPos = incomingData.indexOf("\r\n\r\n") + 1; //+1 skip ? QString urlVariables = incomingData.mid(startPos, endPos-startPos); qDebug() << "[TcpServer::KnxDataHandler] WRITE: urlVariables: " << urlVariables; QStringList args = urlVariables.split('&'); QString groupAddr; QString value; for (int i=0; i<args.length(); i++) { if (args[i].contains("groupAddr")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; groupAddr = args[i].mid(startPos, endPos); qDebug() << "groupAddr: " << groupAddr; } else if (args[i].contains("value")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; value = args[i].mid(startPos, endPos); value.replace("%20", " "); qDebug() << "value: " << value; } } int action = CEMI_ACTION_WRITE; emit TcpServerData((int)action, groupAddr.toInt(), value); response = "<KNX><DATA groupAddr=\"" + groupAddr + "\" value=\"" + value + "\" /></KNX>"; } else if (incomingData.contains("GET")) { startPos = incomingData.indexOf("?") + 1; //+1 skip ? endPos = incomingData.indexOf("HTTP"); QString urlVariables = incomingData.mid(startPos, endPos-startPos); qDebug() << "[TcpServer::KnxDataHandler] READ: urlVariables: " << urlVariables; QStringList args = urlVariables.split('&'); QString groupAddr; QString value; for (int i=0; i<args.length(); i++) { if (args[i].contains("groupAddr")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; groupAddr = args[i].mid(startPos, endPos); } } KnxDB db; if (!db.Connect()) { qDebug() << "[TcpServer::KnxDataHandler]: failed to connect to DB"; //if it can't connect to db then exit abort(); } QString strResult; //qDebug() << "groupAddr: " << groupAddr << " and to int= " << groupAddr.toInt(); db.GetValue(groupAddr.toInt(), strResult); db.Disconnect(); //qDebug() << "[Tcp]: strResult: " + strResult; response = "<KNX><DATA groupAddr=\"" + groupAddr + "\" value=\"" + strResult + "\" /></KNX>"; } }
bool DeckList::loadFromStream_Plain(QTextStream &in) { cleanList(); InnerDecklistNode *main = 0, *side = 0; bool inSideboard = false; int okRows = 0; while (!in.atEnd()) { QString line = in.readLine().simplified(); if (line.startsWith("//")) continue; InnerDecklistNode *zone; if (line.startsWith("Sideboard", Qt::CaseInsensitive)) { inSideboard = true; continue; } else if (line.startsWith("SB:", Qt::CaseInsensitive)) { line = line.mid(3).trimmed(); if (!side) side = new InnerDecklistNode("side", root); zone = side; } else if (inSideboard) { if (!side) side = new InnerDecklistNode("side", root); zone = side; } else { if (!main) main = new InnerDecklistNode("main", root); zone = main; } // Filter out MWS edition symbols and basic land extras QRegExp rx("\\[.*\\]"); line.remove(rx); rx.setPattern("\\(.*\\)"); line.remove(rx); //Filter out post card name editions rx.setPattern("\\|.*$"); line.remove(rx); line = line.simplified(); int i = line.indexOf(' '); bool ok; int number = line.left(i).toInt(&ok); if (!ok) continue; QString cardName = line.mid(i + 1); // Common differences between cockatrice's card names // and what's commonly used in decklists rx.setPattern("’"); cardName.replace(rx, "'"); rx.setPattern("Æ"); cardName.replace(rx, "AE"); rx.setPattern("^Aether"); cardName.replace(rx, "AEther"); rx.setPattern("\\s*[&|/]{1,2}\\s*"); cardName.replace(rx, " // "); ++okRows; new DecklistCardNode(cardName, number, zone); } updateDeckHash(); return (okRows > 0); }
void TcpServer::CalendarDataHandler(QString incomingData, QString & response) { int startPos = 0; int endPos = incomingData.indexOf("HTTP"); if ( incomingData.contains("POST") ) { //app is sending data startPos = incomingData.indexOf("\r\n\r\n") + 1; //+1 skip ? QString urlVariables = incomingData.mid(startPos, endPos-startPos); qDebug() << "[TcpServer::CalendarDataHandler] vars: " << urlVariables; QStringList args = urlVariables.split('&'); //Create a calendar objet Calendar cal("knx","127.0.0.1", "root", ""); QString action; QString eventTime; QString eventText; QString eventAction; QString eventPostAction; for (int i=0; i<args.length(); i++) { if (args[i].contains("action")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; action = args[i].mid(startPos, endPos); } else if (args[i].contains("eventTimestamp")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; eventTime = args[i].mid(startPos, endPos); } else if (args[i].contains("eventText")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; eventText = args[i].mid(startPos, endPos); } else if (args[i].contains("eventAction")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; eventAction = args[i].mid(startPos, endPos); } else if (args[i].contains("postEventAction")) { startPos = args[i].indexOf('=')+1; endPos = args[i].length() - startPos; eventPostAction = args[i].mid(startPos, endPos); } } /* qDebug() << "action: " << action; qDebug() << "eventTimestamp: " << eventTime; qDebug() << "eventText: " << eventText; qDebug() << "eventAction: " << eventAction; qDebug() << "eventPostAction: " << eventPostAction; */ cal.SetEvent(action, eventTime, eventText, eventAction, EVENT_KEEP, response); } else if ( incomingData.contains("GET") ) { //set data //the data that are received here have the following format // http://serverip:serverport/calendar/filename.xml startPos = incomingData.indexOf("calendar/") + 9; //+1 skip ? endPos = incomingData.indexOf(".xml?"); QString datefile; datefile = incomingData.mid(startPos, endPos-startPos); qDebug() << "[TcpServer::CalendarDataHandler] vars: " << datefile; QString xmlData; //Create a calendar objet Calendar cal("knx","127.0.0.1", "root", ""); cal.GetEvent(datefile, xmlData); response = "<Calendar></Calendar>\r\n"; } }
void ExtensionManager::migrateMenubar() { // lame, lame, lame. // the menubar applet was just plunked into kicker and not much // thought was put into how it should be used. great idea, but no // integration. >:-( // so now we have to check to see if we HAVE another extension that // will have a menubar in it, and if so, abort creating one of our // own. // // the reason i didn't do this as a kconfig_update script is that // most people don't use this feature, so no reason to penalize // everyone, and moreover the user may added this to their main // panel, meaning kickerrc itself would have to be vastly modified // with lots of complications. not work it IMHO. KConfigGroup config(KGlobal::config(), "General"); if (config.readEntry("CheckedForMenubar", false)) { return; } if (!KStandardDirs::locate("config", "kicker_menubarpanelrc").isEmpty()) { // don't overwrite/override something that's already there return; } QStringList elist = config.readEntry("Extensions2", QStringList() ); foreach (QString extensionId, elist) { if (extensionId.indexOf("Extension") == -1) { continue; } config.changeGroup(extensionId); // is there a config group for this extension? if (!config.exists() ) { continue; } QString extension = config.readPathEntry("ConfigFile", false); KConfig extensionConfig(KStandardDirs::locate("config", extension)); KConfigGroup eg (&extensionConfig, "General"); if (eg.hasKey("Applets2")) { QStringList containers = eg.readEntry("Applets2", QStringList() ); foreach (QString appletId, containers) { // is there a config group for this applet? if (!extensionConfig.hasGroup(appletId)) { continue; } KConfigGroup group(&extensionConfig, appletId); QString appletType = appletId.left(appletId.lastIndexOf('_')); if (appletType == "Applet") { QString appletFile = group.readPathEntry("DesktopFile", false); if (appletFile.indexOf("menuapplet.desktop") != -1) { QString menubarConfig = KStandardDirs::locate("config", extension); KIO::NetAccess::file_copy(menubarConfig, KStandardDirs::locateLocal("config", "kicker_menubarpanelrc"), 0); elist.removeAll(appletId); config.changeGroup("General"); config.writeEntry("Extensions2", elist); config.writeEntry("CheckedForMenubar", true); config.sync(); return; } } } } }
void PropertyEditorModel::setModelIndexes(const QModelIndex &logicalModelIndex , const QModelIndex &graphicalModelIndex) { beginResetModel(); mField.reset(new Field()); endResetModel(); mTargetLogicalObject = logicalModelIndex; mTargetGraphicalObject = graphicalModelIndex; if (!isValid()) { return; } const Id logicalId = mTargetLogicalObject.data(roles::idRole).value<Id>(); const QString dynamicProperties = dynamic_cast<models::details::LogicalModel *>(mTargetLogicalModel)-> logicalModelAssistApi().logicalRepoApi().stringProperty(logicalId, "dynamicProperties"); if (logicalModelIndex != QModelIndex()) { const QStringList logicalProperties = mEditorManagerInterface.propertyNames(logicalId.type()); int role = roles::customPropertiesBeginRole; QStringList cloneWithRoles; QStringList cloneWithPure; for (const QString &prop : logicalProperties) { if (prop.contains("!")) { cloneWithRoles.append(prop); } else { cloneWithPure.append(prop); } } int i = 0; role = roles::customPropertiesBeginRole; while (cloneWithRoles.size() > 0) { const QString roleName = cloneWithRoles.takeAt(0); const int first = roleName.indexOf("!"); const QString beginPartName = roleName.mid(0, first); mField->appendChild(new Field(beginPartName)); auto parent = mField->child(i); QString endPartName = roleName.mid(first + 1); mField->appendChild( new Field( endPartName , logicalAttribute , role , parent , mTargetLogicalObject , mTargetGraphicalObject) ); ++i; ++role; int j = 0; while (j < cloneWithRoles.size()) { if (cloneWithRoles.at(j).mid(0, first) == beginPartName) { QString roleName = cloneWithRoles.takeAt(j); roleName = roleName.mid(first + 1); mField->appendChild( new Field( roleName , logicalAttribute , role , parent , mTargetLogicalObject , mTargetGraphicalObject) ); ++i; ++role; j = 0; } else { ++j; } } ++i; } while (cloneWithPure.size() > 0) { QString roleName = cloneWithPure.takeAt(0); mField->appendChild( new Field( roleName , logicalAttribute , role , nullptr , mTargetLogicalObject , mTargetGraphicalObject) ); ++i; ++role; } if (!dynamicProperties.isEmpty()) { QDomDocument dynamProperties; dynamProperties.setContent(dynamicProperties); for (QDomElement element = dynamProperties.firstChildElement("properties").firstChildElement("property") ; !element.isNull() ; element = element.nextSiblingElement("property")) { mField->appendChild( new Field( element.attribute("displayedName") , logicalAttribute , role , nullptr , mTargetLogicalObject , mTargetGraphicalObject)); ++role; } } /* * Uncomment to display block Ids in a property editor * mField->appendChild( new Field( "logicalId" , logicalAttribute , roles::idRole , nullptr , mTargetLogicalObject , mTargetGraphicalObject ) ); mField->appendChild( new Field( "graphicalId" , graphicalAttribute , roles::idRole , nullptr , mTargetLogicalObject , mTargetGraphicalObject ) ); /**/ } beginResetModel(); endResetModel(); }
BookmarkItem* HtmlImporter::importBookmarks() { QString bookmarks = QString::fromUtf8(m_file.readAll()); m_file.close(); // Converting tags to lower case -,- // For some reason Qt::CaseInsensitive is not everytime insensitive :-D bookmarks.replace(QLatin1String("<DL"), QLatin1String("<dl")); bookmarks.replace(QLatin1String("</DL"), QLatin1String("</dl")); bookmarks.replace(QLatin1String("<DT"), QLatin1String("<dt")); bookmarks.replace(QLatin1String("</DT"), QLatin1String("</dt")); bookmarks.replace(QLatin1String("<P"), QLatin1String("<p")); bookmarks.replace(QLatin1String("</P"), QLatin1String("</p")); bookmarks.replace(QLatin1String("<A"), QLatin1String("<a")); bookmarks.replace(QLatin1String("</A"), QLatin1String("</a")); bookmarks.replace(QLatin1String("HREF="), QLatin1String("href=")); bookmarks.replace(QLatin1String("<H3"), QLatin1String("<h3")); bookmarks.replace(QLatin1String("</H3"), QLatin1String("</h3")); bookmarks = bookmarks.left(bookmarks.lastIndexOf(QLatin1String("</dl><p>"))); int start = bookmarks.indexOf(QLatin1String("<dl><p>")); BookmarkItem* root = new BookmarkItem(BookmarkItem::Folder); root->setTitle("HTML Import"); QList<BookmarkItem*> folders; folders.append(root); while (start > 0) { QString string = bookmarks.mid(start); int posOfFolder = string.indexOf(QLatin1String("<dt><h3")); int posOfEndFolder = string.indexOf(QLatin1String("</dl><p>")); int posOfLink = string.indexOf(QLatin1String("<dt><a")); int nearest = qzMin(posOfLink, qzMin(posOfFolder, posOfEndFolder)); if (nearest == -1) { break; } if (nearest == posOfFolder) { // Next is folder QzRegExp rx("<dt><h3(.*)>(.*)</h3>"); rx.setMinimal(true); rx.indexIn(string); // QString arguments = rx.cap(1); QString folderName = rx.cap(2).trimmed(); BookmarkItem* folder = new BookmarkItem(BookmarkItem::Folder, folders.isEmpty() ? root : folders.last()); folder->setTitle(folderName); folders.append(folder); start += posOfFolder + rx.cap(0).size(); } else if (nearest == posOfEndFolder) { // Next is end of folder if (!folders.isEmpty()) { folders.removeLast(); } start += posOfEndFolder + 8; } else { // Next is link QzRegExp rx("<dt><a(.*)>(.*)</a>"); rx.setMinimal(true); rx.indexIn(string); QString arguments = rx.cap(1); QString linkName = rx.cap(2).trimmed(); QzRegExp rx2("href=\"(.*)\""); rx2.setMinimal(true); rx2.indexIn(arguments); QUrl url = QUrl::fromEncoded(rx2.cap(1).trimmed().toUtf8()); start += posOfLink + rx.cap(0).size(); if (linkName.isEmpty() || url.isEmpty() || url.scheme() == QLatin1String("place") || url.scheme() == QLatin1String("about")) { continue; } BookmarkItem* b = new BookmarkItem(BookmarkItem::Url, folders.isEmpty() ? root : folders.last()); b->setTitle(linkName); b->setUrl(url); } } return root; }
void Boat::load() { if (m_type == 2049) { m_boatFile.load("vfx:sobjects/hiob.des"); m_moviePrefix = "hiob"; m_maxBuzzers = 2; addMounting("DEFE", 0, 3, 280, 173, "TopLeft"); addMounting("GENE", 0, 4, 80, 132, "BottomRight"); addMounting("GUN", 1, 1, 324, 188, "BottomLeft"); addMounting("TORP", 1, 0, 276, 129, "TopLeft"); } if (m_type == 2050) { m_boatFile.load("vfx:sobjects/gator.des"); m_moviePrefix = "gator"; m_maxBuzzers = 2; addMounting("DEFE", 0, 3, 240, 183, "BottomLeft"); addMounting("GENE", 0, 4, 56, 163, "TopRight"); addMounting("GUN", 1, 1, 311, 163, "TopLeft"); addMounting("TORP", 1, 0, 175, 148, "BottomRight"); addMounting("TUR1", 1, 2, 90, 175, "TopRight"); } if (m_type == 2051) { m_boatFile.load("vfx:sobjects/zorn.des"); m_moviePrefix = "zorn"; m_maxBuzzers = 2; addMounting("DEFE", 0, 3, 217, 194, "BottomLeft"); addMounting("GENE", 0, 4, 116, 175, "BottomLeft"); addMounting("TUR2", 0, 2, 132, 129, "BottomRight"); addMounting("GUN", 1, 1, 235, 180, "TopLeft"); addMounting("TORP", 1, 0, 251, 211, "BottomLeft"); addMounting("TUR1", 1, 2, 119, 146, "TopRight"); } if (m_type == 2052) { m_boatFile.load("vfx:sobjects/succubus.des"); m_moviePrefix = "succub"; m_maxBuzzers = 2; addMounting("DEFE", 0, 3, 216, 191, "BottomLeft"); addMounting("GENE", 0, 4, 155, 143, "TopRight"); addMounting("TUR2", 0, 2, 106, 175, "BottomRight"); addMounting("GUN", 1, 1, 253, 186, "BottomLeft"); addMounting("TORP", 1, 0, 253, 161, "TopLeft"); addMounting("TUR1", 1, 2, 143, 174, "BottomLeft"); } m_boatFile.setSection("Ship"); m_name = m_boatFile.value("Name").toString(); m_boatFile.setSection("Cockpit"); m_cockpit = m_boatFile.value("Name").toString(); m_boatFile.setSection("Compatibility"); for (int comp = 0; m_boatFile.contains(QString("Comp%1").arg(comp)); comp++) { QString str = m_boatFile.value(QString("Comp%1").arg(comp)).toString(); str.truncate(str.indexOf(' ')); int model = str.toInt(); if (model != 99999) m_compatibility.insert(model); } }
void ChatEdit::send() { QString text = textEditToPlainText(); QString trimmed = text.trimmed(); if(!m_session || trimmed.isEmpty()) return; ChatUnit *unit = m_session->getCurrentUnit(); if (trimmed.startsWith(QLatin1Char('/')) && trimmed.size() > 1) { int index = trimmed.indexOf(QLatin1Char(' ')); QStringRef cmd = trimmed.midRef(1, (index == -1 ? trimmed.size() : index) - 1); const QMetaObject *meta = unit->metaObject(); for (int i = meta->propertyCount() - 1; i >= 0; --i) { QMetaProperty prop = meta->property(i); if (prop.isWritable() && QLatin1String(prop.name()) == cmd) { prop.write(unit, trimmed.mid(index + 1)); clear(); return; } } QByteArray signature = cmd.toString().toLatin1(); int methodIndex = meta->indexOfMethod(signature + "(QString)"); if (methodIndex != -1) { QMetaMethod method = meta->method(methodIndex); QString arg = trimmed.mid(index + 1); if (method.invoke(unit, Q_ARG(QString, arg))) { clear(); return; } } methodIndex = meta->indexOfMethod(signature + "(QVariant)"); if (methodIndex != -1) { QMetaMethod method = meta->method(methodIndex); QVariant arg = trimmed.mid(index + 1); if (method.invoke(unit, Q_ARG(QVariant, arg))) { clear(); return; } } methodIndex = meta->indexOfMethod(signature + "()"); if (methodIndex != -1) { QMetaMethod method = meta->method(methodIndex); if (method.invoke(unit)) { clear(); return; } } } Message message(text); message.setIncoming(false); message.setChatUnit(unit); message.setTime(QDateTime::currentDateTime()); qint64 result = m_session->appendMessage(message); if (MessageHandler::Error != -result) clear(); // if (!unit->sendMessage(message)) { // NotificationRequest request(Notification::System); // request.setObject(this); // request.setText(tr("Unable to send message to %1").arg(unit->title())); // request.send(); // } // else { // m_session->appendMessage(message); // clear(); // } }
QString DataOp::getId(QString record) { return record.mid(0,record.indexOf('#')); }
int main(int argc, char **argv) { #ifdef CONSOLE_APPLICATION QApplication app(argc, argv, QApplication::Tty); #else QApplication app(argc, argv); #endif #ifdef DO_QWS_DEBUGGING qt_show_painter_debug_output = false; #endif DeviceType type = WidgetType; bool checkers_background = true; QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied; QLocale::setDefault(QLocale::c()); QStringList files; bool interactive = false; bool printdlg = false; bool highres = false; bool show_cmp = false; int width = 800, height = 800; int scaledWidth = width, scaledHeight = height; qreal scalefactor = 1.0; bool verboseMode = false; #ifndef QT_NO_OPENGL QGLFormat f = QGLFormat::defaultFormat(); f.setSampleBuffers(true); f.setStencil(true); f.setAlpha(true); f.setAlphaBufferSize(8); QGLFormat::setDefaultFormat(f); #endif char *arg; for (int i=1; i<argc; ++i) { arg = argv[i]; if (*arg == '-') { QString option = QString(arg + 1).toLower(); if (option == "widget") type = WidgetType; else if (option == "bitmap") type = BitmapType; else if (option == "pixmap") type = PixmapType; else if (option == "image") type = ImageType; else if (option == "imageformat") { Q_ASSERT_X(i + 1 < argc, "main", "-imageformat must be followed by a value"); QString format = QString(argv[++i]).toLower(); imageFormat = QImage::Format_Invalid; static const int formatCount = sizeof(imageFormats) / sizeof(imageFormats[0]); for (int ff = 0; ff < formatCount; ++ff) { if (QLatin1String(imageFormats[ff].name) == format) { imageFormat = imageFormats[ff].format; break; } } if (imageFormat == QImage::Format_Invalid) { printf("Invalid image format. Available formats are:\n"); for (int ff = 0; ff < formatCount; ++ff) printf("\t%s\n", imageFormats[ff].name); return -1; } } else if (option == "imagemono") type = ImageMonoType; else if (option == "imagewidget") type = ImageWidgetType; #ifndef QT_NO_OPENGL else if (option == "opengl") type = OpenGLType; else if (option == "glbuffer") type = OpenGLBufferType; #endif #ifdef USE_CUSTOM_DEVICE else if (option == "customdevice") type = CustomDeviceType; else if (option == "customwidget") type = CustomWidgetType; #endif else if (option == "pdf") type = PdfType; else if (option == "ps") type = PsType; else if (option == "picture") type = PictureType; else if (option == "printer") type = PrinterType; else if (option == "highres") { type = PrinterType; highres = true; } else if (option == "printdialog") { type = PrinterType; printdlg = true; } else if (option == "grab") type = GrabType; else if (option == "i") interactive = true; else if (option == "v") verboseMode = true; else if (option == "commands") { displayCommands(); return 0; } else if (option == "w") { Q_ASSERT_X(i + 1 < argc, "main", "-w must be followed by a value"); width = atoi(argv[++i]); } else if (option == "h") { Q_ASSERT_X(i + 1 < argc, "main", "-h must be followed by a value"); height = atoi(argv[++i]); } else if (option == "scalefactor") { Q_ASSERT_X(i + 1 < argc, "main", "-scalefactor must be followed by a value"); scalefactor = atof(argv[++i]); } else if (option == "cmp") { show_cmp = true; } else if (option == "bg-white") { checkers_background = false; } } else { #if defined (Q_WS_WIN) QString input = QString::fromLocal8Bit(argv[i]); if (input.indexOf('*') >= 0) { QFileInfo info(input); QDir dir = info.dir(); QFileInfoList infos = dir.entryInfoList(QStringList(info.fileName())); for (int ii=0; ii<infos.size(); ++ii) files.append(infos.at(ii).absoluteFilePath()); } else { files.append(input); } #else files.append(QString(argv[i])); #endif } } scaledWidth = width * scalefactor; scaledHeight = height * scalefactor; PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); QWidget *activeWidget = 0; if (interactive) { runInteractive(); if (!files.isEmpty()) interactive_widget->load(files.at(0)); } else if (files.isEmpty()) { printHelp(); return 0; } else { for (int j=0; j<files.size(); ++j) { const QString &fileName = files.at(j); QStringList content; QFile file(fileName); QFileInfo fileinfo(file); if (file.open(QIODevice::ReadOnly)) { QTextStream textFile(&file); QString script = textFile.readAll(); content = script.split("\n", QString::SkipEmptyParts); } else { printf("failed to read file: '%s'\n", qPrintable(fileinfo.absoluteFilePath())); continue; } pcmd.setContents(content); if (show_cmp) { QString pmFile = QString(files.at(j)).replace(".qps", "_qps") + ".png"; qDebug() << pmFile << QFileInfo(pmFile).exists(); QPixmap pixmap(pmFile); if (!pixmap.isNull()) { QLabel *label = createLabel(); label->setWindowTitle("VERIFY: " + pmFile); label->setPixmap(pixmap); label->show(); } } switch (type) { case WidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } case ImageWidgetType: { OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>(files.at(j)); qWidget->setVerboseMode(verboseMode); qWidget->setType(type); qWidget->setCheckersBackground(checkers_background); qWidget->m_commands = content; qWidget->resize(width, height); qWidget->show(); activeWidget = qWidget; break; } #ifndef QT_NO_OPENGL case OpenGLBufferType: { QWindow win; win.setSurfaceType(QSurface::OpenGLSurface); win.create(); QOpenGLFramebufferObjectFormat fmt; fmt.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); fmt.setSamples(4); QOpenGLContext ctx; ctx.create(); ctx.makeCurrent(&win); QOpenGLFramebufferObject fbo(width, height, fmt); fbo.bind(); QOpenGLPaintDevice pdev(width, height); QPainter pt(&pdev); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image = fbo.toImage(); QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case OpenGLType: { OnScreenWidget<QGLWidget> *qGLWidget = new OnScreenWidget<QGLWidget>(files.at(j)); qGLWidget->setVerboseMode(verboseMode); qGLWidget->setType(type); qGLWidget->setCheckersBackground(checkers_background); qGLWidget->m_commands = content; qGLWidget->resize(width, height); qGLWidget->show(); activeWidget = qGLWidget; break; } #else case OpenGLType: case OpenGLBufferType: { printf("OpenGL type not supported in this Qt build\n"); break; } #endif #ifdef USE_CUSTOM_DEVICE case CustomDeviceType: { CustomPaintDevice custom(width, height); QPainter pt; pt.begin(&custom); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage *img = custom.image(); if (img) { QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(*img)); label->resize(label->sizeHint()); label->show(); activeWidget = label; img->save("custom_output_pixmap.png", "PNG"); } else { custom.save("custom_output_pixmap.png", "PNG"); } break; } case CustomWidgetType: { OnScreenWidget<CustomWidget> *cWidget = new OnScreenWidget<CustomWidget>; cWidget->setVerboseMode(verboseMode); cWidget->setType(type); cWidget->setCheckersBackground(checkers_background); cWidget->m_filename = files.at(j); cWidget->setWindowTitle(fileinfo.filePath()); cWidget->m_commands = content; cWidget->resize(width, height); cWidget->show(); activeWidget = cWidget; break; } #endif case PixmapType: { QPixmap pixmap(scaledWidth, scaledHeight); pixmap.setDevicePixelRatio(scalefactor); pixmap.fill(Qt::white); QPainter pt(&pixmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); pixmap.save("output_pixmap.png", "PNG"); break; } case BitmapType: { QBitmap bitmap(scaledWidth, scaledHeight); bitmap.setDevicePixelRatio(scalefactor); QPainter pt(&bitmap); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); bitmap.save("output_bitmap.png", "PNG"); QLabel *label = createLabel(); label->setPixmap(bitmap); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case ImageMonoType: case ImageType: { qDebug() << "Creating image"; QImage image(scaledWidth, scaledHeight, type == ImageMonoType ? QImage::Format_MonoLSB : imageFormat); image.setDevicePixelRatio(scalefactor); image.fill(0); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); image.convertToFormat(QImage::Format_ARGB32).save("output_image.png", "PNG"); image.setDevicePixelRatio(1.0); // reset scale factor: display "large" image. #ifndef CONSOLE_APPLICATION QLabel *label = createLabel(); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; #endif break; } case PictureType: { QPicture pic; QPainter pt(&pic); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(0); pt.begin(&image); pt.drawPicture(0, 0, pic); pt.end(); QLabel *label = createLabel(); label->setWindowTitle(fileinfo.absolutePath()); label->setPixmap(QPixmap::fromImage(image)); label->resize(label->sizeHint()); label->show(); activeWidget = label; break; } case PrinterType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QString file = QString(files.at(j)).replace(".", "_") + ".ps"; QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); if (printdlg) { QPrintDialog printDialog(&p, 0); if (printDialog.exec() != QDialog::Accepted) break; } else { p.setOutputFileName(file); } QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); if (!printdlg) { printf("wrote file: %s\n", qPrintable(file)); } Q_ASSERT(!p.paintingActive()); #endif break; } case PsType: case PdfType: { #ifndef QT_NO_PRINTER PaintCommands pcmd(QStringList(), 800, 800); pcmd.setVerboseMode(verboseMode); pcmd.setType(type); pcmd.setCheckersBackground(checkers_background); pcmd.setContents(content); QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution); QFileInfo input(files.at(j)); const QString file = input.baseName() + QLatin1Char('_') + input.suffix() + QStringLiteral(".pdf"); p.setOutputFormat(QPrinter::PdfFormat); p.setOutputFileName(file); p.setPageSize(QPrinter::A4); QPainter pt(&p); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); printf("write file: %s\n", qPrintable(file)); #endif break; } case GrabType: { QImage image(width, height, QImage::Format_ARGB32_Premultiplied); image.fill(QColor(Qt::white).rgb()); QPainter pt(&image); pcmd.setPainter(&pt); pcmd.setFilePath(fileinfo.absolutePath()); pcmd.runCommands(); pt.end(); QImage image1(width, height, QImage::Format_RGB32); image1.fill(QColor(Qt::white).rgb()); QPainter pt1(&image1); pt1.drawImage(QPointF(0, 0), image); pt1.end(); QString filename = QString(files.at(j)).replace(".qps", "_qps") + ".png"; image1.save(filename, "PNG"); printf("%s grabbed to %s\n", qPrintable(files.at(j)), qPrintable(filename)); break; } default: break; } } } #ifndef CONSOLE_APPLICATION if (activeWidget || interactive) { QObject::connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit())); app.exec(); } delete activeWidget; #endif delete interactive_widget; return 0; }
bool ShaderVariation::Create() { Release(); if (!owner_) { compilerOutput_ = "Owner shader has expired"; return false; } object_ = glCreateShader(type_ == VS ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER); if (!object_) { compilerOutput_ = "Could not create shader object"; return false; } const QString& originalShaderCode = owner_->GetSourceCode(type_); QString shaderCode; // Check if the shader code contains a version define int verStart = originalShaderCode.indexOf('#'); int verEnd = 0; if (verStart != -1) { if (originalShaderCode.midRef(verStart + 1, 7) == "version") { verEnd = verStart + 9; while (verEnd < originalShaderCode.length()) { if (originalShaderCode[verEnd].isDigit()) ++verEnd; else break; } // If version define found, insert it first QString versionDefine = originalShaderCode.mid(verStart, verEnd - verStart); shaderCode += versionDefine + "\n"; } } // Force GLSL version 150 if no version define and GL3 is being used if (!verEnd) shaderCode += "#version 150\n"; // Distinguish between VS and PS compile in case the shader code wants to include/omit different things shaderCode += type_ == VS ? "#define COMPILEVS\n" : "#define COMPILEPS\n"; // Add define for the maximum number of supported bones shaderCode += "#define MAXBONES " + QString::number(Graphics::GetMaxBones()) + "\n"; // Prepend the defines to the shader code QStringList defineVec = defines_.split(' ',QString::SkipEmptyParts); for (QString &str : defineVec) { // Add extra space for the checking code below QString defineString = "#define " + str.replace('=', ' ') + " \n"; shaderCode += defineString; // In debug mode, check that all defines are referenced by the shader code #ifdef _DEBUG QString defineCheck = defineString.mid(8, defineString.indexOf(' ', 8) - 8); if (originalShaderCode.indexOf(defineCheck) == -1) URHO3D_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defineCheck); #endif } shaderCode += "#define GL3\n"; // When version define found, do not insert it a second time if (verEnd > 0) shaderCode += originalShaderCode.midRef(verEnd); else shaderCode += originalShaderCode; QByteArray shaderCodeBytes= shaderCode.toLatin1(); const char* shaderCStr = shaderCodeBytes.data(); glShaderSource(object_, 1, &shaderCStr, nullptr); glCompileShader(object_); int compiled, length; glGetShaderiv(object_, GL_COMPILE_STATUS, &compiled); if (!compiled) { glGetShaderiv(object_, GL_INFO_LOG_LENGTH, &length); QByteArray compilerOutputBytes(length,0); int outLength; glGetShaderInfoLog(object_, length, &outLength, compilerOutputBytes.data()); glDeleteShader(object_); object_ = 0; compilerOutput_ = compilerOutputBytes; } else compilerOutput_.clear(); return object_ != 0; }
bool QLinuxFbIntegration::connect(const QString &displaySpec) { const QStringList args = displaySpec.split(QLatin1Char(':')); if (args.contains(QLatin1String("nographicsmodeswitch"))) d_ptr->doGraphicsMode = false; #ifdef QT_QWS_DEPTH_GENERIC if (args.contains(QLatin1String("genericcolors"))) d_ptr->doGenericColors = true; #endif QRegExp ttyRegExp(QLatin1String("tty=(.*)")); if (args.indexOf(ttyRegExp) != -1) d_ptr->ttyDevice = ttyRegExp.cap(1); #if 0 #if Q_BYTE_ORDER == Q_BIG_ENDIAN #ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN if (args.contains(QLatin1String("littleendian"))) #endif QScreen::setFrameBufferLittleEndian(true); #endif #endif // Check for explicitly specified device const int len = 8; // "/dev/fbx" int m = displaySpec.indexOf(QLatin1String("/dev/fb")); QString dev; if (m > 0) dev = displaySpec.mid(m, len); else dev = QLatin1String("/dev/fb0"); if (access(dev.toLatin1().constData(), R_OK|W_OK) == 0) d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDWR); if (d_ptr->fd == -1) { if (access(dev.toLatin1().constData(), R_OK) == 0) d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDONLY); if (d_ptr->fd == 1) { qWarning("Error opening framebuffer device %s", qPrintable(dev)); return false; } } fb_fix_screeninfo finfo; fb_var_screeninfo vinfo; //####################### // Shut up Valgrind memset(&vinfo, 0, sizeof(vinfo)); memset(&finfo, 0, sizeof(finfo)); //####################### /* Get fixed screen information */ if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_FSCREENINFO, &finfo)) { perror("QLinuxFbIntegration::connect"); qWarning("Error reading fixed information"); return false; } if (finfo.type == FB_TYPE_VGA_PLANES) { qWarning("VGA16 video mode not supported"); return false; } /* Get variable screen information */ if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_VSCREENINFO, &vinfo)) { perror("QLinuxFbIntegration::connect"); qWarning("Error reading variable information"); return false; } grayscale = vinfo.grayscale; d = vinfo.bits_per_pixel; if (d == 24) { d = vinfo.red.length + vinfo.green.length + vinfo.blue.length; if (d <= 0) d = 24; // reset if color component lengths are not reported } else if (d == 16) { d = vinfo.red.length + vinfo.green.length + vinfo.blue.length; if (d <= 0) d = 16; } lstep = finfo.line_length; int xoff = vinfo.xoffset; int yoff = vinfo.yoffset; const char* qwssize; if((qwssize=::getenv("QWS_SIZE")) && sscanf(qwssize,"%dx%d",&w,&h)==2) { if (d_ptr->fd != -1) { if ((uint)w > vinfo.xres) w = vinfo.xres; if ((uint)h > vinfo.yres) h = vinfo.yres; } dw=w; dh=h; int xxoff, yyoff; if (sscanf(qwssize, "%*dx%*d+%d+%d", &xxoff, &yyoff) == 2) { if (xxoff < 0 || xxoff + w > (int)(vinfo.xres)) xxoff = vinfo.xres - w; if (yyoff < 0 || yyoff + h > (int)(vinfo.yres)) yyoff = vinfo.yres - h; xoff += xxoff; yoff += yyoff; } else { xoff += (vinfo.xres - w)/2; yoff += (vinfo.yres - h)/2; } } else { dw=w=vinfo.xres; dh=h=vinfo.yres; } if (w == 0 || h == 0) { qWarning("QLinuxFbIntegration::connect(): Unable to find screen geometry, " "will use 320x240."); dw = w = 320; dh = h = 240; } setPixelFormat(vinfo); // Handle display physical size spec. QStringList displayArgs = displaySpec.split(QLatin1Char(':')); QRegExp mmWidthRx(QLatin1String("mmWidth=?(\\d+)")); int dimIdxW = displayArgs.indexOf(mmWidthRx); QRegExp mmHeightRx(QLatin1String("mmHeight=?(\\d+)")); int dimIdxH = displayArgs.indexOf(mmHeightRx); if (dimIdxW >= 0) { mmWidthRx.exactMatch(displayArgs.at(dimIdxW)); physWidth = mmWidthRx.cap(1).toInt(); if (dimIdxH < 0) physHeight = dh*physWidth/dw; } if (dimIdxH >= 0) { mmHeightRx.exactMatch(displayArgs.at(dimIdxH)); physHeight = mmHeightRx.cap(1).toInt(); if (dimIdxW < 0) physWidth = dw*physHeight/dh; } if (dimIdxW < 0 && dimIdxH < 0) { if (vinfo.width != 0 && vinfo.height != 0 && vinfo.width != UINT_MAX && vinfo.height != UINT_MAX) { physWidth = vinfo.width; physHeight = vinfo.height; } else { const int dpi = 72; physWidth = qRound(dw * 25.4 / dpi); physHeight = qRound(dh * 25.4 / dpi); } } dataoffset = yoff * lstep + xoff * d / 8; //qDebug("Using %dx%dx%d screen",w,h,d); /* Figure out the size of the screen in bytes */ size = h * lstep; mapsize = finfo.smem_len; data = (unsigned char *)-1; if (d_ptr->fd != -1) data = (unsigned char *)mmap(0, mapsize, PROT_READ | PROT_WRITE, MAP_SHARED, d_ptr->fd, 0); if ((long)data == -1) { perror("QLinuxFbIntegration::connect"); qWarning("Error: failed to map framebuffer device to memory."); return false; } else { data += dataoffset; } #if 0 canaccel = useOffscreen(); if(canaccel) setupOffScreen(); #endif canaccel = false; // Now read in palette if((vinfo.bits_per_pixel==8) || (vinfo.bits_per_pixel==4)) { screencols= (vinfo.bits_per_pixel==8) ? 256 : 16; int loopc; fb_cmap startcmap; startcmap.start=0; startcmap.len=screencols; startcmap.red=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); startcmap.green=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); startcmap.blue=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); startcmap.transp=(unsigned short int *) malloc(sizeof(unsigned short int)*screencols); if (d_ptr->fd == -1 || ioctl(d_ptr->fd, FBIOGETCMAP, &startcmap)) { perror("QLinuxFbIntegration::connect"); qWarning("Error reading palette from framebuffer, using default palette"); createPalette(startcmap, vinfo, finfo); } int bits_used = 0; for(loopc=0;loopc<screencols;loopc++) { screenclut[loopc]=qRgb(startcmap.red[loopc] >> 8, startcmap.green[loopc] >> 8, startcmap.blue[loopc] >> 8); bits_used |= startcmap.red[loopc] | startcmap.green[loopc] | startcmap.blue[loopc]; } // WORKAROUND: Some framebuffer drivers only return 8 bit // color values, so we need to not bit shift them.. if ((bits_used & 0x00ff) && !(bits_used & 0xff00)) { for(loopc=0;loopc<screencols;loopc++) { screenclut[loopc] = qRgb(startcmap.red[loopc], startcmap.green[loopc], startcmap.blue[loopc]); } qWarning("8 bits cmap returned due to faulty FB driver, colors corrected"); } free(startcmap.red); free(startcmap.green); free(startcmap.blue); free(startcmap.transp); } else {
// Every unix must have its own. It's a standard. Here is AIX. void qt_parseQconfig(QList<QPrinterDescription> *printers) { QFile qconfig(QLatin1String("/etc/qconfig")); if (!qconfig.open(QIODevice::ReadOnly)) return; QTextStream ts(&qconfig); QString line; QString stanzaName; // either a queue or a device name bool up = true; // queue up? default true, can be false QString remoteHost; // null if local QString deviceName; // null if remote QRegExp newStanza(QLatin1String("^[0-z\\-]*:$")); // our basic strategy here is to process each line, detecting new // stanzas. each time we see a new stanza, we check if the // previous stanza was a valid queue for a) a remote printer or b) // a local printer. if it wasn't, we assume that what we see is // the start of the first stanza, or that the previous stanza was // a device stanza, or that there is some syntax error (we don't // report those). do { line = ts.readLine(); bool indented = line[0].isSpace(); line = line.simplified(); int i = line.indexOf(QLatin1Char('=')); if (indented && i != -1) { // line in stanza QString variable = line.left(i).simplified(); QString value=line.mid(i+1, line.length()).simplified(); if (variable == QLatin1String("device")) deviceName = value; else if (variable == QLatin1String("host")) remoteHost = value; else if (variable == QLatin1String("up")) up = !(value.toLower() == QLatin1String("false")); } else if (line[0] == QLatin1Char('*')) { // comment // nothing to do } else if (ts.atEnd() || // end of file, or beginning of new stanza (!indented && line.contains(newStanza))) { if (up && stanzaName.length() > 0 && stanzaName.length() < 21) { if (remoteHost.length()) // remote printer qt_perhapsAddPrinter(printers, stanzaName, remoteHost, QString()); else if (deviceName.length()) // local printer qt_perhapsAddPrinter(printers, stanzaName, QString(), QString()); } line.chop(1); if (line.length() >= 1 && line.length() <= 20) stanzaName = line; up = true; remoteHost.clear(); deviceName.clear(); } else { // syntax error? ignore. } } while (!ts.atEnd()); }