Beispiel #1
0
Instance MemoryDump::queryInstance(const QString& queryString,
                                   KnowledgeSources src) const
{
    QStringList components = queryString.split('.', QString::SkipEmptyParts);

    if (components.isEmpty())
        queryError("Empty query string given");

	Instance result, prev;
	
	while (!components.isEmpty()) {
		result = getNextInstance(components.first(), result, src);

        if (!result.isValid()) {
            QString s(prev.fullName());
            if (!s.isEmpty())
                s += ".";
            s += components.first();
            if (result.origin() == Instance::orCandidate)
                queryError(QString("The selected member candidate for \"%1\" is invalid")
                            .arg(s));
            else if (result.origin() == Instance::orRuleEngine)
                queryError(QString("The instance \"%1\" returned by the rule engine is invalid.")
                           .arg(s));
            else
                queryError(QString("The instance \"%1\" is invalid (origin: %2)")
                           .arg(s)
                           .arg(Instance::originToString(result.origin())));
        }

        prev = result;
        components.pop_front();
    }

	return result;
}
Beispiel #2
0
void GenGraphForm::doDisplay()
{
    if (exportedFile==QString("")) return;

    std::cout << "OPEN " << (const char*)exportedFile << std::endl;

#ifdef WIN32
    ShellExecuteA(NULL, "open", exportedFile, NULL, NULL, SW_SHOWNORMAL);
#else
    QStringList argv;
    argv << "display" << exportedFile;
#ifdef SOFA_QT4
    QString program = argv.front();
    argv.pop_front();
    //QProcess::startDetached(program, argv); //QString("start \"\"\"")+exportedFile+QString("\"\"\""));
    QProcess::startDetached(program, argv); //QString("start \"\"\"")+exportedFile+QString("\"\"\""));
#else
    QProcess* p = new QProcess(argv, this);
    p->setCommunication(0);
    connect(p,SIGNAL(processExited()),p,SLOT(deleteLater()));
    p->start();
#endif
#endif
}
Beispiel #3
0
bool HRProcessor::run(const Element &parent, QStringList &blocks)
{
    std::shared_ptr<BlockParser> parser = this->parser.lock();

    QString block = blocks.front();
    blocks.pop_front();
    //! Check for lines in block before hr.
    QString prelines = pypp::rstrip(block.left(this->match.capturedStart()), [](const QChar &ch) -> bool { return ch == '\n'; });
    if ( ! prelines.isEmpty() ) {
        //! Recursively parse lines before hr so they get parsed first.
        QStringList new_blocks = {prelines};
        parser->parseBlocks(parent, new_blocks);
    }
    //! create hr
    Element hr = createSubElement(parent, "hr");
    //! check for lines in block after hr.
    int begin = this->match.capturedStart()+this->match.capturedLength();
    QString postlines = pypp::lstrip(block.mid(begin), [](const QChar &ch) -> bool { return ch == '\n'; });
    if ( ! postlines.isEmpty() ) {
        //! Add lines after hr to master blocks for later parsing.
        blocks.push_front(postlines);
    }
    return true;
}
    void ReadFromFile(QString fileName)
    {
        QFile file(fileName);
        if (file.open(QFile::ReadOnly)==false)
            throw "Read file failed";
        QTextStream in(&file);
        while (!in.atEnd())
        {
            QString line = in.readLine();
            if (line.isEmpty())
                continue;
            QStringList lineList = line.split("\t",QString::SkipEmptyParts);
            int vertexID = lineList[0].toInt();
            lineList.pop_front();
//            qDebug()<<vertexID<<":"<<lineList;
            vertexList<<vertexID;
            foreach (QString word, lineList) {
                QStringList list = word.split(",");
                int toID = list[0].toInt();
                int weight = list[1].toDouble();
                Edge e(vertexID,toID,weight);
                edges.push_back(e);
            }
        }
Beispiel #5
0
QDomNode XmlConfiguration::FindNode( QStringList &sParts, QDomNode &curNode, bool bCreate )
{
    if (sParts.empty())
        return curNode;

    QString sName = sParts.front();
    sParts.pop_front();

    QDomNode child = curNode.namedItem( sName );

    if (child.isNull() )
    {
        if (bCreate)
        {
            QDomNode newNode = m_config.createElement( sName );
            if (!curNode.isNull())
                child = curNode.appendChild( newNode );
        }
        else
            sParts.clear();
    }

    return FindNode( sParts, child, bCreate );
}
bool Polyhedron_demo_polylines_io_plugin::save(const Scene_item* item, QFileInfo fileinfo)
{
  const Scene_polylines_item* poly_item = 
    qobject_cast<const Scene_polylines_item*>(item);

  if(!poly_item)
    return false;

  std::ofstream out(fileinfo.filePath().toUtf8());

  out.precision(17);

  if(!out) {
    std::cerr << "Error! Cannot open file " << (const char*)fileinfo.filePath().toUtf8() << std::endl;
    return false;
  }

  typedef Scene_polylines_item::Polylines_container Polylines_container;
  typedef Polylines_container::value_type Polyline;
  typedef Polyline::value_type Point_3;

  QStringList metadata = item->property("polylines metadata").toStringList();

  BOOST_FOREACH(const Polyline& polyline, poly_item->polylines) {
    out << polyline.size();
    BOOST_FOREACH(const Point_3& p, polyline) {
      out << " " << p.x() << " " << p.y() << " " << p.z();
    }
    if(!metadata.isEmpty()) {
      out << " " << qPrintable(metadata.front());
      metadata.pop_front();
    }
    out << std::endl;
  }
  return (bool) out;
}
Beispiel #7
0
void QuotaJobs::GetQuotarootJob::slotInfoMessage(KIO::Job *, const QString &str)
{
    // Parse the result
    QStringList results = QStringList::split("\r", str);
    QStringList roots;
    QuotaInfoList quotas;
    if(results.size() > 0)
    {
        // the first line is the available roots
        roots = QStringList::split(" ", results.front());
        results.pop_front();
        // the rest are pairs of root -> list of triplets
        while(results.size() > 0)
        {
            QString root = results.front();
            results.pop_front();
            // and the quotas
            if(results.size() > 0)
            {
                QStringList triplets = QStringList::split(" ", results.front());
                results.pop_front();
                while(triplets.size() > 0)
                {
                    // there's always three, the label, current and max values
                    QString name = triplets.front();
                    triplets.pop_front();
                    QString current = triplets.front();
                    triplets.pop_front();
                    QString max = triplets.front();
                    triplets.pop_front();
                    QuotaInfo info(name, root, current, max);
                    quotas.append(info);
                }
            }
        }
    }
    if(!quotas.isEmpty())
    {
        emit quotaInfoReceived(quotas);
    }
    emit quotaRootResult(roots);
}
Beispiel #8
0
NodeCombat::NodeCombat(QString &create, GamerList &gl) : NodeCombat(0,0,0,0,gl,0)
{
    QStringList nodeStr = create.split(",");
    if(nodeStr.size() == 7)
    {
        nodeStr.pop_front();
        setId(nodeStr.first().toInt());
        nodeStr.pop_front();
        setX(nodeStr.first().toInt());
        nodeStr.pop_front();
        setY(nodeStr.first().toInt());
        nodeStr.pop_front();
        radius = nodeStr.first().toInt();
        nodeStr.pop_front();
        ressourcesMax = nodeStr.first().toInt();
        nodeStr.pop_front();
        setOwner(lstGamer.getGamer(nodeStr.first().toInt()));
    }
    else
    {
        qCritical()<<"NodeCombat : unexpected case in 'NodeCombat'";
    }
}
Beispiel #9
0
EventTemplate::EventTemplate(QStringList initStringList, QListWidgetItem * newHolder, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EventTemplate),
    holder(newHolder)

{
    ui->setupUi(this);
    QString tmpDateString = initStringList.front();
    initStringList.pop_front();
    QString dateTimeFormatString = initStringList.front();
    initStringList.pop_front();
        QDateTime dateTime = QDateTime::fromString(tmpDateString,dateTimeFormatString);
        ui->labelDayOfWeek->setText(dateTime.toString("dddd"));
        ui->labelDate->setText(dateTime.toString("dd.MM.yyyy"));
        ui->labelTime->setText(dateTime.toString("hh:mm"));
    ui->labelType->setText(initStringList.front());
    initStringList.pop_front();
    ui->labelTitle->setText(initStringList.front());
    initStringList.pop_front();
    ui->labelRoom->setText(initStringList.front());
    initStringList.pop_front();
    ui->description->setText(initStringList.front());
    initStringList.pop_front();
}
Beispiel #10
0
QString MemoryDump::dump(const QString& type, quint64 address, int length,
                         const ColorPalette& col) const
{
    if (type == "char") {
        char c;
        if (_vmem->readAtomic(address, &c, sizeof(char)) != sizeof(char))
            queryError(QString("Cannot read memory from address 0x%1")
                       .arg(address, (_specs.sizeofPointer << 1), 16, QChar('0')));
        return QString("%1 (0x%2)").arg(c).arg(c, (sizeof(c) << 1), 16, QChar('0'));
    }
    if (type == "int") {
        qint32 i;
        if (_vmem->readAtomic(address, (char*)&i, sizeof(qint32)) != sizeof(qint32))
            queryError(QString("Cannot read memory from address 0x%1")
                       .arg(address, (_specs.sizeofPointer << 1), 16, QChar('0')));
        return QString("%1 (0x%2)").arg(i).arg((quint32)i, (sizeof(i) << 1), 16, QChar('0'));
    }
    if (type == "long") {
        qint64 l;
        if (_vmem->readAtomic(address, (char*)&l, sizeof(qint64)) != sizeof(qint64))
            queryError(QString("Cannot read memory from address 0x%1")
                       .arg(address, (_specs.sizeofPointer << 1), 16, QChar('0')));
        return QString("%1 (0x%2)").arg(l).arg((quint64)l, (sizeof(l) << 1), 16, QChar('0'));
    }
    if (type == "raw" || type == "hex") {
        QString ret;
        const int buflen = 256, linelen = 16;
        char buf[buflen];
        char bufstr[linelen + 1] = {0};

        // Make sure we got a valid length
        if (length < 0)
            queryError(QString("No valid length given for dumping raw memory"));

        int totalBytesRead = 0, col = 0;
        while (length > 0) {
            int bytesRead = _vmem->readAtomic(address, buf, qMin(buflen, length));
            length -= bytesRead;

            int i = 0;
            while (i < bytesRead) {
                // New line every 16 bytes begins with address
                if (totalBytesRead % 16 == 0) {
                    if (totalBytesRead > 0) {
                        ret += QString("  |%0|\n").arg(bufstr, -linelen);
                        memset(bufstr, 0, linelen + 1);
                        col = 0;
                    }
                    ret += QString("%1 ").arg(address, _specs.sizeofPointer << 1, 16, QChar('0'));
                }

                // Wider column after 8 bytes
                if (totalBytesRead % 8 == 0)
                    ret += ' ';
                // Write the character as hex string
                if ((unsigned char)buf[i] < 16)
                    ret += '0';
                ret += QString::number((unsigned char)buf[i], 16) + ' ';
                // Add character to string buffer, if it's an ASCII char
                if ( ((unsigned char)buf[i] >= 32) && ((unsigned char)buf[i] < 127) )
                    bufstr[col] = buf[i];
                else
                    bufstr[col] = '.';

                ++col;
                ++totalBytesRead;
                ++address;
                ++i;
            }
        }

        // Finish it up
        if (col > 0) {
            while (col < linelen) {
                ret += "   ";
                if (col % 8 == 0)
                    ret += ' ';
                ++col;
            }
            ret += QString("  |%0|").arg(bufstr, -linelen);
        }

        return ret;
    }

	QStringList components = type.split('.', QString::SkipEmptyParts);
	Instance result;
	
    if (!components.isEmpty()) {
		// Get first instance
		result = getInstanceAt(components.first(), address, QStringList("user"));
		components.pop_front();
	
		while (!components.isEmpty()) {
			result = getNextInstance(components.first(), result, ksNone);
			components.pop_front();
		}
			
		return QString("%1%2%3 (ID%4 0x%5%6) @%7 0x%8%9\n")
				.arg(col.color(ctType))
				.arg(result.typeName())
				.arg(col.color(ctReset))
				.arg(col.color(ctTypeId))
				.arg((uint)result.type()->id(), 0, 16)
				.arg(col.color(ctReset))
				.arg(col.color(ctAddress))
				.arg(result.address(), 0, 16)
				.arg(col.color(ctReset)) + result.toString(&col);
	}

    queryError3("Unknown type: " + type,
    		QueryException::ecUnresolvedType, type);

    return QString();
}
bool FeatureProxyConnector::processReply()
{
   mLastReplyIsError = false;
   QString data = mPartialResponse + mStream.readAll();
   QStringList lines = data.split("\n", QString::SkipEmptyParts);
   if (data[data.size()-1] != '\n')
   {
      mPartialResponse = lines.takeLast();
   }
   else
   {
      mPartialResponse.clear();
   }

   while (!mLastReplyIsError && !lines.empty())
   {
      QString line = lines.takeFirst();
      if (!mExecutableInitialized)
      {
         if (line != APP_VERSION_NUMBER)
         {
            terminate();
            return false;
         }
         mExecutableInitialized = true;
         emit initialized();
      }
      else
      {
         QStringList args = line.split(" ", QString::SkipEmptyParts);
         if (!args.empty())
         {
            if (args.front() == "ERROR")
            {
               args.pop_front();
               mResponses.clear();
               mLastReplyIsError = true;
               QString response = args.join(" ");
               mResponses.enqueue(response);
               emit error(response);
            }
            else
            {
               switch (mPendingCommand)
               {
               case OPEN_DATA_SOURCE:
                  if (args.front() == "SUCCESS")
                  {
                     args.pop_front();
                     QString response = args.join(" ");
                     mResponses.enqueue(response);
                     emit dataSourceOpen(response);
                  }
                  break;
               case CLOSE_DATA_SOURCE:
                  if (args.front() == "SUCCESS")
                  {
                     args.pop_front();
                     QString response = args.join(" ");
                     mResponses.enqueue(response);
                     emit dataSourceClosed(response);
                  }
                  break;
               case GET_FEATURE_CLASS_PROPERTIES:
                  if (args.front() == "SUCCESS" && args.size() >= 2)
                  {
                     args.pop_front();
                     QString response = args.join(" ");
                     mResponses.enqueue(response);
                     emit featureClassProperties(response);
                  }
                  break;
               case QUERY:
                  mResponses.enqueue(args.join(" "));
                  if (args.front() != "END")
                  {
                     continue; // don't reset mPendingCommand until we hit the end
                  }
                  break;
               default:
                  mResponses.enqueue(args.join(" "));
                  break;
               }
            }
         }
         mPendingCommand = NO_COMMAND;
      }
   }
   return true;
}
/**
 * Emulate perl shift().
 */
QString shift(QStringList& l)
{
    QString first = l.first();
    l.pop_front();
    return first;
}
/**
 * Parse a file into the PetalNode internal tree representation
 * and then create Umbrello objects by traversing the tree.
 *
 * @return  In case of error: NULL
 *          In case of success with non NULL parentPkg: pointer to UMLPackage created for controlled unit
 *          In case of success with NULL parentPkg: pointer to root folder of Logical View
 */
UMLPackage* loadFromMDL(QFile& file, UMLPackage *parentPkg /* = 0 */) 
{
    if (parentPkg == NULL) {
        QString fName = file.fileName();
        int lastSlash = fName.lastIndexOf(QLatin1Char('/'));
        if (lastSlash > 0) {
            dirPrefix = fName.left(lastSlash + 1);
        }
    }
    QTextStream stream(&file);
    stream.setCodec("ISO 8859-1");
    QString line;
    PetalNode *root = NULL;
    uint nClosures_sav = nClosures;
    uint linum_sav = linum;
    nClosures = 0;
    linum = 0;
    while (!(line = stream.readLine()).isNull()) {
        linum++;
        if (line.contains(QRegExp(QLatin1String("^\\s*\\(object Petal")))) {
            bool finish = false;
            // Nested loop determines character set to use
            while (!(line = stream.readLine()).isNull()) {
                linum++; // CHECK: do we need petal version info?
                if (line.contains(QLatin1Char(')'))) {
                    finish = true;
                    line = line.replace(QLatin1String(QLatin1String(")")), QString());
                }
                QStringList a = line.trimmed().split(QRegExp(QLatin1String("\\s+")));
                if (a.size() == 2 && a[0] == QLatin1String("charSet")) {
                    const QString& charSet = a[1];
                    if (!charSet.contains(QRegExp(QLatin1String("^\\d+$")))) {
                        uWarning() << "Unimplemented charSet " << charSet;
                        if (finish)
                            break;
                        continue;
                    }
                    const int charSetNum = charSet.toInt();
                    switch (charSetNum) {
                        case 0:         // ASCII
                            ;
                        case 1:    // Default
                            SETCODEC("System");
                        case 2:    // Symbol
                            ; // @todo     SETCODEC("what");
                        case 77:   // Mac
                            SETCODEC("macintosh");
                        case 128:  // ShiftJIS (Japanese)
                            SETCODEC("Shift_JIS");
                        case 129:  // Hangul (Korean)
                            SETCODEC("EUC-KR");
                        case 130:  // Johab (Korean)
                            SETCODEC("EUC-KR");
                        case 134:  // GB2312 (Chinese)
                            SETCODEC("GB18030");  // "Don't use GB2312 here" (Ralf H.)
                        case 136:  // ChineseBig5
                            SETCODEC("Big5");
                        case 161:  // Greek
                            SETCODEC("windows-1253");
                        case 162:  // Turkish
                            SETCODEC("windows-1254");
                        case 163:  // Vietnamese
                            SETCODEC("windows-1258");
                        case 177:  // Hebrew
                            SETCODEC("windows-1255");
                        case 178:  // Arabic
                            SETCODEC("windows-1256");
                        case 186:  // Baltic
                            SETCODEC("windows-1257");
                        case 204:  // Russian
                            SETCODEC("windows-1251");
                        case 222:  // Thai
                            SETCODEC("TIS-620");
                        case 238:  // EastEurope
                            SETCODEC("windows-1250");
                        case 255:  // OEM (extended ASCII)
                            SETCODEC("windows-1252");
                        default:
                            uWarning() << "Unimplemented charSet number" << charSetNum;
                    }
                }
                if (finish)
                     break;
            }
            if (line.isNull())
                break;
        } else {
            QRegExp objectRx(QLatin1String("^\\s*\\(object "));
            if (line.contains(objectRx)) {
                nClosures = 0;
                QStringList initialArgs = scan(line);
                initialArgs.pop_front();  // remove opening parenthesis
                root = readAttributes(initialArgs, stream);
                break;
            }
        }
    }
    file.close();
    nClosures = nClosures_sav;
    linum = linum_sav;
    if (root == NULL)
        return NULL;

    if (parentPkg) {
        UMLPackage *child = petalTree2Uml(root, parentPkg);
        delete root;
        return child;
    }

    if (root->name() != QLatin1String("Design")) {
        uError() << "expecting root name Design";
        delete root;
        return NULL;
    }
    Import_Utils::assignUniqueIdOnCreation(false);
    UMLDoc *umldoc = UMLApp::app()->document();

    //*************************** import Logical View *********************************
    umldoc->setCurrentRoot(Uml::ModelType::Logical);
    UMLPackage *logicalView = umldoc->rootFolder(Uml::ModelType::Logical);
    importView(root, logicalView,
               QLatin1String("root_category"), QLatin1String("logical_models"),
               QLatin1String("Class_Category"), QLatin1String("logical_presentations"));

    //*************************** import Use Case View ********************************
    umldoc->setCurrentRoot(Uml::ModelType::UseCase);
    UMLPackage *useCaseView = umldoc->rootFolder(Uml::ModelType::UseCase);
    importView(root, useCaseView,
               QLatin1String("root_usecase_package"), QLatin1String("logical_models"),
               QLatin1String("Class_Category"), QLatin1String("logical_presentations"));

    //*************************** import Component View *******************************
    umldoc->setCurrentRoot(Uml::ModelType::Component);
    UMLPackage *componentView = umldoc->rootFolder(Uml::ModelType::Component);
    importView(root, componentView,
               QLatin1String("root_subsystem"), QLatin1String("physical_models"),
               QLatin1String("SubSystem"), QLatin1String("physical_presentations"));

    //*************************** import Deployment View ******************************
    umldoc->setCurrentRoot(Uml::ModelType::Deployment);
    UMLPackage *deploymentView = umldoc->rootFolder(Uml::ModelType::Deployment);
    importView(root, deploymentView, QLatin1String("process_structure"),
                                     QLatin1String("ProcsNDevs"), QLatin1String("Processes"));

    //***************************       wrap up        ********************************
    delete root;
    umldoc->setCurrentRoot(Uml::ModelType::Logical);
    Import_Utils::assignUniqueIdOnCreation(true);
    umldoc->resolveTypes();
    return logicalView;
}
Beispiel #14
0
int main( int argc, char *argv[] )
{
    QApplication app(argc, argv);

    QStringList arguments (QApplication::arguments());
    arguments.pop_front(); // application path

    // Pass files to existing instance and quit

    SingleInstanceGuard guard;
    if (guard.tryConnect(arguments))
        return 0;

    // Set up translations

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&qtTranslator);

    char resourcePath[PATH_MAX];
    sc_GetResourceDirectory(resourcePath, PATH_MAX);
    QString ideTranslationPath = QString(resourcePath) + "/translations";

    bool translationLoaded;

    // Load fallback translator that only handles plural forms in English
    QTranslator fallbackTranslator;
    translationLoaded = fallbackTranslator.load( "scide", ideTranslationPath );
    app.installTranslator(&fallbackTranslator);
    if (!translationLoaded)
        qWarning("scide warning: Failed to load fallback translation file.");

    // Load translator for locale
    QString ideTranslationFile = "scide_" + QLocale::system().name();
    QTranslator scideTranslator;
    scideTranslator.load( ideTranslationFile, ideTranslationPath );
    app.installTranslator(&scideTranslator);

    // Set up style

    app.setStyle( new ScIDE::Style(app.style()) );

    // Go...

    Main * main = Main::instance();

    MainWindow *win = new MainWindow(main);

    // NOTE: load session after GUI is created, so that GUI can respond
    Settings::Manager *settings = main->settings();
    SessionManager *sessions = main->sessionManager();

    // NOTE: window has to be shown before restoring its geometry,
    // or else restoring maximized state will fail, if it has ever before
    // been saved un-maximized.
    win->show();

    QString startSessionName = settings->value("IDE/startWithSession").toString();
    if (startSessionName == "last") {
        QString lastSession = sessions->lastSession();
        if (!lastSession.isEmpty()) {
            sessions->openSession(lastSession);
        }
    }
    else if (!startSessionName.isEmpty()) {
        sessions->openSession(startSessionName);
    }

    if (!sessions->currentSession()) {
        win->restoreWindowState();
        sessions->newSession();
    }

    foreach (QString argument, arguments) {
        main->documentManager()->open(argument);
    }
Beispiel #15
0
int main(int argc, char *argv[])
{
	QCoreApplication app(argc, argv);

	initLogger(QsLogging::InfoLevel);

	bool expectVerbosity = false;
	bool expectDBusAddress = false;
	QString portName;
	QString dbusAddress = "system";
	QStringList args = app.arguments();
	args.pop_front();
	foreach (QString arg, args) {
		if (expectVerbosity) {
			QsLogging::Logger &logger = QsLogging::Logger::instance();
			QsLogging::Level logLevel = static_cast<QsLogging::Level>(qBound(
				static_cast<int>(QsLogging::TraceLevel),
				arg.toInt(),
				static_cast<int>(QsLogging::OffLevel)));
			logger.setLoggingLevel(logLevel);
			expectVerbosity = false;
		} else if (expectDBusAddress) {
			dbusAddress = arg;
			expectDBusAddress = false;
		} else if (arg == "-h" || arg == "--help") {
			QLOG_INFO() << app.arguments().first();
			QLOG_INFO() << "\t-h, --help";
			QLOG_INFO() << "\t Show this message.";
			QLOG_INFO() << "\t-V, --version";
			QLOG_INFO() << "\t Show the application version.";
			QLOG_INFO() << "\t-d level, --debug level";
			QLOG_INFO() << "\t Set log level";
			QLOG_INFO() << "\t-b, --dbus";
			QLOG_INFO() << "\t dbus address or 'session' or 'system'";
			QLOG_INFO() << "\t <Port Name>";
			QLOG_INFO() << "\t Name of communication port (eg. /dev/ttyUSB0)";
			exit(1);
		} else if (arg == "-V" || arg == "--version") {
			QLOG_INFO() << VERSION;
			exit(0);
		} else if (arg == "-d" || arg == "--debug") {
			expectVerbosity = true;
		} else if (arg == "-t" || arg == "--timestamp") {
			QsLogging::Logger &logger = QsLogging::Logger::instance();
			logger.setIncludeTimestamp(true);
		} else if (arg == "-b" || arg == "--dbus") {
			expectDBusAddress = true;
		} else if (!arg.startsWith('-')) {
			portName = arg;
		}
	}

	if (portName.isEmpty()) {
		QLOG_ERROR() << "No communication port specified on command line";
		exit(2);
	} else {
		QLOG_INFO() << "Connecting to" << portName;
	}

	initDBus(dbusAddress);

	DBusRedflow a(portName);

	app.connect(&a, SIGNAL(connectionLost()), &app, SLOT(quit()));

	return app.exec();
}
/**
   return the property that matches the given key sequence, if any

   @param scope scope of key
   @param key keyname
   @param rootProperty is likely to be the top level QgsPropertyKey in QgsProject:e:Imp.

   @return null if not found, otherwise located Property
*/
static
QgsProperty * findKey_( QString const & scope,
                        QString const & key,
                        QgsPropertyKey &   rootProperty )
{
  QgsPropertyKey * currentProperty = &rootProperty;
  QgsProperty * nextProperty;           // link to next property down hiearchy

  QStringList keySequence = makeKeyTokens_( scope, key );

  while ( ! keySequence.isEmpty() )
  {
    // if the current head of the sequence list matches the property name,
    // then traverse down the property hierarchy
    if ( keySequence.first() == currentProperty->name() )
    {
      // remove front key since we're traversing down a level
      keySequence.pop_front();

      // if we have only one key name left, then return the key found
      if ( 1 == keySequence.count() )
      {
        return currentProperty->find( keySequence.front() );

      }
      // if we're out of keys then the current property is the one we
      // want; i.e., we're in the rate case of being at the top-most
      // property node
      else if ( keySequence.isEmpty() )
      {
        return currentProperty;
      }
      else if (( nextProperty = currentProperty->find( keySequence.first() ) ) )
      {
        if ( nextProperty->isKey() )
        {
          currentProperty = dynamic_cast<QgsPropertyKey*>( nextProperty );
        }
        // it may be that this may be one of several property value
        // nodes keyed by QDict string; if this is the last remaining
        // key token and the next property is a value node, then
        // that's the situation, so return the currentProperty
        else if ( nextProperty->isValue() && ( 1 == keySequence.count() ) )
        {
          return currentProperty;
        }
        else            // QgsPropertyValue not Key, so return null
        {
          return 0x0;
        }
      }
      else                // if the next key down isn't found
      {                   // then the overall key sequence doesn't exist
        return 0x0;
      }
    }
    else
    {
      return 0x0;
    }
  }

  return 0x0;
} // findKey_
Beispiel #17
0
void SSDP::ProcessData( MSocketDevice *pSocket )
{
    QByteArray buffer;
    long nBytes = 0;

    while ((nBytes = pSocket->bytesAvailable()) > 0)
    {
        buffer.resize(nBytes);

        long nRead = 0;
        do
        {
            long ret = pSocket->readBlock( buffer.data() + nRead, nBytes - nRead );
            if (ret < 0)
            {
                LOG(VB_GENERAL, LOG_ERR, QString("Socket readBlock error %1")
                    .arg(pSocket->error()));
                buffer.clear();
                break;
            }

            nRead += ret;

            if (0 == ret)
            {
                LOG(VB_SOCKET, LOG_WARNING,
                    QString("%1 bytes reported available, "
                            "but only %2 bytes read.")
                    .arg(nBytes).arg(nRead));
                nBytes = nRead;
                buffer.resize(nBytes);
                break;
            }
        }
        while (nRead < nBytes);

        if (buffer.isEmpty())
            continue;

        QHostAddress  peerAddress = pSocket->peerAddress();
        quint16       peerPort    = pSocket->peerPort   ();

        // ------------------------------------------------------------------
        QString     str          = QString(buffer.constData());
        QStringList lines        = str.split("\r\n", QString::SkipEmptyParts);
        QString     sRequestLine = lines.size() ? lines[0] : "";

        lines.pop_front();

        // ------------------------------------------------------------------
        // Parse request Type
        // ------------------------------------------------------------------

        LOG(VB_UPNP, LOG_DEBUG, QString("SSDP::ProcessData - requestLine: %1")
                .arg(sRequestLine));

        SSDPRequestType eType = ProcessRequestLine( sRequestLine );

        // ------------------------------------------------------------------
        // Read Headers into map
        // ------------------------------------------------------------------

        QStringMap  headers;

        for ( QStringList::Iterator it = lines.begin();
                                    it != lines.end(); ++it ) 
        {
            QString sLine  = *it;
            QString sName  = sLine.section( ':', 0, 0 ).trimmed();
            QString sValue = sLine.section( ':', 1 );

            sValue.truncate( sValue.length() );  //-2

            if ((sName.length() != 0) && (sValue.length() !=0))
                headers.insert( sName.toLower(), sValue.trimmed() );
        }

#if 0
        pSocket->SetDestAddress( peerAddress, peerPort );
#endif

        // --------------------------------------------------------------
        // See if this is a valid request
        // --------------------------------------------------------------

        switch( eType )
        {
            case SSDP_MSearch:
            {
                // ----------------------------------------------------------
                // If we haven't enabled notifications yet, then we don't 
                // want to answer search requests.
                // ----------------------------------------------------------

                if (m_pNotifyTask != NULL)
                    ProcessSearchRequest( headers, peerAddress, peerPort ); 

                break;
            }

            case SSDP_MSearchResp:
                ProcessSearchResponse( headers); 
                break;

            case SSDP_Notify:
                ProcessNotify( headers ); 
                break;

            case SSDP_Unknown:
            default:
                LOG(VB_UPNP, LOG_ERR,
                    "SSPD::ProcessData - Unknown request Type.");
                break;
        }
    }
}
void CreateObjectsPage::initializePage()
{
    if (fwbdebug) qDebug() << "CreateObjectsPage::initializePage()";

    int lib_index = field("libIndex").toInt();
    QStringList libraries = field("libraries").toStringList();
    QStringList objects = field("objectsToUse").toStringList();

    if (fwbdebug)
    {
        qDebug() << "libraries=" << libraries;
        qDebug() << "objects=" << objects;
    }

    m_dialog->progressBar->setFormat("%v / %m");
    m_dialog->progressBar->setMaximum(objects.size() / 2);

    FWObject *last_object = NULL;
    QString name;
    QString addr;
    int counter = 1;
    while (objects.size() > 0)
    {
        name = objects.front(); objects.pop_front();
        addr = objects.front(); objects.pop_front();

        QString type;
        try
        {
            InetAddr(AF_INET6, addr.toLatin1().constData() );
            type = IPv6::TYPENAME;
        } catch (FWException &ex)
        {
        }

        if (type.isEmpty())
        {
            try
            {
                InetAddr(AF_INET, addr.toLatin1().constData() );
                type = IPv4::TYPENAME;
            } catch (FWException &ex)
            {
            }
        }

        if (! type.isEmpty())
        {
            Address *obj = Address::cast(mw->createObject(type, name));
            assert(obj!=NULL);
            obj->setName(name.toUtf8().constData());
            obj->setAddress(InetAddr(addr.toStdString()));
            obj->setNetmask(InetAddr(InetAddr::getAllOnes()));
            mw->moveObject(libraries[lib_index], obj);
            last_object = obj;
        }

        m_dialog->progressBar->setValue(counter);
        qApp->processEvents();

        counter++;
    }

    ProjectPanel *pp = mw->activeProject();
    QString filename = pp->getFileName();
    QCoreApplication::postEvent(mw, new reloadObjectTreeEvent(filename));
    QCoreApplication::postEvent(
        mw->activeProject(), new openLibraryForObjectEvent(
            filename, last_object->getId()));
}
Beispiel #19
0
void Project::addFile(QTreeView* treeView, QSortFilterProxyModel* sort, const QString &fileName)
{
    if (_files.contains(fileName))
        return;
    QFileInfo fi(fileName);
    QString absFileName = fi.absoluteFilePath();
    QString relFileName;
    if (!projectRoot.isEmpty()) {
        QDir projectDir(QFileInfo(projectRoot).absoluteDir());
        relFileName = projectDir.relativeFilePath(absFileName);
    } else {
        relFileName = absFileName;
    }

    QStringList path = relFileName.split(QDir::separator());
    while (path.first().isEmpty()) {
        path.pop_front();
    }
    QStandardItem* curItem;
    bool isMiniZinc = true;
    bool isCoursera = false;
    if (fi.suffix()=="mzn") {
        curItem = mzn;
    } else if (fi.suffix()=="dzn") {
        curItem = dzn;
    } else if (fi.suffix()=="fzn") {
        return;
    } else {
        curItem = other;
        isMiniZinc = false;
        isCoursera = fi.completeBaseName()=="_coursera";
    }

    if (isCoursera) {
        if (_courseraProject) {
            QMessageBox::warning(treeView,"MiniZinc IDE",
                                "Cannot add second Coursera options file",
                                QMessageBox::Ok);
            return;
        }
        QFile metadata(absFileName);
        if (!metadata.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(treeView,"MiniZinc IDE",
                                 "Cannot open Coursera options file",
                                 QMessageBox::Ok);
            return;
        }
        QTextStream in(&metadata);
        CourseraProject* cp = new CourseraProject;
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->course = in.readLine();
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->checkpwdSid= in.readLine();
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->name = in.readLine();
        QString nSolutions_s = in.readLine();
        int nSolutions = nSolutions_s.toInt();
        for (int i=0; i<nSolutions; i++) {
            if (in.status() != QTextStream::Ok) {
                delete cp;
                goto coursera_done;
            }
            QString line = in.readLine();
            QStringList tokens = line.split(", ");
            if (tokens.size() < 5) {
                delete cp;
                goto coursera_done;
            }
            CourseraItem item(tokens[0].trimmed(),tokens[1].trimmed(),tokens[2].trimmed(),
                              tokens[3].trimmed(),tokens[4].trimmed());
            cp->problems.append(item);
        }
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        nSolutions_s = in.readLine();
        nSolutions = nSolutions_s.toInt();
        for (int i=0; i<nSolutions; i++) {
            if (in.status() != QTextStream::Ok) {
                delete cp;
                goto coursera_done;
            }
            QString line = in.readLine();
            QStringList tokens = line.split(", ");
            if (tokens.size() < 3) {
                delete cp;
                goto coursera_done;
            }
            CourseraItem item(tokens[0].trimmed(),tokens[1].trimmed(),tokens[2].trimmed());
            cp->models.append(item);
        }
        _courseraProject = cp;
        ui->actionSubmit_to_Coursera->setVisible(true);
    }
coursera_done:

    setModified(true, true);
    QStandardItem* prevItem = curItem;
    treeView->expand(sort->mapFromSource(curItem->index()));
    curItem = curItem->child(0);
    int i=0;
    while (curItem != NULL) {
        if (curItem->text() == path.first()) {
            path.pop_front();
            treeView->expand(sort->mapFromSource(curItem->index()));
            prevItem = curItem;
            curItem = curItem->child(0);
            i = 0;
        } else {
            i += 1;
            curItem = curItem->parent()->child(i);
        }
    }
    for (int i=0; i<path.size(); i++) {
        QStandardItem* newItem = new QStandardItem(path[i]);
        prevItem->appendRow(newItem);
        if (i<path.size()-1) {
            newItem->setIcon(QIcon(":/icons/images/folder.png"));
        } else {
            _files.insert(absFileName,newItem->index());
            if (isMiniZinc) {
                newItem->setIcon(QIcon(":/images/mznicon.png"));
            }
        }
        treeView->expand(sort->mapFromSource(newItem->index()));
        prevItem = newItem;
    }
}
Beispiel #20
0
void CandidateWindow::activateCand( const QStringList &list )
{
#if defined(ENABLE_DEBUG)
    qDebug( "uim-candwin-qt: activateCand()" );
#endif
    /**
     * format: activate\fcharset=$charset\fdisplay_limit=$value\fhead1\acand1\aannot1\fhead2\acand2\aannot2\fhead3\acand3\aannot3\f
     */

    // remove old data
    cList->clear();
    stores.clear();

    // get charset and create codec
    QTextCodec *codec = NULL;
    if ( !list[ 1 ].isEmpty() && list[ 1 ].startsWith( "charset" ) )
    {
        const QStringList l = QStringList::split( "=", list[ 1 ] );
        codec = QTextCodec::codecForName( l[ 1 ] );
    }

    // get display_limit
    if ( !list[ 2 ].isEmpty() && list[ 2 ].startsWith( "display_limit" ) )
    {
        const QStringList l = QStringList::split( "=", list[ 2 ] );
        displayLimit = l[ 1 ].toInt();
    }

    for ( int i = 3; !list[ i ].isNull(); i++ )
    {
        // case list[i] = ""
        if ( list[ i ].isEmpty() )
            break;

        // split heading_label and cand_str
        QStringList l = QStringList::split( "\a", list [ i ], true );

        // store data
        CandData d;
        QString headString;
        if ( codec )
            headString = codec->toUnicode( l [ 0 ] );
        else
            headString = l [ 0 ];

        d.label = headString;

	l.pop_front();
	QString candString = l [ 0 ];

        if ( codec )
            d.str = codec->toUnicode( candString );
        else
            d.str = candString;

	l.pop_front();
	QString annotString = l [ 0 ];

        stores.append( d );
    }

    // set default value
    candidateIndex = -1;
    nrCandidates = stores.count();

    // shift to default page
    setPage( 0 );

    adjustCandidateWindowSize();
    show();

    isActive = true;
}
Beispiel #21
0
int bandageImage(QStringList arguments)
{
    QTextStream out(stdout);
    QTextStream err(stderr);

    if (checkForHelp(arguments))
    {
        printImageUsage(&out, false);
        return 0;
    }

    if (checkForHelpAll(arguments))
    {
        printImageUsage(&out, true);
        return 0;
    }

    if (arguments.size() < 2)
    {
        printImageUsage(&err, false);
        return 1;
    }

    QString graphFilename = arguments.at(0);
    arguments.pop_front();

    if (!checkIfFileExists(graphFilename))
    {
        err << "Bandage error: " << graphFilename << " does not exist" << endl;
        return 1;
    }

    QString imageSaveFilename = arguments.at(0);
    arguments.pop_front();

    QString imageFileExtension = imageSaveFilename.right(4);
    bool pixelImage;
    if (imageFileExtension == ".png" || imageFileExtension == ".jpg")
        pixelImage = true;
    else if (imageFileExtension == ".svg")
        pixelImage = false;
    else
    {
        err << "Bandage error: the output filename must end in .png, .jpg or .svg" << endl;
        return 1;
    }

    QString error = checkForInvalidImageOptions(arguments);
    if (error.length() > 0)
    {
        err << "Bandage error: " << error << endl;
        return 1;
    }

    bool loadSuccess = g_assemblyGraph->loadGraphFromFile(graphFilename);
    if (!loadSuccess)
    {
        err << "Bandage error: could not load " << graphFilename << endl;
        return 1;
    }

    int width = 0;
    int height = 0;
    parseImageOptions(arguments, &width, &height);

    //For Bandage image, it is necessary to position node labels at the
    //centre of the node, not the visible centre(s).  This is because there
    //is no viewport.
    g_settings->positionTextNodeCentre = true;

    //Since frame rate performance doesn't matter for a fixed image, set the
    //default node outline to a nonzero value.
    g_settings->outlineThickness = 0.3;

    bool blastUsed = isOptionPresent("--query", &arguments);

    if (blastUsed)
    {
        if (!createBlastTempDirectory())
        {
            err << "Error creating temporary directory for BLAST files" << endl;
            return 1;
        }

        QString blastError = g_blastSearch->doAutoBlastSearch();

        if (blastError != "")
        {
            err << blastError << endl;
            return 1;
        }
    }

    QString errorTitle;
    QString errorMessage;
    std::vector<DeBruijnNode *> startingNodes = g_assemblyGraph->getStartingNodes(&errorTitle, &errorMessage,
                                                                                  g_settings->doubleMode,
                                                                                  g_settings->startingNodes,
                                                                                  "all");

    if (errorMessage != "")
    {
        err << errorMessage << endl;
        return 1;
    }

    g_assemblyGraph->buildOgdfGraphFromNodesAndEdges(startingNodes, g_settings->nodeDistance);
    g_assemblyGraph->layoutGraph();

    MyGraphicsScene scene;
    g_assemblyGraph->addGraphicsItemsToScene(&scene);
    scene.setSceneRectangle();
    double sceneRectAspectRatio = scene.sceneRect().width() / scene.sceneRect().height();

    //Determine image size
    //If neither height nor width set, use a default of height = 1000.
    if (height == 0 && width == 0)
        height = 1000;

    //If only height or width is set, scale the other to fit.
    if (height > 0 && width == 0)
        width = height * sceneRectAspectRatio;
    else if (height == 0 && width > 0)
        height = width / sceneRectAspectRatio;

    bool success = true;
    QPainter painter;
    if (pixelImage)
    {
        QImage image(width, height, QImage::Format_ARGB32);
        image.fill(Qt::white);
        painter.begin(&image);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::TextAntialiasing);
        scene.render(&painter);
        success = image.save(imageSaveFilename);
        painter.end();
    }
    else //SVG
    {
        QSvgGenerator generator;
        generator.setFileName(imageSaveFilename);
        generator.setSize(QSize(width, height));
        generator.setViewBox(QRect(0, 0, width, height));
        painter.begin(&generator);
        painter.fillRect(0, 0, width, height, Qt::white);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::TextAntialiasing);
        scene.render(&painter);
        painter.end();
    }

    int returnCode;
    if (!success)
    {
        out << "There was an error writing the image to file." << endl;
        returnCode = 1;
    }
    else
        returnCode = 0;

    if (blastUsed)
        deleteBlastTempDirectory();

    return returnCode;
}
Beispiel #22
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QApplication::setApplicationName("Bandage");
    QApplication::setApplicationVersion("0.6.2");

    QTextStream out(stdout);
    QTextStream err(stdout);

    //Create the important global objects.
    g_settings.reset(new Settings());
    g_blastSearch.reset(new BlastSearch());
    g_assemblyGraph.reset(new AssemblyGraph());
    g_graphicsView = new MyGraphicsView();

    QStringList arguments = QCoreApplication::arguments();
    arguments.pop_front();

    if (checkForVersion(arguments))
    {
        out << "Version: " << QApplication::applicationVersion() << endl;
        return 0;
    }

    //If the first argument was a recognised command, move to that command's function.
    if (arguments.size() > 0)
    {
        QString first = arguments.at(0);
        if (first == "load")
        {
            arguments.pop_front();
            g_settings->commandLineCommand = BANDAGE_LOAD;
            return bandageLoad(&a, arguments);
        }
        else if (first == "image")
        {
            arguments.pop_front();
            g_settings->commandLineCommand = BANDAGE_IMAGE;
            return bandageImage(arguments);
        }
//        else if (first == "contiguous")
//        {
//            arguments.pop_front();
//            return bandageContiguous(arguments);
//        }
    }

    //Since a recognised command was not seen, we now check to see if the user
    //was looking for help information.
    if (checkForHelp(arguments))
    {
        out << "" << endl;
        out << "Program: Bandage" << endl;
        out << "Version: " << QApplication::applicationVersion() << endl;
        printUsage(&out, false);
        return 0;
    }
    if (checkForHelpAll(arguments))
    {
        out << "" << endl;
        out << "Program: Bandage" << endl;
        out << "Version: " << QApplication::applicationVersion() << endl;
        printUsage(&out, true);
        return 0;
    }

    //If the code got here, we assume the user is simply launching Bandage,
    //with or without some options to specify settings.

    //Check the settings.
    QStringList argumentsCopy = arguments;
    QString error = checkForInvalidOrExcessSettings(&argumentsCopy);
    if (error.length() > 0)
    {
        err << "Bandage error: " + error << endl;
        return 1;
    }

    //If the code got here, then the settings are good.  Parse them now and
    //run the program.
    parseSettings(arguments);
    MainWindow w;
    w.show();
    return a.exec();
}
Beispiel #23
0
void ChatWindow::setLogfileName(const QString& name)
{
    // Only change name of logfile if the window was new.
    if(firstLog)
    {
        if (getTextView())
            getTextView()->setContextMenuOptions(IrcContextMenus::ShowLogAction, true);

        // status panels get special treatment here, since they have no server at the beginning
        if (getType() == Status || getType() == DccChat)
        {
            logName = name + ".log";
        }
        else if (m_server)
        {
            // make sure that no path delimiters are in the name
            logName = QString(m_server->getDisplayName().toLower()).append('_').append(name).append(".log").replace('/','_');
        }

        // load backlog to show
        if(Preferences::self()->showBacklog())
        {
            // "cd" into log path or create path, if it's not there
            cdIntoLogPath();
            // Show last log lines. This idea was stole ... um ... inspired by PMP :)
            // Don't do this for the server status windows, though
            if((getType() != Status) && logfile.open(QIODevice::ReadOnly))
            {
                qint64 filePosition;

                QString backlogLine;
                QTextStream backlog(&logfile);
                backlog.setCodec(QTextCodec::codecForName("UTF-8"));
                backlog.setAutoDetectUnicode(true);

                QStringList firstColumns;
                QStringList messages;
                int offset = 0;
                qint64 lastPacketHeadPosition = backlog.device()->size();
                const unsigned int packetSize = 4096;
                while(messages.count() < Preferences::self()->backlogLines() && backlog.device()->size() > packetSize * offset)
                {
                    QStringList firstColumnsInPacket;
                    QStringList messagesInPacket;

                    // packetSize * offset < size <= packetSize * ( offset + 1 )

                    // Check if the log is bigger than packetSize * ( offset + 1 )
                    if(backlog.device()->size() > packetSize * ( offset + 1 ))
                    {
                        // Set file pointer to the packet size above the offset
                        backlog.seek(backlog.device()->size() - packetSize * ( offset + 1 ));
                        // Skip first line, since it may be incomplete
                        backlog.readLine();
                    }
                    else
                    {
                        // Set file pointer to the head

                        // Qt 4.5 Doc: Note that when using a QTextStream on a
                        // QFile, calling reset() on the QFile will not have the
                        // expected result because QTextStream buffers the  file.
                        // Use the QTextStream::seek() function instead.
                        // backlog.device()->reset();
                        backlog.seek( 0 );
                    }

                    // remember actual file position to check for deadlocks
                    filePosition = backlog.pos();

                    qint64 currentPacketHeadPosition = filePosition;

                    // Loop until end of file reached
                    while(!backlog.atEnd() && filePosition < lastPacketHeadPosition)
                    {
                        backlogLine = backlog.readLine();

                        // check for deadlocks
                        if(backlog.pos() == filePosition)
                        {
                            backlog.seek(filePosition + 1);
                        }

                        // if a tab character is present in the line, meaning it is a valid chatline
                        if (backlogLine.contains('\t'))
                        {
                            // extract first column from log
                            QString backlogFirst = backlogLine.left(backlogLine.indexOf('\t'));
                            // cut first column from line
                            backlogLine = backlogLine.mid(backlogLine.indexOf('\t') + 1);
                            // Logfile is in utf8 so we don't need to do encoding stuff here
                            // append backlog with time and first column to text view
                            firstColumnsInPacket << backlogFirst;
                            messagesInPacket << backlogLine;
                        }

                        // remember actual file position to check for deadlocks
                        filePosition = backlog.pos();
                    } // while

                    // remember the position not to read the same lines again
                    lastPacketHeadPosition = currentPacketHeadPosition;
                    ++offset;

                    firstColumns = firstColumnsInPacket + firstColumns;
                    messages = messagesInPacket + messages;
                }
                backlog.setDevice(0);
                logfile.close();

                // trim
                int surplus = messages.count() - Preferences::self()->backlogLines();
                // "surplus" can be a minus value. (when the backlog is too short)
                if(surplus > 0)
                {
                    for(int i = 0 ; i < surplus ; ++i)
                    {
                        firstColumns.pop_front();
                        messages.pop_front();
                    }
                }

                QStringList::Iterator itFirstColumn = firstColumns.begin();
                QStringList::Iterator itMessage = messages.begin();
                for( ; itFirstColumn != firstColumns.end() ; ++itFirstColumn, ++itMessage )
                    appendBacklogMessage(*itFirstColumn, *itMessage);
            }
        } // if(Preferences::showBacklog())
    }
}
Beispiel #24
0
QMap<QString, CallTip> CallTipsList::extractTips(const QString& context) const
{
    Base::PyGILStateLocker lock;
    QMap<QString, CallTip> tips;
    if (context.isEmpty())
        return tips;

    try {
        Py::Module module("__main__");
        Py::Dict dict = module.getDict();
#if 0
        QStringList items = context.split(QLatin1Char('.'));
        QString modname = items.front();
        items.pop_front();
        if (!dict.hasKey(std::string(modname.toLatin1())))
            return tips; // unknown object

        // get the Python object we need
        Py::Object obj = dict.getItem(std::string(modname.toLatin1()));
        while (!items.isEmpty()) {
            QByteArray name = items.front().toLatin1();
            std::string attr = name.constData();
            items.pop_front();
            if (obj.hasAttr(attr))
                obj = obj.getAttr(attr);
            else
                return tips;
        }
#else
        // Don't use hasattr & getattr because if a property is bound to a method this will be executed twice.
        PyObject* code = Py_CompileString(static_cast<const char*>(context.toLatin1()), "<CallTipsList>", Py_eval_input);
        if (!code) {
            PyErr_Clear();
            return tips;
        }

        PyObject* eval = 0;
        if (PyCode_Check(code)) {
            eval = PyEval_EvalCode(reinterpret_cast<PyCodeObject*>(code), dict.ptr(), dict.ptr());
        }
        Py_DECREF(code);
        if (!eval) {
            PyErr_Clear();
            return tips;
        }
        Py::Object obj(eval, true);
#endif

        // Checks whether the type is a subclass of PyObjectBase because to get the doc string
        // of a member we must get it by its type instead of its instance otherwise we get the
        // wrong string, namely that of the type of the member. 
        // Note: 3rd party libraries may use their own type object classes so that we cannot 
        // reliably use Py::Type. To be on the safe side we should use Py::Object to assign
        // the used type object to.
        //Py::Object type = obj.type();
        Py::Object type(PyObject_Type(obj.ptr()), true);
        Py::Object inst = obj; // the object instance 
        union PyType_Object typeobj = {&Base::PyObjectBase::Type};
        union PyType_Object typedoc = {&App::DocumentObjectPy::Type};
        union PyType_Object basetype = {&PyBaseObject_Type};

        if (PyObject_IsSubclass(type.ptr(), typedoc.o) == 1) {
            // From the template Python object we don't query its type object because there we keep
            // a list of additional methods that we won't see otherwise. But to get the correct doc
            // strings we query the type's dict in the class itself.
            // To see if we have a template Python object we check for the existence of supportedProperties
            if (!type.hasAttr("supportedProperties")) {
                obj = type;
            }
        }
        else if (PyObject_IsSubclass(type.ptr(), typeobj.o) == 1) {
            obj = type;
        }
        else if (PyInstance_Check(obj.ptr())) {
            // instances of old style classes
            PyInstanceObject* inst = reinterpret_cast<PyInstanceObject*>(obj.ptr());
            PyObject* classobj = reinterpret_cast<PyObject*>(inst->in_class);
            obj = Py::Object(classobj);
        }
        else if (PyObject_IsInstance(obj.ptr(), basetype.o) == 1) {
            // New style class which can be a module, type, list, tuple, int, float, ...
            // Make sure it's not a type objec
            union PyType_Object typetype = {&PyType_Type};
            if (PyObject_IsInstance(obj.ptr(), typetype.o) != 1) {
                // this should be now a user-defined Python class
                // http://stackoverflow.com/questions/12233103/in-python-at-runtime-determine-if-an-object-is-a-class-old-and-new-type-instan
                if (Py_TYPE(obj.ptr())->tp_flags & Py_TPFLAGS_HEAPTYPE) {
                    obj = type;
                }
            }
        }

        // If we have an instance of PyObjectBase then determine whether it's valid or not
        if (PyObject_IsInstance(inst.ptr(), typeobj.o) == 1) {
            Base::PyObjectBase* baseobj = static_cast<Base::PyObjectBase*>(inst.ptr());
            const_cast<CallTipsList*>(this)->validObject = baseobj->isValid();
        }
        else {
            // PyObject_IsInstance might set an exception
            PyErr_Clear();
        }

        Py::List list(obj.dir());

        // If we derive from PropertyContainerPy we can search for the properties in the
        // C++ twin class.
        union PyType_Object proptypeobj = {&App::PropertyContainerPy::Type};
        if (PyObject_IsSubclass(type.ptr(), proptypeobj.o) == 1) {
            // These are the attributes of the instance itself which are NOT accessible by
            // its type object
            extractTipsFromProperties(inst, tips);
        }

        // If we derive from App::DocumentPy we have direct access to the objects by their internal
        // names. So, we add these names to the list, too.
        union PyType_Object appdoctypeobj = {&App::DocumentPy::Type};
        if (PyObject_IsSubclass(type.ptr(), appdoctypeobj.o) == 1) {
            App::DocumentPy* docpy = (App::DocumentPy*)(inst.ptr());
            App::Document* document = docpy->getDocumentPtr();
            // Make sure that the C++ object is alive
            if (document) {
                std::vector<App::DocumentObject*> objects = document->getObjects();
                Py::List list;
                for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
                    list.append(Py::String((*it)->getNameInDocument()));
                extractTipsFromObject(inst, list, tips);
            }
        }

        // If we derive from Gui::DocumentPy we have direct access to the objects by their internal
        // names. So, we add these names to the list, too.
        union PyType_Object guidoctypeobj = {&Gui::DocumentPy::Type};
        if (PyObject_IsSubclass(type.ptr(), guidoctypeobj.o) == 1) {
            Gui::DocumentPy* docpy = (Gui::DocumentPy*)(inst.ptr());
            if (docpy->getDocumentPtr()) {
                App::Document* document = docpy->getDocumentPtr()->getDocument();
                // Make sure that the C++ object is alive
                if (document) {
                    std::vector<App::DocumentObject*> objects = document->getObjects();
                    Py::List list;
                    for (std::vector<App::DocumentObject*>::iterator it = objects.begin(); it != objects.end(); ++it)
                        list.append(Py::String((*it)->getNameInDocument()));
                    extractTipsFromObject(inst, list, tips);
                }
            }
        }

        // These are the attributes from the type object
        extractTipsFromObject(obj, list, tips);
    }
    catch (Py::Exception& e) {
        // Just clear the Python exception
        e.clear();
    }

    return tips;
}
/** add the given key and value

@param scope scope of key
@param key key name
@param rootProperty is the property from which to start adding
@param value the value associated with the key
*/
static
QgsProperty * addKey_( QString const & scope,
                       QString const & key,
                       QgsPropertyKey * rootProperty,
                       QVariant value )
{
  QStringList keySequence = makeKeyTokens_( scope, key );

  // cursor through property key/value hierarchy
  QgsPropertyKey * currentProperty = rootProperty;

  QgsProperty * newProperty; // link to next property down hiearchy

  while ( ! keySequence.isEmpty() )
  {
    // if the current head of the sequence list matches the property name,
    // then traverse down the property hierarchy
    if ( keySequence.first() == currentProperty->name() )
    {
      // remove front key since we're traversing down a level
      keySequence.pop_front();

      // if key sequence has one last element, then we use that as the
      // name to store the value
      if ( 1 == keySequence.count() )
      {
        currentProperty->setValue( keySequence.front(), value );
        return currentProperty;
      }
      // we're at the top element if popping the keySequence element
      // will leave it empty; in that case, just add the key
      else if ( keySequence.isEmpty() )
      {
        currentProperty->setValue( value );

        return currentProperty;
      }
      else if (( newProperty = currentProperty->find( keySequence.first() ) ) )
      {
        currentProperty = dynamic_cast<QgsPropertyKey*>( newProperty );

        if ( currentProperty )
        {
          continue;
        }
        else            // QgsPropertyValue not Key, so return null
        {
          return 0x0;
        }
      }
      else                // the next subkey doesn't exist, so add it
      {
        newProperty = currentProperty->addKey( keySequence.first() );

        if ( newProperty )
        {
          currentProperty = dynamic_cast<QgsPropertyKey*>( newProperty );
        }
        continue;
      }
    }
    else
    {
      return 0x0;
    }
  }

  return 0x0;

} // addKey_
Beispiel #26
0
Tellico::Data::EntryPtr IBSFetcher::parseEntry(const QString& str_) {
//  QString pat = QLatin1String("%1(?:<[^>]+>)+([^<>\\s][^<>]+)");
  QString pat = QLatin1String("%1(?:<[^>]+>)+(.+)</td.*>");

  Data::CollPtr coll(new Data::BookCollection(true));

 // map captions in HTML to field names
  QHash<QString, QString> fieldMap;
  fieldMap.insert(QLatin1String("Titolo"), QLatin1String("title"));
  fieldMap.insert(QLatin1String("Autore"), QLatin1String("author"));
  fieldMap.insert(QLatin1String("Anno"), QLatin1String("pub_year"));
  fieldMap.insert(QLatin1String("Categoria"), QLatin1String("genre"));
  fieldMap.insert(QLatin1String("Rilegatura"), QLatin1String("binding"));
  fieldMap.insert(QLatin1String("Editore"), QLatin1String("publisher"));
  fieldMap.insert(QLatin1String("Dati"), QLatin1String("edition"));
  fieldMap.insert(QLatin1String("Traduttore"), QLatin1String("translator"));
  fieldMap.insert(QLatin1String("Curatore"), QLatin1String("editor"));

  QRegExp tagRx(QLatin1String("<.*>"));
  tagRx.setMinimal(true);

  QRegExp pagesRx(QLatin1String("\\s*(\\d+) p\\.(\\s*,\\s*)?"));
  QRegExp yearRx(QLatin1String("^\\d{4}"));

  Data::EntryPtr entry(new Data::Entry(coll));

  for(QHash<QString, QString>::Iterator it = fieldMap.begin(); it != fieldMap.end(); ++it) {
    QRegExp infoRx(pat.arg(it.key()));
    infoRx.setMinimal(true);
    int pos = infoRx.indexIn(str_);
    if(pos > -1) {
      if(it.value() == QLatin1String("edition")) {
        QString data = infoRx.cap(1).remove(tagRx).trimmed();
        int pos2 = pagesRx.indexIn(data);
        if(pos2 > -1) {
          entry->setField(QLatin1String("pages"), pagesRx.cap(1));
          data = data.remove(pagesRx);
        }
        // assume that if the value starts with 4 digits, then it's a year
        pos2 = yearRx.indexIn(data);
        if(pos2 > -1) {
          entry->setField(QLatin1String("pub_year"), yearRx.cap(0));
          data = data.remove(yearRx).trimmed();
          // might start with a comma now
          if(data.startsWith(QLatin1String(","))) {
            data = data.mid(1).trimmed();
          }
        }
        // now it might be the binding
        if(data == QLatin1String("brossura")) {
          entry->setField(QLatin1String("binding"), i18n("Paperback"));
        } else if(data == QLatin1String("rilegato")) {
          entry->setField(QLatin1String("binding"), i18n("Hardback"));
        } else {
          entry->setField(it.value(), data);
        }
      } else {
        entry->setField(it.value(), infoRx.cap(1).remove(tagRx).trimmed());
      }
    }
  }

  QRegExp isbnRx(QLatin1String("isbn=([\\dxX]{13})"), Qt::CaseInsensitive);
  QString isbn;
  int pos = isbnRx.indexIn(str_);
  if(pos > -1) {
    isbn = isbnRx.cap(1);
  }
  // image
  if(!isbn.isEmpty()) {
    entry->setField(QLatin1String("isbn"), isbn);
#if 1
    QUrl imgURL(QString::fromLatin1("http://giotto.ibs.it/cop/copt13.asp?f=%1").arg(isbn));
//    myLog() << "cover = " << imgURL;
    QString id = ImageFactory::addImage(imgURL, true, QUrl(QString::fromLatin1("http://internetbookshop.it")));
    if(!id.isEmpty()) {
      entry->setField(QLatin1String("cover"), id);
    }
#else
    QRegExp imgRx(QString::fromLatin1("<img\\s+[^>]*\\s*src\\s*=\\s*\"(http://[^/]*\\.ibs\\.it/[^\"]+e=%1)").arg(isbn));
    imgRx.setMinimal(true);
    pos = imgRx.indexIn(str_);
    if(pos > -1) {
//      myLog() << "cover = " << imgRx.cap(1);
      QString id = ImageFactory::addImage(imgRx.cap(1), true, QUrl("http://internetbookshop.it"));
      if(!id.isEmpty()) {
        entry->setField(QLatin1String("cover"), id);
      }
    }
#endif
  }

  // now look for description
  QRegExp descRx(QLatin1String("Descrizione(?:<[^>]+>)+([^<>\\s].+)</span>"), Qt::CaseInsensitive);
  descRx.setMinimal(true);
  pos = descRx.indexIn(str_);
  if(pos == -1) {
    descRx.setPattern(QLatin1String("In sintesi(?:<[^>]+>)+([^<>\\s].+)</span>"));
    pos = descRx.indexIn(str_);
  }
  if(pos > -1) {
    Data::FieldPtr f(new Data::Field(QLatin1String("plot"), i18n("Plot Summary"), Data::Field::Para));
    coll->addField(f);
    entry->setField(f, descRx.cap(1).simplified());
  }

  // IBS switches the surname and family name of the author and translator
  const QStringList peopleFields = QStringList() << QLatin1String("author")
                                                 << QLatin1String("editor")
                                                 << QLatin1String("translator");
  foreach(const QString& fieldName, peopleFields) {
    QStringList names = FieldFormat::splitValue(entry->field(fieldName));
    if(!names.isEmpty() && !names[0].isEmpty()) {
      for(QStringList::Iterator it = names.begin(); it != names.end(); ++it) {
        if((*it).indexOf(QLatin1Char(',')) > -1) {
          continue; // skip if it has a comma
        }
        QStringList words = (*it).split(QLatin1Char(' '));
        if(words.isEmpty()) {
          continue;
        }
        // put first word in back
        words.append(words[0]);
        words.pop_front();
        *it = words.join(QLatin1String(" "));
      }
      entry->setField(fieldName, names.join(FieldFormat::delimiterString()));
    }
  }
Beispiel #27
0
void ConnectorOld::stringParser(QByteArray recv)
{
  QString recvStr = codec->toUnicode(recv);
  QChar category = recvStr[0];                        // First symbol of string
  QStringList message = recvStr.mid(1).split("\t");   // Remove first symbol & splitting
  QString cmd;
  switch (category.toAscii())
  {
  case 'R':       // Authentification request
    qDebug() << "CONN :: Auth_req:" << message;
    emit authRequestRecv(message.at(0));
    break;
  case 'b':       // Information
    qDebug() << "CONN :: Inform:" << message;
    emit infoMessage(message.at(0));
    // Verify for success auth string
    if (message.at(0).split(" ").count() == 7)
      if (message.at(0).split(" ").at(2).at(8) == ',')
        emit authSuccess();
    break;
  case 'd':       // Board
    cmd = message.at(0);
    if (cmd == "channels")  // Receved channel list
    {
      qDebug() << "CONN :: Board: channels recv";
      message.pop_front();    // Remove command from message
      emit boardChannelsRecv(parseBoardChannels(message.join("\t")));
    }
    else
    {
      if (cmd == "new")  // New messages
      {
        qDebug() << "CONN :: Board: new messages avaible";
        emit boardNewMessages();
      }
      else
      {
        if (cmd == "skins")
        {
          qDebug() << "CONN :: Board: \"skins\" cmd recv";
        }
        else
        {
          if (cmd == "admin")
          {
            qDebug() << "CONN :: Board: \"admin\" cmd recv";
          }
          else
          {
            qDebug() << "CONN :: Board: messages recv";
            emit boardMessagesRecv(parseBoardMessages(message.join("\t")));
          }
        }
      }
    }
//    qDebug() << "DBoard :: " << message;
    break;
  case 'c':       // Chat
    cmd = message.at(0);
    message.pop_front();    // Remove command from message
    if (cmd == "main")
    {
      qDebug() << "CONN :: Chat: channel message recv";
      emit chatPublicMessage(message.at(0),
                             getUserIdByName(message.at(0), message.at(2)),
                             message.at(3));
    }
    else
    {
      if (cmd == "enter")
      {
        QString channelId = message.at(0);
        if (QHostAddress().setAddress(channelId))
        {
          qDebug() << "CONN :: Host entered"
                   << message.at(2) << "@" << channelId;
        }
        else
        {
          qDebug() << "CONN :: Chat: new user entered" << message.at(3);
          emit chatUserEnter(channelId, parseEnteredUser(message));
        }
      }
      else
      {
        if (cmd == "leave")
        {
          QString channelId = message.at(0);
          if (QHostAddress().setAddress(channelId))
          {
            qDebug() << "CONN :: Host leave"
                     << message.at(2) << "@" << channelId;
          }
          else
          {
            shared_ptr<ChatChannel> ch =
                getChatInstance()->getChannel(channelId);
            bool online; // Verify for user connect state
            ch->getUser(message.at(2), &online);
            if (online)
            {
              qDebug() << "CONN :: Chat: user leave" << message.at(3);
              emit chatUserLeave(channelId, message.at(2));
            }
          }
        }
        else
        {
          if (cmd == "private")
          {
            qDebug() << "CONN :: Chat: new private message";
            emit chatPrivateMessage(parseChatPrivate(message));
          }
          else
          {
            if (cmd == "infoGet")
            {
              qDebug() << "CONN :: Chat: \"infoGet\" cmd recv";
            }
            else
            {
              if (cmd == "channels")
              {
                qDebug() << "CONN :: Chat: channels recv";
                emit chatChannelsRecv(parseChatChannels(message.join("\t")));
              }
              else
              {
                if (cmd == "userlist")
                {
                  qDebug() << "CONN :: Chat: userlist recv";
                  emit chatUsersRecv(message.at(0), parseChatUsers(message));
                }
                else
                {
                  if (cmd == "privateresived")
                  {
                    emit chatPrivateDelivered(
                          message.at(0), message.at(1), message.at(2));
                  }
                  else
                    qDebug() << "CONN ::" << cmd << message;
                }
              }
            }
          }
        }
      }
    }
//    qDebug() << "Chat   :: " << message;
    break;
  default:       // Uncategorised
    qDebug() << "Unctg  :: " << recvStr;
  }
}
Beispiel #28
0
int main (int argc, char *argv[]) {
	QApplication app (argc, argv);
	QStringList args = app.arguments ();
	if (!args.isEmpty ()) args.pop_front ();	// The command itself
	qputenv ("DESKTOP_STARTUP_ID", qgetenv ("STARTUP_ID_COPY"));	// for startup notifications (set via rkward.desktop)
	qputenv ("STARTUP_ID_COPY", "");

	// Parse arguments that need handling in the wrapper
	bool usage = false;
	QStringList debugger_args;
	QStringList file_args;
	bool reuse = false;
	bool warn_external = true;
	QString r_exe_arg;
	int debug_level = 2;

	for (int i=0; i < args.size (); ++i) {
		if (args[i] == "--debugger") {
			args.removeAt (i);
			while (i < args.size ()) {
				QString arg = args.takeAt (i);
				if (arg == "--") break;
				debugger_args.append (arg);
			}
			if (debugger_args.isEmpty ()) usage = true;
		} else if (args[i] == "--r-executable") {
			if ((i+1) < args.size ()) {
				r_exe_arg = args.takeAt (i + 1);
			} else usage = true;
			args.removeAt (i);
			--i;
		} else if (args[i] == "--debug-level") {
			if ((i+1) < args.size ()) {
				debug_level = args[i+1].toInt ();
			}
		} else if (args[i] == "--reuse") {
			reuse = true;
		} else if (args[i] == "--nowarn-external") {
			warn_external = false;
		} else if (args[i].startsWith ("--")) {
			// all RKWard and KDE options (other than --reuse) are of the for --option <value>. So skip over the <value>
			i++;
		} else {
			QUrl url (args[i]);
			if (url.isRelative ()) {
				file_args.append (QDir::current ().absoluteFilePath (url.toLocalFile ()));
			} else {
				file_args.append (args[i]);
			}
		}
	}

	if (reuse) {
		if (!QDBusConnection::sessionBus ().isConnected ()) {
			if (debug_level > 2) qDebug ("Could not connect to session dbus");
		} else {
			QDBusInterface iface (RKDBUS_SERVICENAME, "/", "", QDBusConnection::sessionBus ());
			if (iface.isValid ()) {
				QDBusReply<void> reply = iface.call ("openAnyUrl", file_args, warn_external);
				if (!reply.isValid ()) {
					if (debug_level > 2) qDebug ("Error while placing dbus call: %s", qPrintable (reply.error ().message ()));
					return 1;
				}
				return 0;
			}
		}
	}

	// MacOS may need some path adjustments, first
#ifdef Q_WS_MAC
	QString oldpath = qgetenv ("PATH");
	if (!oldpath.contains (INSTALL_PATH)) {
		//ensure that PATH is set to include what we deliver with the bundle
		qputenv ("PATH", QString ("%1/bin:%1/sbin:%2").arg (INSTALL_PATH).arg (oldpath).toLocal8Bit ());
		if (debug_level > 3) qDebug ("Adjusting system path to %s", qPrintable (qgetenv ("PATH")));
	}
	// ensure that RKWard finds its own packages
	qputenv ("R_LIBS", R_LIBS);
	QProcess::execute ("launchctl", QStringList () << "load" << "-w" << INSTALL_PATH "/Library/LaunchAgents/org.freedesktop.dbus-session.plist");
#endif

	// Locate KDE and RKWard installations
	QString kde4_config_exe = findExeAtPath ("kde4-config", QDir::currentPath ());
	if (kde4_config_exe.isNull ()) kde4_config_exe = findExeAtPath ("kde4-config", app.applicationDirPath ());
	if (kde4_config_exe.isNull ()) kde4_config_exe = findExeAtPath ("kde4-config", QDir (app.applicationDirPath ()).filePath ("KDE/bin"));
	if (kde4_config_exe.isNull ()) {
#ifdef Q_WS_WIN
	QStringList syspath = QString (qgetenv ("PATH")).split (';');
#else
	QStringList syspath = QString (qgetenv ("PATH")).split (':');
#endif
		for (int i = 0; i < syspath.size (); ++i) {
			kde4_config_exe = findExeAtPath ("kde4-config", syspath[i]);
			if (!kde4_config_exe.isNull ()) break;
		}
	}

	if (kde4_config_exe.isNull ()) {
		QMessageBox::critical (0, "Could not find KDE installation", "The KDE installation could not be found (kde4-config). When moving / copying RKWard, make sure to copy the whole application folder, or create a shorcut / link, instead.");
		exit (1);
	}

	QDir kde_dir (QFileInfo (kde4_config_exe).absolutePath ());
	kde_dir.makeAbsolute ();
	QString kde_dir_safe_path = quoteCommand (kde_dir.path ());
#ifdef Q_WS_WIN
	QString kdeinit4_exe = findExeAtPath ("kdeinit4", kde_dir.path ());
	qputenv ("PATH", QString (kde_dir_safe_path + ';' + qgetenv ("PATH")).toLocal8Bit ());
	if (debug_level > 3) qDebug ("Adding %s to the system path", qPrintable (kde_dir_safe_path));
#endif
	// important if RKWard is not in KDEPREFIX/bin but e.g. KDEPREFIX/lib/libexec
	qputenv ("RKWARD_ENSURE_PREFIX", kde_dir_safe_path.toLocal8Bit ());
	if (debug_level > 3) qDebug ("Setting environment variable RKWARD_ENSURE_PREFIX=%s", qPrintable (kde_dir_safe_path));

	QString rkward_frontend_exe = findRKWardAtPath (app.applicationDirPath ());	// this is for running directly from a build tree
#ifdef Q_WS_MAC
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (app.applicationDirPath () + "/rkward.frontend.app/Contents/MacOS"); 	// this is for running directly from a build tree
#endif
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (RKWARD_FRONTEND_LOCATION);
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (kde_dir.absoluteFilePath ("bin"));
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (kde_dir.absoluteFilePath ("../lib/libexec"));

	if (rkward_frontend_exe.isNull ()) {
		QMessageBox::critical (0, "RKWard frontend binary missing", "RKWard frontend binary could not be found. When moving / copying RKWard, make sure to copy the whole application folder, or create a shorcut / link, instead.");
		exit (1);
	}

	if (usage) {
		QProcess::execute (rkward_frontend_exe, QStringList ("--help"));
		exit (1);
	}

#ifdef Q_WS_WIN
	// Explicit initialization of KDE, in case Windows 7 asks for admin privileges
	if (kdeinit4_exe.isNull ()) {
		kdeinit4_exe = findExeAtPath ("kdeinit4", QFileInfo (rkward_frontend_exe).absolutePath ());
	}
	if (!kdeinit4_exe.isNull ()) QProcess::execute (kdeinit4_exe, QStringList ());
#endif

	// Look for R:
	//- command line parameter
	//- Specified in cfg file next to rkward executable
	//- compile-time default
	QString r_exe = r_exe_arg;
	if (!r_exe.isNull ()) {
		if (!QFileInfo (r_exe).isExecutable ()) {
			QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified on the command line (%1) does not exist or is not executable.").arg (r_exe));
			exit (1);
		}
		if (debug_level > 3) qDebug ("Using R specified on command line");
	} else {
		QFileInfo frontend_info (rkward_frontend_exe);
		QDir frontend_path = frontend_info.absoluteDir ();
		QFileInfo rkward_ini_file (frontend_path.absoluteFilePath ("rkward.ini"));
		if (rkward_ini_file.isReadable ()) {
			QSettings rkward_ini (rkward_ini_file.absoluteFilePath (), QSettings::IniFormat);
			r_exe = rkward_ini.value ("R executable").toString ();
			if (!r_exe.isNull ()) {
				if (QDir::isRelativePath (r_exe)) {
					r_exe = frontend_path.absoluteFilePath (r_exe);
				}
				if (!QFileInfo (r_exe).isExecutable ()) {
					QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified in the rkward.ini file (%1) does not exist or is not executable.").arg (rkward_ini_file.absoluteFilePath ()));
					exit (1);
				}
			}
			if (debug_level > 3) qDebug ("Using R as configured in config file %s", qPrintable (rkward_ini_file.absoluteFilePath ()));
		}
		if (r_exe.isNull ()) {
			r_exe = R_EXECUTABLE;
			if (!QFileInfo (r_exe).isExecutable ()) {
				QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified at compile time (%1) does not exist or is not executable. Probably the installation of R has moved. You can use the command line parameter '--R', or supply an rkward.ini file to specify the new location.").arg (r_exe));
				exit (1);
			}
			if (debug_level > 3) qDebug ("Using R as configured at compile time");
		}
	}

	qputenv ("R_BINARY", r_exe.toLocal8Bit ());
	QStringList call_args ("CMD");
	call_args.append (debugger_args);
	call_args.append (quoteCommand (rkward_frontend_exe));

	if (!args.isEmpty ()) {
		// NOTE: QProcess quotes its arguments, *but* properly passing all spaces and quotes through the R CMD wrapper, seems near(?) impossible on Windows. Instead, we use percent encoding, internally.
		for (int i = 0; i < args.size (); ++i) {
			call_args.append (QString::fromUtf8 (QUrl::toPercentEncoding (args[i], QByteArray (), " \"")));
		}
	}

	if (debug_level > 2) qDebug ("Starting frontend: %s %s", qPrintable (r_exe), qPrintable (call_args.join (" ")));

	InteractiveProcess proc;
#ifdef Q_WS_WIN
	if (debugger_args.isEmpty ()) {
		// start _without_ opening an annoying console window
		QTemporaryFile *vbsf = new QTemporaryFile (QDir::tempPath () + "/rkwardlaunchXXXXXX.vbs");
		vbsf->setAutoRemove (false);
		if (vbsf->open ()) {
			QTextStream vbs (vbsf);
			vbs << "Dim WinScriptHost\r\nSet WinScriptHost = CreateObject(\"WScript.Shell\")\r\nWinScriptHost.Run \"" << quoteCommand (r_exe);
			for (int i = 0;  i < call_args.length (); ++i) {
				vbs << " " << call_args[i];
			}
			vbs << "\", 0\r\nSet WomScriptHost = Nothing\r\n";
			vbsf->close ();
			QString filename = vbsf->fileName ();
			delete (vbsf);  // somehow, if creating vbsf on the stack, we cannot launch it, because "file is in use by another process", despite we have closed it.
			proc.start ("WScript.exe", QStringList (filename));
			bool ok = proc.waitForFinished (-1);
			if (proc.exitCode () || !ok) {
				QMessageBox::critical (0, "Error starting RKWard", QString ("Starting RKWard failed with error \"%1\"").arg (proc.errorString ()));
			}
			QFile (filename).remove ();
			return (0);
		}
	}
	// if that did not work or not on windows:
#endif
	proc.setProcessChannelMode (QProcess::ForwardedChannels);
	proc.start (quoteCommand (r_exe), call_args);
	bool ok = proc.waitForFinished (-1);
	if (proc.exitCode () || !ok) {
		QMessageBox::critical (0, "Error starting RKWard", QString ("Starting RKWard failed with error \"%1\"").arg (proc.errorString ()));
	}

	return (0);
}
Beispiel #29
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QVector<Server> servers;

    //wczytanie konfiguracji
    QSettings settings("client.cfg", QSettings::IniFormat);
    settings.sync();

    int serversCount = settings.value("info/serversCount", 0).toInt();

    if(serversCount == 0)
    {
        //błąd, nie ma adresów
        std::cerr << "No known servers in configuration file" << std::endl;
        return 2;
    }

    for(int i=1; i<=serversCount; ++i)
    {
        Server server;
        server.name = settings.value("server"+QString::number(i)+"/name", "unknown server").toString();
        server.ip = QHostAddress(settings.value("server"+QString::number(i)+"/ip", "0.0.0.0").toString());
        server.port = settings.value("server"+QString::number(i)+"/port", "0").toInt();
        servers.push_back(server);
    }

    //połączenie i pobranie listy serwerów
    Client client;
    client.setServers(&servers);
    client.settings = &settings;

    //std::cout << "ACT?" << std::endl;
    if(client.send(QStringList() << "ACTIVE_SERVERS") == NO_SERVERS)
    {
        std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n";
        exit(10);
    }
    client.socket.waitForReadyRead(15000);

    /*if(client.queue == 0)
        exit(0);*/
    //sprawdzenie parametrów wywołania
    QStringList args = QCoreApplication::arguments();

    if(args.size() > 1)
    {
        if(args.at(1) == "list")
        {
            if(client.send(QStringList() << "GET_AVAILABLE_RESULTS" << "*") == NO_SERVERS)
            {
                std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n";
                exit(10);
            }
        }
        else if(args.at(1) == "get")
        {
            if(client.send(QStringList() << "GET_RESULT" << args.at(2)) == NO_SERVERS)
            {
                std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n";
                exit(10);
            }
        }
        else if(args.at(1) == "find")
        {
            //<nazwa badania>,<kraj>,<płeć>,<rasa>,<minimalny wiek>,<maksymalny wiek>
            if(client.send(QStringList() << "GET_AVAILABLE_RESULTS" << args.at(2) << args.at(3) << \
                           args.at(4) << args.at(5) << args.at(6) << args.at(7)) == NO_SERVERS)
            {
                std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n";
                exit(10);
            }
        }
        else if(args.at(1) == "stats")
        {
            //<nazwa badania>,<data od>,<data do>,<kraj>,<płeć>,<rasa>,<minimalny wiek>,<maksymalny wiek>,
            //{<pole grupowania 1>,<pole grupowania 2>,<...>}
            QStringList a = args.at(10).split("");
            a.pop_back();
            a.pop_front();
            QString grupowanie = "{"+a.join(",")+"}";
            std::cout << grupowanie.toStdString() << std::endl;
            if(client.send(QStringList() << "GET_AVAILABLE_RESULTS" << args.at(2) << args.at(3) << \
                           args.at(4) << args.at(5) << args.at(6) << args.at(7) << args.at(8) << args.at(9)\
                           << grupowanie) == NO_SERVERS)
            {
                std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n";
                exit(10);
            }
        }
    }
    client.socket.waitForReadyRead(15000);
    exit(0);

    return a.exec();
}
Beispiel #30
0
bool MythCoreContext::SendReceiveStringList(QStringList &strlist,
                                        bool quickTimeout, bool block)
{
    if (HasGUI() && IsUIThread())
    {
        QString msg = "SendReceiveStringList(";
        for (uint i=0; i<(uint)strlist.size() && i<2; i++)
            msg += (i?",":"") + strlist[i];
        msg += (strlist.size() > 2) ? "...)" : ")";
        msg += " called from UI thread";
        VERBOSE(VB_GENERAL|VB_EXTRA, msg);
    }

    QString query_type = "UNKNOWN";

    if (!strlist.isEmpty())
        query_type = strlist[0];

    QMutexLocker locker(&d->m_sockLock);
    if (!d->m_serverSock)
    {
        bool blockingClient = GetNumSetting("idleTimeoutSecs",0) > 0;
        ConnectToMasterServer(blockingClient);
    }

    bool ok = false;

    if (d->m_serverSock)
    {
        QStringList sendstrlist = strlist;
        d->m_serverSock->writeStringList(sendstrlist);
        ok = d->m_serverSock->readStringList(strlist, quickTimeout);

        if (!ok)
        {
            VERBOSE(VB_IMPORTANT, QString("Connection to backend server lost"));
            d->m_serverSock->DownRef();
            d->m_serverSock = NULL;

            if (d->m_eventSock)
            {
                d->m_eventSock->DownRef();
                d->m_eventSock = NULL;
            }

            bool blockingClient = GetNumSetting("idleTimeoutSecs",0);
            ConnectToMasterServer(blockingClient);

            if (d->m_serverSock)
            {
                d->m_serverSock->writeStringList(sendstrlist);
                ok = d->m_serverSock->readStringList(strlist, quickTimeout);
            }
        }

        // this should not happen
        while (ok && strlist[0] == "BACKEND_MESSAGE")
        {
            // oops, not for us
            VERBOSE(VB_IMPORTANT, "SRSL you shouldn't see this!!");
            QString message = strlist[1];
            strlist.pop_front(); strlist.pop_front();

            MythEvent me(message, strlist);
            dispatch(me);

            ok = d->m_serverSock->readStringList(strlist, quickTimeout);
        }

        if (!ok)
        {
            if (d->m_serverSock)
            {
                d->m_serverSock->DownRef();
                d->m_serverSock = NULL;
            }

            VERBOSE(VB_IMPORTANT,
                    QString("Reconnection to backend server failed"));

            QCoreApplication::postEvent(d->m_GUIcontext,
                                new MythEvent("PERSISTENT_CONNECTION_FAILURE"));
        }
    }

    if (ok)
    {
        if (strlist.isEmpty())
            ok = false;
        else if (strlist[0] == "ERROR")
        {
            if (strlist.size() == 2)
                VERBOSE(VB_GENERAL, QString("Protocol query '%1' reponded "
                                            "with the error '%2'")
                                            .arg(query_type).arg(strlist[1]));
            else
                VERBOSE(VB_GENERAL, QString("Protocol query '%1' reponded "
                                        "with an error, but no error message.")
                                        .arg(query_type));

            ok = false;
        }
    }

    return ok;
}