/** @brief Parse xml-data *----------------------------------------------------------------------------*/ void ParseObject::slotParse(const QByteArray &xmlData, const int &feedId, const QDateTime &dtReply, const QString &codecName) { if (mainApp->isSaveDataLastFeed()) { QFile file(mainApp->dataDir() + "/lastfeed.dat"); file.open(QIODevice::WriteOnly); file.write(xmlData); file.close(); } qDebug() << "=================== parseXml:start ============================"; db_.transaction(); // extract feed id and duplicate news mode from feed table parseFeedId_ = feedId; QString feedUrl; duplicateNewsMode_ = false; QSqlQuery q(db_); q.setForwardOnly(true); q.exec(QString("SELECT duplicateNewsMode, xmlUrl FROM feeds WHERE id=='%1'").arg(parseFeedId_)); if (q.first()) { duplicateNewsMode_ = q.value(0).toBool(); feedUrl = q.value(1).toString(); } // id not found (ex. feed deleted while updating) if (feedUrl.isEmpty()) { qWarning() << QString("Feed with id = '%1' not found").arg(parseFeedId_); emit signalFinishUpdate(parseFeedId_, false, 0, "0"); db_.commit(); return; } qDebug() << QString("Feed '%1' found with id = %2").arg(feedUrl).arg(parseFeedId_); // actually parsing feedChanged_ = false; bool codecOk = false; QString convertData(xmlData); QString feedType; QDomDocument doc; QString errorStr; int errorLine; int errorColumn; QRegExp rx("encoding=\"([^\"]+)", Qt::CaseInsensitive, QRegExp::RegExp2); int pos = rx.indexIn(xmlData); if (pos == -1) { rx.setPattern("encoding='([^']+)"); pos = rx.indexIn(xmlData); } if (pos > -1) { QString codecNameT = rx.cap(1); qDebug() << "Codec name (1):" << codecNameT; QTextCodec *codec = QTextCodec::codecForName(codecNameT.toUtf8()); if (codec) { convertData = codec->toUnicode(xmlData); } else { qWarning() << "Codec not found (1): " << codecNameT << feedUrl; if (codecNameT.contains("us-ascii", Qt::CaseInsensitive)) { QString str(xmlData); convertData = str.remove(rx.cap(0)+"\""); } } } else { if (!codecName.isEmpty()) { qDebug() << "Codec name (2):" << codecName; QTextCodec *codec = QTextCodec::codecForName(codecName.toUtf8()); if (codec) { convertData = codec->toUnicode(xmlData); codecOk = true; } else { qWarning() << "Codec not found (2): " << codecName << feedUrl; } } if (!codecOk) { codecOk = false; QStringList codecNameList; codecNameList << "UTF-8" << "Windows-1251" << "KOI8-R" << "KOI8-U" << "ISO 8859-5" << "IBM 866"; foreach (QString codecNameT, codecNameList) { QTextCodec *codec = QTextCodec::codecForName(codecNameT.toUtf8()); if (codec && codec->canEncode(xmlData)) { qDebug() << "Codec name (3):" << codecNameT; convertData = codec->toUnicode(xmlData); codecOk = true; break; } } if (!codecOk) { convertData = QString::fromLocal8Bit(xmlData); } }
int main(int argc, char *argv[]) { QString title; title = title + "********************************************************************* \n"; title = title + " * Create from XML * \n"; title = title + " * This tool create a SQL DDL script file from a XML schema file * \n"; title = title + " * created by ODKToMySQL. * \n"; title = title + " * * \n"; title = title + " * This tool is usefull when dealing with multiple versions of an * \n"; title = title + " * ODK survey that were combined into a common XML schema using * \n"; title = title + " * compareCreateXML. * \n"; title = title + " ********************************************************************* \n"; TCLAP::CmdLine cmd(title.toUtf8().constData(), ' ', "2.0"); TCLAP::ValueArg<std::string> inputArg("i","input","Input create XML file",true,"","string"); TCLAP::ValueArg<std::string> outputArg("o","output","Output SQL file",false,"./create.sql","string"); for (int i = 1; i < argc; i++) { command = command + argv[i] + " "; } cmd.add(inputArg); cmd.add(outputArg); //Parsing the command lines cmd.parse( argc, argv ); //Getting the variables from the command QString input = QString::fromUtf8(inputArg.getValue().c_str()); QString output = QString::fromUtf8(outputArg.getValue().c_str()); idx = 0; if (input != output) { if (QFile::exists(input)) { //Openning and parsing input file A QDomDocument docA("input"); QFile fileA(input); if (!fileA.open(QIODevice::ReadOnly)) { log("Cannot open input file"); return 1; } if (!docA.setContent(&fileA)) { log("Cannot parse input file"); fileA.close(); return 1; } fileA.close(); QDomElement rootA = docA.documentElement(); if (rootA.tagName() == "XMLSchemaStructure") { QFile file(output); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { log("Cannot create output file"); return 1; } QDateTime date; date = QDateTime::currentDateTime(); QTextStream out(&file); out << "-- Code generated by createFromXML" << "\n"; out << "-- " + command << "\n"; out << "-- Created: " + date.toString("ddd MMMM d yyyy h:m:s ap") << "\n"; out << "-- by: createFromXML Version 1.0" << "\n"; out << "-- WARNING! All changes made in this file might be lost when running createFromXML again" << "\n\n"; QDomNode lkpTables = docA.documentElement().firstChild(); QDomNode tables = docA.documentElement().firstChild().nextSibling(); if (!lkpTables.isNull()) { procLKPTables(lkpTables.firstChild(),out); } if (!tables.isNull()) { procTables(tables.firstChild(),out); } } else { log("Input document is not a XML create file"); return 1; } } else { log("Input file does not exists"); return 1; } } else { log("Fatal: Input files and output file are the same."); return 1; } return 0; }
Action::Action(const QIcon &icon, const QString &text, QObject *parent) : QAction(icon, text, parent), m_identifier(UnknownAction), m_scope(MainWindowScope) { setText(QCoreApplication::translate("actions", text.toUtf8().constData())); }
void MainWindow::on_btnConvert_clicked() { static QString myArray[35][1500]; static QString myArray2[35][1500]; // const char * filename = argv[1]; /* Declare the variables to be used */ QByteArray ba = fileName.toLatin1(); const char *filename = ba.data(); const char field_terminator = ','; const char line_terminator = '\n'; const char enclosure_char = '"'; csv_parser file_parser; /* Define how many records we're gonna skip. This could be used to skip the column definitions. */ file_parser.set_skip_lines(1); /* Specify the file to parse */ file_parser.init(filename); /* Here we tell the parser how to parse the file */ file_parser.set_enclosed_char(enclosure_char, ENCLOSURE_NONE); file_parser.set_field_term_char(field_terminator); file_parser.set_line_term_char(line_terminator); long row_count = 1; long row_width = 0; /* Check to see if there are more records, then grab each row one at a time */ while(file_parser.has_more_rows()) { long i = 0; /* Get the record */ csv_row row = file_parser.get_row(); row_width = row.size(); QString strTmp; for (i = 0; i < row.size(); i++) { if (row_count < 4 || row_count > 5) { strTmp = QString::fromStdString(row[i]); strTmp.simplified(); if (i > 1) { if ( strTmp.isEmpty() && row_count > 5 ) { myArray[i][row_count] = "No translation currently available."; } else { strTmp.remove(QRegExp("\"")); myArray[i][row_count] = strTmp; // LANGUAGE_CODE - enGB etc. } } else if (i == 0) { myArray2[1][row_count] = strTmp; } else if (i == 1) { strTmp.remove(QRegExp("\"")); myArray2[2][row_count] = strTmp; } } } row_count++; } QString strOut = fileName.left(fileName.length() - 3); if ( bJSON ) { strOut = strOut + "json"; ofstream myfile (strOut.toUtf8()); if (myfile.is_open()) { strOut = "{ \"polyglot\": [\n"; myfile << strOut.toStdString(); for (int x = 2; x < row_width; x++) { strOut = "\t{\t\"lang_code\": \"" + myArray[x][1].toUtf8() + "\",\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t\"lang_name_en\": \"" + myArray[x][2].toUtf8() + "\",\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t\"lang_direction\": \"" + myArray[x][3].toUtf8() + "\",\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t\"codes\": [\n"; myfile << strOut.toStdString(); for (int y = 6; y < row_count; y++) { strOut = "\t\t\t{\t\"code\": \"" + myArray2[1][y].toUtf8() + "\",\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t\t\t\"comment\": \"" + myArray2[2][y].toUtf8() + "\",\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t\t\t\"translation\": \"" + myArray[x][y].toUtf8() + "\"\n"; strOut.simplified(); myfile << strOut.toStdString(); if ( y == row_count - 1 && x != row_width - 1) { strOut = "\t\t\t}\n"; myfile << strOut.toStdString(); strOut = "\t\t]\n"; myfile << strOut.toStdString(); strOut = "\t},\n"; myfile << strOut.toStdString(); } else if (y == row_count - 1 && x == row_width - 1) { strOut = "\t\t\t}\n"; myfile << strOut.toStdString(); strOut = "\t\t]\n"; myfile << strOut.toStdString(); strOut = "\t}\n"; myfile << strOut.toStdString(); strOut = "\t]\n"; myfile << strOut.toStdString(); } else { strOut = "\t\t\t},\n"; myfile << strOut.toStdString(); } } myfile.flush(); } strOut = "}"; myfile << strOut.toStdString(); myfile.close(); } else { strOut = ""; ui->txtFile->setText("JSON Conversion Failed! Unable to Open File for Writing."); } } else { strOut = strOut + "xml"; ofstream myfile (strOut.toUtf8()); if (myfile.is_open()) { strOut = "<?xml version = \"1.0\" encoding = \"UTF-8\" ?>\n"; myfile << strOut.toStdString(); strOut = "<root>\n"; myfile << strOut.toStdString(); strOut = "\t<polyglot>\n"; myfile << strOut.toStdString(); for (int x = 2; x < row_width; x++) { strOut = "\t\t<lang_code>" + myArray[x][1].toUtf8() + "</lang_code>\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t<lang_name_en>" + myArray[x][2].toUtf8() + "</lang_name_en>\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t<lang_direction>" + myArray[x][3].toUtf8() + "</lang_direction>\n"; strOut.simplified(); myfile << strOut.toStdString(); for (int y = 6; y < row_count; y++) { strOut = "\t\t<codes>\n"; myfile << strOut.toStdString(); strOut = "\t\t\t<code>" + myArray2[1][y].toUtf8() + "</code>\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t\t<comment>" + myArray2[2][y].toUtf8() + "</comment>\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t\t<translation>" + myArray[x][y].toUtf8() + "</translation>\n"; strOut.simplified(); myfile << strOut.toStdString(); strOut = "\t\t</codes>\n"; myfile << strOut.toStdString(); } myfile.flush(); strOut = "\t</polyglot>\n"; myfile << strOut.toStdString(); if ( x < row_width - 1 ) { strOut = "\t<polyglot>\n"; myfile << strOut.toStdString(); } } strOut = "</root>"; myfile << strOut.toStdString(); myfile.close(); } else { strOut = ""; ui->txtFile->setText("XML Conversion Failed! Unable to Open File for Writing."); } } if ( !strOut.isEmpty() ) { ui->btnConvert->setEnabled(false); if ( bJSON ) { ui->txtFile->setText("JSON Conversion Successful. Please select another file to convert."); } else { ui->txtFile->setText("XML Conversion Successful. Please select another file to convert."); } ui->txtConversion->setText(""); } }
/// // Send message to zsys log sink (may be stdout, or system facility as // configured by zsys_set_logstream). Prefix shows before frame, if not null. void QZframe::print (const QString &prefix) { zframe_print (self, prefix.toUtf8().data()); }
int main(int argc, char **argv ) { QString command; QString user; int c; while ((c = getopt (argc, argv, "c:u:h")) != -1) { if (c == 'c') { command = optarg; qDebug() << "command" << command; continue; } else if (c == 'u') { user = optarg; qDebug() << "user" << user; continue; } else if (c == 'h') { help(); exit(2); } } QApplication app(argc, argv); // expect "root" if there is no user given. I'm not sure if it's right but for now it works... if (user.isNull()) user = "******"; // Get target uid QString auth_user = user; struct passwd *pw = getpwnam(user.toUtf8()); if (pw == 0L) { qDebug() << "User " << user << " does not exist\n"; exit(1); } bool other_uid = (getuid() != pw->pw_uid); bool change_uid = other_uid; if (!change_uid) { char *cur_user = getenv("USER"); if (!cur_user) cur_user = getenv("LOGNAME"); change_uid = (!cur_user || user != cur_user); } // Don't change uid if we're don't need to. if (!change_uid) { int result = system(command.toUtf8()); result = WEXITSTATUS(result); return result; } // Set core dump size to 0 because we will have // root's password in memory. struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 0; if (setrlimit(RLIMIT_CORE, &rlim)) { qDebug() << "rlimit(): " << strerror(errno) << "\n"; exit(1); } // TODO/FIXME: Check if we need a password // Start the Password dialog QString password; SuDialog dlg(user, auth_user, command); int ret = dlg.exec(); if (ret == QDialog::Rejected) { exit(1); } password = dlg.password(); // Some events may need to be handled (like a button animation) qApp->processEvents(); // Run command SuProcess proc(user, password, command); return proc.execute(); }
int main(int argc, char* argv[]) { qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "1"); MyApplication application(argc, argv); QFile f(QString("%1/style.css").arg(QCoreApplication::applicationDirPath())); if(f.open(QFile::ReadOnly | QFile::Text)) { QTextStream in(&f); auto style = in.readAll(); f.close(); application.setStyleSheet(style); } #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QAbstractEventDispatcher::instance(application.thread())->setEventFilter(MyApplication::globalEventFilter); #else auto eventFilter = new MyEventFilter(); application.installNativeEventFilter(eventFilter); #endif // Get the hidden language setting (for testers) if(!BridgeSettingGet("Engine", "Language", currentLocale) || !isValidLocale(currentLocale)) { QStringList uiLanguages = QLocale::system().uiLanguages(); QString sysLocale = uiLanguages.size() ? QLocale(uiLanguages[0]).name() : QLocale::system().name(); strcpy_s(currentLocale, sysLocale.toUtf8().constData()); BridgeSettingSet("Engine", "Language", currentLocale); } // Load translations for Qt QTranslator qtTranslator; if(qtTranslator.load(QString("qt_%1").arg(currentLocale), QLibraryInfo::location(QLibraryInfo::TranslationsPath))) application.installTranslator(&qtTranslator); //x64dbg and x32dbg can share the same translation QTranslator x64dbgTranslator; auto path = QString("%1/../translations").arg(QCoreApplication::applicationDirPath()); if(x64dbgTranslator.load(QString("x64dbg_%1").arg(currentLocale), path)) application.installTranslator(&x64dbgTranslator); TLS_TranslatedStringMap = new std::map<DWORD, TranslatedStringStorage>(); // initialize capstone Capstone::GlobalInitialize(); // load config file + set config font mConfiguration = new Configuration; application.setFont(ConfigFont("Application")); // Register custom data types qRegisterMetaType<dsint>("dsint"); qRegisterMetaType<duint>("duint"); qRegisterMetaType<byte_t>("byte_t"); qRegisterMetaType<DBGSTATE>("DBGSTATE"); // Set QString codec to UTF-8 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); #endif // Init communication with debugger Bridge::initBridge(); // Start GUI MainWindow* mainWindow; mainWindow = new MainWindow(); mainWindow->show(); // Set some data Bridge::getBridge()->winId = (void*)mainWindow->winId(); // Init debugger const char* errormsg = DbgInit(); if(errormsg) { QMessageBox msg(QMessageBox::Critical, QObject::tr("DbgInit Error!"), QString(errormsg)); msg.setWindowIcon(DIcon("compile-error.png")); msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint)); msg.exec(); exit(1); } //execute the application int result = application.exec(); #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) application.removeNativeEventFilter(eventFilter); #else QAbstractEventDispatcher::instance(application.thread())->setEventFilter(nullptr); #endif delete mainWindow; mConfiguration->save(); //save config on exit { //delete tls auto temp = TLS_TranslatedStringMap; TLS_TranslatedStringMap = nullptr; delete temp; } //TODO free capstone/config/bridge and prevent use after free. return result; }
void Posterous::upload(const QUrl &localUrl, const QByteArray &medium, const QByteArray &mediumType) { PosterousSettings::self()->load(); KIO::StoredTransferJob *job = 0; if (PosterousSettings::basic()) { QString login = PosterousSettings::login(); QString pass = Choqok::PasswordManager::self()->readPassword(QStringLiteral("posterous_%1").arg(PosterousSettings::login())); QString token = getAuthToken(localUrl); if (!token.isEmpty()) { QUrl url(QLatin1String("http://posterous.com/api/2/users/me/sites/primary/posts")); QMap<QString, QByteArray> formdata; formdata[QLatin1String("post[title]")] = QByteArray(); formdata[QLatin1String("post[body]")] = QByteArray(); formdata[QLatin1String("autopost")] = "0"; formdata[QLatin1String("source")] = "Choqok"; formdata[QLatin1String("api_token")] = token.toUtf8(); QMap<QString, QByteArray> mediafile; mediafile[QLatin1String("name")] = "media"; mediafile[QLatin1String("filename")] = localUrl.fileName().toUtf8(); mediafile[QLatin1String("mediumType")] = mediumType; mediafile[QLatin1String("medium")] = medium; QList< QMap<QString, QByteArray> > listMediafiles; listMediafiles.append(mediafile); QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles); job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo); job->addMetaData(QLatin1String("customHTTPHeader"), QLatin1String("Authorization: Basic ") + QLatin1String(QStringLiteral("%1:%2").arg(login).arg(pass).toUtf8().toBase64())); } } else if (PosterousSettings::oauth()) { QString alias = PosterousSettings::alias(); if (alias.isEmpty()) { qCritical() << "No account to use"; Q_EMIT uploadingFailed(localUrl, i18n("There is no Twitter account configured to use.")); return; } TwitterApiAccount *acc = qobject_cast<TwitterApiAccount *> (Choqok::AccountManager::self()->findAccount(alias)); if (!acc) { return; } QUrl url(QLatin1String("http://posterous.com/api2/upload.json")); QMap<QString, QByteArray> formdata; formdata[QLatin1String("source")] = "Choqok"; formdata[QLatin1String("sourceLink")] = "http://choqok.gnufolks.org/"; QMap<QString, QByteArray> mediafile; mediafile[QLatin1String("name")] = "media"; mediafile[QLatin1String("filename")] = localUrl.fileName().toUtf8(); mediafile[QLatin1String("mediumType")] = mediumType; mediafile[QLatin1String("medium")] = medium; QList< QMap<QString, QByteArray> > listMediafiles; listMediafiles.append(mediafile); QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles); KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo) ; QOAuth::ParamMap params; QString requrl = QLatin1String("https://api.twitter.com/1/account/verify_credentials.json"); QByteArray credentials = acc->oauthInterface()->createParametersString(requrl, QOAuth::GET, acc->oauthToken(), acc->oauthTokenSecret(), QOAuth::HMAC_SHA1, params, QOAuth::ParseForHeaderArguments); QString cHeader = QLatin1String("X-Verify-Credentials-Authorization: ") + QLatin1String(credentials) + QLatin1String("\r\n"); cHeader.append(QLatin1String("X-Auth-Service-Provider: https://api.twitter.com/1/account/verify_credentials.json")); job->addMetaData(QLatin1String("customHTTPHeader"), cHeader); } if (!job) { qCritical() << "Cannot create a http POST request!"; return; } job->addMetaData(QStringLiteral("content-type"), QStringLiteral("Content-Type: multipart/form-data; boundary=AaB03x")); mUrlMap[job] = localUrl; connect(job, SIGNAL(result(KJob*)), SLOT(slotUpload(KJob*))); job->start(); }
void Logger(QtMsgType type, const char *msg) { #else void Logger(QtMsgType type, const QMessageLogContext &, const QString& qmsg) { const QByteArray msgArray = qmsg.toLocal8Bit(); const char* msg = msgArray.constData(); #endif switch (type) { case QtDebugMsg: fprintf(stdout, "Debug: %s\n", msg); if (sLogfile) fprintf(sLogfile, "Debug: %s\n", msg); break; case QtWarningMsg: fprintf(stdout, "Warning: %s\n", msg); if (sLogfile) fprintf(sLogfile, "Warning: %s\n", msg); break; case QtCriticalMsg: fprintf(stderr, "Critical: %s\n", msg); if (sLogfile) fprintf(sLogfile, "Critical: %s\n", msg); break; case QtFatalMsg: fprintf(stderr, "Fatal: %s\n", msg); if (sLogfile) fprintf(sLogfile, "Fatal: %s\n", msg); abort(); } fflush(0); } int main(int argc, char *argv[]) { // has no effect if qInstallMessageHandler() called //qSetMessagePattern("%{function} @%{line}: %{message}"); QOptions options = get_common_options(); options.add("player options") ("-vo", "gl", "video renderer engine. can be gl, qt, d2d, gdi, xv.") ("ao", "", "audio output. can be 'null'") ("no-ffmpeg-log", "disable ffmpeg log") ; options.parse(argc, argv); if (options.value("help").toBool()) { qDebug() << aboutQtAV_PlainText(); options.print(); return 0; } QApplication a(argc, argv); set_opengl_backend(options.option("gl").value().toString(), a.arguments().first()); load_qm(QStringList() << "player", options.value("language").toString()); sLogfile = fopen(QString(qApp->applicationDirPath() + "/log.txt").toUtf8().constData(), "w+"); if (!sLogfile) { qWarning("Failed to open log file"); sLogfile = stdout; } qInstallMessageHandler(Logger); qDebug() <<a.arguments(); QOption op = options.option("vo"); QString vo = op.value().toString(); if (!op.isSet()) { QString exe(a.arguments().at(0)); int i = exe.lastIndexOf('-'); if (i > 0) { vo = exe.mid(i+1, exe.indexOf('.') - i - 1); } } qDebug("vo: %s", vo.toUtf8().constData()); vo = vo.toLower(); if (vo != "gl" && vo != "d2d" && vo != "gdi" && vo != "xv" && vo != "qt") vo = "gl"; QString title = "QtAV " /*+ vo + " "*/ + QtAV_Version_String_Long() + " [email protected]"; #ifndef QT_NO_OPENGL VideoRendererId vid = VideoRendererId_GLWidget2; #else VideoRendererId vid = VideoRendererId_Widget; #endif // TODO: move to VideoRendererTypes or factory to query name struct { const char* name; VideoRendererId id; } vid_map[] = { { "gl", VideoRendererId_GLWidget2 }, { "d2d", VideoRendererId_Direct2D }, { "gdi", VideoRendererId_GDI }, { "xv", VideoRendererId_XV }, { "qt", VideoRendererId_Widget }, { 0, 0 } }; for (int i = 0; vid_map[i].name; ++i) { if (vo == vid_map[i].name) { vid = vid_map[i].id; break; } } VideoOutput *renderer = new VideoOutput(vid); //or VideoRenderer if (!renderer) { QMessageBox::critical(0, "QtAV", "vo '" + vo + "' not supported"); return 1; } //renderer->scaleInRenderer(false); renderer->setOutAspectRatioMode(VideoRenderer::VideoAspectRatio); MainWindow window; AppEventFilter ae(&window); qApp->installEventFilter(&ae); window.show(); window.setWindowTitle(title); window.setRenderer(renderer); int w = renderer->widget()->width(); int h = renderer->widget()->width()*9/16; int x = window.x(); int y = window.y(); op = options.option("width"); w = op.value().toInt(); op = options.option("height"); h = op.value().toInt(); op = options.option("x"); if (op.isSet()) x = op.value().toInt(); op = options.option("y"); if (op.isSet()) y = op.value().toInt(); window.resize(w, h); window.move(x, y); if (options.value("fullscreen").toBool()) window.showFullScreen(); window.enableAudio(options.value("ao").toString() != "null"); op = options.option("vd"); if (op.isSet()) { QStringList vd = op.value().toString().split(";", QString::SkipEmptyParts); if (!vd.isEmpty()) window.setVideoDecoderNames(vd); } if (options.value("no-ffmpeg-log").toBool()) setFFmpegLogHandler(0); op = options.option("file"); if (op.isSet()) { qDebug() << "-f set: " << op.value().toString(); window.play(op.value().toString()); } else { if (argc > 1 && !a.arguments().last().startsWith('-') && !a.arguments().at(argc-2).startsWith('-')) window.play(a.arguments().last()); } int ret = a.exec(); return ret; }
bool loadPlayerScript(QString path, int player, int difficulty) { ASSERT_OR_RETURN(false, player < MAX_PLAYERS, "Player index %d out of bounds", player); QScriptEngine *engine = new QScriptEngine(); UDWORD size; char *bytes = NULL; if (!loadFile(path.toAscii().constData(), &bytes, &size)) { debug(LOG_ERROR, "Failed to read script file \"%s\"", path.toAscii().constData()); return false; } QString source = QString::fromAscii(bytes, size); free(bytes); QScriptSyntaxCheckResult syntax = QScriptEngine::checkSyntax(source); ASSERT_OR_RETURN(false, syntax.state() == QScriptSyntaxCheckResult::Valid, "Syntax error in %s line %d: %s", path.toAscii().constData(), syntax.errorLineNumber(), syntax.errorMessage().toAscii().constData()); // Special functions engine->globalObject().setProperty("setTimer", engine->newFunction(js_setTimer)); engine->globalObject().setProperty("queue", engine->newFunction(js_queue)); engine->globalObject().setProperty("removeTimer", engine->newFunction(js_removeTimer)); engine->globalObject().setProperty("include", engine->newFunction(js_include)); engine->globalObject().setProperty("bind", engine->newFunction(js_bind)); // Special global variables //== \item[version] Current version of the game, set in \emph{major.minor} format. engine->globalObject().setProperty("version", "3.2", QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[selectedPlayer] The player ontrolled by the client on which the script runs. engine->globalObject().setProperty("selectedPlayer", selectedPlayer, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[gameTime] The current game time. Updated before every invokation of a script. engine->globalObject().setProperty("gameTime", gameTime, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[difficulty] The currently set campaign difficulty, or the current AI's difficulty setting. It will be one of //== EASY, MEDIUM, HARD or INSANE. if (game.type == SKIRMISH) { engine->globalObject().setProperty("difficulty", difficulty, QScriptValue::ReadOnly | QScriptValue::Undeletable); } else // campaign { engine->globalObject().setProperty("difficulty", (int)getDifficultyLevel(), QScriptValue::ReadOnly | QScriptValue::Undeletable); } //== \item[mapName] The name of the current map. engine->globalObject().setProperty("mapName", game.map, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[baseType] The type of base that the game starts with. It will be one of CAMP_CLEAN, CAMP_BASE or CAMP_WALLS. engine->globalObject().setProperty("baseType", game.base, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[alliancesType] The type of alliances permitted in this game. It will be one of NO_ALLIANCES, ALLIANCES or ALLIANCES_TEAMS. engine->globalObject().setProperty("alliancesType", game.alliance, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[powerType] The power level set for this game. engine->globalObject().setProperty("powerType", game.power, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[maxPlayers] The number of active players in this game. engine->globalObject().setProperty("maxPlayers", game.maxPlayers, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[scavengers] Whether or not scavengers are activated in this game. engine->globalObject().setProperty("scavengers", game.scavengers, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[mapWidth] Width of map in tiles. engine->globalObject().setProperty("mapWidth", mapWidth, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[mapHeight] Height of map in tiles. engine->globalObject().setProperty("mapHeight", mapHeight, QScriptValue::ReadOnly | QScriptValue::Undeletable); //== \item[scavengerPlayer] Index of scavenger player. (3.2+ only) engine->globalObject().setProperty("scavengerPlayer", scavengerPlayer(), QScriptValue::ReadOnly | QScriptValue::Undeletable); // Regular functions QFileInfo basename(path); registerFunctions(engine, basename.baseName()); // Remember internal, reserved names QScriptValueIterator it(engine->globalObject()); while (it.hasNext()) { it.next(); internalNamespace.insert(it.name(), 1); } // We need to always save the 'me' special variable. //== \item[me] The player the script is currently running as. engine->globalObject().setProperty("me", player, QScriptValue::ReadOnly | QScriptValue::Undeletable); QScriptValue result = engine->evaluate(source, path); ASSERT_OR_RETURN(false, !engine->hasUncaughtException(), "Uncaught exception at line %d, file %s: %s", engine->uncaughtExceptionLineNumber(), path.toAscii().constData(), result.toString().toAscii().constData()); // We also need to save the special 'scriptName' variable. //== \item[scriptName] Base name of the script that is running. engine->globalObject().setProperty("scriptName", basename.baseName(), QScriptValue::ReadOnly | QScriptValue::Undeletable); // Register script scripts.push_back(engine); debug(LOG_SAVE, "Created script engine %d for player %d from %s", scripts.size() - 1, player, path.toUtf8().constData()); return true; }
void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) { // To clean the progress info emit folderDiscovered(false, QString()); if (discoveryResult < 0 ) { handleSyncError(_csync_ctx, "csync_update"); return; } qDebug() << "<<#### Discovery end #################################################### " << _stopWatch.addLapTime(QLatin1String("Discovery Finished")); // Sanity check if (!_journal->isConnected()) { qDebug() << "Bailing out, DB failure"; emit csyncError(tr("Cannot open the sync journal")); finalize(); return; } else { // Commits a possibly existing (should not though) transaction and starts a new one for the propagate phase _journal->commitIfNeededAndStartNewTransaction("Post discovery"); } if( csync_reconcile(_csync_ctx) < 0 ) { handleSyncError(_csync_ctx, "csync_reconcile"); return; } qDebug() << "<<#### Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Reconcile Finished")); _hasNoneFiles = false; _hasRemoveFile = false; bool walkOk = true; _seenFiles.clear(); _temporarilyUnavailablePaths.clear(); if( csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0 ) { qDebug() << "Error in local treewalk."; walkOk = false; } if( walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0 ) { qDebug() << "Error in remote treewalk."; } if (_csync_ctx->remote.root_perms) { _remotePerms[QLatin1String("")] = _csync_ctx->remote.root_perms; qDebug() << "Permissions of the root folder: " << _remotePerms[QLatin1String("")]; } // Re-init the csync context to free memory csync_commit(_csync_ctx); // The map was used for merging trees, convert it to a list: _syncedItems = _syncItemMap.values().toVector(); _syncItemMap.clear(); // free memory // Adjust the paths for the renames. for (SyncFileItemVector::iterator it = _syncedItems.begin(); it != _syncedItems.end(); ++it) { (*it)->_file = adjustRenamedPath((*it)->_file); } // Sort items per destination std::sort(_syncedItems.begin(), _syncedItems.end()); // make sure everything is allowed checkForPermission(); // To announce the beginning of the sync emit aboutToPropagate(_syncedItems); // it's important to do this before ProgressInfo::start(), to announce start of new sync emit transmissionProgress(*_progressInfo); _progressInfo->start(); if (!_hasNoneFiles && _hasRemoveFile) { qDebug() << Q_FUNC_INFO << "All the files are going to be changed, asking the user"; bool cancel = false; emit aboutToRemoveAllFiles(_syncedItems.first()->_direction, &cancel); if (cancel) { qDebug() << Q_FUNC_INFO << "Abort sync"; finalize(); return; } } // FIXME: The propagator could create his session in propagator_legacy.cpp // There's no reason to keep csync_owncloud.c around ne_session_s *session = 0; // that call to set property actually is a get which will return the session csync_set_module_property(_csync_ctx, "get_dav_session", &session); // post update phase script: allow to tweak stuff by a custom script in debug mode. if( !qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT").isEmpty() ) { #ifndef NDEBUG QString script = qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT"); qDebug() << "OOO => Post Update Script: " << script; QProcess::execute(script.toUtf8()); #else qWarning() << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG"; #endif } // do a database commit _journal->commit("post treewalk"); _propagator = QSharedPointer<OwncloudPropagator>( new OwncloudPropagator (_account, session, _localPath, _remoteUrl, _remotePath, _journal, &_thread)); connect(_propagator.data(), SIGNAL(itemCompleted(const SyncFileItem &, const PropagatorJob &)), this, SLOT(slotItemCompleted(const SyncFileItem &, const PropagatorJob &))); connect(_propagator.data(), SIGNAL(progress(const SyncFileItem &,quint64)), this, SLOT(slotProgress(const SyncFileItem &,quint64))); connect(_propagator.data(), SIGNAL(adjustTotalTransmissionSize(qint64)), this, SLOT(slotAdjustTotalTransmissionSize(qint64))); connect(_propagator.data(), SIGNAL(finished()), this, SLOT(slotFinished()), Qt::QueuedConnection); // apply the network limits to the propagator setNetworkLimits(_uploadLimit, _downloadLimit); deleteStaleDownloadInfos(); deleteStaleUploadInfos(); deleteStaleErrorBlacklistEntries(); _journal->commit("post stale entry removal"); // Emit the started signal only after the propagator has been set up. if (_needsUpdate) emit(started()); _propagator->start(_syncedItems); qDebug() << "<<#### Post-Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Post-Reconcile Finished")); }
/* Currently documented in doc/src/declarative/globalobject.qdoc */ static QScriptValue qmlsqldatabase_open_sync(QScriptContext *context, QScriptEngine *engine) { #ifndef QT_NO_SETTINGS qmlsqldatabase_initDatabasesPath(engine); QSqlDatabase database; QString dbname = context->argument(0).toString(); QString dbversion = context->argument(1).toString(); QString dbdescription = context->argument(2).toString(); int dbestimatedsize = context->argument(3).toNumber(); QScriptValue dbcreationCallback = context->argument(4); QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(dbname.toUtf8()); QString dbid(QLatin1String(md5.result().toHex())); QString basename = qmlsqldatabase_databaseFile(dbid, engine); bool created = false; QString version = dbversion; { QSettings ini(basename+QLatin1String(".ini"),QSettings::IniFormat); if (QSqlDatabase::connectionNames().contains(dbid)) { database = QSqlDatabase::database(dbid); version = ini.value(QLatin1String("Version")).toString(); if (version != dbversion && !dbversion.isEmpty() && !version.isEmpty()) THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch")); } else { created = !QFile::exists(basename+QLatin1String(".sqlite")); if (created) { ini.setValue(QLatin1String("Name"), dbname); if (dbcreationCallback.isFunction()) version = QString(); ini.setValue(QLatin1String("Version"), version); ini.setValue(QLatin1String("Description"), dbdescription); ini.setValue(QLatin1String("EstimatedSize"), dbestimatedsize); ini.setValue(QLatin1String("Driver"), QLatin1String("QSQLITE")); } else { if (!dbversion.isEmpty() && ini.value(QLatin1String("Version")) != dbversion) { // Incompatible THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch")); } version = ini.value(QLatin1String("Version")).toString(); } database = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), dbid); database.setDatabaseName(basename+QLatin1String(".sqlite")); } if (!database.isOpen()) database.open(); } QScriptValue instance = engine->newObject(); instance.setProperty(QLatin1String("transaction"), engine->newFunction(qmlsqldatabase_transaction,1)); instance.setProperty(QLatin1String("readTransaction"), engine->newFunction(qmlsqldatabase_read_transaction,1)); instance.setProperty(QLatin1String("version"), version, QScriptValue::ReadOnly); instance.setProperty(QLatin1String("changeVersion"), engine->newFunction(qmlsqldatabase_change_version,3)); QScriptValue result = engine->newVariant(instance,QVariant::fromValue(database)); if (created && dbcreationCallback.isFunction()) { dbcreationCallback.call(QScriptValue(), QScriptValueList() << result); } return result; #else return engine->undefinedValue(); #endif // QT_NO_SETTINGS }
//SLOT to readyRead. Called upon data arrival void MiniServer::readyRead() { QTcpSocket *socket = (QTcpSocket *)sender(); //Get the socket that sent data int p = 0, len = socDataList.size(); socketData *socDes = NULL; for ( ; p < len; p++) { //Get socDes according to that socket if (socDataList.at(p)->socketDesciptor == socket->socketDescriptor()) { socDes = socDataList.at(p); break; } } QByteArray Data = socket->readAll(); //Read data from the buffer that comes on the socket int i = 0; //Process the message which will start with start byte and then data for (i = 0; i < Data.size(); i++) { //If dataRead is on then read data into buffer till buffer's size is matched to expected size if (!socDes->readingStart && socDes->dataRead && socDes->buffer.size() < (socDes->end-(qint64)(socDes->start.toLong())+1)) { socDes->buffer.append(Data[i]); continue; } //If expected data is in buffer then .... if ((socDes->buffer.size() == (socDes->end - (qint64)(socDes->start.toLong()) + 1)) && socDes->dataRead) { //qDebug() << "got"; fstream file; file.open(this->filename.toUtf8().constData(), ios::in | ios::out | ios::ate); if (!map[(qint64)(socDes->start.toLong())]) { //If data is already not written QCryptographicHash *ha = new QCryptographicHash(QCryptographicHash::Md5); ha->addData(socDes->buffer.constData()); QString hash = QString(ha->result().toHex()); if (!hash.compare(this->pieceHashes.at(((qint64)socDes->start.toLong())/this->pieceSize))) { //Check hash of the piece //Mark it as data written and write data and emit signal that data is written map[(qint64)(socDes->start.toLong())] = true; file.seekp(socDes->start.toLong(), ios::beg); file.write(socDes->buffer.constData(), socDes->buffer.size()); this->numberOfBytesWritten += socDes->buffer.size(); //Update number of bytes written emit dataGot(); if (this->numberOfBytesWritten == this->size) { file.close(); //Check if file transfer is done emit fileTransferDone(); } } else { //If piece is dirty then ask the request the next client to send data. qint64 end = this->size-1 < ((qint64)socDes->start.toLong() + this->pieceSize - 1) ? this->size-1 : ((qint64)socDes->start.toLong() + this->pieceSize - 1); QString request = " R " + QString::number((qint64)socDes->start.toLong()) + " " + QString::number(end) + " "; int i = 0; for ( ; i < clientList.size(); i++) { if (clientList.at(i)->socketDescriptor() == socket->socketDescriptor()) break; } i = (i + 1) % clientList.size(); clientList.at(i)->write(request.toUtf8()); clientList.at(i)->waitForBytesWritten(); file.close(); continue; } } //Issue next request till sizechk is less than size if(this->sizechk < this->size) { qint64 end = this->size-1 < (this->sizechk + this->pieceSize - 1) ? this->size-1 : (this->sizechk + this->pieceSize - 1); QString request = " R " + QString::number(this->sizechk) + " " + QString::number(end) + " "; this->sizechk = end + 1; socket->write(request.toUtf8()); socket->waitForBytesWritten(); } else { //Else check if there is some data missing and request that data qint64 start = 0; while (start < this->size) { if (!map[start]) { qint64 end = this->size-1 < (start + this->pieceSize - 1) ? (this->size - 1) : (start + this->pieceSize - 1); QString request = " R " + QString::number(start) + " " + QString::number(end) + " "; socket->write(request.toUtf8()); socket->waitForBytesWritten(); break; } start += this->pieceSize; } } file.close(); socDes->buffer.clear(); socDes->dataRead = false; continue; } if (!socDes->readingStart) { //Start reading start byte socDes->start.clear(); socDes->readingStart = true; socDes->dataRead = false; continue; } if (socDes->readingStart) { //start reading start till ' ' comes if (char(Data[i]) != ' ') { socDes->start.append(Data[i]); continue; } else { socDes->readingStart = false; //Decide end byte and make dataRead true socDes->end = (this->size - 1) < ((qint64)(socDes->start.toLong()) + this->pieceSize - 1) ? (this->size - 1) : (qint64)(socDes->start.toLong()) + this->pieceSize - 1; socDes->dataRead = true; continue; } } } }
void Core::makeTox(QByteArray savedata) { // IPv6 needed for LAN discovery, but can crash some weird routers. On by default, can be disabled in options. bool enableIPv6 = Settings::getInstance().getEnableIPv6(); bool forceTCP = Settings::getInstance().getForceTCP(); ProxyType proxyType = Settings::getInstance().getProxyType(); int proxyPort = Settings::getInstance().getProxyPort(); QString proxyAddr = Settings::getInstance().getProxyAddr(); QByteArray proxyAddrData = proxyAddr.toUtf8(); if (enableIPv6) qDebug() << "Core starting with IPv6 enabled"; else qWarning() << "Core starting with IPv6 disabled. LAN discovery may not work properly."; Tox_Options toxOptions; tox_options_default(&toxOptions); toxOptions.ipv6_enabled = enableIPv6; toxOptions.udp_enabled = !forceTCP; toxOptions.start_port = toxOptions.end_port = 0; // No proxy by default toxOptions.proxy_type = TOX_PROXY_TYPE_NONE; toxOptions.proxy_host = nullptr; toxOptions.proxy_port = 0; toxOptions.savedata_type = (!savedata.isNull() ? TOX_SAVEDATA_TYPE_TOX_SAVE : TOX_SAVEDATA_TYPE_NONE); toxOptions.savedata_data = (uint8_t*)savedata.data(); toxOptions.savedata_length = savedata.size(); if (proxyType != ProxyType::ptNone) { if (proxyAddr.length() > 255) { qWarning() << "proxy address" << proxyAddr << "is too long"; } else if (proxyAddr != "" && proxyPort > 0) { qDebug() << "using proxy" << proxyAddr << ":" << proxyPort; // protection against changings in TOX_PROXY_TYPE enum if (proxyType == ProxyType::ptSOCKS5) toxOptions.proxy_type = TOX_PROXY_TYPE_SOCKS5; else if (proxyType == ProxyType::ptHTTP) toxOptions.proxy_type = TOX_PROXY_TYPE_HTTP; toxOptions.proxy_host = proxyAddrData.data(); toxOptions.proxy_port = proxyPort; } } TOX_ERR_NEW tox_err; tox = tox_new(&toxOptions, &tox_err); switch (tox_err) { case TOX_ERR_NEW_OK: break; case TOX_ERR_NEW_PORT_ALLOC: if (enableIPv6) { toxOptions.ipv6_enabled = false; tox = tox_new(&toxOptions, &tox_err); if (tox_err == TOX_ERR_NEW_OK) { qWarning() << "Core failed to start with IPv6, falling back to IPv4. LAN discovery may not work properly."; break; } } qCritical() << "can't to bind the port"; emit failedToStart(); return; case TOX_ERR_NEW_PROXY_BAD_HOST: case TOX_ERR_NEW_PROXY_BAD_PORT: qCritical() << "bad proxy"; emit badProxy(); return; case TOX_ERR_NEW_PROXY_NOT_FOUND: qCritical() << "proxy not found"; emit badProxy(); return; case TOX_ERR_NEW_LOAD_ENCRYPTED: qCritical() << "load data is encrypted"; emit failedToStart(); return; case TOX_ERR_NEW_LOAD_BAD_FORMAT: qWarning() << "bad load data format"; break; default: qCritical() << "Tox core failed to start"; emit failedToStart(); return; } av = new CoreAV(tox); if (av->getToxAv() == nullptr) { qCritical() << "Toxav core failed to start"; emit failedToStart(); return; } }
static QByteArray getResponseValue(const QMap<QByteArray, QByteArray> &AResponse, const QString &APassword) { QByteArray secret = QCryptographicHash::hash(AResponse.value("username")+':'+AResponse.value("realm")+':'+APassword.toUtf8(),QCryptographicHash::Md5); QByteArray a1Hex = QCryptographicHash::hash(secret+':'+AResponse.value("nonce")+':'+AResponse.value("cnonce"),QCryptographicHash::Md5).toHex(); QByteArray a2Hex = QCryptographicHash::hash("AUTHENTICATE:"+AResponse.value("digest-uri"),QCryptographicHash::Md5).toHex(); QByteArray value = QCryptographicHash::hash(a1Hex+':'+AResponse.value("nonce")+':'+AResponse.value("nc")+':'+AResponse.value("cnonce")+':'+AResponse.value("qop")+':'+a2Hex,QCryptographicHash::Md5); return value.toHex(); }
QByteArray SimpleCrypt::encryptToByteArray(const QString& plaintext) { QByteArray plaintextArray = plaintext.toUtf8(); return encryptToByteArray(plaintextArray); }
void MythSystemUnix::Fork(time_t timeout) { QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd()); // For use in the child char locerr[MAX_BUFLEN]; strncpy(locerr, (const char *)LOC_ERR.toUtf8().constData(), MAX_BUFLEN); locerr[MAX_BUFLEN-1] = '\0'; LOG(VB_SYSTEM, LOG_DEBUG, QString("Launching: %1").arg(GetLogCmd())); GetBuffer(0)->setBuffer(0); GetBuffer(1)->setBuffer(0); GetBuffer(2)->setBuffer(0); int p_stdin[] = {-1,-1}; int p_stdout[] = {-1,-1}; int p_stderr[] = {-1,-1}; /* set up pipes */ if( GetSetting("UseStdin") ) { if( pipe(p_stdin) == -1 ) { LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdin pipe() failed"); SetStatus( GENERIC_EXIT_NOT_OK ); } else fcntl(p_stdin[1], F_SETFL, O_NONBLOCK); } if( GetSetting("UseStdout") ) { if( pipe(p_stdout) == -1 ) { LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout pipe() failed"); SetStatus( GENERIC_EXIT_NOT_OK ); } else fcntl(p_stdout[0], F_SETFL, O_NONBLOCK); } if( GetSetting("UseStderr") ) { if( pipe(p_stderr) == -1 ) { LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr pipe() failed"); SetStatus( GENERIC_EXIT_NOT_OK ); } else fcntl(p_stderr[0], F_SETFL, O_NONBLOCK); } // set up command args if (GetSetting("UseShell")) { QStringList args = QStringList("-c"); args << GetCommand() + " " + GetArgs().join(" "); SetArgs( args ); QString cmd = "/bin/sh"; SetCommand( cmd ); } QStringList args = GetArgs(); args.prepend(GetCommand().split('/').last()); SetArgs( args ); QByteArray cmdUTF8 = GetCommand().toUtf8(); const char *command = strdup(cmdUTF8.constData()); char **cmdargs = (char **)malloc((args.size() + 1) * sizeof(char *)); int i; QStringList::const_iterator it; for (i = 0, it = args.constBegin(); it != args.constEnd(); ++it) { cmdargs[i++] = strdup(it->toUtf8().constData()); } cmdargs[i] = NULL; const char *directory = NULL; QString dir = GetDirectory(); if (GetSetting("SetDirectory") && !dir.isEmpty()) directory = strdup(dir.toUtf8().constData()); // check before fork to avoid QString use in child bool setpgidsetting = GetSetting("SetPGID"); int niceval = m_parent->GetNice(); int ioprioval = m_parent->GetIOPrio(); /* Do this before forking in case the child miserably fails */ m_timeout = timeout; if( timeout ) m_timeout += time(NULL); pid_t child = fork(); if (child < 0) { /* Fork failed, still in parent */ LOG(VB_SYSTEM, LOG_ERR, "fork() failed: " + ENO); SetStatus( GENERIC_EXIT_NOT_OK ); } else if( child > 0 ) { /* parent */ m_pid = child; SetStatus( GENERIC_EXIT_RUNNING ); LOG(VB_SYSTEM, LOG_INFO, QString("Managed child (PID: %1) has started! " "%2%3 command=%4, timeout=%5") .arg(m_pid) .arg(GetSetting("UseShell") ? "*" : "") .arg(GetSetting("RunInBackground") ? "&" : "") .arg(GetLogCmd()) .arg(timeout)); /* close unused pipe ends */ CLOSE(p_stdin[0]); CLOSE(p_stdout[1]); CLOSE(p_stderr[1]); // store the rest m_stdpipe[0] = p_stdin[1]; m_stdpipe[1] = p_stdout[0]; m_stdpipe[2] = p_stderr[0]; } else if (child == 0) { /* Child - NOTE: it is not safe to use LOG or QString between the * fork and execv calls in the child. It causes occasional locking * issues that cause deadlocked child processes. */ /* handle standard input */ if( p_stdin[0] >= 0 ) { /* try to attach stdin to input pipe - failure is fatal */ if( dup2(p_stdin[0], 0) < 0 ) { cerr << locerr << "Cannot redirect input pipe to standard input: " << strerror(errno) << endl; _exit(GENERIC_EXIT_PIPE_FAILURE); } } else { /* try to attach stdin to /dev/null */ int fd = open("/dev/null", O_RDONLY); if( fd >= 0 ) { if( dup2(fd, 0) < 0) { cerr << locerr << "Cannot redirect /dev/null to standard input," "\n\t\t\tfailed to duplicate file descriptor: " << strerror(errno) << endl; } } else { cerr << locerr << "Cannot redirect /dev/null to standard input, " "failed to open: " << strerror(errno) << endl; } } /* handle standard output */ if( p_stdout[1] >= 0 ) { /* try to attach stdout to output pipe - failure is fatal */ if( dup2(p_stdout[1], 1) < 0) { cerr << locerr << "Cannot redirect output pipe to standard output: " << strerror(errno) << endl; _exit(GENERIC_EXIT_PIPE_FAILURE); } } /* handle standard err */ if( p_stderr[1] >= 0 ) { /* try to attach stderr to error pipe - failure is fatal */ if( dup2(p_stderr[1], 2) < 0) { cerr << locerr << "Cannot redirect error pipe to standard error: " << strerror(errno) << endl; _exit(GENERIC_EXIT_PIPE_FAILURE); } } /* Close all open file descriptors except stdin/stdout/stderr */ for( int i = sysconf(_SC_OPEN_MAX) - 1; i > 2; i-- ) close(i); /* set directory */ if( directory && chdir(directory) < 0 ) { cerr << locerr << "chdir() failed: " << strerror(errno) << endl; } /* Set the process group id to be the same as the pid of this child * process. This ensures that any subprocesses launched by this * process can be killed along with the process itself. */ if (setpgidsetting && setpgid(0,0) < 0 ) { cerr << locerr << "setpgid() failed: " << strerror(errno) << endl; } /* Set nice and ioprio values if non-default */ if (niceval) myth_nice(niceval); if (ioprioval) myth_ioprio(ioprioval); /* run command */ if( execv(command, cmdargs) < 0 ) { // Can't use LOG due to locking fun. cerr << locerr << "execv() failed: " << strerror(errno) << endl; } /* Failed to exec */ _exit(GENERIC_EXIT_DAEMONIZING_ERROR); // this exit is ok } /* Parent */ // clean up the memory use if( command ) free((void *)command); if( directory ) free((void *)directory); if( cmdargs ) { for (i = 0; cmdargs[i]; i++) free( cmdargs[i] ); free( cmdargs ); } if( GetStatus() != GENERIC_EXIT_RUNNING ) { CLOSE(p_stdin[0]); CLOSE(p_stdin[1]); CLOSE(p_stdout[0]); CLOSE(p_stdout[1]); CLOSE(p_stderr[0]); CLOSE(p_stderr[1]); } }
void Codri::Resource::postError(int iSessionId, int iRequestId, int iErrorCode, QString iErrorMessage) { postEvent(new QxtWebErrorEvent(iSessionId, iRequestId, iErrorCode, iErrorMessage.toUtf8())); }
void QED2KHandle::rename_file(int index, const QString& new_name) const { m_delegate.rename_file(new_name.toUtf8().constData()); }
bool WizNoteManager::updateLocalTemplates(const QByteArray& newJsonData, QNetworkAccessManager& manager) { rapidjson::Document d; d.Parse(newJsonData.constData()); if (d.HasParseError()) return false; QString localFile = Utils::WizPathResolve::wizTemplateJsonFilePath(); bool needUpdateJs = true; QMap<int, TemplateData> localTmplMap; QFile file(localFile); if (file.open(QFile::ReadOnly)) { QTextStream stream(&file); QString jsonData = stream.readAll(); rapidjson::Document localD; localD.Parse(jsonData.toUtf8().constData()); if (!localD.HasParseError()) { if (localD.HasMember("template_js_version") && d.HasMember("template_js_version")) { needUpdateJs = (localD.FindMember("template_js_version")->value.GetString() != d.FindMember("template_js_version")->value.GetString()); } } getTemplatesFromJsonData(jsonData.toUtf8(), localTmplMap); } // if (needUpdateJs) { QString link; if (d.HasMember("template_js_link")) { link = d.FindMember("template_js_link")->value.GetString(); } if (!link.isEmpty()) { qDebug() << "get templates js file from url : " << link; QString file = Utils::WizPathResolve::wizTemplateJsFilePath(); QNetworkReply* reply = manager.get(QNetworkRequest(link)); // WizAutoTimeOutEventLoop loop(reply); loop.exec(); // if (loop.error() != QNetworkReply::NoError || loop.result().isEmpty()) return false; QByteArray ba = loop.result(); std::ofstream jsFile(file.toUtf8().constData(), std::ios::out | std::ios::trunc); jsFile << ba.constData(); } } // QMap<int, TemplateData> serverTmplMap; getTemplatesFromJsonData(newJsonData, serverTmplMap); //下载服务器上有更新的模板 for (auto it = serverTmplMap.begin(); it != serverTmplMap.end(); ++it) { auto iter = localTmplMap.find(it.key()); if (iter == localTmplMap.end()) continue; if (iter.value().strVersion != it.value().strVersion || !QFile::exists(it.value().strFileName)) { QString strUrl = WizCommonApiEntry::asServerUrl() + "/a/templates/download/" + QString::number(it.value().id); QFileInfo info(it.value().strFileName); WizFileDownloader* downloader = new WizFileDownloader(strUrl, info.fileName(), info.absolutePath() + "/", false); downloader->startDownload(); } } //删除服务器上不存在的模板 for (auto it = localTmplMap.begin(); it != localTmplMap.end(); ++it) { auto iter = serverTmplMap.find(it.key()); if (iter == localTmplMap.end()) { WizDeleteFile(it.value().strFileName); } } return true; }
QString User::EncryptPw(QString Password) { return QString(QCryptographicHash::hash(Password.toUtf8(), QCryptographicHash::Md5).toHex()); }
QString AFormatter::formatHyperlinks (const QString& text) { QString result = text; QRegExp url1("\\[url\\](.+)\\[/url\\]", Qt::CaseInsensitive, QRegExp::RegExp); QRegExp url2("\\[url=(\\S+)\\](.+)\\[/url\\]", Qt::CaseInsensitive, QRegExp::RegExp); url1.setMinimal(true); url2.setMinimal(true); int index = 0; while ((index = url1.indexIn(result, index)) != -1) { QString html; QString lstr = url1.cap(1); int lval = AParser::isURL(lstr); if (lval == 1) html = QString::fromUtf8("<a href='") + lstr + "'>" + lstr + "</a>"; else if (lval == 2) // опасная ссылка html = "<span class='alert'>" + lstr + "</span>"; else // невалидная ссылка html = lstr; result.replace(url1.cap(0), html); index += std::min(url1.matchedLength(), html.length()); } index = 0; while ((index = url2.indexIn(result, index)) != -1) { QString html; QString lstr = url2.cap(1); QString rstr = url2.cap(2); int lval = AParser::isURL(lstr); int rval = AParser::isURL(rstr); if (lval == 1) html = "<a href='" + lstr + "'>" + rstr + "</a>"; else if (rval == 1) html = "<a href='" + rstr + "'>" + lstr + "</a>"; else if (lval == 2) html = "<span class='alert'>" + rstr + "</span>"; else if (rval == 2) html = "<span class='alert'>" + lstr + "</span>"; else // невалидная ссылка html = rstr + " (" + lstr + ")"; result.replace(url2.cap(0), html); index += std::min(url2.matchedLength(), html.length()); } // ссылки без тэгов QRegExp url3("[^'>]((http://|https://|ftp://|[^/]www\\.)[^<\\s]+)", Qt::CaseInsensitive, QRegExp::RegExp); index = 0; while ((index = url3.indexIn(result, index)) != -1) { QString html; QString lstr = url3.cap(1); int lval = AParser::isURL(lstr); if (lval == 1) { html = QString::fromUtf8("<a href='") + lstr + "'>" + QUrl::fromPercentEncoding(lstr.toUtf8()) + "</a>"; result.replace(lstr, html); index += std::min(url3.matchedLength(), html.length()); } else // невалидная или опасная ссылка index += url3.matchedLength(); } // email url QRegExp email("\\[email\\](\\S+)\\[/email\\]", Qt::CaseInsensitive, QRegExp::RegExp); email.setMinimal(true); index = 0; while ((index = email.indexIn(result, index)) != -1) { QString html; QString lstr = email.cap(1); int lval = AParser::isURL(lstr); if (lval == 1) html = QString::fromUtf8("<a href='mailto:") + lstr + "'>" + lstr + "</a>"; else if (lval == 2) html = lstr; else // невалидная ссылка html = lstr; result.replace(email.cap(0), html); index += std::min(email.matchedLength(), html.length()); } // msdn url QRegExp msdn("\\[msdn\\](\\S+)\\[/msdn\\]", Qt::CaseInsensitive, QRegExp::RegExp); msdn.setMinimal(true); result.replace(msdn, "<a href='http://search.msdn.microsoft.com/Default.aspx?brand=Msdn&query=\\1'>\\1</a>"); return result; }
/// // Return TRUE if frame body is equal to string, excluding terminator bool QZframe::streqNoConflict (const QString &string) { bool rv = zframe_streq (self, string.toUtf8().data()); return rv; }
Settings::KeyPair CertWizard::generateNewCert(QString qsname, const QString &qsemail) { CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); X509 *x509 = X509_new(); EVP_PKEY *pkey = EVP_PKEY_new(); RSA *rsa = RSA_generate_key(2048,RSA_F4,NULL,NULL); EVP_PKEY_assign_RSA(pkey, rsa); X509_set_version(x509, 2); ASN1_INTEGER_set(X509_get_serialNumber(x509),1); X509_gmtime_adj(X509_get_notBefore(x509),0); X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365*20); X509_set_pubkey(x509, pkey); X509_NAME *name=X509_get_subject_name(x509); if (qsname.isEmpty()) qsname = tr("Mumble User"); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char *>(qsname.toUtf8().data()), -1, -1, 0); X509_set_issuer_name(x509, name); add_ext(x509, NID_basic_constraints, SSL_STRING("critical,CA:FALSE")); add_ext(x509, NID_ext_key_usage, SSL_STRING("clientAuth")); add_ext(x509, NID_subject_key_identifier, SSL_STRING("hash")); add_ext(x509, NID_netscape_comment, SSL_STRING("Generated by Mumble")); add_ext(x509, NID_subject_alt_name, QString::fromLatin1("email:%1").arg(qsemail).toUtf8().data()); X509_sign(x509, pkey, EVP_sha1()); QByteArray crt, key; crt.resize(i2d_X509(x509, NULL)); unsigned char *dptr=reinterpret_cast<unsigned char *>(crt.data()); i2d_X509(x509, &dptr); QSslCertificate qscCert = QSslCertificate(crt, QSsl::Der); key.resize(i2d_PrivateKey(pkey, NULL)); dptr=reinterpret_cast<unsigned char *>(key.data()); i2d_PrivateKey(pkey, &dptr); QSslKey qskKey = QSslKey(key, QSsl::Rsa, QSsl::Der); QList<QSslCertificate> qlCert; qlCert << qscCert; return Settings::KeyPair(qlCert, qskKey); }
PyObject* Application::sExport(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/) { PyObject* object; char* Name; if (!PyArg_ParseTuple(args, "Oet",&object,"utf-8",&Name)) return NULL; std::string Utf8Name = std::string(Name); PyMem_Free(Name); PY_TRY { App::Document* doc = 0; Py::Sequence list(object); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr(); doc = obj->getDocument(); break; } } // get the view that belongs to the found document if (doc) { QString fileName = QString::fromUtf8(Utf8Name.c_str()); QFileInfo fi; fi.setFile(fileName); QString ext = fi.completeSuffix().toLower(); if (ext == QLatin1String("iv") || ext == QLatin1String("wrl") || ext == QLatin1String("vrml") || ext == QLatin1String("wrz") || ext == QLatin1String("svg") || ext == QLatin1String("idtf")) { Gui::Document* gui_doc = Application::Instance->getDocument(doc); std::list<MDIView*> view3d = gui_doc->getMDIViewsOfType(View3DInventor::getClassTypeId()); if (view3d.empty()) { PyErr_SetString(Base::BaseExceptionFreeCADError, "Cannot export to SVG because document doesn't have a 3d view"); return 0; } else { QString cmd = QString::fromLatin1( "Gui.getDocument(\"%1\").mdiViewsOfType('Gui::View3DInventor')[0].dump(\"%2\")" ).arg(QLatin1String(doc->getName())).arg(fi.absoluteFilePath()); Base::Interpreter().runString(cmd.toUtf8()); } } else if (ext == QLatin1String("pdf")) { Gui::Document* gui_doc = Application::Instance->getDocument(doc); if (gui_doc) { Gui::MDIView* view = gui_doc->getActiveView(); if (view) { View3DInventor* view3d = qobject_cast<View3DInventor*>(view); if (view3d) view3d->viewAll(); QPrinter printer(QPrinter::ScreenResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); view->print(&printer); } } } } } PY_CATCH; Py_Return; }
//--------------------------------------------------------------------------------- void MagicRules::initialize(const QString& p_jsonFile) { // Read the JSON file QString val; QFile file; file.setFileName(p_jsonFile); file.open(QIODevice::ReadOnly | QIODevice::Text); val = file.readAll(); file.close(); // Read document QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8(), &error); if (error.error != QJsonParseError::NoError) { qCritical() << QString("Error while reading file: %1\nError: %2").arg(p_jsonFile, error.errorString()); return; } // Parse each magic type and add to the rules QJsonArray magicTypesArray = doc.object().value("magic_types").toArray(); QJsonObject currentType; MagicTypeDefinition* typeDef = 0; MagicTypePriorityDefinition* prioDef = 0; QJsonArray tempArray; QJsonObject tempObject; QJsonObject tempObject2; for (int i = 0; i < magicTypesArray.size(); ++i) { currentType = magicTypesArray.at(i).toObject(); // Add type definition typeDef = new MagicTypeDefinition(); // Translations tempObject = currentType["translations"].toObject(); for (int j = 0; j < tempObject.keys().size(); ++j) { typeDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString(); } // Types tempArray = currentType["types"].toArray(); for (int j = 0; j < tempArray.size(); ++j) { typeDef->types.push_back(tempArray.at(j).toString()); } // Priorities tempObject = currentType["priorities"].toObject(); for (int j = 0; j < tempObject.keys().size(); ++j) { tempObject2 = tempObject[tempObject.keys().at(j)].toObject(); prioDef = new MagicTypePriorityDefinition(); // Starting magic if (tempObject2.contains("starting_magic")) { prioDef->startingMagic = tempObject2.value("starting_magic").toString().toInt(); } // Free spells if (tempObject2.contains("free_spells")) { prioDef->freeSpells = tempObject2.value("free_spells").toString().toInt(); } // Free skills if (tempObject2.contains("free_skills")) { prioDef->freeSkills.first = tempObject2.value("free_skills").toArray().at(0).toString().toInt(); prioDef->freeSkills.second = tempObject2.value("free_skills").toArray().at(1).toString().toInt(); } // Forced skill group if (tempObject2.contains("free_skill_groups")) { prioDef->freeSkillGroup.first = tempObject2.value("free_skill_groups").toArray().at(0).toString().toInt(); prioDef->freeSkillGroup.second = tempObject2.value("free_skill_groups").toArray().at(1).toString().toInt(); } // Store priority typeDef->priorities[tempObject.keys().at(j).toInt()] = prioDef; } // Make sure the definition doesn't already exist if (_typeDefinitions.contains(currentType["unique_id"].toString())) { qCritical() << "Magic type \"" << currentType["unique_id"].toString() << "\" already exists. Parsing aborted."; return; } _typeDefinitions[currentType["unique_id"].toString()] = typeDef; }// END magic types // Parse spell category strings QJsonArray categoryArray = doc.object().value("spell_categories").toArray(); QJsonObject currentCat; SpellDefinition* spellCat = NULL; MagicAbilityDefinition* category = NULL; MagicAbilityDefinition* abilityDef = NULL; QString tempString; QString uniqueId = ""; for (int i = 0; i < categoryArray.size(); ++i) { currentCat = categoryArray.at(i).toObject(); uniqueId = currentCat["unique_id"].toString(); // Make sure the definition doesn't already exist if (_spellCategoryDefinitions.contains(uniqueId)) { qCritical() << "Spell category \"" << uniqueId << "\" already exists. Parsing aborted."; return; } // Get correct category category = _rootItem->children[MAGICABILITYTYPE_SPELL]; // Add spell definition abilityDef = new MagicAbilityDefinition(category); abilityDef->id = uniqueId; abilityDef->abilityType = MAGICABILITYTYPE_SPELL; spellCat = new SpellDefinition(); abilityDef->spell = spellCat; abilityDef->spell->isSpellCategory = true; category->children.push_back(abilityDef); // Translations tempObject = currentCat["translations"].toObject(); for (int j = 0; j < tempObject.keys().size(); ++j) { abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString(); } _definitions[uniqueId] = abilityDef; _spellCategoryDefinitions[uniqueId] = spellCat; } // Parse each spell and add to the rules QJsonArray spellsArray = doc.object().value("spells").toArray(); QJsonObject currentSpell; SpellDefinition* spellDef = 0; for (int i = 0; i < spellsArray.size(); ++i) { currentSpell = spellsArray.at(i).toObject(); uniqueId = currentSpell["unique_id"].toString(); // Make sure the definition doesn't already exist if (_spellDefinitions.contains(uniqueId)) { qCritical() << "Spell \"" << uniqueId << "\" already exists. Parsing aborted."; return; } // Add spell definition abilityDef = new MagicAbilityDefinition(); abilityDef->id = uniqueId; abilityDef->abilityType = MAGICABILITYTYPE_SPELL; spellDef = new SpellDefinition(); abilityDef->spell = spellDef; // Translations tempObject = currentSpell["translations"].toObject(); for (int j = 0; j < tempObject.keys().size(); ++j) { abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString(); } // Category spellDef->category = currentSpell["category"].toString(); if (!_spellCategoryDefinitions.contains(spellDef->category)) { qCritical() << "Spell \"" << currentSpell["unique_id"].toString() << "\" of non existing category \"" << spellDef->category << "\". Parsing aborted."; return; } // Get correct spell category and add to it category = _definitions[spellDef->category]; abilityDef->parent = category; category->children.push_back(abilityDef); // Type tempString = currentSpell["type"].toString(); if (tempString == "P") { spellDef->type = SPELLTYPE_PHYSICAL; } else if (tempString == "M") { spellDef->type = SPELLTYPE_MAGICAL; } // Range tempString = currentSpell["range"].toString(); if (tempString == "T") { spellDef->range = SPELLRANGE_TOUCH; } else if (tempString == "LOS") { spellDef->range = SPELLRANGE_LOS; } else if (tempString == "LOS(A)") { spellDef->range = SPELLRANGE_LOS_AREA; } // Damage (optional) if (currentSpell.contains("damage")) { tempString = currentSpell["damage"].toString(); if (tempString == "P") { spellDef->damageType = SPELLDAMAGE_PHYSICAL; } else if (tempString == "M") { spellDef->damageType = SPELLDAMAGE_MENTAL; } } // Duration tempString = currentSpell["duration"].toString(); if (tempString == "I") { spellDef->duration = SPELLDURATION_INSTANT; } else if (tempString == "S") { spellDef->duration = SPELLDURATION_SUSTAINED; } else if (tempString == "P") { spellDef->duration = SPELLDURATION_PERMANENT; } // Drain spellDef->drain = currentSpell["drain"].toString(); // Descriptors (optional) if (currentSpell.contains("descriptors")) { QVariantList list = currentSpell["descriptors"].toArray().toVariantList(); QListIterator<QVariant> i(list); while (i.hasNext()) { spellDef->descriptors << i.next().toString(); } } // Does this spell require a custom choice? if (currentSpell.contains("requires_custom")) { abilityDef->requiresCustom = currentSpell["requires_custom"].toString() == "true"; if (currentSpell.contains("custom_choices")) { QJsonObject obj = currentSpell["custom_choices"].toObject(); abilityDef->customChoices = new CustomChoice(&obj); } } // Is this spell affected by the essence value? if (currentSpell.contains("essence_effect")) { spellDef->essenceEffect = currentSpell["essence_effect"].toString() == "true"; } _definitions[uniqueId] = abilityDef; _spellDefinitions[uniqueId] = spellDef; }// END spells // Parse each adept power and add to the rules QJsonArray powersArray = doc.object().value("adept_powers").toArray(); QJsonObject currentPower; AdeptPowerDefinition* powerDef = 0; for (int i = 0; i < powersArray.size(); ++i) { currentPower = powersArray.at(i).toObject(); uniqueId = currentPower["unique_id"].toString(); // Make sure the definition doesn't already exist if (_adeptPowerDefinitions.contains(uniqueId)) { qCritical() << "Adept Power \"" << uniqueId << "\" already exists. Parsing aborted."; return; } // Add type definition abilityDef = new MagicAbilityDefinition(); abilityDef->id = uniqueId; abilityDef->abilityType = MAGICABILITYTYPE_ADEPT_POWER; powerDef = new AdeptPowerDefinition(); abilityDef->adeptPower = powerDef; // Get correct spell category and add to it category = _rootItem->children[MAGICABILITYTYPE_ADEPT_POWER]; abilityDef->parent = category; category->children.push_back(abilityDef); // Translations tempObject = currentPower["translations"].toObject(); for (int j = 0; j < tempObject.keys().size(); ++j) { abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString(); } // Cost if (currentPower.contains("cost_per_level")) { powerDef->costType = COSTTYPE_PER_LEVEL; powerDef->costArray.push_back(currentPower["cost_per_level"].toString().toDouble()); } else if (currentPower.contains("cost")) { QJsonValue::Type type = currentPower["cost"].type(); // Normal cost or array if (type != QJsonValue::Array) { powerDef->costType = COSTTYPE_NORMAL; powerDef->costArray.push_back(currentPower["cost"].toString().toDouble()); } else { powerDef->costType = COSTTYPE_ARRAY; tempArray = currentPower["cost"].toArray(); // Add each array entry for (int j = 0; j < tempArray.size(); ++j) { powerDef->costArray.push_back(tempArray[j].toString().toDouble()); } } } // Activation (optional) if (currentPower.contains("activation")) { tempString = currentPower["activation"].toString(); if (tempString == "interrupt") { powerDef->activationType = ACTIVATIONTYPE_INTERRUPT; } else if (tempString == "free") { powerDef->activationType = ACTIVATIONTYPE_FREE; } else if (tempString == "simple") { powerDef->activationType = ACTIVATIONTYPE_SIMPLE; } } // Does this power require a custom choice? if (currentPower.contains("requires_custom")) { abilityDef->requiresCustom = currentPower["requires_custom"].toString() == "true"; if (currentPower.contains("custom_choices")) { QJsonObject obj = currentPower["custom_choices"].toObject(); abilityDef->customChoices = new CustomChoice(&obj); } } // Does this power have effects? if (currentPower.contains("effects")) { tempArray = currentPower["effects"].toArray(); for (int j = 0; j < tempArray.size(); ++j) { QJsonValueRef obj = tempArray[j]; EffectSource source; source.magicAbility = abilityDef; abilityDef->effects.push_back(new Effect(&obj, source)); } } _definitions[uniqueId] = abilityDef; _adeptPowerDefinitions[uniqueId] = powerDef; } // END adept powers // Parse each complex form and add to the rules QJsonArray formsArray = doc.object().value("complex_forms").toArray(); QJsonObject currentForm; ComplexFormDefinition* formDef = 0; for (int i = 0; i < formsArray.size(); ++i) { currentForm = formsArray.at(i).toObject(); uniqueId = currentForm["unique_id"].toString(); // Make sure the definition doesn't already exist if (_complexFormDefinitions.contains(uniqueId)) { qCritical() << "Complex Form \"" << uniqueId << "\" already exists. Parsing aborted."; return; } // Add form definition abilityDef = new MagicAbilityDefinition(); abilityDef->id = uniqueId; abilityDef->abilityType = MAGICABILITYTYPE_COMPLEX_FORM; formDef = new ComplexFormDefinition(); abilityDef->complexForm = formDef; // Get correct spell category and add to it category = _rootItem->children[MAGICABILITYTYPE_COMPLEX_FORM]; abilityDef->parent = category; category->children.push_back(abilityDef); // Translations tempObject = currentForm["translations"].toObject(); for (int j = 0; j < tempObject.keys().size(); ++j) { abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString(); } // Target tempString = currentForm["target"].toString(); if (tempString == "persona") { formDef->targetType = TARGETTYPE_PERSONA; } else if (tempString == "device") { formDef->targetType = TARGETTYPE_DEVICE; } else if (tempString == "file") { formDef->targetType = TARGETTYPE_FILE; } else if (tempString == "sprite") { formDef->targetType = TARGETTYPE_SPRITE; } // Duration tempString = currentForm["duration"].toString(); if (tempString == "I") { formDef->duration = SPELLDURATION_INSTANT; } else if (tempString == "S") { formDef->duration = SPELLDURATION_SUSTAINED; } else if (tempString == "P") { formDef->duration = SPELLDURATION_PERMANENT; } // Fading Value formDef->fadingValue = currentForm["fading_value"].toString(); // Does this form require a custom choice? if (currentForm.contains("requires_custom")) { abilityDef->requiresCustom = currentForm["requires_custom"].toString() == "true"; if (currentForm.contains("custom_choices")) { QJsonObject obj = currentForm["custom_choices"].toObject(); abilityDef->customChoices = new CustomChoice(&obj); } } _definitions[uniqueId] = abilityDef; _complexFormDefinitions[uniqueId] = formDef; } // END complex forms }
void log(QString message) { QString temp; temp = message + "\n"; printf("%s",temp.toUtf8().data()); }
bool Global::sendMemoEMail(const QString mailPrefixMessage, const QList<RepoChanges> & repoChanges) { QStringList attachments; const QString tmpPath = QString(BOXIT_STATUS_TMP) + "/" + QString::number(qrand()) + "_" + QDateTime::currentDateTime().toString(Qt::ISODate); bool success = true; // Create working folder if (QDir(tmpPath).exists() && !Global::rmDir(tmpPath)) { cerr << "error: failed to remove folder '" << tmpPath.toUtf8().data() << "'" << endl; return false; } if (!QDir().mkpath(tmpPath)) { cerr << "error: failed to create folder '" << tmpPath.toUtf8().data() << "'" << endl; return false; } QString message = mailPrefixMessage; for (int i = 0; i < repoChanges.size(); ++i) { const RepoChanges *repo = &repoChanges.at(i); message += QString(" - %1 %2 %3: %4 new and %5 removed package(s)\n").arg(repo->branchName, repo->repoName, repo->repoArchitecture, QString::number(repo->addedPackages.size()), QString::number(repo->removedPackages.size())); // Create attachment file QFile file(QString(tmpPath) + "/" + repo->branchName + "_" + repo->repoName + "_" + repo->repoArchitecture); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { success = false; goto remove_tmp_dir; } QTextStream out(&file); if (!repo->addedPackages.isEmpty()) { out << "[New Packages]\n" << repo->addedPackages.join("\n"); if (!repo->removedPackages.isEmpty()) out << "\n\n\n"; } if (!repo->removedPackages.isEmpty()) out << "[Removed Packages]\n" << repo->removedPackages.join("\n"); file.close(); // Add to list attachments.append(file.fileName()); } // Send e-mail if (!Global::sendMemoEMail(message, attachments)) { cerr << "error: failed to send e-mail!" << endl; success = false; goto remove_tmp_dir; } remove_tmp_dir: // Remove working folder again if (QDir(tmpPath).exists() && !Global::rmDir(tmpPath)) cerr << "error: failed to remove folder '" << tmpPath.toUtf8().data() << "'" << endl; return success; }
bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid ) { QString radius, parameter2; // // SQLITE3 stuff - get parameters for selected ellipsoid // sqlite3 *myDatabase; const char *myTail; sqlite3_stmt *myPreparedStatement; int myResult; // Shortcut if ellipsoid is none. if ( ellipsoid == GEO_NONE ) { mEllipsoid = GEO_NONE; return true; } // Check if we have a custom projection, and set from text string. // Format is "PARAMETER:<semi-major axis>:<semi minor axis> // Numbers must be with (optional) decimal point and no other separators (C locale) // Distances in meters. Flattening is calculated. if ( ellipsoid.startsWith( "PARAMETER" ) ) { QStringList paramList = ellipsoid.split( ":" ); bool semiMajorOk, semiMinorOk; double semiMajor = paramList[1].toDouble( & semiMajorOk ); double semiMinor = paramList[2].toDouble( & semiMinorOk ); if ( semiMajorOk && semiMinorOk ) { return setEllipsoid( semiMajor, semiMinor ); } else { return false; } } // Continue with PROJ.4 list of ellipsoids. //check the db is available myResult = sqlite3_open_v2( QgsApplication::srsDbFilePath().toUtf8().data(), &myDatabase, SQLITE_OPEN_READONLY, NULL ); if ( myResult ) { QgsMessageLog::logMessage( QObject::tr( "Can't open database: %1" ).arg( sqlite3_errmsg( myDatabase ) ) ); // XXX This will likely never happen since on open, sqlite creates the // database if it does not exist. return false; } // Set up the query to retrieve the projection information needed to populate the ELLIPSOID list QString mySql = "select radius, parameter2 from tbl_ellipsoid where acronym='" + ellipsoid + "'"; myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); // XXX Need to free memory from the error msg if one is set if ( myResult == SQLITE_OK ) { if ( sqlite3_step( myPreparedStatement ) == SQLITE_ROW ) { radius = QString(( char * )sqlite3_column_text( myPreparedStatement, 0 ) ); parameter2 = QString(( char * )sqlite3_column_text( myPreparedStatement, 1 ) ); } } // close the sqlite3 statement sqlite3_finalize( myPreparedStatement ); sqlite3_close( myDatabase ); // row for this ellipsoid wasn't found? if ( radius.isEmpty() || parameter2.isEmpty() ) { QgsDebugMsg( QString( "setEllipsoid: no row in tbl_ellipsoid for acronym '%1'" ).arg( ellipsoid ) ); return false; } // get major semiaxis if ( radius.left( 2 ) == "a=" ) mSemiMajor = radius.mid( 2 ).toDouble(); else { QgsDebugMsg( QString( "setEllipsoid: wrong format of radius field: '%1'" ).arg( radius ) ); return false; } // get second parameter // one of values 'b' or 'f' is in field parameter2 // second one must be computed using formula: invf = a/(a-b) if ( parameter2.left( 2 ) == "b=" ) { mSemiMinor = parameter2.mid( 2 ).toDouble(); mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor ); } else if ( parameter2.left( 3 ) == "rf=" ) { mInvFlattening = parameter2.mid( 3 ).toDouble(); mSemiMinor = mSemiMajor - ( mSemiMajor / mInvFlattening ); } else { QgsDebugMsg( QString( "setEllipsoid: wrong format of parameter2 field: '%1'" ).arg( parameter2 ) ); return false; } QgsDebugMsg( QString( "setEllipsoid: a=%1, b=%2, 1/f=%3" ).arg( mSemiMajor ).arg( mSemiMinor ).arg( mInvFlattening ) ); // get spatial ref system for ellipsoid QString proj4 = "+proj=longlat +ellps=" + ellipsoid + " +no_defs"; QgsCoordinateReferenceSystem destCRS; destCRS.createFromProj4( proj4 ); //TODO: createFromProj4 used to save to the user database any new CRS // this behavior was changed in order to separate creation and saving. // Not sure if it necessary to save it here, should be checked by someone // familiar with the code (should also give a more descriptive name to the generated CRS) if ( destCRS.srsid() == 0 ) { QString myName = QString( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ) ) .arg( destCRS.toProj4() ); destCRS.saveAsUserCRS( myName ); } // // set transformation from project CRS to ellipsoid coordinates mCoordTransform->setDestCRS( destCRS ); // precalculate some values for area calculations computeAreaInit(); mEllipsoid = ellipsoid; return true; }
void Widget::GroupNumber(){ QString QgroupName = ui->lineEdit_NomGroupe->text(); GroupName = QgroupName.toUtf8().constData(); QString QnbOfPersons = ui->lineEdit_NbPersonnes->text(); string nbOfPersons = QnbOfPersons.toUtf8().constData(); numberOfPersons = atoi((char*)nbOfPersons.c_str()); if(ui->lineEdit_NomGroupe->text() == "") { ui->lineEdit_NomGroupe->setStyleSheet( QString("background-color: red")); ui->lineEdit_NbPersonnes->setStyleSheet( QString("background-color: white")); QMessageBox::warning(this, tr("Champs vide"), tr("Nom du groupe à renseigner.\n")); return; } if(ui->lineEdit_NbPersonnes->text() == "") { ui->lineEdit_NbPersonnes->setStyleSheet( QString("background-color: red")); QMessageBox::warning(this, tr("Champs vide"), tr("Nombre de personnes à renseigner.\n")); return; } if(numberOfPersons<2){ ui->lineEdit_NomGroupe->setStyleSheet( QString("background-color: white")); ui->lineEdit_NbPersonnes->setStyleSheet( QString("background-color: red")); ui->lineEdit_NbPersonnes->clear(); QMessageBox::warning(this, tr("Nombre de personnes trop faible"), tr("Veuillez indiquer au moins 2 personnes.\n")); return; } ui->lineEdit_NbPersonnes->setStyleSheet(""); ui->lineEdit_NomGroupe->setStyleSheet(""); ui->textEdit_2->appendPlainText( "----------------------------------------------" ); ui->textEdit_2->appendPlainText( "Groupe : " + QString(GroupName.c_str())); ui->textEdit_2->appendPlainText(QnbOfPersons + " personnes"); ui->lineEdit_depenses->setEnabled(true); ui->lineEdit_mail->setEnabled(true); ui->lineEdit_telephone->setEnabled(true); ui->lineEdit_prenom->setEnabled(true); ui->comboBox_statut->setEnabled(1); ui->lineEdit_NomGroupe->setEnabled(false); ui->lineEdit_NbPersonnes->setEnabled(false); ui->pushButton_clear->setEnabled(1); ui->pushButton_group->setEnabled(0); ui->pushButton_next->setEnabled(1); ui->pushButton_run->setEnabled(0); ui->pushButton_saveAs->setEnabled(0); }