void MainWindowPreferencesFrame::on_maxFilterLineEdit_textEdited(const QString &new_max) { prefs_set_uint_value(pref_recent_df_entries_max_, new_max.toUInt(), pref_stashed); }
void App::loadUnits(Battle *battle) { int count; QFile file("units.txt"); QTextStream stream(&file); if (!file.open(QIODevice::ReadOnly)) { return; } QString inputStr; input(stream, inputStr); count = inputStr.toInt(); for (int i = 0; i < count; i++) { QString name; AttackType atkType; QString animationPath; int lines; int maxFrames; int *frames = new int[lines]; SDL_Rect rect; bool flip; int delay; Position position = Position(0, 0); Size size; int type; bool collideable = true; bool barrier = false; float speed; int HP; uint atkFrame; uint damage; uint range; QSet<int> enemies; QString attackAnimationPath; uint attackAnimationFrames; input(stream, inputStr); name = inputStr; input(stream, inputStr); atkType = AttackType(inputStr.toInt()); input(stream, inputStr); animationPath = inputStr; input(stream, inputStr); lines = inputStr.toInt(); input(stream, inputStr); maxFrames = inputStr.toInt(); for (int j = 0; j < lines; j++) { input(stream, inputStr); frames[j] = inputStr.toInt(); } input(stream, inputStr); rect.w = inputStr.toInt(); input(stream, inputStr); rect.h = inputStr.toInt(); input(stream, inputStr); flip = inputStr.toInt(); input(stream, inputStr); delay = inputStr.toInt(); input(stream, inputStr); size.width = inputStr.toFloat(); input(stream, inputStr); size.height = inputStr.toFloat(); input(stream, inputStr); type = inputStr.toInt(); input(stream, inputStr); speed = inputStr.toFloat(); input(stream, inputStr); HP = inputStr.toInt(); input(stream, inputStr); atkFrame = inputStr.toUInt(); input(stream, inputStr); damage = inputStr.toUInt(); input(stream, inputStr); range = inputStr.toUInt(); input(stream, inputStr); int enemyCount = inputStr.toInt(); for (int j = 0; j < enemyCount; j++) { input(stream, inputStr); enemies << inputStr.toInt(); } input(stream, inputStr); attackAnimationPath = inputStr; input(stream, inputStr); attackAnimationFrames = inputStr.toUInt(); CombinedAnimation *animation = new CombinedAnimation(); animation->setSurface(_core->getSurface(animationPath)); animation->setFrameLines(lines); animation->setMaxFrames(maxFrames); for (int j = 0; j < lines; j++) animation->setFrames(j, frames[j]); animation->setRect(rect); if (flip) animation->flipHorizontal(); AreaItem *item = new AreaItem(position, size, type, collideable, barrier); Animation *atkAnimation = new Animation(); atkAnimation->setSurface(_core->getSurface(attackAnimationPath)); atkAnimation->setFrames(attackAnimationFrames); if (atkType == MELEE) { Melee *unit = new Melee(speed, HP, 0, atkFrame, damage, range, *item, *animation); unit->addEnemyType(enemies); unit->setAtkAnimation(*atkAnimation); unit->startTimer(delay); battle->addPreset(name, unit); } else { Ranger *unit = new Ranger(speed, HP, 0, atkFrame, damage, range, *item, *animation); unit->addEnemyType(enemies); unit->setArrowAnimation(*atkAnimation); unit->startTimer(delay); battle->addPreset(name, unit); } delete animation; delete item; delete atkAnimation; delete[] frames; } }
int preview_helper(const QString &_chanid, const QString &starttime, long long previewFrameNumber, long long previewSeconds, const QSize &previewSize, const QString &infile, const QString &outfile) { // Lower scheduling priority, to avoid problems with recordings. if (setpriority(PRIO_PROCESS, 0, 9)) VERBOSE(VB_GENERAL, "Setting priority failed." + ENO); uint chanid = _chanid.toUInt(); QDateTime recstartts = myth_dt_from_string(starttime); if (!chanid || !recstartts.isValid()) ProgramInfo::ExtractKeyFromPathname(infile, chanid, recstartts); ProgramInfo *pginfo = NULL; if (chanid && recstartts.isValid()) { pginfo = new ProgramInfo(chanid, recstartts); if (!pginfo->GetChanID()) { VERBOSE(VB_IMPORTANT, QString( "Cannot locate recording made on '%1' at '%2'") .arg(chanid).arg(starttime)); delete pginfo; return GENERIC_EXIT_NOT_OK; } pginfo->SetPathname(pginfo->GetPlaybackURL(false, true)); } else if (!infile.isEmpty()) { if (!QFileInfo(infile).isReadable()) { VERBOSE(VB_IMPORTANT, QString( "Cannot read this file '%1'").arg(infile)); return GENERIC_EXIT_NOT_OK; } pginfo = new ProgramInfo( infile, ""/*plot*/, ""/*title*/, ""/*subtitle*/, ""/*director*/, 0/*season*/, 0/*episode*/, 120/*length_in_minutes*/, 1895/*year*/); } else { VERBOSE(VB_IMPORTANT, "Cannot locate recording to preview"); return GENERIC_EXIT_NOT_OK; } PreviewGenerator *previewgen = new PreviewGenerator( pginfo, QString(), PreviewGenerator::kLocal); if (previewFrameNumber >= 0) previewgen->SetPreviewTimeAsFrameNumber(previewFrameNumber); if (previewSeconds >= 0) previewgen->SetPreviewTimeAsSeconds(previewSeconds); previewgen->SetOutputSize(previewSize); previewgen->SetOutputFilename(outfile); bool ok = previewgen->RunReal(); previewgen->deleteLater(); delete pginfo; return (ok) ? GENERIC_EXIT_OK : GENERIC_EXIT_NOT_OK; }
QList<KeyData> QCrmlParser::parseKeyRange(quint32 repoUid) { QList<KeyData> rv; //if keyRange has no ref attribute it must //only be used for creating access control //policies which we do not need to worry about if (attributes().value(QLatin1String("ref")).isNull()) return rv; QStringList mandatoryAttributes; mandatoryAttributes << QLatin1String("firstInt") << QLatin1String("lastInt"); if (!checkMandatoryAttributes(mandatoryAttributes)) return rv; bool ok = false; QString pathPrefix; pathPrefix = attributes().value(QLatin1String("ref")).toString(); if (!pathPrefix.startsWith(QLatin1Char('/'))) pathPrefix.prepend(QLatin1Char('/')); if (!attributes().value(QLatin1String("countInt")).isNull()) { quint32 countInt = uidStringToUInt32(attributes().value(QLatin1String("countInt")).toString(), &ok); if (!ok) { setError(ParseError, QObject::tr("keyRange element has invalid countInt attribute on line %1") .arg(QString::number(lineNumber()))); rv.clear(); return rv; } rv.append(KeyData(pathPrefix,(quint64)countInt + (((quint64)repoUid) << 32), m_target)); } if (!pathPrefix.endsWith(QLatin1Char('/'))) pathPrefix.append(QLatin1Char('/')); quint32 firstInt = uidStringToUInt32(attributes().value(QLatin1String("firstInt")).toString(), &ok); if (!ok) { setError(ParseError, QObject::tr("keyRange element has invalid firstInt attribute on line %1") .arg(QString::number(lineNumber()))); rv.clear(); return rv; } quint32 lastInt = uidStringToUInt32(attributes().value(QLatin1String("lastInt")).toString(),&ok); if (!ok) { setError(ParseError, QObject::tr("keyRange element has invalid lastInt attribute on line %1") .arg(QString::number(lineNumber()))); rv.clear(); return rv; } quint32 maxNum =0; quint32 indexBits = 0; quint32 firstIndex = 0; if (attributes().value(QLatin1String("indexBits")).isNull()) { //keyRange doesn't map to sequence setting maxNum = lastInt - firstInt + 1; for (quint32 i=0; i < maxNum; i++) { rv.append(KeyData(pathPrefix + QString::number(i), (quint64)firstInt + (((quint64)repoUid) << 32) + i, m_target)); } while (!atEnd()) { readNext(); if (QXmlStreamReader::error() != QXmlStreamReader::NoError) { setError(ParseError, QXmlStreamReader::errorString()); rv.clear(); return rv; } if (isEndElement()) break; if (isStartElement()) parseUnknownElement(); } } else { //keyRanges does map to sequence setting indexBits = uidStringToUInt32(attributes().value(QLatin1String("indexBits")).toString(), &ok); if (!ok) { setError(ParseError, QObject::tr("keyRange elment has invalid indexBits attribute on line %1") .arg(QString::number(lineNumber()))); rv.clear(); return rv; } if (!attributes().value(QLatin1String("firstIndex")).isNull()) { QString firstIndexStr = attributes().value(QLatin1String("firstIndex")).toString(); firstIndex = firstIndexStr.toUInt(&ok, 10); if (!ok) { setError(ParseError, QObject::tr("keyRange element has invalid firstIndex attribute on line %1") .arg(QString::number(lineNumber()))); rv.clear(); return rv; } } int indexBitsLSB =0; quint32 bitmask = 1; while ( (bitmask & indexBits) == 0) { bitmask = bitmask << 1; bitmask +=1; indexBitsLSB+=1; } maxNum =( ((lastInt - firstInt) & indexBits) >> indexBitsLSB) + 1 - firstIndex; int indexBitsMSB=31; bitmask = 0x80000000; while ((bitmask & indexBits) == 0) { bitmask = bitmask >> 1; bitmask += 0x80000000; indexBitsMSB -=1; } bitmask = bitmask << 1; quint32 settingIdentifier = lastInt & bitmask; QList<KeyData> subSettings; while (!atEnd()) { readNext(); if (QXmlStreamReader::error() != QXmlStreamReader::NoError) { setError(ParseError, QXmlStreamReader::errorString()); rv.clear(); return rv; } if (isEndElement()) break; if (isStartElement()) { if (name() == "key") { subSettings.append(parseKey(repoUid)); if (QXmlStreamReader::error() != QXmlStreamReader::NoError) { rv.clear(); return rv; } } else { parseUnknownElement(); } } } for(quint32 i = 0; i < maxNum; i++) { for(int j = 0; j < subSettings.count(); j++) { rv.append(KeyData(pathPrefix + QString::number(i) + subSettings.at(j).path(), subSettings.at(j).uid() + settingIdentifier + ((firstIndex + 1*i) << indexBitsLSB), m_target, subSettings.at(j).bitIndex())); } } } return rv; }
bool AnalyzeTask::parseUnsigned(const QString &str, quint32 &value) { bool okay = false; value = str.toUInt(&okay); return okay; }
void WorldController::show(const QString &pk) { World world = World::get(pk.toUInt()); texport(world); render(); }
bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info) { QProcess process; MUtils::init_process(process, QFileInfo(m_avs2wavBin).absolutePath()); process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?"); if(!process.waitForStarted()) { qWarning("AVS2WAV process failed to create!"); qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData()); process.kill(); process.waitForFinished(-1); return false; } bool bInfoHeaderFound = false; while(process.state() != QProcess::NotRunning) { if(*m_abortFlag) { process.kill(); qWarning("Process was aborted on user request!"); break; } if(!process.waitForReadyRead()) { if(process.state() == QProcess::Running) { qWarning("AVS2WAV time out. Killing process and skipping file!"); process.kill(); process.waitForFinished(-1); return false; } } QByteArray data; while(process.canReadLine()) { QString line = QString::fromUtf8(process.readLine().constData()).simplified(); if(!line.isEmpty()) { int index = line.indexOf(':'); if(index > 0) { QString key = line.left(index).trimmed(); QString val = line.mid(index+1).trimmed(); if(bInfoHeaderFound && !key.isEmpty() && !val.isEmpty()) { if(key.compare("TotalSeconds", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int duration = val.toUInt(&ok); if(ok) info.techInfo().setDuration(duration); } if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int samplerate = val.toUInt(&ok); if(ok) info.techInfo().setAudioSamplerate (samplerate); } if(key.compare("Channels", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int channels = val.toUInt(&ok); if(ok) info.techInfo().setAudioChannels(channels); } if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0) { bool ok = false; unsigned int bitdepth = val.toUInt(&ok); if(ok) info.techInfo().setAudioBitdepth(bitdepth); } } } else { if(line.contains("[Audio Info]", Qt::CaseInsensitive)) { info.techInfo().setAudioType("Avisynth"); info.techInfo().setContainerType("Avisynth"); bInfoHeaderFound = true; } } } } } process.waitForFinished(); if(process.state() != QProcess::NotRunning) { process.kill(); process.waitForFinished(-1); } //Check exit code switch(process.exitCode()) { case 0: qDebug("Avisynth script was analyzed successfully."); return true; break; case -5: qWarning("It appears that Avisynth is not installed on the system!"); return false; break; default: qWarning("Failed to open the Avisynth script, bad AVS file?"); return false; break; } }
// Processes the commands entered directly in the server, not the chat messages void Widget::sendCmdLine() { if (!enableGameServer) { logMessage(QObject::tr("This is not a game server, commands are disabled")); return; } QString str = ui->cmdLine->text(); if (str == "clear") { ui->log->clear(); return; } else if (str == "stop") { delete this; return; } else if (str == "listTcpPlayers") { for (int i=0; i<tcpPlayers.size(); i++) { Player* p = tcpPlayers[i]; logMessage(p->name+" "+p->IP+":"+QString().setNum(p->port)); } return; } else if (str.startsWith("setPeer")) { if (udpPlayers.size() == 1) { cmdPeer = udpPlayers[0]; QString peerName = cmdPeer->IP + " " + QString().setNum(cmdPeer->port); logMessage(QObject::tr("UDP: Peer set to %1").arg(peerName)); return; } str = str.right(str.size()-8); QStringList args = str.split(':'); bool ok; if (args.size() != 2) { if (args.size() != 1) { logMessage(QObject::tr("UDP: setPeer takes a pony id or ip:port combination")); return; } quint16 id = args[0].toUInt(&ok); if (!ok) { logMessage(QObject::tr("UDP: setPeer takes a pony id as argument")); return; } for (int i=0; i<udpPlayers.size();i++) { if (udpPlayers[i]->pony.id == id) { cmdPeer = Player::findPlayer(udpPlayers,udpPlayers[i]->IP, udpPlayers[i]->port); logMessage(QObject::tr("UDP: Peer set to %1").arg(udpPlayers[i]->pony.name)); return; } } logMessage(QObject::tr("UDP: Peer not found (id %1)").arg(args[0])); return; } quint16 port = args[1].toUInt(&ok); if (!ok) { logMessage(QObject::tr("UDP: setPeer takes a port as argument")); return; } cmdPeer = Player::findPlayer(udpPlayers,args[0], port); if (cmdPeer->IP!="") logMessage(QObject::tr("UDP: Peer set to %1").arg(str)); else logMessage(QObject::tr("UDP: Peer not found (%1)").arg(str)); return; } else if (str.startsWith("listPeers")) { if (str.size()<=10) { for (int i=0; i<win.udpPlayers.size();i++) win.logMessage(QString().setNum(win.udpPlayers[i]->pony.id) +" ("+QString().setNum(win.udpPlayers[i]->pony.netviewId)+")" +" "+win.udpPlayers[i]->pony.name +" "+win.udpPlayers[i]->IP +":"+QString().setNum(win.udpPlayers[i]->port) +" "+QString().setNum((int)timestampNow()-win.udpPlayers[i]->lastPingTime)+"s"); return; } str = str.right(str.size()-10); Scene* scene = findScene(str); if (scene->name.isEmpty()) win.logMessage(QObject::tr("Can't find scene")); else for (int i=0; i<scene->players.size();i++) win.logMessage(win.udpPlayers[i]->IP +":"+QString().setNum(win.udpPlayers[i]->port) +" "+QString().setNum((int)timestampNow()-win.udpPlayers[i]->lastPingTime)+"s"); return; } else if (str.startsWith("listVortexes")) { for (int i=0; i<scenes.size(); i++) { win.logMessage("Scene "+scenes[i].name); for (int j=0; j<scenes[i].vortexes.size(); j++) win.logMessage("Vortex "+QString().setNum(scenes[i].vortexes[j].id) +" to "+scenes[i].vortexes[j].destName+" " +QString().setNum(scenes[i].vortexes[j].destPos.x)+" " +QString().setNum(scenes[i].vortexes[j].destPos.y)+" " +QString().setNum(scenes[i].vortexes[j].destPos.z)); } return; } else if (str.startsWith("sync")) { win.logMessage(QObject::tr("UDP: Syncing manually")); sync.doSync(); return; } // DEBUG global commands from now on else if (str==("dbgStressLoad")) { // Send all the players to the GemMines at the same time for (int i=0; i<udpPlayers.size(); i++) sendLoadSceneRPC(udpPlayers[i], "GemMines"); return; } else if (str.startsWith("dbgStressLoad")) { str = str.mid(14); // Send all the players to the given scene at the same time for (int i=0; i<udpPlayers.size(); i++) sendLoadSceneRPC(udpPlayers[i], str); return; } else if (str.startsWith("tele")) { str = str.right(str.size()-5); QStringList args = str.split(' '); if (args.size() != 2) { logStatusMessage(QObject::tr("Error: Usage is tele ponyIdToMove destinationPonyId")); return; } bool ok; bool ok1; bool ok2 = false; quint16 sourceID = args[0].toUInt(&ok); quint16 destID = args[1].toUInt(&ok1); Player* sourcePeer; if (!ok && !ok1) { logStatusMessage(QObject::tr("Error: Usage is tele ponyIdToMove destinationPonyId")); return; } for (int i=0; i<udpPlayers.size();i++) { if (udpPlayers[i]->pony.id == sourceID) { sourcePeer = udpPlayers[i]; ok2 = true; break; } } if (!ok2) { logStatusMessage(QObject::tr("Error: Source peer does not exist!")); return; } for (int i=0; i<udpPlayers.size();i++) { if (udpPlayers[i]->pony.id == destID) { logMessage(QObject::tr("UDP: Teleported %1 to %2").arg(sourcePeer->pony.name,udpPlayers[i]->pony.name)); if (udpPlayers[i]->pony.sceneName.toLower() != sourcePeer->pony.sceneName.toLower()) sendLoadSceneRPC(sourcePeer, udpPlayers[i]->pony.sceneName, udpPlayers[i]->pony.pos); else sendMove(sourcePeer, udpPlayers[i]->pony.pos.x, udpPlayers[i]->pony.pos.y, udpPlayers[i]->pony.pos.z); return; } } logMessage(QObject::tr("Error: Destination peer does not exist!")); } if (cmdPeer->IP=="") { logMessage(QObject::tr("Select a peer first with setPeer/listPeers")); return; } else // Refresh peer info { cmdPeer = Player::findPlayer(udpPlayers,cmdPeer->IP, cmdPeer->port); if (cmdPeer->IP=="") { logMessage(QObject::tr("UDP: Peer not found")); return; } } // User commands from now on (requires setPeer) if (str.startsWith("disconnect")) { logMessage(QObject::tr("UDP: Disconnecting")); sendMessage(cmdPeer,MsgDisconnect, "Connection closed by the server admin"); Player::disconnectPlayerCleanup(cmdPeer); // Save game and remove the player } else if (str.startsWith("load")) { str = str.mid(5); sendLoadSceneRPC(cmdPeer, str); } else if (str.startsWith("getPos")) { logMessage(QObject::tr("Pos : ","Short for position") + QString().setNum(cmdPeer->pony.pos.x) + " " + QString().setNum(cmdPeer->pony.pos.y) + " " + QString().setNum(cmdPeer->pony.pos.z)); } else if (str.startsWith("getRot")) { logMessage(QObject::tr("Rot : x=","Short for rotation") + QString().setNum(cmdPeer->pony.rot.x) + ", y=" + QString().setNum(cmdPeer->pony.rot.y) + ", z=" + QString().setNum(cmdPeer->pony.rot.z) + ", w=" + QString().setNum(cmdPeer->pony.rot.w)); } else if (str.startsWith("getPonyData")) { logMessage("ponyData : "+cmdPeer->pony.ponyData.toBase64()); } else if (str.startsWith("sendPonies")) { sendPonies(cmdPeer); } else if (str.startsWith("sendUtils3")) { logMessage(QObject::tr("UDP: Sending Utils3 request")); QByteArray data(1,3); sendMessage(cmdPeer,MsgUserReliableOrdered6,data); } else if (str.startsWith("setPlayerId")) { str = str.right(str.size()-12); QByteArray data(3,4); bool ok; unsigned id = str.toUInt(&ok); if (ok) { logMessage(QObject::tr("UDP: Sending setPlayerId request")); data[1]=(quint8)(id&0xFF); data[2]=(quint8)((id >> 8)&0xFF); sendMessage(cmdPeer,MsgUserReliableOrdered6,data); } else
void RDCddbLookup::readyReadData() { QString line; QString tag; QString value; int index; int code; char buffer[2048]; char offset[256]; int hex; int start; while(lookup_socket->canReadLine()) { line=lookup_socket->readLine(); Profile("recevied from server: \""+line+"\""); sscanf((const char *)line,"%d",&code); switch(lookup_state) { case 0: // Login Banner if((code==200)||(code==201)) { sprintf(buffer,"cddb hello %s %s %s %s", (const char *)lookup_username, (const char *)lookup_hostname, (const char *)lookup_appname, (const char *)lookup_appver); SendToServer(buffer); lookup_state=1; } else { FinishCddbLookup(RDCddbLookup::ProtocolError); } break; case 1: // Handshake Response if((code==200)||(code==402)) { sprintf(buffer,"cddb query %08x %d", lookup_record->discId(),lookup_record->tracks()); for(int i=0;i<lookup_record->tracks();i++) { sprintf(offset," %d",lookup_record->trackOffset(i)); strcat(buffer,offset); } sprintf(offset," %d",lookup_record->discLength()/75); strcat(buffer,offset); SendToServer(buffer); lookup_state=2; } else { FinishCddbLookup(RDCddbLookup::ProtocolError); } break; case 2: // Query Response switch(code) { case 200: // Exact Match start=4; if(sscanf((const char *)line+start,"%s",offset)==1) { lookup_record->setDiscGenre(offset); start+=lookup_record->discGenre().length()+1; } if(sscanf((const char *)line+start,"%x",&hex)==1) { lookup_record->setDiscId(hex); start+=9; } lookup_record->setDiscTitle((const char *)line+start); sprintf(buffer,"cddb read %s %08x\n", (const char *)lookup_record->discGenre(), lookup_record->discId()); SendToServer(buffer); lookup_state=3; break; case 211: // Inexact Match FinishCddbLookup(RDCddbLookup::PartialMatch); break; default: FinishCddbLookup(RDCddbLookup::ProtocolError); break; } break; case 3: // Read Response if((code==210)) { lookup_state=4; } else { FinishCddbLookup(RDCddbLookup::ProtocolError); } break; case 4: // Record Lines if(line[0]!='#') { // Ignore Comments if(line[0]=='.') { // Done FinishCddbLookup(RDCddbLookup::ExactMatch); } ParsePair(&line,&tag,&value,&index); if(tag=="DTITLE") { lookup_record->setDiscTitle(value.left(value.length()-1)); } if(tag=="DYEAR") { lookup_record->setDiscYear(value.toUInt()); } if(tag=="EXTD") { lookup_record-> setDiscExtended(lookup_record->discExtended()+ DecodeString(value)); } if(tag=="PLAYORDER") { lookup_record->setDiscPlayOrder(value); } if((tag=="TTITLE")&&(index!=-1)) { lookup_record->setTrackTitle(index,value.left(value.length()-1)); } if((tag=="EXTT")&&(index!=-1)) { lookup_record-> setTrackExtended(index, lookup_record->trackExtended(index)+value); } } break; } } }
static bool bool_cast(const QString& s) { return !QString::compare(s, QLatin1String("true")) || s.toUInt() == 1; }
/** @brief Compare two version strings. * @param s1 first version string * @param s2 second version string * @return 0 if strings identical, 1 if second is newer, -1 if first. */ int Utils::compareVersionStrings(QString s1, QString s2) { qDebug() << "[Utils] comparing version strings" << s1 << "and" << s2; QString a = s1.trimmed(); QString b = s2.trimmed(); // if strings are identical return 0. if(a.isEmpty()) return 1; if(b.isEmpty()) return -1; while(!a.isEmpty() || !b.isEmpty()) { // trim all leading non-digits and non-dots (dots are removed afterwards) a.remove(QRegExp("^[^\\d\\.]*")); b.remove(QRegExp("^[^\\d\\.]*")); // trim all trailing non-digits for conversion (QString::toInt() // requires this). Copy strings first as replace() changes the string. QString numa = a; QString numb = b; numa.remove(QRegExp("\\D+.*$")); numb.remove(QRegExp("\\D+.*$")); // convert to number bool ok1, ok2; int vala = numa.toUInt(&ok1); int valb = numb.toUInt(&ok2); // if none of the numbers converted successfully we're at trailing garbage. if(!ok1 && !ok2) break; if(!ok1) return 1; if(!ok2) return -1; // if numbers mismatch we have a decision. if(vala != valb) return (vala > valb) ? -1 : 1; // trim leading digits. a.remove(QRegExp("^\\d*")); b.remove(QRegExp("^\\d*")); // If only one of the following characters is a dot that one is // "greater" then anything else. Make sure it's followed by a number, // Otherwise it might be the end of the string or suffix. Do this // before version addon characters check to avoid stopping too early. bool adot = a.contains(QRegExp("^[a-zA-Z]*\\.[0-9]")); bool bdot = b.contains(QRegExp("^[a-zA-Z]*\\.[0-9]")); if(adot && !bdot) return -1; if(!adot && bdot) return 1; // if number is immediately followed by a character consider it as // version addon (like 1.2.3b). In this case compare characters and end // (version numbers like 1.2b.3 aren't handled). QChar ltra; QChar ltrb; if(a.contains(QRegExp("^[a-zA-Z]"))) ltra = a.at(0); if(b.contains(QRegExp("^[a-zA-Z]"))) ltrb = b.at(0); if(ltra != ltrb) return (ltra < ltrb) ? 1 : -1; // both are identical or no addon characters, ignore. // remove modifiers and following dot. a.remove(QRegExp("^[a-zA-Z]*\\.")); b.remove(QRegExp("^[a-zA-Z]*\\.")); } // no differences found. return 0; }
bool Traits<Network::Xml::PConnections>::parse(const QString& src_, Network::Xml::PConnections::value_type& dst_) { bool output = false; dst_ = src_.toUInt(&output); return output; }
bool Traits<Network::Xml::PIpv6Prefix>::parse(const QString& src_, Network::Xml::PIpv6Prefix::value_type& dst_) { bool output = false; dst_ = src_.toUInt(&output); return output; }
void MainWindowPreferencesFrame::on_maxRecentLineEdit_textEdited(const QString &new_max) { prefs_set_uint_value(pref_recent_files_count_max_, new_max.toUInt(), pref_stashed); }
int main( int argc, char *argv[] ) { QApplication::setColorSpec( QApplication::ManyColor ); DesignerApplication a( argc, argv ); DesignerApplication::setOverrideCursor( Qt::WaitCursor ); bool creatPid = FALSE; if ( a.argc() > 1 ) { QString arg1 = a.argv()[ 1 ]; if ( arg1 == "-client" ) { QFile pf( QDir::homeDirPath() + "/.designerpid" ); if ( pf.exists() && pf.open( IO_ReadOnly ) ) { QString pidStr; pf.readLine( pidStr, pf.size() ); QFile f( QDir::homeDirPath() + "/.designerargs" ); f.open( IO_WriteOnly ); QTextStream ts( &f ); for ( int i = 1; i < a.argc(); ++i ) ts << a.argv()[ i ] << " "; ts << endl; f.close(); #if defined(Q_OS_UNIX) if ( kill( pidStr.toInt(), SIGUSR1 ) == -1 ) creatPid = TRUE; else return 0; #elif defined(Q_OS_WIN32) if ( !GetProcessVersion( pidStr.toUInt() ) ) { creatPid = TRUE; } else { if ( a.winVersion() & Qt::WV_NT_based ) SendMessage( HWND_BROADCAST, RegisterWindowMessage((TCHAR*)"QT_DESIGNER_OPEN_FILE"), 0, 0 ); else SendMessage( HWND_BROADCAST, RegisterWindowMessageA("QT_DESIGNER_OPEN_FILE"), 0, 0 ); return 0; } #endif } else { creatPid = TRUE; } } else if(arg1 == "-debug_stderr") { extern bool debugToStderr; //outputwindow.cpp debugToStderr = TRUE; } } if ( creatPid ) { QFile pf( QDir::homeDirPath() + "/.designerpid" ); pf.open( IO_WriteOnly ); QTextStream ts( &pf ); #if defined(Q_OS_UNIX) signal( SIGUSR1, signalHandler ); #endif ts << getpid() << endl; pf.close(); signal( SIGABRT, exitHandler ); signal( SIGFPE, exitHandler ); signal( SIGILL, exitHandler ); signal( SIGINT, exitHandler ); signal( SIGSEGV, exitHandler ); signal( SIGTERM, exitHandler ); } extern void qInitImages_designercore(); qInitImages_designercore(); QSettings config; QString keybase = DesignerApplication::settingsKey(); config.insertSearchPath( QSettings::Windows, "/Trolltech" ); QStringList pluginPaths = config.readListEntry( keybase + "PluginPaths" ); if (pluginPaths.count()) QApplication::setLibraryPaths(pluginPaths); QSplashScreen *splash = a.showSplash(); MainWindow *mw = new MainWindow( creatPid ); a.setMainWidget( mw ); #if defined(QT_NON_COMMERCIAL) mw->setCaption( "Qt Designer by Trolltech for non-commercial use" ); #else mw->setCaption( "Qt Designer by Trolltech" ); #endif if ( config.readBoolEntry( keybase + "Geometries/MainwindowMaximized", FALSE ) ) { int x = config.readNumEntry( keybase + "Geometries/MainwindowX", 0 ); int y = config.readNumEntry( keybase + "Geometries/MainwindowY", 0 ); mw->move( x, y ); mw->showMaximized(); } else { mw->show(); } if ( splash ) splash->finish( mw ); delete splash; QApplication::restoreOverrideCursor(); for ( int i = 1; i < a.argc(); ++i ) { QString arg = a.argv()[ i ]; if ( arg[0] != '-' ) mw->fileOpen( "", "", arg ); } return a.exec(); }
void CustomDownload::onFinished() { // 触发自定义信号 emit requestFinished(request.url().toString()); // 其他数据计算 requestEndTime = QDateTime::currentDateTime().toMSecsSinceEpoch(); totalTime = requestEndTime - requestStartTime; downloadTime = QDateTime::currentDateTime().toMSecsSinceEpoch() - downloadTime; MonitorData *monitorData = new MonitorData(); // TODO: 此部分参见 // http://doc.qt.nokia.com/4.7-snapshot/qnetworkrequest.html // http://doc.qt.nokia.com/4.7-snapshot/qnetworkreply.html monitorData->StatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // 状态码短语:OK/Not Found.... monitorData->ReasonPhrase = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); // 是否来自缓存内容 monitorData->FromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); monitorData->RequestURL = request.url().toString(); monitorData->ResponseSize = bytesTotal; monitorData->ResponseDuration = totalTime; monitorData->ResponseDNSLookupDuration = dnsLookupTime; monitorData->ResponseWaitingDuration = waitingTime; monitorData->ResponseDownloadDuration = downloadTime; monitorData->RequestStartTime = requestStartTime; monitorData->RequestEndTime = requestEndTime; // GET or POST // TODO: 这里有6中状态 偶们把它们都记录下来 // 参看 http://doc.qt.nokia.com/4.7/qnetworkaccessmanager.html monitorData->ResponseMethod = (reply->operation() == QNetworkAccessManager::GetOperation) ? "GET" : (reply->operation() == QNetworkAccessManager::PostOperation) ? "POST" : (reply->operation() == QNetworkAccessManager::HeadOperation) ? "HEAD" : (reply->operation() == QNetworkAccessManager::PutOperation) ? "PUT" : (reply->operation() == QNetworkAccessManager::DeleteOperation) ? "DELETE" : (reply->operation() == QNetworkAccessManager::CustomOperation) ? "CUSTOM": "Unknown"; monitorData->UserAgent = request.rawHeader("User-Agent"); monitorData->Accept = request.rawHeader("Accept"); monitorData->Referer = request.rawHeader("Referer"); QList<QPair<QByteArray, QByteArray> > rawHeaderPairs = reply->rawHeaderPairs(); int c = rawHeaderPairs.size(); for (int i = 0; i < c; ++i) { QString key = rawHeaderPairs.at(i).first; QString value = rawHeaderPairs.at(i).second; //qDebug()<< rawHeaderPairs.at(i).first << " : " << rawHeaderPairs.at(i).second; // 蛋疼的赋值…… if ("Age" == key) { monitorData->Age = value; } else if ("Access-Control-Allow-Origin" == key) { monitorData->AccessControlAllowOrigin = value; } else if ("Cache-Control" == key) { monitorData->CacheControl = value; } else if ("Connection" == key) { monitorData->Connection = value; } else if ("Content-Type" == key) { monitorData->ContentType = value; } else if ("Content-Length" == key) { monitorData->ContentLength = value.toUInt(); } else if ("Content-Encoding" == key) { monitorData->ContentEncoding = value; } else if ("Content-Language" == key) { monitorData->ContentLanguage = value; } else if ("Location" == key) { monitorData->Location = value; } else if ("Cookie" == key) { monitorData->Cookie = value; } else if ("Date" == key) { monitorData->Date = value; } else if ("ETag" == key) { monitorData->ETag= value; } else if ("Expires" == key) { monitorData->Expires = value; } else if ("If-Modified-Since" == key) { monitorData->IfModifiedSince= value; } else if ("Last-Modified" == key) { monitorData->LastModified = value; } else if ("Server" == key) { monitorData->Server = value; } else if ("Set-Cookie" == key) { monitorData->SetCookie = value; } else if ("P3P" == key) { monitorData->P3P = value; } else if ("Accept-Ranges" == key) { monitorData->AcceptRanges = value; } else if ("Vary" == key) { monitorData->Vary = value; } else if ("Transfer-Encoding" == key) { monitorData->TransferEncoding = value; } else if ("Via" == key) { monitorData->Via = value; } else if ("X-Via" == key) { monitorData->XVia = value; } else if ("X-DEBUG-IDC" == key) { monitorData->XDEBUGIDC = value; } else if ("X-Powered-By" == key) { monitorData->XPoweredBy = value; } else if ("X-Cache" == key) { monitorData->XCache = value; } else if ("X-Cache-Lookup" == key) { monitorData->XCacheLookup = value; } else if ("X-Cache-Varnish" == key) { monitorData->XCacheVarnish = value; } else if ("Powered-By-ChinaCache" == key) { monitorData->PoweredByChinaCache = value; } else if ("SINA-LB" == key) { monitorData->SINALB = value; } else { monitorData->other[key] = value; } MonitorDataMap::getMonitorDataMap()->set(monitorData->RequestURL, monitorData); } }
void HistoryConfig::copy() { int cur = cmbStyle->currentItem(); if (cur < 0) return; QString name = m_styles[cur].name; QString newName; QRegExp re("\\.[0-9]+$"); unsigned next = 0; for (vector<StyleDef>::iterator it = m_styles.begin(); it != m_styles.end(); ++it){ QString nn = (*it).name; int n = nn.find(re); if (n < 0) continue; nn = nn.mid(n + 1); next = QMAX(next, nn.toUInt()); } int nn = name.find(re); if (nn >= 0){ newName = name.left(nn); }else{ newName = name; } newName += "."; newName += QString::number(next + 1); string n; n = STYLES; n += QFile::encodeName(name); n += EXT; if (m_styles[cur].bCustom){ n = user_file(n.c_str()); }else{ n = app_file(n.c_str()); } QFile from(QFile::decodeName(n.c_str())); if (!from.open(IO_ReadOnly)){ log(L_WARN, "Can't open %s", n.c_str()); return; } n = STYLES; n += QFile::encodeName(newName); n += EXT; n = user_file(n.c_str()); QFile to(QFile::decodeName((n + BACKUP_SUFFIX).c_str())); if (!to.open(IO_WriteOnly | IO_Truncate)){ log(L_WARN, "Cam't create %s", n.c_str()); return; } string s; s.append(from.size(), '\x00'); from.readBlock((char*)(s.c_str()), from.size()); to.writeBlock(s.c_str(), s.length()); from.close(); const int status = to.status(); #if QT_VERSION >= 0x030200 const QString errorMessage = to.errorString(); #else const QString errorMessage = "write file fail"; #endif to.close(); if (status != IO_Ok) { log(L_ERROR, "IO error during writting to file %s : %s", (const char*)to.name().local8Bit(), (const char*)errorMessage.local8Bit()); return; } // rename to normal file QFileInfo fileInfo(to.name()); QString desiredFileName = QFile::decodeName(n.c_str()); if (!fileInfo.dir().rename(fileInfo.fileName(), desiredFileName)) { log(L_ERROR, "Can't rename file %s to %s", (const char*)fileInfo.fileName().local8Bit(), (const char*)desiredFileName.local8Bit()); return; } s = ""; StyleDef d; d.name = newName; d.bCustom = true; m_styles.push_back(d); fillCombo(QFile::encodeName(newName)); }
StringDataInformation* OsdParser::stringFromXML(const QDomElement& node) { const QString name = node.attribute(QLatin1String("name"), i18n("<invalid name>")); const QString terminatedBy = node.attribute(QLatin1String("terminatedBy")); const QString charCount = node.attribute(QLatin1String("maxCharCount")); const QString byteCount = node.attribute(QLatin1String("maxByteCount")); const QString encoding = node.attribute(QLatin1String("encoding")); StringData::TerminationModes mode = StringData::None; if (!terminatedBy.isEmpty()) mode |= StringData::Sequence; if (!charCount.isEmpty()) mode |= StringData::CharCount; if (!byteCount.isEmpty()) mode |= StringData::ByteCount; if ((mode & StringData::CharCount) && (mode & StringData::ByteCount)) mode &= ~StringData::ByteCount; //when both exists charcount wins StringDataInformation* data = new StringDataInformation(name, encoding); //if mode is None, we assume zero terminated strings bool ok; if (mode == StringData::None) { mode = StringData::Sequence; data->setTerminationCodePoint(0); } else if (mode & StringData::Sequence) { uint term; if (terminatedBy.startsWith(QLatin1String("0x"))) term = terminatedBy.mid(2).toUInt(&ok, 16); else term = terminatedBy.toUInt(&ok, 16); // always a hex value, never okay as normal val if (!ok) kDebug() << "invalid termination codepoint specified " << terminatedBy << " (should be a hex number). Defaulting to 0"; data->setTerminationCodePoint(term); } if (mode & StringData::CharCount) { uint count; if (charCount.startsWith(QLatin1String("0x"))) count = charCount.mid(2).toUInt(&ok, 16); else count = charCount.toUInt(&ok, 10); if (!ok) { kDebug() << "unparseable char count: " << charCount << ", defaulting to 1"; count = 1; } data->setMaxCharCount(count); } if (mode & StringData::ByteCount) { uint count; if (byteCount.startsWith(QLatin1String("0x"))) count = byteCount.mid(2).toUInt(&ok, 16); else count = byteCount.toUInt(&ok, 10); if (!ok) { kDebug() << "unparseable char count: " << byteCount << ", defaulting to 1"; count = 1; } data->setMaxByteCount(count); } return data; }
void AnalyzeTask::updateInfo(AudioFileModel &audioFile, bool &skipNext, QPair<quint32, quint32> &id_val, quint32 &coverType, QByteArray &coverData, const QString &key, const QString &value) { //qWarning("'%s' -> '%s'", MUTILS_UTF8(key), MUTILS_UTF8(value)); /*New Stream*/ if(IS_KEY("Gen_ID") || IS_KEY("Aud_ID")) { if(value.isEmpty()) { skipNext = false; } else { //We ignore all ID's, except for the lowest one! bool ok = false; unsigned int id = value.toUInt(&ok); if(ok) { if(IS_KEY("Gen_ID")) { id_val.first = qMin(id_val.first, id); skipNext = (id > id_val.first); } if(IS_KEY("Aud_ID")) { id_val.second = qMin(id_val.second, id); skipNext = (id > id_val.second); } } else { skipNext = true; } } if(skipNext) { qWarning("Skipping info for non-primary stream!"); } return; } /*Skip or empty?*/ if((skipNext) || value.isEmpty()) { return; } /*Playlist file?*/ if(IS_KEY("Aud_Source")) { skipNext = true; audioFile.techInfo().setContainerType(QString()); audioFile.techInfo().setAudioType(QString()); qWarning("Skipping info for playlist file!"); return; } /*General Section*/ if(IS_SEC("Gen")) { if(IS_KEY("Gen_Format")) { audioFile.techInfo().setContainerType(value); } else if(IS_KEY("Gen_Format_Profile")) { audioFile.techInfo().setContainerProfile(value); } else if(IS_KEY("Gen_Title") || IS_KEY("Gen_Track")) { audioFile.metaInfo().setTitle(value); } else if(IS_KEY("Gen_Duration")) { unsigned int tmp = parseDuration(value); if(tmp > 0) audioFile.techInfo().setDuration(tmp); } else if(IS_KEY("Gen_Artist") || IS_KEY("Gen_Performer")) { audioFile.metaInfo().setArtist(value); } else if(IS_KEY("Gen_Album")) { audioFile.metaInfo().setAlbum(value); } else if(IS_KEY("Gen_Genre")) { audioFile.metaInfo().setGenre(value); } else if(IS_KEY("Gen_Released_Date") || IS_KEY("Gen_Recorded_Date")) { unsigned int tmp = parseYear(value); if(tmp > 0) audioFile.metaInfo().setYear(tmp); } else if(IS_KEY("Gen_Comment")) { audioFile.metaInfo().setComment(value); } else if(IS_KEY("Gen_Track/Position")) { bool ok = false; unsigned int tmp = value.toUInt(&ok); if(ok) audioFile.metaInfo().setPosition(tmp); } else if(IS_KEY("Gen_Cover") || IS_KEY("Gen_Cover_Type")) { if(coverType == UINT_MAX) { coverType = 0; } } else if(IS_KEY("Gen_Cover_Mime")) { QString temp = FIRST_TOK(value); for (quint32 i = 0; MIME_TYPES[i].type; i++) { if (temp.compare(QString::fromLatin1(MIME_TYPES[i].type), Qt::CaseInsensitive) == 0) { coverType = i; break; } } } else if(IS_KEY("Gen_Cover_Data")) { if(!coverData.isEmpty()) coverData.clear(); coverData.append(QByteArray::fromBase64(FIRST_TOK(value).toLatin1())); } else { qWarning("Unknown key '%s' with value '%s' found!", MUTILS_UTF8(key), MUTILS_UTF8(value)); } return; } /*Audio Section*/ if(IS_SEC("Aud")) { if(IS_KEY("Aud_Format")) { audioFile.techInfo().setAudioType(value); } else if(IS_KEY("Aud_Format_Profile")) { audioFile.techInfo().setAudioProfile(value); } else if(IS_KEY("Aud_Format_Version")) { audioFile.techInfo().setAudioVersion(value); } else if(IS_KEY("Aud_Channel(s)")) { bool ok = false; unsigned int tmp = value.toUInt(&ok); if(ok) audioFile.techInfo().setAudioChannels(tmp); } else if(IS_KEY("Aud_SamplingRate")) { bool ok = false; unsigned int tmp = value.toUInt(&ok); if(ok) audioFile.techInfo().setAudioSamplerate(tmp); } else if(IS_KEY("Aud_BitDepth")) { bool ok = false; unsigned int tmp = value.toUInt(&ok); if(ok) audioFile.techInfo().setAudioBitdepth(tmp); } else if(IS_KEY("Aud_Duration")) { unsigned int tmp = parseDuration(value); if(tmp > 0) audioFile.techInfo().setDuration(tmp); } else if(IS_KEY("Aud_BitRate")) { bool ok = false; unsigned int tmp = value.toUInt(&ok); if(ok) audioFile.techInfo().setAudioBitrate(tmp/1000); } else if(IS_KEY("Aud_BitRate_Mode")) { if(!value.compare("CBR", Qt::CaseInsensitive)) audioFile.techInfo().setAudioBitrateMode(AudioFileModel::BitrateModeConstant); if(!value.compare("VBR", Qt::CaseInsensitive)) audioFile.techInfo().setAudioBitrateMode(AudioFileModel::BitrateModeVariable); } else if(IS_KEY("Aud_Encoded_Library")) { audioFile.techInfo().setAudioEncodeLib(value); } else { qWarning("Unknown key '%s' with value '%s' found!", MUTILS_UTF8(key), MUTILS_UTF8(value)); } return; } /*Section not recognized*/ qWarning("Unknown section: %s", MUTILS_UTF8(key)); }
bool Chaser::loadXML(const QDomElement& root) { if (root.tagName() != KXMLQLCFunction) { qWarning() << Q_FUNC_INFO << "Function node not found"; return false; } if (root.attribute(KXMLQLCFunctionType) != typeToString(Function::Chaser)) { qWarning() << Q_FUNC_INFO << root.attribute(KXMLQLCFunctionType) << "is not a chaser"; return false; } /* Load chaser contents */ QDomNode node = root.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCBus) { m_legacyHoldBus = tag.text().toUInt(); } else if (tag.tagName() == KXMLQLCFunctionSpeed) { loadXMLSpeed(tag); } else if (tag.tagName() == KXMLQLCFunctionDirection) { loadXMLDirection(tag); } else if (tag.tagName() == KXMLQLCFunctionRunOrder) { loadXMLRunOrder(tag); } else if (tag.tagName() == KXMLQLCChaserSpeedModes) { QString str; str = tag.attribute(KXMLQLCFunctionSpeedFadeIn); setFadeInMode(stringToSpeedMode(str)); str = tag.attribute(KXMLQLCFunctionSpeedFadeOut); setFadeOutMode(stringToSpeedMode(str)); str = tag.attribute(KXMLQLCFunctionSpeedDuration); setDurationMode(stringToSpeedMode(str)); } else if (tag.tagName() == KXMLQLCChaserSequenceTag) { QString str = tag.attribute(KXMLQLCChaserSequenceBoundScene); enableSequenceMode(str.toUInt()); if (tag.hasAttribute(KXMLQLCChaserSequenceStartTime)) setStartTime(tag.attribute(KXMLQLCChaserSequenceStartTime).toUInt()); if (tag.hasAttribute(KXMLQLCChaserSequenceColor)) setColor(QColor(tag.attribute(KXMLQLCChaserSequenceColor))); if (tag.hasAttribute(KXMLQLCChaserSequenceLocked)) setLocked(true); } else if (tag.tagName() == KXMLQLCFunctionStep) { //! @todo stepNumber is useless if the steps are in the wrong order ChaserStep step; int stepNumber = -1; if (step.loadXML(tag, stepNumber) == true) { if (isSequence() == true) step.fid = getBoundSceneID(); if (stepNumber >= m_steps.size()) m_steps.append(step); else m_steps.insert(stepNumber, step); } } else { qWarning() << Q_FUNC_INFO << "Unknown chaser tag:" << tag.tagName(); } node = node.nextSibling(); } return true; }
unsigned int AnalyzeTask::parseDuration(const QString &str) { bool ok = false; unsigned int value = str.toUInt(&ok); return ok ? (value/1000) : 0; }
void MainWindowPreferencesFrame::on_maxRecentLineEdit_textEdited(const QString &new_max) { pref_recent_df_entries_max_->stashed_val.uint = new_max.toUInt(); }
void MorseTextChannel::messageAcknowledgedCallback(const QString &messageId) { m_core->setMessageRead(m_targetID, messageId.toUInt()); }
void MainWindowPreferencesFrame::on_autoScrollPercentageLineEdit_textEdited(const QString &new_pct) { pref_auto_scroll_percentage_->stashed_val.uint = new_pct.toUInt(); pref_auto_scroll_on_expand_->stashed_val.boolval = TRUE; ui->autoScrollCheckBox->setChecked(true); }
void osg::QMLUniform::setValuetoParse(QString s) { QString temp; vector<string> split; string word; stringstream stream(s.toStdString()); while( getline(stream, word, ' ') ) split.push_back( (word)); switch(_model->getType()) { case osg::Uniform::FLOAT: { float f; f=s.toFloat(); _model->set(f); emit stringValueChanged(s); } break; case osg::Uniform::SAMPLER_1D: case osg::Uniform::SAMPLER_2D: case osg::Uniform::SAMPLER_3D: case osg::Uniform::INT: { stringstream ss; ss<< (s.toInt()); temp=QString(ss.str().c_str()); if(temp==s) { _model->set(s.toInt()); emit stringValueChanged(s); } } break; case osg::Uniform::UNSIGNED_INT: { stringstream ss; ss<< (s.toUInt()); temp=QString(ss.str().c_str()); if(temp==s) { _model->set(s.toUInt()); emit stringValueChanged(s); } } break; case osg::Uniform::FLOAT_VEC4 : { osg::Vec4f v; for(int i=0; i<split.size()&&i<4; i++) { stringstream ss; float f; ss<< (split[i]); ss>>f; v[i]= f; } _model->set(v); emit stringValueChanged(s); } break; case osg::Uniform::FLOAT_VEC3 : { osg::Vec3f v; for(int i=0; i<split.size()&&i<3; i++) { stringstream ss; float f; ss<< (split[i]); ss>>f; v[i]= f; } _model->set(v); emit stringValueChanged(s); } break; case osg::Uniform::FLOAT_VEC2: { osg::Vec2f v; for(int i=0; i<split.size()&&i<2; i++) { stringstream ss; float f; ss<< (split[i]); ss>>f; v[i]= f; } _model->set(v); emit stringValueChanged(s); } break; default: cerr<<" type not parsed YET"<<endl; } _model->dirty(); }
int parseArgs(ParseArgs * a) { QString szServer; QString szPort; int idx; if(a->argc < 2)return KVI_ARGS_RETCODE_OK; for(idx = 1;idx < a->argc;idx++) { QString szMessage; char * p = a->argv[idx]; if((kvi_strLen(p) > 3) && (*p == '-') && (*(p+1) == '-'))p++; if(kvi_strEqualCI("-v",p) || kvi_strEqualCI("-version",p)) { KviQString::appendFormatted(szMessage,"KVIrc %s '%s'\n",KVI_VERSION,KVI_RELEASE_NAME); KviQString::appendFormatted(szMessage,"Sources date: %s\n",KVI_SOURCES_DATE); szMessage += "Build date: "; szMessage += KviBuildInfo::buildDate(); szMessage += "\n"; KviQString::appendFormatted(szMessage,"Home page: http://www.kvirc.net/\n"); #if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) MessageBox(0,szMessage.toLocal8Bit().data(),"KVIrc",0); #else qDebug("%s",szMessage.toLocal8Bit().data()); #endif return KVI_ARGS_RETCODE_STOP; } if(kvi_strEqualCI("-h",p) || kvi_strEqualCI("-help",p)) { KviQString::appendFormatted(szMessage,"Usage:\n"); KviQString::appendFormatted(szMessage," %s [options] [server [port]] [ircurl [ircurl [...]]]\n",a->argv[0]); KviQString::appendFormatted(szMessage," \n"); KviQString::appendFormatted(szMessage,"Available options:\n"); KviQString::appendFormatted(szMessage," -h, --help : Print this help and exit\n"); KviQString::appendFormatted(szMessage," -v, --version: Print version information and exit\n"); KviQString::appendFormatted(szMessage," -c <file> : Use <file> as config file instead of ~/%s\n",KVI_HOME_CONFIG_FILE_NAME); KviQString::appendFormatted(szMessage," (defaults to $HOME/%s if <file> does not exist)\n",KVI_HOME_CONFIG_FILE_NAME); KviQString::appendFormatted(szMessage," -n <file> : Use <file> as config file instead of $HOME/%s\n",KVI_HOME_CONFIG_FILE_NAME); KviQString::appendFormatted(szMessage," (create <file> if it does not exist)\n"); #ifdef COMPILE_NO_IPC KviQString::appendFormatted(szMessage," -f : Accepted but ignored (for compatibility)\n"); #else KviQString::appendFormatted(szMessage," -f : Force a new KVIrc session, even if there is already\n"); KviQString::appendFormatted(szMessage," a running one.\n"); #endif KviQString::appendFormatted(szMessage," -e <commands>: If a KVIrc session is already running, execute\n"); KviQString::appendFormatted(szMessage," the <commands> in that session, otherwise start up\n"); KviQString::appendFormatted(szMessage," normally and execute <commands>\n"); KviQString::appendFormatted(szMessage," <commands> must be a single shell token.\n"); KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); KviQString::appendFormatted(szMessage," -x <commands>: If a KVIrc session is already running, execute\n"); KviQString::appendFormatted(szMessage," the <commands> in that session, otherwise exit from application without doing anything/\n"); KviQString::appendFormatted(szMessage," <commands> must be a single shell token.\n"); KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); KviQString::appendFormatted(szMessage," -r <commands>: If a KVIrc session is already running, execute the <commands>\n"); KviQString::appendFormatted(szMessage," in that session, otherwise start up normally (do not execute).\n"); KviQString::appendFormatted(szMessage," <commands> must be a single shell token.\n"); KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); KviQString::appendFormatted(szMessage," -m : If a KVIrc session is already running, show an informational\n"); KviQString::appendFormatted(szMessage," popup dialog instead of writing to the console\n"); KviQString::appendFormatted(szMessage," --nosplash : Do not show the splash screen at startup\n"); KviQString::appendFormatted(szMessage," [server] : Connect to this server after startup\n"); KviQString::appendFormatted(szMessage," [port] : Use this port for connection\n"); KviQString::appendFormatted(szMessage," [ircurl] : URL in the following form:\n"); KviQString::appendFormatted(szMessage," irc[6]://<server>[:<port>][/<channel>[?<pass>]]\n"); #if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) MessageBox(0,szMessage.toLocal8Bit().data(),"KVIrc",0); #else qDebug("%s",szMessage.toLocal8Bit().data()); #endif return KVI_ARGS_RETCODE_STOP; } if(kvi_strEqualCI("-c",p)) { idx++; if(idx >= a->argc) { qDebug("Option -c requires a config file name"); return KVI_ARGS_RETCODE_ERROR; } p = a->argv[idx]; a->configFile = p; qDebug("Using file %s as config",p); continue; } if(kvi_strEqualCI("-e",p)) { idx++; if(idx >= a->argc) { qDebug("Option -e requires a command"); return KVI_ARGS_RETCODE_ERROR; } p = a->argv[idx]; if(!a->szExecCommand.isEmpty()) a->szExecCommand.append("\n"); a->szExecCommand.append(p); continue; } if(kvi_strEqualCI("-x",p)) { idx++; if(idx >= a->argc) { qDebug("Option -x requires a command"); return KVI_ARGS_RETCODE_ERROR; } p = a->argv[idx]; if(!a->szExecCommand.isEmpty()) a->szExecCommand.append("\n"); a->szExecCommand.append(p); a->bExecuteCommandAndClose=true; continue; } if(kvi_strEqualCI("-r",p)) { idx++; if(idx >= a->argc) { qDebug("Option -r requires a command"); return KVI_ARGS_RETCODE_ERROR; } p = a->argv[idx]; if(!a->szExecRemoteCommand.isEmpty()) a->szExecRemoteCommand.append("\n"); a->szExecRemoteCommand.append(p); continue; } if(kvi_strEqualCI("-m",p)) { a->bShowPopup = true; continue; } if(kvi_strEqualCI("-n",p)) { idx++; if(idx >= a->argc) { qDebug("Option -n requires a config file name"); return KVI_ARGS_RETCODE_ERROR; } p = a->argv[idx]; a->configFile = p; a->createFile=true; qDebug("Using file %s as config",p); continue; } if(kvi_strEqualCI("-nosplash",p)) { a->bShowSplashScreen = false; continue; } if(kvi_strEqualCI("-f",p)) { a->bForceNewSession = true; continue; } if(kvi_strEqualCI("-session",p)||kvi_strEqualCI("-display",p)||kvi_strEqualCI("-name",p)) { // Qt apps are supposed to handle the params to these switches, but we'll skip arg for now idx++; continue; } if(kvi_strEqualCI("-external",p)) { idx++; if(idx >= a->argc) { qDebug("Option --external requires n irc:// url"); return KVI_ARGS_RETCODE_ERROR; } p = a->argv[idx]; if(kvi_strEqualCIN(p,"irc://",6) || kvi_strEqualCIN(p,"irc6://",7) || kvi_strEqualCIN(p,"ircs://",7) || kvi_strEqualCIN(p,"ircs6://",8)) { a->szExecCommand = "openurl "; a->szExecCommand.append(QString::fromLocal8Bit(p).remove(QChar('$')).remove(QChar(';')).remove(QChar('%'))); return KVI_ARGS_RETCODE_OK; } return KVI_ARGS_RETCODE_ERROR; } if(*p != '-') { // no dash if(kvi_strEqualCIN(p,"irc://",6) || kvi_strEqualCIN(p,"irc6://",7) || kvi_strEqualCIN(p,"ircs://",7) || kvi_strEqualCIN(p,"ircs6://",8)) { if(!a->szExecCommand.isEmpty()) a->szExecCommand.append('\n'); a->szExecCommand = "openurl "; a->szExecCommand.append(QString::fromLocal8Bit(p).remove(QChar('$')).remove(QChar(';')).remove(QChar('%'))); } else { QString szTmp = QString::fromLocal8Bit(p); bool bOk; szTmp.toUInt(&bOk); if(bOk) { szPort = szTmp; } else { QString ri = szTmp.right(4); if(KviQString::equalCI(ri,".kvs")) { if(!a->szExecCommand.isEmpty()) a->szExecCommand.append('\n'); a->szExecCommand.append("parse \""); szTmp.replace(QChar('$'), QString("\\$")); szTmp.replace(QChar('\\'), QString("\\\\")); a->szExecCommand.append(szTmp); a->szExecCommand.append('"'); } else if(KviQString::equalCI(ri,".kvt")) { if(!a->szExecCommand.isEmpty()) a->szExecCommand.append('\n'); a->szExecCommand.append("theme.install \""); szTmp.replace(QChar('$'), QString("\\$")); szTmp.replace(QChar('\\'), QString("\\\\")); a->szExecCommand.append(szTmp); a->szExecCommand.append('"'); } else if(KviQString::equalCI(ri,".kva")) { if(!a->szExecCommand.isEmpty()) a->szExecCommand.append('\n'); a->szExecCommand.append("addon.install \""); szTmp.replace(QChar('$'), QString("\\$")); szTmp.replace(QChar('\\'), QString("\\\\")); a->szExecCommand.append(szTmp); a->szExecCommand.append('"'); } else { szServer = szTmp; // assume a plain server name } } } } } if(!szServer.isEmpty()) { if(!a->szExecCommand.isEmpty()) a->szExecCommand.append('\n'); a->szExecCommand.append("server -u "); a->szExecCommand.append(szServer); if(!szPort.isEmpty()) { a->szExecCommand.append(' '); a->szExecCommand.append(szPort); } } return KVI_ARGS_RETCODE_OK; }
CSecureRule* CSecureRule::fromXML(QXmlStreamReader& oXMLdocument, float nVersion) { QXmlStreamAttributes attributes = oXMLdocument.attributes(); const QString sType = attributes.value( "type" ).toString(); if ( sType.isEmpty() ) return NULL; CSecureRule* pRule = NULL; if ( sType.compare( "address", Qt::CaseInsensitive ) == 0 ) { QString sAddress = attributes.value( "address" ).toString(); pRule = new CIPRule(); pRule->parseContent( sAddress ); } else if ( sType.compare( "addressrange", Qt::CaseInsensitive ) == 0 ) { QString sStartAddress = attributes.value( "startaddress" ).toString(); QString sEndAddress = attributes.value( "endaddress" ).toString(); pRule = new CIPRangeRule(); pRule->parseContent( QString("%1-%2").arg(sStartAddress).arg(sEndAddress) ); } else if ( sType.compare( "hash", Qt::CaseInsensitive ) == 0 ) { CHashRule* rule = new CHashRule(); if ( !rule->parseContent( attributes.value( "content" ).toString() ) ) { delete rule; return NULL; } pRule = rule; } else if ( sType.compare( "regexp", Qt::CaseInsensitive ) == 0 ) { CRegularExpressionRule* rule = new CRegularExpressionRule(); if ( !rule->parseContent( attributes.value( "content" ).toString() ) ) { delete rule; return NULL; } pRule = rule; } else if ( sType.compare( "content", Qt::CaseInsensitive ) == 0 ) { const QString sMatch = attributes.value( "match" ).toString(); const QString sContent = attributes.value( "content" ).toString(); const QString sUrn = sContent.left( 4 ); if ( nVersion < 2.0 ) { // This handles "old style" Shareaza RegExp rules. if ( sMatch.compare( "regexp", Qt::CaseInsensitive ) == 0 ) { CRegularExpressionRule* rule = new CRegularExpressionRule(); if ( !rule->parseContent( sContent ) ) { delete rule; return NULL; } pRule = rule; } // This handles "old style" Shareaza hash rules. else if ( sUrn.compare( "urn:", Qt::CaseInsensitive ) == 0 ) { CHashRule* rule = new CHashRule(); if ( !rule->parseContent( sContent ) ) { delete rule; return NULL; } pRule = rule; } } if ( !pRule ) { bool all = ( sMatch.compare( "all", Qt::CaseInsensitive ) == 0 ); if ( all || sMatch.compare( "any", Qt::CaseInsensitive ) == 0 ) { CContentRule* rule = new CContentRule(); if ( !rule->parseContent( sContent ) ) { delete rule; return NULL; } rule->setAll( all ); pRule = rule; } else { return NULL; } } } else { return NULL; } const QString sAction = attributes.value( "action" ).toString(); if ( sAction.compare( "deny", Qt::CaseInsensitive ) == 0 || sAction.isEmpty() ) { pRule->m_nAction = RuleAction::Deny; } else if ( sAction.compare( "accept", Qt::CaseInsensitive ) == 0 ) { pRule->m_nAction = RuleAction::Accept; } else if ( sAction.compare( "null", Qt::CaseInsensitive ) == 0 ) { pRule->m_nAction = RuleAction::None; } else { delete pRule; return NULL; } const QString sAutomatic = attributes.value( "automatic" ).toString(); if(sAutomatic == "true") pRule->m_bAutomatic = true; else pRule->m_bAutomatic = false; pRule->m_sComment = attributes.value( "comment" ).toString().trimmed(); QString sExpire = attributes.value( "expire" ).toString(); if ( sExpire.compare( "forever", Qt::CaseInsensitive ) == 0 ) { pRule->setForever(true); } else if ( sExpire.compare( "session", Qt::CaseInsensitive ) == 0 ) { pRule->setForever(false); pRule->m_tExpire = RuleTime::Special; } else { pRule->m_tExpire = sExpire.toUInt(); } QString sUUID = attributes.value( "uuid" ).toString(); if ( sUUID.isEmpty() ) sUUID = attributes.value( "guid" ).toString(); if ( sUUID.isEmpty() ) { pRule->m_oUUID = QUuid::createUuid(); } else { pRule->m_oUUID = QUuid( sUUID ); } return pRule; }
/* * Capture Factory constructor. * Arguments can be * - [-d | --device] <device number> : camera number * - [-f | --file] <filename> : video file name * - [-m | --mirror] : flip image horizontally * - [-g | --gray] : convert to gray level * - [-s | --size] <width>x<height>: preferred width and height * @param argList program the argument list provided as a list of * strings */ CaptureFactory::CaptureFactory(const QStringList & argList) : capture(NULL), deviceNumber(0), liveVideo(true), flippedVideo(false), grayVideo(false), skipImages(false), preferredWidth(0), preferredHeight(0), videoPath() { // C++ Like iterator // for (QStringList::const_iterator it = argList.begin(); it != argList.end(); ++it) // Java like iterator (because we use hasNext multiple times) for (QListIterator<QString> it(argList); it.hasNext(); ) { QString currentArg(it.next()); if (currentArg == "-d" || currentArg =="--device") { // Next argument should be device number integer if (it.hasNext()) { QString deviceString(it.next()); bool convertOk; deviceNumber = deviceString.toInt(&convertOk,10); if (!convertOk || deviceNumber < 0) { qWarning("Warning: Invalid device number %d",deviceNumber); deviceNumber = 0; } liveVideo = true; } else { qWarning("Warning: device tag found with no following device number"); } } else if (currentArg == "-v" || currentArg == "--video") { // Next argument should be a path name to video file or URL if (it.hasNext()) { videoPath = it.next(); liveVideo = false; } else { qWarning("file tag found with no following filename"); } } else if (currentArg == "-m" || currentArg == "--mirror") { flippedVideo = true; } else if (currentArg == "-g" || currentArg == "--gray") { grayVideo = true; } else if (currentArg == "-k" || currentArg == "--skip") { skipImages = true; } else if (currentArg == "-s" || currentArg == "--size") { if (it.hasNext()) { // search for <width>x<height> QString sizeString = it.next(); int xIndex = sizeString.indexOf(QChar('x'), 0, Qt::CaseInsensitive); if (xIndex != -1) { QString widthString = sizeString.left(xIndex); preferredWidth = widthString.toUInt(); qDebug("preferred width is %d", preferredWidth); QString heightString = sizeString.remove(0, xIndex+1); preferredHeight = heightString.toUInt(); qDebug("preferred height is %d", preferredHeight); } else { qWarning("invalid <width>x<height>"); } } else { qWarning("size not found after --size"); } } } }
void SendMPDialog::sendMPTransaction() { // get the property being sent and get divisibility QString spId = ui->propertyComboBox->itemData(ui->propertyComboBox->currentIndex()).toString(); if (spId.toStdString().empty()) { QMessageBox::critical( this, "Unable to send transaction", "The property selected is not valid.\n\nPlease double-check the transction details thoroughly before retrying your send transaction." ); return; } uint32_t propertyId = spId.toUInt(); bool divisible = isPropertyDivisible(propertyId); // obtain the selected sender address string strFromAddress = ui->sendFromComboBox->currentText().toStdString(); // push recipient address into a CBitcoinAddress type and check validity CBitcoinAddress fromAddress; if (false == strFromAddress.empty()) { fromAddress.SetString(strFromAddress); } if (!fromAddress.IsValid()) { QMessageBox::critical( this, "Unable to send transaction", "The sender address selected is not valid.\n\nPlease double-check the transction details thoroughly before retrying your send transaction." ); return; } // obtain the entered recipient address string strRefAddress = ui->sendToLineEdit->text().toStdString(); // push recipient address into a CBitcoinAddress type and check validity CBitcoinAddress refAddress; if (false == strRefAddress.empty()) { refAddress.SetString(strRefAddress); } if (!refAddress.IsValid()) { QMessageBox::critical( this, "Unable to send transaction", "The recipient address entered is not valid.\n\nPlease double-check the transction details thoroughly before retrying your send transaction." ); return; } // warn if we have to truncate the amount due to a decimal amount for an indivisible property, but allow send to continue string strAmount = ui->amountLineEdit->text().toStdString(); if (!divisible) { size_t pos = strAmount.find("."); if (pos!=std::string::npos) { string tmpStrAmount = strAmount.substr(0,pos); string strMsgText = "The amount entered contains a decimal however the property being sent is indivisible.\n\nThe amount entered will be truncated as follows:\n"; strMsgText += "Original amount entered: " + strAmount + "\nAmount that will be sent: " + tmpStrAmount + "\n\n"; strMsgText += "Do you still wish to proceed with the transaction?"; QString msgText = QString::fromStdString(strMsgText); QMessageBox::StandardButton responseClick; responseClick = QMessageBox::question(this, "Amount truncation warning", msgText, QMessageBox::Yes|QMessageBox::No); if (responseClick == QMessageBox::No) { QMessageBox::critical( this, "Send transaction cancelled", "The send transaction has been cancelled.\n\nPlease double-check the transction details thoroughly before retrying your send transaction." ); return; } strAmount = tmpStrAmount; ui->amountLineEdit->setText(QString::fromStdString(strAmount)); } } // use strToInt64 function to get the amount, using divisibility of the property int64_t sendAmount = StrToInt64(strAmount, divisible); if (0>=sendAmount) { QMessageBox::critical( this, "Unable to send transaction", "The amount entered is not valid.\n\nPlease double-check the transction details thoroughly before retrying your send transaction." ); return; } // check if sending address has enough funds int64_t balanceAvailable = getUserAvailableMPbalance(fromAddress.ToString(), propertyId); //getMPbalance(fromAddress.ToString(), propertyId, MONEY); if (sendAmount>balanceAvailable) { QMessageBox::critical( this, "Unable to send transaction", "The selected sending address does not have a sufficient balance to cover the amount entered.\n\nPlease double-check the transction details thoroughly before retrying your send transaction." ); return; } // check if wallet is still syncing, as this will currently cause a lockup if we try to send - compare our chain to peers to see if we're up to date // Bitcoin Core devs have removed GetNumBlocksOfPeers, switching to a time based best guess scenario uint32_t intBlockDate = GetLatestBlockTime(); // uint32, not using time_t for portability QDateTime currentDate = QDateTime::currentDateTime(); int secs = QDateTime::fromTime_t(intBlockDate).secsTo(currentDate); if(secs > 90*60) { QMessageBox::critical( this, "Unable to send transaction", "The client is still synchronizing. Sending transactions can currently be performed only when the client has completed synchronizing." ); return; } // validation checks all look ok, let's throw up a confirmation dialog string strMsgText = "You are about to send the following transaction, please check the details thoroughly:\n\n"; string propDetails = getPropertyName(propertyId).c_str(); string spNum = strprintf("%d", propertyId); propDetails += " (#" + spNum + ")"; strMsgText += "From: " + fromAddress.ToString() + "\nTo: " + refAddress.ToString() + "\nProperty: " + propDetails + "\nAmount that will be sent: "; if (divisible) { strMsgText += FormatDivisibleMP(sendAmount); } else { strMsgText += FormatIndivisibleMP(sendAmount); } strMsgText += "\n\nAre you sure you wish to send this transaction?"; QString msgText = QString::fromStdString(strMsgText); QMessageBox::StandardButton responseClick; responseClick = QMessageBox::question(this, "Confirm send transaction", msgText, QMessageBox::Yes|QMessageBox::No); if (responseClick == QMessageBox::No) { QMessageBox::critical( this, "Send transaction cancelled", "The send transaction has been cancelled.\n\nPlease double-check the transction details thoroughly before retrying your send transaction." ); return; } // unlock the wallet WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { QMessageBox::critical( this, "Send transaction failed", "The send transaction has been cancelled.\n\nThe wallet unlock process must be completed to send a transaction." ); return; // unlock wallet was cancelled/failed } // create a payload for the transaction std::vector<unsigned char> payload = CreatePayload_SimpleSend(propertyId, sendAmount); // request the wallet build the transaction (and if needed commit it) - note UI does not support added reference amounts currently uint256 txid; std::string rawHex; int result = WalletTxBuilder(fromAddress.ToString(), refAddress.ToString(), "", 0, payload, txid, rawHex, autoCommit); // check error and return the txid (or raw hex depending on autocommit) if (result != 0) { QMessageBox::critical( this, "Send transaction failed", "The send transaction has failed.\n\nThe error code was: " + QString::number(result) + "\nThe error message was:\n" + QString::fromStdString(error_str(result))); return; } else { if (!autoCommit) { PopulateSimpleDialog(rawHex, "Raw Hex (auto commit is disabled)", "Raw transaction hex"); } else { PendingAdd(txid, fromAddress.ToString(), MSC_TYPE_SIMPLE_SEND, propertyId, sendAmount); PopulateTXSentDialog(txid.GetHex()); } } clearFields(); }
bool MyMoneyReport::read ( const QDomElement& e ) { // The goal of this reading method is 100% backward AND 100% forward // compatability. Any report ever created with any version of KMyMoney // should be able to be loaded by this method (as long as it's one of the // report types supported in this version, of course) bool result = false; if ( "REPORT" == e.tagName() && ( ( e.attribute ( "type" ).find ( "pivottable 1." ) == 0 ) || ( e.attribute ( "type" ).find ( "querytable 1." ) == 0 ) || ( e.attribute ( "type" ).find ( "infotable 1." ) == 0 ) ) ) { result = true; clear(); int i; m_name = e.attribute ( "name" ); m_comment = e.attribute ( "comment", "Extremely old report" ); //set report type if(!e.attribute ( "type" ).find ( "pivottable" )) { m_reportType = MyMoneyReport::ePivotTable; } else if(!e.attribute ( "type" ).find ( "querytable" )) { m_reportType = MyMoneyReport::eQueryTable; } else if(!e.attribute ( "type" ).find ( "infotable" )) { m_reportType = MyMoneyReport::eInfoTable; } else { m_reportType = MyMoneyReport::eNoReport; } // Removed the line that screened out loading reports that are called // "Default Report". It's possible for the user to change the comment // to this, and we'd hate for it to break as a result. m_group = e.attribute ( "group" ); m_id = e.attribute ( "id" ); //check for reports with older settings which didn't have the detail attribute if ( e.hasAttribute ( "detail" ) ) { i = kDetailLevelText.findIndex ( e.attribute ( "detail", "all" ) ); if ( i != -1 ) m_detailLevel = static_cast<EDetailLevel> ( i ); } else if ( e.attribute ( "showsubaccounts", "0" ).toUInt() ) { //set to show all accounts m_detailLevel = eDetailAll; } else { //set to show the top level account instead m_detailLevel = eDetailTop; } m_convertCurrency = e.attribute ( "convertcurrency", "1" ).toUInt(); m_favorite = e.attribute ( "favorite", "0" ).toUInt(); m_tax = e.attribute ( "tax", "0" ).toUInt(); m_investments = e.attribute ( "investments", "0" ).toUInt(); m_loans = e.attribute ( "loans", "0" ).toUInt(); m_includeSchedules = e.attribute ( "includeschedules", "0" ).toUInt(); m_columnsAreDays = e.attribute ( "columnsaredays", "0" ).toUInt(); m_includeTransfers = e.attribute ( "includestransfers", "0" ).toUInt(); if ( e.hasAttribute ( "budget" ) ) m_budgetId = e.attribute ( "budget" ); m_includeBudgetActuals = e.attribute ( "includesactuals", "0" ).toUInt(); m_includeUnusedAccounts = e.attribute ( "includeunused", "0" ).toUInt(); m_includeForecast = e.attribute ( "includesforecast", "0" ).toUInt(); m_includePrice = e.attribute ( "includesprice", "0" ).toUInt(); m_includeAveragePrice = e.attribute ( "includesaverageprice", "0" ).toUInt(); m_includeMovingAverage = e.attribute ( "includesmovingaverage", "0" ).toUInt(); if( m_includeMovingAverage ) m_movingAverageDays = e.attribute ( "movingaveragedays", "1" ).toUInt(); //only load chart data if it is a pivot table if ( m_reportType == ePivotTable ) { i = kChartTypeText.findIndex ( e.attribute ( "charttype" ) ); if ( i != -1 ) m_chartType = static_cast<EChartType> ( i ); //if it is invalid, set to first type if (m_chartType == eChartEnd) m_chartType = eChartLine; m_chartDataLabels = e.attribute ( "chartdatalabels", "1" ).toUInt(); m_chartGridLines = e.attribute ( "chartgridlines", "1" ).toUInt(); m_chartByDefault = e.attribute ( "chartbydefault", "0" ).toUInt(); m_chartLineWidth = e.attribute ( "chartlinewidth", "2" ).toUInt(); } else { m_chartType = static_cast<EChartType> ( 0 ); m_chartDataLabels = true; m_chartGridLines = true; m_chartByDefault = false; m_chartLineWidth = 1; } QString datelockstr = e.attribute ( "datelock", "userdefined" ); // Handle the pivot 1.2/query 1.1 case where the values were saved as // numbers bool ok = false; i = datelockstr.toUInt ( &ok ); if ( !ok ) { i = kDateLockText.findIndex ( datelockstr ); if ( i == -1 ) i = userDefined; } setDateFilter ( static_cast<dateOptionE> ( i ) ); i = kRowTypeText.findIndex ( e.attribute ( "rowtype", "expenseincome" ) ); if ( i != -1 ) { setRowType ( static_cast<ERowType> ( i ) ); // recent versions of KMyMoney always showed a total column for // income/expense reports. We turn it on for backward compatability // here. If the total column is turned off, the flag will be reset // in the next step if ( i == eExpenseIncome ) m_showRowTotals = true; } if ( e.hasAttribute ( "showrowtotals" ) ) m_showRowTotals = e.attribute ( "showrowtotals" ).toUInt(); i = kColumnTypeText.findIndex ( e.attribute ( "columntype", "months" ) ); if ( i != -1 ) setColumnType ( static_cast<EColumnType> ( i ) ); unsigned qc = 0; QStringList columns = QStringList::split ( ",", e.attribute ( "querycolumns", "none" ) ); QStringList::const_iterator it_column = columns.begin(); while ( it_column != columns.end() ) { i = kQueryColumnsText.findIndex ( *it_column ); if ( i > 0 ) qc |= ( 1 << ( i - 1 ) ); ++it_column; } setQueryColumns ( static_cast<EQueryColumns> ( qc ) ); QDomNode child = e.firstChild(); while ( !child.isNull() && child.isElement() ) { QDomElement c = child.toElement(); if ( "TEXT" == c.tagName() && c.hasAttribute ( "pattern" ) ) { setTextFilter ( QRegExp ( c.attribute ( "pattern" ), c.attribute ( "casesensitive", "1" ).toUInt(), !c.attribute ( "regex", "1" ).toUInt() ), c.attribute ( "inverttext", "0" ).toUInt() ); } if ( "TYPE" == c.tagName() && c.hasAttribute ( "type" ) ) { i = kTypeText.findIndex ( c.attribute ( "type" ) ); if ( i != -1 ) addType ( i ); } if ( "STATE" == c.tagName() && c.hasAttribute ( "state" ) ) { i = kStateText.findIndex ( c.attribute ( "state" ) ); if ( i != -1 ) addState ( i ); } if ( "NUMBER" == c.tagName() ) { setNumberFilter ( c.attribute ( "from" ), c.attribute ( "to" ) ); } if ( "AMOUNT" == c.tagName() ) { setAmountFilter ( MyMoneyMoney ( c.attribute ( "from", "0/100" ) ), MyMoneyMoney ( c.attribute ( "to", "0/100" ) ) ); } if ( "DATES" == c.tagName() ) { QDate from, to; if ( c.hasAttribute ( "from" ) ) from = QDate::fromString ( c.attribute ( "from" ), Qt::ISODate ); if ( c.hasAttribute ( "to" ) ) to = QDate::fromString ( c.attribute ( "to" ), Qt::ISODate ); MyMoneyTransactionFilter::setDateFilter ( from, to ); } if ( "PAYEE" == c.tagName() ) { addPayee ( c.attribute ( "id" ) ); } if ( "CATEGORY" == c.tagName() && c.hasAttribute ( "id" ) ) { addCategory ( c.attribute ( "id" ) ); } if ( "ACCOUNT" == c.tagName() && c.hasAttribute ( "id" ) ) { addAccount ( c.attribute ( "id" ) ); } if ( "ACCOUNTGROUP" == c.tagName() && c.hasAttribute ( "group" ) ) { i = kAccountTypeText.findIndex ( c.attribute ( "group" ) ); if ( i != -1 ) addAccountGroup ( static_cast<MyMoneyAccount::accountTypeE> ( i ) ); } child = child.nextSibling(); } } return result; }