Example #1
0
void Client::onTextMessageReceived(QString message)
{
    ui->resultTextBox->setText(message);

    /*Process server's response
     *  first character represent the user's action
     *  second server's result of action */
    QStringList substrings = message.split("|") ;
    if(substrings.length() == 1)
    {
     QMessageBox::information(this, tr("Error"), tr("Error occurs while trying to proccess request"));
     return;
    }


    switch(message[0].digitValue())
    {
    case authorization:
    {
        QString result = substrings.value(substrings.length()- 2 );

        if(result == SUCCESS)
        {
            ui->resultTextBox->setText("Authorization succeed");
            //check user's type
            ui->authorization->setVisible(false);
            ui->mainForm->setVisible(true);
        }
        else
        {
            QMessageBox::information(this, tr("Error"), tr("Authorization failed. Please check login and password"));
            return;
        }

        QString userRigths = substrings.value(substrings.length()- 2 );

        if(userRigths == QString::number(Admin))
      {
          ui->adminFrame->setVisible(true);
          ui->advancUserFrame->setVisible(true);
      }
      else if(userRigths == QString::number(AdvancedUser))
      {
          ui->advancUserFrame->setVisible(true);
       }
      }
    break;

    case seeHistory:
    {
        QString result = substrings.value(substrings.length()- 2 );
        if(result == SUCCESS)
        {
            QString result = substrings.value(substrings.length()- 1 );
            result.replace("*", " ");
            ui->userHistory->setText(result);
        }
        else
        {
            QMessageBox::information(this, tr("Error"), tr("Cann't load history. Please contact to developers to fix the problem."));
        }
     }
        break;



    case sendVideo:
    {
        ui->resultTextBox->setText(message);
        QString result = substrings.value(substrings.length()- 1 );
        if(result == SUCCESS)
        {
            on_SendVideo_clicked();
        }
        else
        {
            QMessageBox::information(this, tr("Error"), tr("Server cann't receive video/picture at the moment"));
        }
     }
        break;

    case addPicture:
    {
        ui->resultTextBox->setText(message);
        QString result = substrings.value(substrings.length()- 1 );
        if(result == SUCCESS)
        {
            on_addPictures_clicked();
        }
        else
        {
            QMessageBox::information(this, tr("Error"), tr("Server cann't receive video/picture at the moment"));
        }
     }
        break;

    case addUser:
    {
        QString result = substrings.value(substrings.length()- 1 );
        if(result == SUCCESS)
        {
            QMessageBox::information(this, tr("Message"), tr("New user was successfully added"));
        }
        else
        {
            QMessageBox::information(this, tr("Warning"), tr("User with this login already exist"));
        }
     }
        break;

     /*if server doesn't support user's request*/
    default:
        QMessageBox::information(this, tr("Error"), tr("Error occurs while trying to proccess request"));
        return;
    }
 }
Example #2
0
static QStringList qt_win_CID_get_open_file_names(const QFileDialogArgs &args,
                                       QString *initialDirectory,
                                       const QStringList &filterList,
                                       QString *selectedFilter,
                                       int selectedFilterIndex)
{
    QStringList result;
    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(args.parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);
    // Multiple selection is allowed only in IFileOpenDialog.
    IFileOpenDialog *pfd = 0;
    HRESULT hr = CoCreateInstance(QT_CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, QT_IID_IFileOpenDialog, 
        reinterpret_cast<void**>(&pfd));

    if (SUCCEEDED(hr)) {
        qt_win_set_IFileDialogOptions(pfd, args.selection,
                                      args.directory, args.caption,
                                      filterList, QFileDialog::ExistingFiles,
                                      args.options);
        // Set the currently selected filter (one-based index).
        hr = pfd->SetFileTypeIndex(selectedFilterIndex+1);
        QWidget *parentWindow = args.parent;
        if (parentWindow)
            parentWindow = parentWindow->window();
        else
            parentWindow = QApplication::activeWindow();
        // Show the file dialog.
        hr = pfd->Show(parentWindow ? parentWindow->winId() : 0);
        if (SUCCEEDED(hr)) {
            // Retrieve the results.
            IShellItemArray *psiaResults;
            hr = pfd->GetResults(&psiaResults);
            if (SUCCEEDED(hr)) {
                DWORD numItems = 0;
                psiaResults->GetCount(&numItems);
                for (DWORD i = 0; i<numItems; i++) {
                    IShellItem *psi = 0;
                    hr = psiaResults->GetItemAt(i, &psi);
                    if (SUCCEEDED(hr)) {
                        // Retrieve the file name from shell item.
                        wchar_t *pszPath;
                        hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
                        if (SUCCEEDED(hr)) {
                            QString fileName = QString::fromWCharArray(pszPath);
                            result.append(fileName);
                            CoTaskMemFree(pszPath);
                        }
                        psi->Release(); // Free the current item.
                    }
                }
                psiaResults->Release(); // Free the array of items.
            }
        }
    }
    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (!result.isEmpty()) {
        // Retrieve the current folder name.
        IShellItem *psi = 0;
        hr = pfd->GetFolder(&psi);
        if (SUCCEEDED(hr)) {
            wchar_t *pszPath;
            hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
            if (SUCCEEDED(hr)) {
                *initialDirectory = QString::fromWCharArray(pszPath);
                CoTaskMemFree(pszPath);
            }
            psi->Release();
        }
        // Retrieve the currently selected filter.
        if (selectedFilter) {
            quint32 filetype = 0;
            hr = pfd->GetFileTypeIndex(&filetype);
            if (SUCCEEDED(hr) && filetype && filetype <= (quint32)filterList.length()) {
                // This is a one-based index, not zero-based.
                *selectedFilter = filterList[filetype-1];
            }
        }
    }
    if (pfd)
        pfd->Release();
    return result;
}
Example #3
0
void MainWindow::on_gameBoard_customContextMenuRequested(const QPoint &pos)
{
    QMenu submenu, *dragons,*worms, *markers;
    QPoint item = ui->gameBoard->mapToGlobal(pos);
    QString vertex;
    submenu.addAction("Clear All Markers");
    markers = submenu.addMenu("Clear Marker");
    QList<QString> marker_list = ui->gameBoard->markers.keys();
    for(int i=0; i<marker_list.length(); i++){
        markers->addAction(QString("Marker:%1").arg(marker_list.at(i)));
    }

    dragons = submenu.addMenu("Dragons");
    dragons->addAction("All Dragons");
    dragons->addAction("Black Dragons");
    dragons->addAction("White Dragons");

    submenu.addAction("Move Reasons");

    worms = submenu.addMenu("Worms");
    worms->addAction("All Worms");
    worms->addAction("Black Worms");
    worms->addAction("White Worms");

    QAction* rightClickItem = submenu.exec(item);
    if(!rightClickItem) return;
    qDebug() << "context menu item "<< rightClickItem->text()<< " clicked";
    vertex = ui->gameBoard->posToAlphaNum(ui->gameBoard->mapToScene(pos));

    rightClickItem->dumpObjectInfo();
    if( rightClickItem->text() == "Move Reasons"){
        QStringList reasons = gtp.move_reasons(vertex);
        if(reasons.length()>0) ui->textHistory->appendPlainText(QString("%1 Move Reasons").arg(vertex));
        for(int i=0; i<reasons.length(); i++){
            ui->textHistory->appendPlainText(reasons.at(i));
        }
    }
    else if( rightClickItem->text() == "All Dragons"){
        ui->gameBoard->dragonStones( gtp.dragon_stones());
    }
    else if( rightClickItem->text() == "Black Dragons"){
        ui->gameBoard->dragonStones( gtp.dragon_stones("black"));
    }
    else if( rightClickItem->text() == "White Dragons"){
        ui->gameBoard->dragonStones( gtp.dragon_stones("white"));
    }
    else if( rightClickItem->text() == "Clear All Markers"){
        ui->gameBoard->clearAllMarkers();
    }
    else if( rightClickItem->text().contains("Marker:")){
        QStringList sl = rightClickItem->text().split(":",QString::SkipEmptyParts);
        ui->gameBoard->removeMarkers(sl.at(1));
    }
    else if( rightClickItem->text() == "All Worms"){
        ui->gameBoard->wormStones( gtp.worm_stones());
    }
    else if( rightClickItem->text() == "Black Worms"){
        ui->gameBoard->wormStones( gtp.worm_stones("black"));
    }
    else if( rightClickItem->text() == "White Worms"){
        ui->gameBoard->wormStones( gtp.worm_stones("white"));
    }

}
QStringList Manager::fetchMonster(const int &id, const int &level) {

    QTextStream cout(stdout); // set cout for console debug

    QStringList array;

    QString idString;
    if ( id < 10 )
        idString = "00" + QString::number(id);
    else if ( id < 100)
        idString = "0" + QString::number(id);
    else
        idString =  QString::number(id);

    array.append(QString::number(id));
    array.append(idString);
    array.append(QString::number(level));

    cout << QDir::setCurrent("/usr/share/harbour-pocketmonsters/qml/pages/xmls/") << endl;
    QFile pokedex( idString + ".xml");

    cout << pokedex.open(QIODevice::ReadOnly) << endl;

    QXmlStreamReader xml(&pokedex);


    while (!xml.atEnd() && !xml.hasError()) {

        xml.readNext();

        if ( xml.isStartElement() && xml.name().toString() == "index" && xml.attributes().value("id").toString() == idString) {
            xml.readNext();
        } else if ( ( xml.name().toString() == "moveset" ) ) {
            break;
        }
        if ( xml.isStartElement() ) {
            QString string = xml.readElementText();
            array.append(string);
        }


    }

    if (xml.hasError())
    {
        cout << "XML error: " << xml.errorString() << "line:column - " << xml.lineNumber() << ":" << xml.columnNumber() << endl;
    }
    else if (xml.atEnd())
    {
        cout << "Reached end, done" << endl;
    }

    QVector <int> levelsArray;
    QVector <int> idsArray;

    while (!xml.atEnd() && !xml.hasError()) {
        xml.readNext();
        QXmlStreamAttributes attributes = xml.attributes();
        if ( xml.isStartElement() && xml.name().toString() == "move") {
            levelsArray.append(attributes.value("level").toInt());
            idsArray.append(attributes.value("id").toInt());
        }
    }

    if (xml.hasError())
    {
        cout << "XML error: " << xml.errorString() << "line:column - " << xml.lineNumber() << ":" << xml.columnNumber() << endl;
    }
    else if (xml.atEnd())
    {
        cout << "Reached end, done" << endl;
    }

    if ( levelsArray.length() < 5 ) {
        if ( level >= levelsArray[0])
            array.append(QString::number(idsArray[0]));
        if ( level >= levelsArray[1])
            array.append(QString::number(idsArray[1]));
        if ( level >= levelsArray[2])
            array.append(QString::number(idsArray[2]));
        if ( level >= levelsArray[3])
            array.append(QString::number(idsArray[3]));
    }
    while ( array.length() < 23 )
        array.append(QString::number(0));

    for ( int i = 0; i < array.length(); i++) {
        cout << array[i] << ";";
    }

    cout << endl;

    fetchMonsterDone();
    return array;
}
Example #5
0
QString TrustAI::askForChoice(const QString &, const QString &choice, const QVariant &)
{
    QStringList choices = choice.split("+");
    return choices.at(qrand() % choices.length());
}
Example #6
0
QUrl parseCmd(int argc, char* argv[], artemis::Options& options)
{

    std::string usage = "\n"
            "artemis [-i <n>][-c <URL>][-t <URL>][-r][-u][-p <path>] <url>\n"
            "\n"
            "Test the JavaScript application found at <url>.\n"
            "\n"
            "-i <n>   : Iterations - Artemis will generate and execute <n>\n"
            "           sequences of events. Default is 4.\n"
            "\n"
            "-f #<formElementId>=<formElementValue> : Set the form element with ID #<formElementId> to the value <formElementValue> at each iteration. Remember to write the # for the element ID.\n"
            "\n"
            "-F #<formElementId>=true|false : As with -f but for boolean value injections (e.g. into check boxes).\n"
            "\n"
            "-c <KEY=VALUE> : Set a cookie value for the global domain.\n"
            "\n"
            "-t <URL>:<PORT> : Set proxy\n"
            "\n"
            "-s       : Enable DOM state checking\n"
            "\n"
            "-e       : Negate the last solved PC printed to stdout (used for testing)\n"
            "\n"
            "--debug-concolic: Run the concolic subsystem on the last iteration and output results.\n"
            "\n"
            "--major-mode <mode>:\n"
            "           The major-mode specifies the top-level test algorithm used by Artemis.\n"
            "\n"
            "           artemis - (default) the top-level test algorithm described in the ICSE'11 Artemis paper\n"
            "           manual - open a browser window for manual testing of web applications\n"
            "           concolic - perform an automated concolic analysis of form validation code\n"
            "\n"
            "--strategy-form-input-generation <strategy>:\n"
            "           Select form input generation strategy.\n"
            "\n"
            "           javascript-constants - select form inputs based in observed JavaScript constants\n"
            "           random - (default) random inputs\n"
            "\n"
            "\n"
            "--strategy-target-selection <strategy>:\n"
            "           Select target selection strategy.\n"
            "\n"
            "           concolic - use concolic testing to select a target\n"
            "           jquery - use a model to support instrumented jQuery\n"
            "           legacy - (default) set the target to the element on which the event-handler is registered\n"
            "\n"
            "--strategy-priority <strategy>:\n"
            "           Select priority strategy.\n"
            "\n"
            "           constant - (default) assign the same priority to new configurations\n"
            "           random - assign a random priority to new configurations\n"
            "           coverage - assign higher priority to configurations with low coverage\n"
            "           readwrite - use read/write-sets for JavaScript properties to assign priorities\n"
            "           all - a combination of the constant, the coverage and the readwrite strategy, as defined in the Artemis article\n"
            "\n"
            "--strategy-event-generation <strategy>:\n"
            "           Select event-sequence generation strategy.\n"
            "\n"
            "           random-incremental - (default) permutates the latest event or extends event sequence with one new event\n"
            "           fasttrack - generate one large event-sequence of all known events (forces -i 2) \n"
            "\n"
            "--event-visibility-check <true|false>:\n"
            "           Enable or disable event visibility checks, which filters out any event which is not attached to a user visible element. Default: (false).\n"
            "\n"
            "--input-strategy-same-length <num>:\n"
            "           Set the number of permutations of an executed sequence (of same length) generated by the input generator.\n"
            "\n"
            "--load-new-urls <true|false>:\n"
            "           Whether URLs should be loaded (e.g. after clicking a link) in major-mode 'artemis'. Default: false.\n"
            "\n"
            "--coverage-report <report-type>:\n"
            "           Select code coverage report formatting.\n"
            "\n"
            "           html - HTML report dumped in the folder you run Artemis from\n"
            "           stdout - text report is printed to std out\n"
            "           none - (default) code coverage report is omitted\n"
            "\n"
            "--coverage-report-ignore <URL>:\n"
            "           Exclude the given URL from the coverage report and coverage statistics.\n"
            "\n"
            "--path-trace-report <report-type>:\n"
            "           Output a report of the execution path through the covered JavaScript.\n"
            "\n"
            "           all - All executed paths are displayed\n"
            "           click - Only paths beginning with a click event are displayed\n"
            "           none - (default) Path trace report is omitted\n"
            "           html - HTML trace report is generated in the folder you run Artemis from\n"
            "\n"
            "--concolic-button <XPath>:\n"
            "           Use the given XPath to locate the button to be used in concolic mode.\n"
            "           If not supplied, the concolic mode will use its built-in button finding, which is not robust.\n"
            "\n"
            "--concolic-tree-output <trees>:\n"
            "           none - Do not output any graphs.\n"
            "           final (default) - Generate a graph of the final tree after analysis.\n"
            "           final-overview - Like final but also includes a simplified overview graph.\n"
            "           all - Generate a graph of the tree at every iteration.\n"
            "           all-overview - Like all but also includes simplified overview graphs.\n"
            "\n"
            "--concolic-search-procedure <search>\n"
            "           Choose the search procedure used to choose new areas of the concolic execution tree to explore.\n"
            "\n"
            "           dfs - (default) Depth first search with iterative deepening\n"
            "           selector - Use the selectors system (see concolic-selection-procedure and concolic-selection-budget)\n"
            "\n"
            "--concolic-dfs-depth <n>x<m>\n"
            "           The depth limit used for the iterative depth-first search.\n"
            "           n is the base depth limit (of symbolic branches).\n"
            "           m is the number of passes of the search, each at a lower depth.\n"
            "           The default is 5x3 for a total depth limit of 15 after two restarts.\n"
            "\n"
            "--concolic-dfs-unlimited-depth\n"
            "           Removes the restart limit from the concolic depth-first search procedure.\n"
            "\n"
            "--concolic-selection-procedure <selector>\n"
            "           The procedure used to select the next exploration when concolic-search-procedure is set to selectors.\n"
            "\n"
            "           dfs - (default) Depth first search (no depth limit)\n"
            "           random - choose new explorations at random\n"
            "           avoid-unsat - experimental procedure which chooses branches with less history of being unsatisfiable\n"
            "           round-robin(<s1>:<s2>:...:<sN>) - comines other selectors\n"
            "\n"
            "--concolic-selection-budget <n>\n"
            "           The number of times the selection procedures will attempt new exploration.\n"
            "           The default is 25. Select 0 for unlimited attempts.\n"
            "\n"
            "--concolic-event-sequences <strategy>\n"
            "           ignore (default) - Ignore handlers for individual field modification.\n"
            "           simple - Fire the onchange event for each field which is injected.\n"
            "\n"
            "--concolic-event-sequence-permutation <permutation>\n"
            "           In the 'simple' mode of concolic-event-sequences, each event handler is\n"
            "           triggered in the DOM order bey default and this option allows the order to be\n"
            "           modified. The new order is a reordering of the default list [1,2,...,N]\n"
            "           where N is the number of event handlers. e.g. if there are 4 fields then a\n"
            "           valid value would be [4,2,1,3].\n"
            "           It is also possible to remove handlers from the event sequence, e.g. [1,2,4]\n"
            "\n"
            "--concolic-event-handler-report\n"
            "           Outputs a graph of the symbolic variables which are read from each event handler.\n"
            "           (Requires major-mode concolic and concolic-event-sequences)\n"
            "\n"
            "--concolic-disable-features <features-list>\n"
            "           Used for benchmarking only. Disables the listed features (comma separated list).\n"
            "           The features which can be disabled with this option are:\n"
            "           radio-restriction, select-restriction, select-restriction-dynamic, select-symbolic-index,\n"
            "           select-link-value-index, select-indirection-option-index, radio-checkbox-symbolic,\n"
            "           concrete-value-property, symbolic-after-injection, cvc4-coercion-opt,\n"
            "           event-sequence-sync-injections\n"
            "\n"
            "--smt-solver <solver>:\n"
            "           z3str - Use the Z3-str SMT solver as backend.\n"
            "           cvc4 (default) - Use the CVC4 SMT solver as backend.\n"
            "           kaluza - Use the Kaluza solver as backend.\n"
            "\n"
            "--export-event-sequence <output type> :\n"
            "           selenium - Will create a selenium test suite of all the iterations.\n"
            "           json - Will create a JSON file containing the iterations.\n"
            "\n"
            "--function-call-heap-report <report-type>\n"
            "           Writes a report containing heaps before all or named functioncalls.\n"
            "\n"
            "           all - All calls are reported\n"
            "           named - Only named calls are reported\n"
            "           none - (default) No calls are reported\n"
            "\n"
            "--function-call-heap-report-random-factor <int>\n"
            "           When faced with many function calls, this parameter saves data with a factor <int>^-1\n"
            "\n"
            "--user-agent <custom-ua>\n"
            "           Change the user-agent reported by Artemis to <custom-ua>.\n"
            "           The following built-in user agents can also be specified (case sensitive):\n"
            "           default, iphone4, ipad4, nexus5, chrome35\n"
            "\n";

    struct option long_options[] = {
    {"strategy-form-input-generation", required_argument, NULL, 'x'},
    {"coverage-report", required_argument, NULL, 'y'},
    {"strategy-priority", required_argument, NULL, 'z'},
    {"input-strategy-same-length", required_argument, NULL, 'j'},
    {"coverage-report-ignore", required_argument, NULL, 'k'},
    {"major-mode", required_argument, NULL, 'm'},
    {"path-trace-report", required_argument, NULL, 'a'},
    {"function-call-heap-report", required_argument, NULL, 'g'},
    {"function-call-heap-report-random-factor", required_argument, NULL, 'l'},
    {"concolic-tree-output", required_argument, NULL, 'd'},
    {"concolic-button", required_argument, NULL, 'b'},
    {"concolic-search-procedure", required_argument, NULL, 'S'},
    {"concolic-dfs-unlimited-depth", no_argument, NULL, 'u'},
    {"concolic-selection-procedure", required_argument, NULL, 'T'},
    {"concolic-selection-budget", required_argument, NULL, 'R'},
    {"concolic-event-sequences", required_argument, NULL, 'w'},
    {"concolic-event-sequence-permutation", required_argument, NULL, 'W'},
    {"concolic-event-handler-report", no_argument, NULL, 'H'},
    {"smt-solver", required_argument, NULL, 'n'},
    {"export-event-sequence", required_argument, NULL, 'o'},
    {"help", no_argument, NULL, 'h'},
    {"option-values", optional_argument, NULL, 'q'},
    {"user-agent", required_argument, NULL, 'U'},
    {"strategy-target-selection", required_argument, NULL, 'A'},
    {"concolic-disable-features", required_argument, NULL, 'B'},
    {"strategy-event-generation", required_argument, NULL, 'C'},
    {"concolic-dfs-depth", required_argument, NULL, 'D'},
    {"debug-concolic", no_argument, NULL, 'E'},
    {"event-visibility-check", required_argument, NULL, 'G'},
    {"load-new-urls", required_argument, NULL, 'L'},
    {0, 0, 0, 0}
    };

    int option_index = 0;
    char c;
    artemis::Log::addLogLevel(artemis::INFO);
    artemis::Log::addLogLevel(artemis::FATAL);

    while ((c = getopt_long(argc, argv, "ehsrp:a:m:I:F:f:t:c:i:v:", long_options, &option_index)) != -1) {

        switch (c) {

        case 'a': {

            if (string(optarg).compare("all") == 0) {
                options.reportPathTrace  = artemis::ALL_TRACES;
            } else if (string(optarg).compare("click") == 0) {
                options.reportPathTrace = artemis::CLICK_TRACES;
            } else if (string(optarg).compare("none") == 0) {
                options.reportPathTrace = artemis::NO_TRACES;
            }else if (string(optarg).compare("html") == 0) {
                options.reportPathTrace = artemis::HTML_TRACES;
            } else {
                cerr << "ERROR: Invalid choice of path-trace-report " << optarg << endl;
                exit(1);
            }

            break;
        }

        case 'b': {
            options.concolicEntryPoint = QString(optarg);
            break;
        }

        case 'B': {
            QStringList features = QString(optarg).split(",");
            foreach(QString feature, features) {
                feature = feature.trimmed();
                if (feature == "radio-restriction") {
                    options.concolicDisabledFeatures |= artemis::RADIO_RESTRICTION;
                } else if (feature == "select-restriction") {
                    options.concolicDisabledFeatures |= artemis::SELECT_RESTRICTION;
                } else if (feature == "select-restriction-dynamic") {
                    options.concolicDisabledFeatures |= artemis::SELECT_RESTRICTION_DYNAMIC;
                } else if (feature == "select-link-value-index") {
                    options.concolicDisabledFeatures |= artemis::SELECT_LINK_VALUE_INDEX;
                } else if (feature == "cvc4-coercion-opt") {
                    options.concolicDisabledFeatures |= artemis::CVC4_COERCION_OPT;
                } else if (feature == "select-indirection-option-index") {
                    Symbolic::SymbolicInterpreter::setFeatureIndirectOptionIndexLookupEnabled(false);
                } else if (feature == "select-symbolic-index") {
                    Symbolic::SymbolicInterpreter::setFeatureSymbolicSelectedIndexEnabled(false);
                } else if (feature == "radio-checkbox-symbolic") {
                    Symbolic::SymbolicInterpreter::setFeatureSymbolicCheckedPropertyEnabled(false);
                } else if (feature == "concrete-value-property") {
                    options.concolicDisabledFeatures |= artemis::CONCRETE_VALUE_PROPERTY;
                    Symbolic::SymbolicInterpreter::setFeatureConcreteValuePropertyEnabled(false);
                } else if (feature == "symbolic-after-injection") {
                    Symbolic::SymbolicInterpreter::setFeatureSymbolicTriggeringEnabled(false);
                } else if (feature == "event-sequence-sync-injections") {
                    options.concolicDisabledFeatures |= artemis::EVENT_SEQUENCE_SYNC_INJECTIONS;
                } else {
                    cerr << "ERROR: Invalid choice of concolic-disable-features " << optarg << endl;
                    exit(1);
                }
            }
            break;
        }

        case 'c': {
            QStringList parts = QString(optarg).split("=");
            options.presetCookies.insert(parts.at(0), parts.at(1));
            break;
        }

        case 'd': {

            if (string(optarg).compare("none") == 0) {
                options.concolicTreeOutput = artemis::TREE_NONE;
            } else if (string(optarg).compare("final") == 0) {
                options.concolicTreeOutput = artemis::TREE_FINAL;
            } else if (string(optarg).compare("all") == 0) {
                options.concolicTreeOutput = artemis::TREE_ALL;
            } else if (string(optarg).compare("final-overview") == 0) {
                options.concolicTreeOutput = artemis::TREE_FINAL;
                options.concolicTreeOutputOverview = true;
            } else if (string(optarg).compare("all-overview") == 0) {
                options.concolicTreeOutput = artemis::TREE_ALL;
                options.concolicTreeOutputOverview = true;
            } else {
                cerr << "ERROR: Invalid choice of concolic-tree-output " << optarg << endl;
                exit(1);
            }

            break;
        }

        case 'e': {
            options.concolicNegateLastConstraint = true;

            break;
        }

        case 'f': {

            QString input = QString(optarg);

            int lastEqualsIndex = QString(optarg).lastIndexOf("=");
            Q_ASSERT(lastEqualsIndex >= 0);

            options.presetFormfields.insert(input.left(lastEqualsIndex), artemis::InjectionValue(input.mid(lastEqualsIndex+1)));
            break;
        }

        case 'I': {
            // Integer injected value

            QString input = QString(optarg);

            int lastEqualsIndex = QString(optarg).lastIndexOf("=");
            Q_ASSERT(lastEqualsIndex >= 0);

            QString name = input.left(lastEqualsIndex);
            QString value = input.mid(lastEqualsIndex+1);

            bool ok;
            int v = value.toInt(&ok);

            options.presetFormfields.insert(name, artemis::InjectionValue(v));

            if (!ok) {
                cerr << "ERROR: Invalid choice of injection " << name.toStdString() << "=" << value.toStdString() << endl;
                cerr << "Should be a valid integer for integer injections." << endl;
                exit(1);
            }

            break;
        }

        case 'g' : {
            if(string(optarg).compare("all") == 0){
                options.reportHeap = artemis::ALL_CALLS;
            } else if (string(optarg).compare("named") == 0){
                options.reportHeap = artemis::NAMED_CALLS;
            } else if (string(optarg).compare("none") == 0){

            } else {
                cerr << "ERROR: Invalid choice of function-call-heap-report " << optarg << endl;
                exit(1);
            }
            break;
        }

        case 'h': {
            std::cout << usage;
            exit(0);
        }

        case 'H': {
            options.concolicEventHandlerReport = true;
            break;
        }

        case 'i': {
            options.iterationLimit = QString(optarg).toInt();
            break;
        }

        case 'j': {
            options.numberSameLength = QString(optarg).toInt();
            break;
        }

        case 'k': {
            options.coverageIgnoreUrls.insert(QUrl(QString(optarg)));
            break;
        }

        case 'l' : {
            options.heapReportFactor = std::max(QString(optarg).toInt(), 1);
            break;
        }

        case 'L': {
            if (string(optarg).compare("true") == 0) {
                options.artemisLoadUrls = true;
            } else if (string(optarg).compare("false") == 0) {
                options.artemisLoadUrls = false;
            } else {
                cerr << "ERROR: Invalid choice of load-new-urls " << optarg << endl;
                exit(1);
            }
            break;
        }

        case 'm': {

            if (string(optarg).compare("artemis") == 0) {
                options.majorMode = artemis::AUTOMATED;
            } else if (string(optarg).compare("manual") == 0) {
                options.majorMode = artemis::MANUAL;
            } else if (string(optarg).compare("concolic") == 0) {
                options.majorMode = artemis::CONCOLIC;
            } else {
                cerr << "ERROR: Invalid choice of major-mode " << optarg << endl;
                exit(1);
            }

            break;
        }

        case 'n': {

            if (string(optarg).compare("kaluza") == 0) {
                options.solver = artemis::KALUZA;
            } else if (string(optarg).compare("z3str") == 0) {
                options.solver = artemis::Z3STR;
            } else if (string(optarg).compare("cvc4") == 0) {
                options.solver = artemis::CVC4;
            } else {
                cerr << "ERROR: Invalid choice of --smt-solver " << optarg << endl;
                exit(1);
            }

            break;
        }

        case 'o':{
            if(string(optarg).compare("selenium") == 0){
                options.exportEventSequence = artemis::EXPORT_SELENIUM;
            } else if(string(optarg).compare("json") == 0){
                options.exportEventSequence = artemis::EXPORT_JSON;
            } else {
                cerr << "ERROR: Invalid choice of export-event-sequnce " << optarg << endl;
                exit(1);
            }
            break;
        }

        case 'q': {
            if(optarg){
                if(string(optarg).compare("--major-mode") == 0){
                    std::cout << "artemis manual concolic";
                } else if(string(optarg).compare("--strategy-form-input-generation") == 0){
                    std::cout << "javascript-constants random";
                } else if(string(optarg).compare("--coverage-report") == 0){
                    std::cout << "html stdout none";
                } else if(string(optarg).compare("--path-trace-report") == 0){
                    std::cout << "all click html none";
                } else if(string(optarg).compare("--concolic-tree-output") == 0){
                    std::cout << "none final all final-overview all-overview";
                } else if(string(optarg).compare("----concolic-search-procedure") == 0){
                    std::cout << "dfs dfs-testing random easily-bored";
                } else if(string(optarg).compare("--concolic-event-sequences") == 0){
                    std::cout << "ignore simple";
                }else if(string(optarg).compare("--strategy-priority") == 0){
                    std::cout << "constant random coverage readwrite all";
                } else if(string(optarg).compare("--export-event-sequence") == 0){
                    std::cout << "selenium json";
                } else if(string(optarg).compare("--function-call-heap-report") == 0){
                    std::cout << "all named none";
                } else if(string(optarg).compare("--smt-solver") == 0){
                    std::cout << "z3str cvc4 kaluza";
                } else if(string(optarg).compare("--export-event-sequence") == 0){
                    std::cout << "selenium";
                }

            } else {
                std::cout << "-c -t -r -p -s -e -i --major-mode "
                             "--strategy-form-input-generation "
                             "--coverage-report "
                             "--coverage-report-ignore "
                             "--path-trace-report "
                             "--concolic-button "
                             "--concolic-tree-output "
                             "--concolic-search-procedure "
                             "--concolic-dfs-depth "
                             "--concolic-dfs-unlimited-depth "
                             "--concolic-selection-procedure "
                             "--concolic-selection-budget "
                             "--concolic-event-sequences "
                             "--strategy-priority "
                             "--smt-solver "
                             "--export-event-sequence "
                             "--input-strategy-same-length "
                             "--function-call-heap-report "
                             "--function-call-heap-report-random-factor "
                             "--export-event-sequence";
            }

            exit(0);
        }

        case 'R': {
            bool ok;
            options.concolicSearchBudget = QString(optarg).toUInt(&ok);
            if(!ok) {
                cerr << "ERROR: Invalid choice of concolic-search-budget " << optarg << endl;
                exit(1);
            }
            break;
        }

        case 's': {
            options.disableStateCheck = false;
            break;
        }

        case 'S': {
            if(string(optarg).compare("dfs") == 0){
                options.concolicSearchProcedure = artemis::SEARCH_DFS;
            } else if(string(optarg).compare("selector") == 0){
                options.concolicSearchProcedure = artemis::SEARCH_SELECTOR;
            } else {
                std::cerr << "ERROR: Invalid choice of concolic-search-procedure " << optarg << std::endl;
                exit(1);
            }
            break;
        }

        case 't': {
            options.useProxy = QString(optarg);
            break;
        }

        case 'T': {
            // getSelector will exit with an error message itself if necesary.
            //std::cerr << optarg << std::endl;
            options.concolicSearchSelector = getSelector(QString(optarg));
            break;
        }

        case 'u': {
            options.concolicDfsRestartLimit = 0;
            break;
        }

        case 'U': {
            if(artemis::UserAgents::userAgents().contains(QString(optarg))) {
                options.customUserAgent = artemis::UserAgents::userAgents().value(QString(optarg));
            } else {
                options.customUserAgent = QString(optarg);
            }

            break;
        }

        case 'v': {
           artemis::Log::addLogLevel(artemis::OFF);

           if(QString(optarg).indexOf("debug",0,Qt::CaseInsensitive)>=0){
               artemis::Log::addLogLevel(artemis::DEBUG);
           }

           if(QString(optarg).indexOf("warning",0,Qt::CaseInsensitive)>=0){
               artemis::Log::addLogLevel(artemis::WARNING);
           }
           if(QString(optarg).indexOf("error",0,Qt::CaseInsensitive)>=0){
               artemis::Log::addLogLevel(artemis::ERROR);
           }
           if(QString(optarg).indexOf("fatal",0,Qt::CaseInsensitive)>=0){
               artemis::Log::addLogLevel(artemis::FATAL);
           }

           if(QString(optarg).indexOf("all",0,Qt::CaseInsensitive)>=0){
               artemis::Log::addLogLevel(artemis::ALL);
           }

           if(QString(optarg).indexOf("off",0,Qt::CaseInsensitive)>=0){
               artemis::Log::addLogLevel(artemis::OFF);
           }

           if(QString(optarg).indexOf("info",0,Qt::CaseInsensitive)>=0){
               artemis::Log::addLogLevel(artemis::INFO);
           }

           break;
       }

        case 'w': {
            if (string(optarg).compare("ignore") == 0) {
                options.concolicTriggerEventHandlers = false;
            } else if (string(optarg).compare("simple") == 0) {
                options.concolicTriggerEventHandlers = true;
            } else {
                cerr << "ERROR: Invalid choice of event-sequence handling strategy " << optarg << endl;
                exit(1);
            }

            break;
        }

        case 'W': {
            // Validity is checked when used in the concolic runtime.
            options.concolicEventHandlerPermutation = QString(optarg);

            break;
        }

        case 'x': {

            if (string(optarg).compare("javascript-constants") == 0) {
                options.formInputGenerationStrategy = artemis::ConstantString;
            } else if (string(optarg).compare("random") == 0) {
                options.formInputGenerationStrategy = artemis::Random;
            } else {
                cerr << "ERROR: Invalid strategy " << optarg << endl;
                exit(1);
            }

            break;

        }

        case 'y': {
            if (QString(optarg).toLower().compare("html") == 0) {
                options.outputCoverage = artemis::HTML;
            } else if (QString(optarg).toLower().compare("stdout") == 0) {
                options.outputCoverage = artemis::STDOUT;
            } else if (QString(optarg).toLower().compare("none") == 0) {
                options.outputCoverage = artemis::NONE;
            } else {
                cerr << "ERROR: Invalid choice of coverage report " << optarg << endl;
                exit(1);
            }
            break;
        }

        case 'z': {
            if (string(optarg).compare("constant") == 0) {
                options.prioritizerStrategy = artemis::CONSTANT;
            } else if (string(optarg).compare("random") == 0) {
                options.prioritizerStrategy = artemis::RANDOM;
            } else if (string(optarg).compare("coverage") == 0) {
                options.prioritizerStrategy = artemis::COVERAGE;
            } else if (string(optarg).compare("readwrite") == 0) {
                options.prioritizerStrategy = artemis::READWRITE;
            } else if (string(optarg).compare("all") == 0){
                options.prioritizerStrategy = artemis::ALL_STRATEGIES;
            } else {
                cerr << "ERROR: Invalid choice of prioritizer strategy " << optarg << endl;
                exit(1);
            }

            break;
        }

        case 'A': {

            if (string(optarg).compare("jquery") == 0) {
                options.targetStrategy = artemis::TARGET_JQUERY;
            } else if (string(optarg).compare("concolic") == 0) {
                options.targetStrategy = artemis::TARGET_CONCOLIC;
            } else if (string(optarg).compare("legacy") == 0) {
                options.targetStrategy = artemis::TARGET_LEGACY;
            } else {
                cerr << "ERROR: Invalid choice of target strategy " << optarg << endl;
                exit(1);
            }

            break;

        }

        case 'C': {

            if (string(optarg).compare("random-incremental") == 0) {
                options.eventGenerationStrategy = artemis::EVENT_LEGACY;
            } else if (string(optarg).compare("fasttrack") == 0) {
                options.eventGenerationStrategy = artemis::EVENT_FASTTRACK;
            } else {
                cerr << "ERROR: Invalid choice of event generation strategy " << optarg << endl;
                exit(1);
            }

            break;

        }

        case 'D': {
            QStringList parts = QString(optarg).split("x");
            if(parts.length() != 2) {
                cerr << "ERROR: Invalid format for concolic-dfs-depth " << optarg << endl;
                exit(1);
            }

            bool ok1, ok2;
            unsigned int depth = parts[0].toUInt(&ok1);
            unsigned int passes = parts[1].toUInt(&ok2);
            if(!ok1 || !ok2 || depth < 1 || passes < 1) {
                cerr << "ERROR: Invalid value for concolic-dfs-depth " << optarg << endl;
                exit(1);
            }

            options.concolicDfsDepthLimit = depth;
            options.concolicDfsRestartLimit = passes;

            break;
        }

        case 'E': {
            options.debugConcolic = true;

            break;
        }

        case 'F': {
            // Boolean injected value

            QString input = QString(optarg);

            int lastEqualsIndex = QString(optarg).lastIndexOf("=");
            Q_ASSERT(lastEqualsIndex >= 0);

            QString name = input.left(lastEqualsIndex);
            QString value = input.mid(lastEqualsIndex+1);

            if (value == "true") {
                options.presetFormfields.insert(name, artemis::InjectionValue(true));
            } else if (value == "false") {
                options.presetFormfields.insert(name, artemis::InjectionValue(false));
            }else {
                cerr << "ERROR: Invalid choice of injection " << name.toStdString() << "=" << value.toStdString() << endl;
                cerr << "Should be 'true' or 'false' only for boolean injections." << endl;
                exit(1);
            }
            break;
        }

        case 'G': {

            if (string(optarg).compare("true") == 0) {
                options.enableEventVisibilityFiltering = true;
            } else if (string(optarg).compare("false") == 0) {
                options.enableEventVisibilityFiltering = false;
            } else {
                cerr << "ERROR: Invalid choice of event visibility filtering " << optarg << endl;
                exit(1);
            }

            break;
        }

        case '?': {
            // getopt has already printed an error
            exit(1);
        }

        default: {
            cerr << "Unhandled option." << endl;
            exit(1);
        }

        }
    }
Example #7
0
void PlayingContextWidget::playerTrackStarted(const QStringList & trackInfo)
{
	QString filename = trackInfo[Ororok::TrackFieldPath];
	Ororok::MusicTrackMetadata * md = Ororok::getMusicFileMetadata(filename);
	if (md == 0) {
		p->webview->setHtml(p->pageTemplate.arg(tr("Unable to detect file metadata")));
		return;
	}

	QStringList htmlRows;

	// order of data fields as follows
	// {title} by {author}
	// on {album-name} / #{track-num}
	// Album date: {year}
	// Genre: {genre}
	// Bitrate: {bitrate}
	// Lyrics by: {lyrics}
	// Composed by: {composer}

	// title
	htmlRows << tr("<div><!--song title--><strong>%1</strong> "
			"by <!--artist name--><strong>%2</strong></div>")
			.arg(md->title)
			.arg(md->artist);

	// album
	QString albumName = tr("<em>Unknown album</em>");
	if (!md->album.isEmpty()) {
		albumName = md->album;
	}

	QString trackNum;
	if (md->track > 0) {
		trackNum = tr(" / #<strong>%1</strong>")
			.arg(md->track);
	}

	htmlRows << tr("<div>on <strong>%1</strong>%2</div>")
			.arg(albumName)
			.arg(trackNum);

	// cover
	QDir albumDir = QFileInfo(filename).absoluteDir();
	QStringList coverFilter;
	coverFilter << QString("cover.jpg") << QString("cover.png") << QString("cover.gif") << QString("cover.bmp");
	QStringList covers = albumDir.entryList(coverFilter);
	if (covers.length() > 0) {
		QString cover = covers.at(0);
		htmlRows << QString("<div class=\"cover\"><img border=\"1\" width=\"100%\" src=\"file://%1\"></div>")
				.arg(albumDir.absoluteFilePath(cover));
	}

	// album date
	if (md->year > 0) {
		htmlRows << tr("<div>Album year: <strong>%1</strong></div>")
			.arg(md->year);
	}

	// genre
	if (!md->genre.isEmpty()) {
		htmlRows << tr("<div>Genre: <strong>%1</strong></div>")
			.arg(md->genre);
	}

	// bitrate
	htmlRows << tr("<div>Bitrate: <strong>%1</strong> kbps</div>")
			.arg(md->bitrate);

	if (!md->composer.isEmpty()) {
		htmlRows << tr("<div>Composed by <strong>%1</strong></div>")
				.arg(md->composer);
	}
	if (!md->lyricsAuthor.isEmpty()) {
		htmlRows << tr("<div>Lyrics by <strong>%1</strong></div>")
				.arg(md->lyricsAuthor);
	}

	QString html = p->pageTemplate.arg(htmlRows.join("\n"));
	p->webview->setHtml(html);
}
Example #8
0
void PCDMgui::createGUIfromTheme(){
  QString style;
  QString tmpIcon; //used for checking image files before loading them
  QWidget *leftscreen = 0;
  for(int i=0; i<screens.length(); i++){
    if(screens[i]->x()==0){
      leftscreen = screens[i];
    }
  }
  //Define the default icon size
  int perc = qRound(leftscreen->height()*0.035); //use 3.5% of the screen height
  defIconSize = QSize(perc,perc);
  //Set the background image
  if(DEBUG_MODE){ qDebug() << "Setting Background Image"; }
  if( currentTheme->itemIsEnabled("background") ){
    tmpIcon = currentTheme->itemIcon("background");
    if( tmpIcon.isEmpty() || !QFile::exists(tmpIcon) ){ tmpIcon = ":/images/backgroundimage.jpg"; }
    //use "border-image" instead of "background-image" to stretch rather than tile the image
    QString bgstyle = "QWidget#BGSCREEN{border-image: url(BGIMAGE) stretch;}"; 
    bgstyle.replace("BGIMAGE", tmpIcon);
    style.append(bgstyle);
  }
  //Set the application style sheet
  style.append(" "+ currentTheme->styleSheet() );
  this->setStyleSheet( style.simplified() );

  //Check for whether the desktop switcher is on the toolbar or not
  simpleDESwitcher = (currentTheme->itemValue("desktop") == "simple");
  
  //get the default translation directory
  if(DEBUG_MODE){ qDebug() << "Load Translations"; }
  translationDir = "/usr/local/share/pcbsd/i18n/";
  //Fill the translator
  m_translator = new QTranslator();
  //Create the Toolbar
  toolbar = new QToolBar();
  //Add the Toolbar to the window
  if(DEBUG_MODE){ qDebug() << "Create Toolbar"; }
    //use the theme location   
    QString tarea = currentTheme->itemValue("toolbar");
    if(tarea == "left"){
      this->addToolBar( Qt::LeftToolBarArea, toolbar ); 	    
    }else if( tarea=="top"){
      this->addToolBar( Qt::TopToolBarArea, toolbar );  	   
      toolbar->setFixedWidth(leftscreen->width());
    }else if(tarea=="right"){
      this->addToolBar( Qt::RightToolBarArea, toolbar );   	    
    }else{ //bottom is default
      this->addToolBar( Qt::BottomToolBarArea, toolbar ); 	
      toolbar->setFixedWidth(leftscreen->width());
    }
    //Set toolbar flags
    toolbar->setVisible(true);
    toolbar->setMovable(false);
    toolbar->setFloatable(false);
    toolbar->setContextMenuPolicy(Qt::PreventContextMenu); //make sure no right-click menu
    //Set the default style and icon sizes
    QString tstyle = currentTheme->itemIcon("toolbar").toLower(); //use the theme style
    if(tstyle=="textonly"){ toolbar->setToolButtonStyle(Qt::ToolButtonTextOnly); }
    else if(tstyle=="textbesideicon"){ toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); }
    else if(tstyle=="textundericon"){ toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); }
    else{ toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); } //default to icon only
    
    QSize tmpsz = currentTheme->itemIconSize("toolbar");
    if(!tmpsz.isValid()){ tmpsz = defIconSize; }
    toolbar->setIconSize( tmpsz ); //use theme size
    toolbar->setFocusPolicy( Qt::NoFocus );
  //Populate the Toolbar with items (starts at leftmost/topmost)
    //----Virtual Keyboard
    if(currentTheme->itemIsEnabled("vkeyboard") ){
      if(DEBUG_MODE){ qDebug() << " - Create Virtual Keyboard Button"; }
      tmpIcon = currentTheme->itemIcon("vkeyboard");
      if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/input-keyboard.png"; }
      virtkeyboardButton = new QAction( QIcon(tmpIcon),tr("Virtual Keyboard"),this );
      toolbar->addAction(virtkeyboardButton);
      connect( virtkeyboardButton, SIGNAL(triggered()), this, SLOT(slotPushVirtKeyboard()) );
    }else{
      virtkeyboardButton = new QAction(this);
    }

    //----Locale Switcher
    if(DEBUG_MODE){ qDebug() << " - Create Locale Button"; }
    tmpIcon = currentTheme->itemIcon("locale");
    if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/language.png"; }
    localeButton = new QAction( QIcon(tmpIcon),tr("Locale"),this );
    toolbar->addAction(localeButton);
    connect( localeButton, SIGNAL(triggered()), this, SLOT(slotChangeLocale()) );
    
    //----Keyboard Layout Switcher
    if(DEBUG_MODE){ qDebug() << " - Create Keyboard Layout Button"; }
    tmpIcon = currentTheme->itemIcon("keyboard");
    if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/keyboard.png"; }
    keyboardButton = new QAction( QIcon(tmpIcon),tr("Keyboard Layout"),this );
    toolbar->addAction(keyboardButton);
    connect( keyboardButton, SIGNAL(triggered()), this, SLOT(slotChangeKeyboardLayout()) );

    //----Add a spacer
    QWidget* spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding);
    toolbar->addWidget(spacer);
        
    //----System Shutdown/Restart
    if(DEBUG_MODE){ qDebug() << " - Create System Button"; }
    tmpIcon = currentTheme->itemIcon("system");
    if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/system.png"; }
    QAction* act = new QAction( QIcon(tmpIcon),tr("System"),this );
    systemButton = new QToolButton();
    systemButton->setDefaultAction(act);
    systemMenu = new QMenu();
    toolbar->addWidget(systemButton);
    systemButton->setPopupMode( QToolButton::InstantPopup );
    systemButton->setFocusPolicy( Qt::NoFocus );
    
  //Create the grid layout
  QGridLayout* grid = new QGridLayout;
  if(DEBUG_MODE){ qDebug() << "Fill Desktop Area"; }
  //Populate the grid with items
    //----Header Image
    QLabel* header = new QLabel; 
    if( currentTheme->itemIsEnabled("header") ){
      if(DEBUG_MODE){ qDebug() << " - Create Header"; }
      tmpIcon = currentTheme->itemIcon("header");
      if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/banner.png"; }
      QPixmap tmp( tmpIcon );
      header->setPixmap( tmp.scaled( currentTheme->itemIconSize("header") ) );
      grid->addWidget( header, currentTheme->itemLocation("header","row"), \
                      currentTheme->itemLocation("header","col"), \
                      currentTheme->itemLocation("header","rowspan"), \
                      currentTheme->itemLocation("header","colspan"), Qt::AlignCenter);
    }
    
    //Username/Password/Login widget
    if(DEBUG_MODE){ qDebug() << " - Create Login Widget"; }
    loginW = new LoginWidget;
    /*loginW->setUsernames(Backend::getSystemUsers()); //add in the detected users
    QString lastUser = Backend::getLastUser();
    if(!lastUser.isEmpty()){ //set the previously used user
    	loginW->setCurrentUser(lastUser); 
    }*/
    //Set Icons from theme
    tmpIcon = currentTheme->itemIcon("login");
    tmpsz = currentTheme->itemIconSize("login");
    if(!tmpsz.isValid()){ tmpsz = defIconSize; }
    if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/next.png"; }
    loginW->changeButtonIcon("login",tmpIcon, tmpsz);
    tmpIcon = currentTheme->itemIcon("anonlogin");
    tmpsz = currentTheme->itemIconSize("login");
    if(!tmpsz.isValid()){ tmpsz = defIconSize; }
    if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/next-stealth.png"; }
    loginW->changeButtonIcon("anonlogin", tmpIcon, tmpsz);
    tmpIcon = currentTheme->itemIcon("user");
    slotUserChanged(loginW->currentUsername()); //Make sure that we have the correct user icon
    tmpIcon = currentTheme->itemIcon("password");
    tmpsz = currentTheme->itemIconSize("password");
    if(!tmpsz.isValid()){ tmpsz = defIconSize; }
    if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/password.png"; }
    loginW->changeButtonIcon("pwview",tmpIcon, tmpsz);
    tmpIcon = currentTheme->itemIcon("encdevice");
    tmpsz = currentTheme->itemIconSize("device");
    if(!tmpsz.isValid()){ tmpsz = defIconSize; }
    if(!QFile::exists(tmpIcon) || tmpIcon.isEmpty() ){ tmpIcon=":/images/usbdevice.png"; }
    loginW->changeButtonIcon("device", tmpIcon, tmpsz);
    //Enable/disable the password view functionality
    loginW->allowPasswordView( Config::allowPasswordView() );
    loginW->allowUserSelection( Config::allowUserSelection() );
    loginW->allowAnonLogin( Config::allowAnonLogin() );
    //Add item to the grid
    grid->addWidget( loginW, currentTheme->itemLocation("login","row"), \
                      currentTheme->itemLocation("login","col"), \
                      currentTheme->itemLocation("login","rowspan"), \
                      currentTheme->itemLocation("login","colspan"), Qt::AlignCenter);
    //Connect the signals/slots
    connect(loginW,SIGNAL(loginRequested(QString,QString)),this,SLOT(slotStartLogin(QString,QString)));
    connect(loginW,SIGNAL(escapePressed()),this,SLOT(slotShutdownComputer()));
    connect(loginW,SIGNAL(UserSelected(QString)), this, SLOT(slotUserSelected(QString)) );
    connect(loginW,SIGNAL(UserChanged(QString)), this, SLOT(slotUserChanged(QString)) );
    
    //----Desktop Environment Switcher
    if(simpleDESwitcher){
      tmpsz = currentTheme->itemIconSize("desktop");
      if(!tmpsz.isValid()){ tmpsz = defIconSize; }
      loginW->setDesktopIconSize(tmpsz);
    }else{
      if(DEBUG_MODE){ qDebug() << " - Create DE Switcher"; }
      //Create the switcher
      deSwitcher = new FancySwitcher(this, !currentTheme->itemIsVertical("desktop") );
      tmpsz = currentTheme->itemIconSize("desktop");
      if(!tmpsz.isValid()){ tmpsz = defIconSize; }
      deSwitcher->setIconSize(tmpsz.height());
      tmpIcon = currentTheme->itemIcon("nextde");
      if( !tmpIcon.isEmpty() && QFile::exists(tmpIcon) ){ deSwitcher->changeButtonIcon("forward", tmpIcon); }
      tmpIcon = currentTheme->itemIcon("previousde");
      if( !tmpIcon.isEmpty() && QFile::exists(tmpIcon) ){ deSwitcher->changeButtonIcon("back", tmpIcon); }
      //Figure out if we need to smooth out the animation
      deSwitcher->setNumberAnimationFrames("4"); 
      //NOTE: A transparent widget background slows the full animation to a crawl with a stretched background image

      grid->addWidget( deSwitcher, currentTheme->itemLocation("desktop","row"), \
                      currentTheme->itemLocation("desktop","col"), \
                      currentTheme->itemLocation("desktop","rowspan"), \
                      currentTheme->itemLocation("desktop","colspan"), Qt::AlignCenter);
    }
    //----WINDOW SPACERS
    QStringList spacers = currentTheme->getSpacers();
    for(int i=0; i<spacers.length(); i++){
      bool isVertical = (spacers[i].section("::",0,0) == "true");
      int row = spacers[i].section("::",1,1).toInt();
      int col = spacers[i].section("::",2,2).toInt();
      //qDebug() << "Add Spacer:" << isVertical << row << col;
      if(isVertical){
        grid->setRowStretch(row,1);
      }else{ //horizontal
        grid->setColumnStretch(col,1);
      }
    }

  //Connect the grid to the leftmost screen widget
  leftscreen->setLayout(grid);
    
  //Now translate the UI and set all the text
  if(DEBUG_MODE){ qDebug() << " - Fill GUI with data"; }
  //retranslateUi();
  LoadAvailableUsers(); //Note: this is the first time it is run
  if(DEBUG_MODE){ qDebug() << " - Translate GUI"; }
  retranslateUi();
  if(DEBUG_MODE){ qDebug() << "Done with initialization"; }

}
int LzExcelOutput::outputMultiTunnels(ClearanceMultiTunnels * inputdata, QString templatepath, QString outputfile, QString insertimgpath) 
{
    QString templatename = "MultiTunnelsTemplate.xls";
    int ret = copy(templatepath, templatename, outputfile);
    if (ret != 0)
        return ret;

    // 插入图片路径不存在
    if (!QFile(insertimgpath).exists())
        return 3;

    //操作已经存在的excel,生成限界尺寸表
    ExcelEngine excel;

    excel.Open(outputfile, 1, false);
    
    QString linename = inputdata->getLineName(); 
    // 限界表名称
    excel.SetCellData(1,1,QObject::tr("%1-区段桥隧综合最小建筑限界尺寸表").arg(linename));
    excel.SetCellData(52,1,QObject::tr("%1-区段桥隧综合最小建筑限界尺寸图").arg(linename));

    // 线路名称
    excel.SetCellData(3,3,linename);
    excel.SetCellData(54,2,linename);
    excel.SetCellData(54,5,linename);

    // 区段
    excel.SetCellData(3,9,linename);

    QString endStationName = inputdata->getEndStationName();
    // 面向站名
    excel.SetCellData(3,15,endStationName);
    excel.SetCellData(54,13,endStationName);

    QStringListModel * tunnelsmodel = inputdata->getTunnelsNames();

    // 桥隧总数
    excel.SetCellData(4,4,tunnelsmodel->rowCount());
    // 桥梁数
    excel.SetCellData(4,11,inputdata->getNumOfOutOfClearanceBridges());
    // 隧道数
    excel.SetCellData(4,14,inputdata->getNumOfOutOfClearanceTunnels());

    // 时间
    // 采集日期
    QModelIndex index = tunnelsmodel->index(0,0);
    QString tunnelinfo = index.data().toString();//这两行代码获取QStringListModel中第一行的值
    QStringList strlist = tunnelinfo.split("-");
    if (strlist.length() < 3)
        return -1;
    QString collectdate = strlist.at(2);
    excel.SetCellData(49,15,collectdate);
    excel.SetCellData(54,16,collectdate);

    // 最小曲线半径

    int minRadius = inputdata->getMinRadius();
    excel.SetCellData(5,5,minRadius);
    // 最大外轨超高
    excel.SetCellData(5,10,inputdata->getWaiGuiChaoGao()); 
    // 最低接触网高度
    excel.SetCellData(5,16,inputdata->getJieChuWangGaoDu()); 

    ClearanceData * data = &inputdata->getClearanceStraightData();
    int rowcount = data->getMaps().size();
    
    // Excel模板从第10行开始为高度限界数据,前面几行为表头或空格
    int startrownum = 10;
    int startcolumnnumdef = 1;
    
    // 临时变量
    int startcolumnnum = startcolumnnumdef;
    float tmpval;
    _int64 tmppos;
    int tmpradius;
    float minHeight;

    for (int i = 0; i < 3; i++)
    {
        startcolumnnum = startcolumnnumdef;
        
        switch(i)
        {
            case Curve_Straight:
                if (inputdata->getNumOfStraight())
                {
                    data = &inputdata->getClearanceStraightData();
                    startcolumnnum += LzOutputTableColumn::Straight_Left_Val;
                }
                else
                    continue;
                break;
            case Curve_Left:
                if (inputdata->getNumOfLeft())
                {
                    data = &inputdata->getClearanceLeftData();
                    startcolumnnum += LzOutputTableColumn::LeftCurve_Left_Val;
                }
                else
                    continue;
                break;
            case Curve_Right:
                if (inputdata->getNumOfRight())
                {
                    data = &inputdata->getClearanceRightData();
                    startcolumnnum += LzOutputTableColumn::RightCurve_Left_Val;
                }
                else
                    continue;
                break;
            default:
                break;
        }

        minHeight = data->getMinCenterHeight();

        // map反向遍历,正向为高度从小到大,插入图表是需要高度从大到小
        std::map<int, ClearanceItem>::reverse_iterator it = data->getMaps().rbegin();
        int k = 0; // 相对行数
        while (it != data->getMaps().rend())
        {
            std::pair<int, ClearanceItem> pair = (*it);

            if (pair.first > minHeight)
            {
                it++;
                k++;
                continue;
            }

            // 此处写要插入的内容
            if (pair.second.leftval >= 0)
                excel.SetCellData(k + startrownum, startcolumnnum, pair.second.leftval); 
            if (pair.second.rightval >= 0)
                excel.SetCellData(k + startrownum, startcolumnnum + 1, pair.second.rightval);
            if (i == Curve_Straight) // 直线
            {
                if (pair.second.leftval >= 0)
                {
                    excel.SetCellData(k + startrownum, startcolumnnum + 2, toTunnelPosString2(pair.second.leftpos, pair.second.lefttunnelid, "0"));
                    qDebug() << toTunnelPosString2(pair.second.leftpos, pair.second.lefttunnelid, "0");
                }
                if (pair.second.rightval >= 0)
                {
                    excel.SetCellData(k + startrownum, startcolumnnum + 3, toTunnelPosString2(pair.second.rightpos, pair.second.righttunnelid, "0"));
                    qDebug() << toTunnelPosString2(pair.second.rightpos, pair.second.righttunnelid, "0");
                }
            }
            else
            {
                if (pair.second.leftval >= 0)
                {
                    excel.SetCellData(k + startrownum, startcolumnnum + 2, pair.second.leftradius); 
                    excel.SetCellData(k + startrownum, startcolumnnum + 4, toTunnelPosString2(pair.second.leftpos, pair.second.lefttunnelid, "0"));
                    qDebug() << toTunnelPosString2(pair.second.leftpos, pair.second.lefttunnelid, "0");
                }
                if (pair.second.rightval >= 0)
                {
                    excel.SetCellData(k + startrownum, startcolumnnum + 3, pair.second.rightradius);
                    excel.SetCellData(k + startrownum, startcolumnnum + 5, toTunnelPosString2(pair.second.rightpos, pair.second.righttunnelid, "0"));
                    qDebug() << toTunnelPosString2(pair.second.rightpos, pair.second.righttunnelid, "0");
                }
            }
            it++;
            k++;
        }
    }

    // <150高度手动输入? ///TODO

    // 线路中心线上方最低净高mm
    excel.SetCellData(rowcount+startrownum+1,9, inputdata->getMinHeight());
    
    excel.setProperty("DisplayAlerts", 0);
    
    // 保存
    excel.Save(); 
    excel.Close();    
    
    // 生成限界图
    initExcelEngine();
    QAxObject *workBooks1 = excel1->querySubObject("Workbooks");
    workBooks1->dynamicCall("Open(const QString&)", outputfile);
    QAxObject *workBook1 = excel1->querySubObject("ActiveWorkBook");
    QAxObject *sheets1 = workBook1->querySubObject("WorkSheets");
    QAxObject *sheet1 = sheets1->querySubObject("Item(int)", 1);//获得第一个工作表

    // QAxObject *range=sheet1->querySubObject("Range(const QVariant&)",QVariant(QString("D52:AA92")));
    // range->dynamicCall("Clear()");//指定清除某个区域

    /////////////AddPicture函数详解////////////////
    // AddPicture(FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height)中7个参数的意思。
    // (1)FileName 必选 String 图片的路径和文件名。
    // (2)LinkToFile 可选 Variant 如果该参数值为 True,则将图片链接到创建它的文件。如果该参数值为 False,则将图片作为该文件的独立副本。默认值为 False。
    // (3)SaveWithDocument 可选 Variant 如果该参数值为 True,则将链接的图片与文档一起保存。默认值为 False。
    // (4)Left 可选 Variant 新图片的左边缘相对于绘图画布的位置,以磅为单位。
    // (5)Top 可选 Variant 新图片的上边缘相对于绘图画布的位置,以磅为单位。
    // (6)Width 可选 Variant 图片的宽度,以磅为单位。
    // (7)Height 可选 Variant 图片的高度,以磅为单位。
    ///////////////////////////////////////////////

    // @author 熊雪、范翔。路径变成反斜杠,否则AddPicture,SaveAs函数出错
    outputfile = toBackSlashStr(outputfile);
    insertimgpath = toBackSlashStr(insertimgpath);

    QAxObject *shapes1 = sheet1->querySubObject("Shapes");
    shapes1->dynamicCall("AddPicture(QString&,bool,bool,double,double,double,double",QString("%1").arg(insertimgpath),true,true,8,770,510,595);//8,750,510,627  QString("%1image.jpg").arg(outputfile)
    excel1->setProperty("DisplayAlerts", 0);
    //excel1->dynamicCall("Save()");
    workBook1->dynamicCall("SaveAs(const QString&)", outputfile);
    // QMessageBox::information(NULL, tr("OK"), tr("成功生成Excel文件!"),QMessageBox::Yes | QMessageBox::No);
    excel1->dynamicCall("Quit()");

    return 0;
}
Example #10
0
void WebServer::EvaluateRequest(const RestInputStruct &REQ){
  RestOutputStruct out;
  if(REQ.VERB != "GET"){
    //Non-supported request (at the moment) - return an error message
    out.CODE = RestOutputStruct::BADREQUEST;
  }else{
    //GET request
    //Now check the body of the message and do what it needs
    QJsonDocument doc = QJsonDocument::fromJson(REQ.Body.toUtf8());
    if(doc.isNull()){ qWarning() << "Empty JSON Message Body!!" << REQ.Body.toUtf8(); }
    //Define the output structures
    QJsonDocument ret; //return message
    //parse the message and do something
    //Objects contain other key/value pairs - this is 99% of cases
    if(doc.isObject()){
      QJsonObject obj;
      QStringList keys = doc.object().keys();
      if(REQ.URI.toLower()=="/syscache"){
        QStringList reqs = keys.filter("request",Qt::CaseInsensitive);
        if(!reqs.isEmpty()){
	  qDebug() << "Parsing Inputs:" << reqs;
	  for(int r=0; r<reqs.length(); r++){
	    QString req =  JsonValueToString(doc.object().value(reqs[r]));
	    qDebug() << "  ["+reqs[r]+"]="+req;
	    QStringList values = SysCacheClient::parseInputs( QStringList() << req ); 
	    values.removeAll("");
	    //Quick check if a list of outputs was returned
	    if(values.length()==1){
	      values = values[0].split(SCLISTDELIM); //split up the return list (if necessary)
	      values.removeAll("");
	    }
	    qDebug() << " - Returns:" << values;
	    keys.removeAll(reqs[r]); //this key was already processed
	    if(values.length()<2){
	      obj.insert(reqs[r],values.join(""));
	    }else{
	      //This is an array of outputs
	      QJsonArray arr;
              for(int i=0; i<values.length(); i++){ arr.append(values[i]); }
	      obj.insert(reqs[r],arr);
            }
          }
        } //end of special "request" objects
      
      }else{
        qDebug() << "Object Variables:" << keys;
        for(int i=0; i<keys.length(); i++){
          qDebug() << keys[i]+"="+JsonValueToString(doc.object().value(keys[i]) );
        }	  
      }
      ret.setObject(obj);
    //Special case for a single syscache input (array of strings)
    }else if(doc.isArray() && REQ.URI.toLower()=="/syscache"){
        QStringList inputs = JsonArrayToStringList(doc.array());
        qDebug() << " syscache inputs:" << inputs;
        QJsonObject obj;
        QStringList values = SysCacheClient::parseInputs(inputs );
        for(int i=0; i<values.length(); i++){
	  if(values[i].contains(SCLISTDELIM)){
	    //This is an array of values
	    QStringList vals = values[i].split(SCLISTDELIM);
	    vals.removeAll("");
	    QJsonArray arr;
                for(int j=0; j<vals.length(); j++){ arr.append(vals[j]); }
	      obj.insert("Value"+QString::number(i),arr);
	  }else{
            obj.insert("Value"+QString::number(i),values[i]);
	  }
        }
      ret.setObject(obj);
    }
    //Assemble the outputs for this "GET" request
    out.CODE = RestOutputStruct::OK;
    out.Body = ret.toJson();
    out.Header << "Content-Type: text/json; charset=utf-8";
  }
  //Return any information
  csock->sendTextMessage(out.assembleMessage());
}
Example #11
0
void PCDMgui::retranslateUi(){
  //All the text-setting for the main interface needs to be done here
  //virtual keyboard button
  //if(currentTheme->itemIsEnabled("vkeyboard")){
    virtkeyboardButton->setToolTip(tr("Virtual Keyboard"));
    virtkeyboardButton->setText(tr("Virtual Keyboard"));
  //}
  //locale switcher button
  localeButton->setToolTip(tr("Change locale"));
  localeButton->setText(tr("Locale"));
  //keyboard layout button
  keyboardButton->setToolTip(tr("Change Keyboard Layout"));
  keyboardButton->setText(tr("Keyboard Layout"));
  //system button
  systemButton->defaultAction()->setToolTip(tr("Shutdown the computer"));
  systemButton->defaultAction()->setText(tr("System"));
  //Menu entries for system button
    systemMenu->clear();	
    systemMenu->addAction( tr("Restart"),this, SLOT(slotRestartComputer()) );
    systemMenu->addAction( tr("Shut Down"), this, SLOT(slotShutdownComputer()) );
    if(DEBUG_MODE){systemMenu->addAction( tr("Close PCDM"), this, SLOT(slotClosePCDM()) ); }
    systemButton->setMenu(systemMenu);
  //The main login widget
  if(hostname.isEmpty()){
    if(DEBUG_MODE){ qDebug() << "Finding Hostname..."; }
    //Find the system hostname
    hostname = pcbsd::Utils::runShellCommand("hostname").join(" ").simplified();
    if(DEBUG_MODE){ qDebug() << " - Host:" << hostname; }
    loginW->displayHostName(hostname);	  
  }
  if(DEBUG_MODE){ qDebug() << "Translate Login Widget"; }
  loginW->retranslateUi();
  
  //The desktop switcher
  
    //Get the new desktop list (translated)
    QStringList deList = Backend::getAvailableDesktops(); //priority ordered
    QString lastDE;
    if(!loginW->currentUsername().isEmpty()){ lastDE = Backend::getLastDE(loginW->currentUsername()); }
    if(DEBUG_MODE){ qDebug() << "DE's:" << deList << lastDE; }
    if(lastDE.isEmpty()){ lastDE = deList[0]; }
    //Organize the desktop list alphabetically by filename
    deList.removeDuplicates();
    QStringList DEL;
    for(int i=0; i<deList.length(); i++){
      //Check the icon
        QString deIcon = Backend::getDesktopIcon(deList[i]);
	if( deIcon.isEmpty() ){ deIcon = currentTheme->itemIcon("desktop"); } //set the default icon if none given
        if( !QFile::exists(deIcon) ){ deIcon = ":/images/desktop.png"; }
      QString entry = deList[i] +":::"+deIcon+":::"+Backend::getDesktopComment(deList[i]);
      DEL << entry;
    }
    DEL.sort(); //make it alphabetical
    //Now fill the switcher
    if(!simpleDESwitcher){
      deSwitcher->removeAllItems();
      for(int i=0; i<DEL.length(); i++){
	//Now add the item
	deSwitcher->addItem( DEL[i].section(":::",0,0), DEL[i].section(":::",1,1), DEL[i].section(":::",2,2) );
      }
      if(DEBUG_MODE){ qDebug() << "Last used DE:" << lastDE; }
      //Set the switcher to the last used desktop environment
      if( !lastDE.isEmpty() ){ deSwitcher->setCurrentItem(lastDE); }

    }else{
      //Simple switcher on the login widget
      QStringList deNames, deIcons, deInfo;
      for(int i=0; i<DEL.length(); i++){
        deNames << DEL[i].section(":::",0,0);
	deIcons << DEL[i].section(":::",1,1);
	deInfo << DEL[i].section(":::",2,2);
      }
      if(DEBUG_MODE){ qDebug() << "Loading DE's into the login widget"; }
      loginW->setDesktops(deNames, deIcons, deInfo);
      //Set the switcher to the last used desktop environment
      if(DEBUG_MODE){ qDebug() << "Last used DE:" << lastDE; }
      loginW->setCurrentDE(lastDE);
    }

}
Example #12
0
    static void execute_js(const QString &js, const QStringList &args, const justice_cmd &cmd) {
        QByteArray r_key = cmd.m_rbuf_key.toUtf8();
        QByteArray w_key = cmd.m_wbuf_key.toUtf8();
        QByteArray info_key = cmd.m_info_key.toUtf8();
        QString TestCount;
        int cnt = args.length();
        QByteArray ref_args[cnt];
        for (int i = 0; i != cnt; i++)
            ref_args[i] = args[i].toUtf8();

        char *argv[3 + cnt];
        char *envp[10];
        char path[] = "node";

        QByteArray script = js.toUtf8();
        argv[0] = path;
        argv[1] = script.data();
        for (int i = 0; i != cnt; i++)
            argv[2 + i] = ref_args[i].data();
        argv[2 + cnt] = NULL;

        envp[0] = r_key.data();
        envp[1] = w_key.data();
        envp[2] = info_key.data();
        envp[3] = NULL;


        if( Command_test_enable == 1 )
        {

            argv[0] = path;
            //argv[1] = "/home/justice/justice-script/execute/1.js";
            argv[1] = "/home/justice/justice-script/command/blocks.js";
            argv[2] = NULL;

            envp[3] = admin_str;
            envp[4] = buff;

            sprintf( Count_str , "TEST_CNT=%s" , TEST_COUNT.toStdString().c_str() );

            envp[5] = Count_str ;
            envp[6] = NULL;

        }


    if( Command_test_enable == 1 )
      {

        qDebug() << "argv";
        for (int i = 0; i < 3; i++)
           qDebug() << argv[i];

        qDebug() << "envp";
        for (int i = 0 ; i < 7 ; i++)
           qDebug() << envp[i];

      }
     else
      {

         qDebug() << "argv";
         for (int i = 0; i != 2 + cnt; i++)
             qDebug() << argv[i];

         qDebug() << "envp";
         for (int i = 0; i != 3; i++)
             qDebug() << envp[i];

      }



        int status =  execvpe( path, argv, envp);

        return ;
    }
Example #13
0
void Parser131500ComAu::parseSearchJourney(QNetworkReply *networkReply)
{
    lastJourneyResultList = new JourneyResultList();

    QBuffer *filebuffer = new QBuffer();
    filebuffer->setData(networkReply->readAll());

    QRegExp regexp = QRegExp("<div class=\"midcolumn3\">(.*)</div>(.*)</div>(.*)<div id=\"righttools\">");
    regexp.setMinimal(true);

    regexp.indexIn(filebuffer->buffer());

    QString element = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">\n<body>\n" + regexp.cap(0) + "\n</div></body>\n</html>\n";

    QRegExp imgReg = QRegExp("icon_(.*)_s.gif\" />");
    imgReg.setMinimal(true);
    element.replace(imgReg, "icon_" + QString("\\1") + "_s.gif\" />" + QString("\\1"));
    element.replace("am+", "am");
    element.replace("pm+", "pm");

    //qDebug()<<element;

    QBuffer readBuffer;
    readBuffer.setData(element.toAscii());
    readBuffer.open(QIODevice::ReadOnly);

    QXmlQuery query;
    query.bindVariable("path", &readBuffer);
    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header2']/string()");

    QStringList departResult;
    if (!query.evaluateTo(&departResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 1 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header3']/string()");

    QStringList arriveResult;
    if (!query.evaluateTo(&arriveResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 2 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header4']/string()");

    QStringList timeResult;
    if (!query.evaluateTo(&timeResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 3 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header5']/string()");

    QStringList trainResult;
    if (!query.evaluateTo(&trainResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 4 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/div/string()");

    QStringList headerResult;
    if (!query.evaluateTo(&headerResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 5 Failed";
    }

    for (int i = 0; i < headerResult.count(); i++) {
        QRegExp regexp = QRegExp("(From:|To:|When:)(.*)$");
        regexp.setMinimal(true);
        regexp.indexIn(headerResult[i].trimmed());
        if (regexp.cap(1) == "From:") {
            lastJourneyResultList->setDepartureStation(regexp.cap(2).trimmed());
        }
        if (regexp.cap(1) == "To:") {
            lastJourneyResultList->setArrivalStation(regexp.cap(2).trimmed());
        }
        if (regexp.cap(1) == "When:") {
            lastJourneyResultList->setTimeInfo(regexp.cap(2).trimmed());
        }
    }

    QRegExp regexp2 = QRegExp("(.*), (\\d\\d) (.*) (\\d\\d\\d\\d)");
    regexp2.setMinimal(true);
    regexp2.indexIn(lastJourneyResultList->timeInfo().trimmed());
    QLocale enLocale = QLocale(QLocale::English, QLocale::UnitedStates);
    int month = 1;
    for (month = 1; month < 10; month++) {
        if (regexp2.cap(3).trimmed() == enLocale.standaloneMonthName(month)) {
            break;
        }
    }

    QDate journeydate = QDate::fromString(regexp2.cap(2).trimmed() + " " + QString::number(month) + " " + regexp2.cap(4).trimmed(), "dd M yyyy");

    //Generate Details search results

    QStringList detailsResult;

    regexp = QRegExp("<table class=\"dataTbl widthcol2and3\" cellspacing=\"0\" style=\"margin:0px ! important;border-right:0px none;\" summary=\"Search Results Details\">(.*)</table>");
    regexp.setMinimal(true);
    int pos = 0;

    while ((pos = regexp.indexIn(filebuffer->buffer(), pos)) != -1) {
        QString element = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">\n<body><table>\n" + regexp.cap(1) + "\n</table></body>\n</html>\n";
        element.replace("&nbsp;", " ");
        element.replace("bulletin.gif\">", "bulletin.gif\" />");

        QBuffer readBuffer;
        readBuffer.setData(element.toAscii());
        readBuffer.open(QIODevice::ReadOnly);

        QXmlQuery query;
        query.bindVariable("path", &readBuffer);

        query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/table/tbody/tr/td[@headers='header2']/string()");

        QStringList detailsContentResult;
        if (!query.evaluateTo(&detailsContentResult))
        {
            qDebug() << "parser131500ComAu::getJourneyData - DetailsQuery 1 Failed";
        }

        detailsResult << detailsContentResult.join("<linesep>");

        pos += regexp.matchedLength();
    }

    //qDebug()<<departResult;

    //Create search result
    for (int i = 0; i < departResult.count(); i++) {

        //Parse transporttypes and changes
        QString tmp = trainResult[i].trimmed();
        tmp.replace("\t", " ");
        tmp.replace("\n", " ");
        tmp.replace("\r", " ");
        QStringList trains = tmp.split(" ", QString::SkipEmptyParts);
        int changes = trains.length() - 1;
        trains.removeDuplicates();

        //Parse travel time
        tmp = timeResult[i].trimmed();
        tmp.replace("mins", "");
        tmp.replace("min", "");
        tmp.replace("hrs ", ":");
        tmp.replace("hr ", ":");
        QStringList durationLst = tmp.split(":", QString::SkipEmptyParts);

        QString durationStr = "";
        if (durationLst.length() == 1) {
            durationStr.sprintf("00: %02d", durationLst[0].toInt());
        }
        if (durationLst.length() == 2) {
            durationStr.sprintf("%02d:%02d", durationLst[0].toInt(), durationLst[1].toInt());
        }

        JourneyResultItem *item = new JourneyResultItem();
        item->setDate(journeydate);
        item->setId(QString::number(i));
        item->setTransfers(QString::number(changes));
        item->setDuration(durationStr);
        item->setTrainType(trains.join(", "));
        item->setDepartureTime(QTime::fromString(departResult[i].trimmed(), "h:map").toString("hh:mm"));
        item->setArrivalTime(QTime::fromString(arriveResult[i].trimmed(), "h:map").toString("hh:mm"));
        item->setInternalData1(detailsResult[i]);

        lastJourneyResultList->appendItem(item);
    }

    emit journeyResult(lastJourneyResultList);
}
Example #14
0
static bool addFontToDatabase(QString familyName, const QString &scriptName,
                              const TEXTMETRIC *textmetric,
                              const FONTSIGNATURE *signature,
                              int type)
{
    // the "@family" fonts are just the same as "family". Ignore them.
    if (familyName.at(0) == QLatin1Char('@') || familyName.startsWith(QStringLiteral("WST_")))
        return false;

    const int separatorPos = familyName.indexOf("::");
    const QString faceName =
            separatorPos != -1 ? familyName.left(separatorPos) : familyName;
    const QString fullName =
            separatorPos != -1 ? familyName.mid(separatorPos + 2) : QString();
    static const int SMOOTH_SCALABLE = 0xffff;
    const QString foundryName; // No such concept.
    const NEWTEXTMETRIC *tm = (NEWTEXTMETRIC *)textmetric;
    const bool fixed = !(tm->tmPitchAndFamily & TMPF_FIXED_PITCH);
    const bool ttf = (tm->tmPitchAndFamily & TMPF_TRUETYPE);
    const bool scalable = tm->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE);
    const int size = scalable ? SMOOTH_SCALABLE : tm->tmHeight;
    const QFont::Style style = tm->tmItalic ? QFont::StyleItalic : QFont::StyleNormal;
    const bool antialias = false;
    const QFont::Weight weight = weightFromInteger(tm->tmWeight);
    const QFont::Stretch stretch = QFont::Unstretched;

    if (QWindowsContext::verboseFonts > 2) {
        QDebug nospace = qDebug().nospace();
        nospace << __FUNCTION__ << faceName << fullName << scriptName
                 << "TTF=" << ttf;
        if (type & DEVICE_FONTTYPE)
            nospace << " DEVICE";
        if (type & RASTER_FONTTYPE)
            nospace << " RASTER";
        if (type & TRUETYPE_FONTTYPE)
            nospace << " TRUETYPE";
        nospace << " scalable=" << scalable << " Size=" << size
                << " Style=" << style << " Weight=" << weight
                << " stretch=" << stretch;
    }

/* Fixme: omitted for the moment
    if(ttf && localizedName(faceName) && family->english_name.isEmpty())
        family->english_name = getEnglishName(faceName);
*/
    QSupportedWritingSystems writingSystems;
    if (type & TRUETYPE_FONTTYPE) {
        quint32 unicodeRange[4] = {
            signature->fsUsb[0], signature->fsUsb[1],
            signature->fsUsb[2], signature->fsUsb[3]
        };
        quint32 codePageRange[2] = {
            signature->fsCsb[0], signature->fsCsb[1]
        };
        writingSystems = QBasicFontDatabase::determineWritingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
        // ### Hack to work around problem with Thai text on Windows 7. Segoe UI contains
        // the symbol for Baht, and Windows thus reports that it supports the Thai script.
        // Since it's the default UI font on this platform, most widgets will be unable to
        // display Thai text by default. As a temporary work around, we special case Segoe UI
        // and remove the Thai script from its list of supported writing systems.
        if (writingSystems.supported(QFontDatabase::Thai) &&
                faceName == QStringLiteral("Segoe UI"))
            writingSystems.setSupported(QFontDatabase::Thai, false);
    } else {
        const QFontDatabase::WritingSystem ws = writingSystemFromScript(scriptName);
        if (ws != QFontDatabase::Any)
            writingSystems.setSupported(ws);
    }

    const QSettings fontRegistry("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts",
                                QSettings::NativeFormat);

    QByteArray value;
    int index = 0;
    foreach (const QString &key, fontRegistry.allKeys()) {
        QString realKey = key;
        realKey = realKey.replace("(TrueType)", "");
        realKey = realKey.trimmed();
        QStringList fonts = realKey.split('&');
        for (int i = 0; i < fonts.length(); ++i) {
            const QString font = fonts[i].trimmed();
            if (font == faceName || (faceName != fullName && fullName == font)) {
                value = fontRegistry.value(key).toByteArray();
                index = i;
                break;
            }
        }
        if (!value.isEmpty())
            break;
    }

    if (value.isEmpty())
        return false;

    if (!QDir::isAbsolutePath(value))
        value = qgetenv("windir") + "\\Fonts\\" + value;

    // Pointer is deleted in QBasicFontDatabase::releaseHandle(void *handle)
    FontFile *fontFile = new FontFile;
    fontFile->fileName = value;
    fontFile->indexValue = index;

    QPlatformFontDatabase::registerFont(faceName, foundryName, weight,
                                        style, stretch, antialias, scalable, size, fixed, writingSystems, fontFile);
    // add fonts windows can generate for us:
    if (weight <= QFont::DemiBold)
        QPlatformFontDatabase::registerFont(faceName, foundryName, QFont::Bold,
                                            style, stretch, antialias, scalable, size, fixed, writingSystems, fontFile);
    if (style != QFont::StyleItalic)
        QPlatformFontDatabase::registerFont(faceName, foundryName, weight,
                                            QFont::StyleItalic, stretch, antialias, scalable, size, fixed, writingSystems, fontFile);
    if (weight <= QFont::DemiBold && style != QFont::StyleItalic)
        QPlatformFontDatabase::registerFont(faceName, foundryName, QFont::Bold,
                                            QFont::StyleItalic, stretch, antialias, scalable, size, fixed, writingSystems, fontFile);
    return true;
}
Example #15
0
TextPalette::TextPalette(QWidget* parent)
   : QWidget(parent)
      {
      setWindowFlags(Qt::Tool);
      setupUi(this);

      pCommon = new Palette;
      pCommon->setMag(0.8);
      pCommon->setGrid(33, 60);
      pCommon->setReadOnly(true);

      pSmufl = new Palette;
      pSmufl->setMag(0.8);
      pSmufl->setGrid(33, 60);
      pSmufl->setReadOnly(true);

      pUnicode = new Palette;
      pUnicode->setMag(0.8);
      pUnicode->setGrid(33, 60);
      pUnicode->setReadOnly(true);

      PaletteScrollArea* psa = new PaletteScrollArea(pCommon);
      psa->setRestrictHeight(false);

      tabWidget->clear();
      tabWidget->addTab(psa, tr("Common Symbols"));

      psa = new PaletteScrollArea(pSmufl);
      psa->setRestrictHeight(false);

      QSplitter* ws = new QSplitter;
      lws = new QListWidget;

      ScoreFont* scoreFont = ScoreFont::fontFactory("Bravura");
      QFile fi(scoreFont->fontPath() + "ranges.json");
      if (!fi.open(QIODevice::ReadOnly))
            qDebug("ScoreFont: open ranges file <%s> failed", qPrintable(fi.fileName()));
      QJsonParseError error;
      QJsonObject o = QJsonDocument::fromJson(fi.readAll(), &error).object();
      if (error.error != QJsonParseError::NoError)
            qDebug("Json parse error in <%s>(offset: %d): %s", qPrintable(fi.fileName()),
               error.offset, qPrintable(error.errorString()));
	int i = 0;
      QStringList smuflRangeNames;
      for (auto s : o.keys()) {
            QJsonObject range = o.value(s).toObject();
            QString desc = range.value("description").toString();
            QJsonArray glyphs = range.value("glyphs").toArray();
            if (glyphs.size() > 0) {
                  for (QJsonValue g : glyphs)
                        smuflMap[i].append(g.toString());
                  smuflRangeNames.append(desc);
                  i++;
                  }
            }

      lws->addItems(smuflRangeNames);
      lws->setCurrentRow(0);

      ws->addWidget(lws);
      ws->addWidget(psa);

      tabWidget->addTab(ws, tr("Musical Symbols"));

      psa = new PaletteScrollArea(pUnicode);
      psa->setRestrictHeight(false);

      QSplitter* wu = new QSplitter;
      lwu = new QListWidget;
      lwu->setSortingEnabled(true);
      for (i = 0; i < unicodeRangeNames.length(); i++) {
            QListWidgetItem* newItem = new QListWidgetItem(qApp->translate("accidental", unicodeRangeNames.at(i).toUtf8().constData()));
            newItem->setData(Qt::UserRole, i);
            lwu->addItem(newItem);
            if (i == 0)
                  lwu->setCurrentItem(newItem);
            }

      wu->addWidget(lwu);
      wu->addWidget(psa);

      tabWidget->addTab(wu, tr("Unicode Symbols"));

      connect(lws, SIGNAL(currentRowChanged(int)), SLOT(populateSmufl()));
      connect(lwu, SIGNAL(currentRowChanged(int)), SLOT(populateUnicode()));

	// others are done in setFont
      populateSmufl();

      setFocusPolicy(Qt::NoFocus);
      }
Example #16
0
bool Phantom::execute()
{
    if (m_terminated)
        return false;

#ifndef QT_NO_DEBUG_OUTPUT
    qDebug() << "Phantom - execute: Configuration";
    const QMetaObject* configMetaObj = m_config.metaObject();
    for (int i = 0, ilen = configMetaObj->propertyCount(); i < ilen; ++i) {
        qDebug() << "    " << i << configMetaObj->property(i).name() << ":" << m_config.property(configMetaObj->property(i).name()).toString();
    }

    qDebug() << "Phantom - execute: Script & Arguments";
    qDebug() << "    " << "script:" << m_config.scriptFile();
    QStringList args = m_config.scriptArgs();
    for (int i = 0, ilen = args.length(); i < ilen; ++i) {
        qDebug() << "    " << i << "arg:" << args.at(i);
    }
#endif

    if (m_config.isWebdriverMode()) {                                   // Remote WebDriver mode requested
        qDebug() << "Phantom - execute: Starting Remote WebDriver mode";

        Terminal::instance()->cout("PhantomJS is launching GhostDriver...");
        if (!Utils::injectJsInFrame(":/ghostdriver/main.js", QString(), m_scriptFileEnc, QDir::currentPath(), m_page->mainFrame(), true)) {
            m_returnValue = -1;
            return false;
        }
    } else if (m_config.scriptFile().isEmpty()) {                       // REPL mode requested
        qDebug() << "Phantom - execute: Starting REPL mode";

        // REPL is only valid for javascript
        const QString &scriptLanguage = m_config.scriptLanguage();
        if (scriptLanguage != "javascript" && !scriptLanguage.isNull()) {
            QString errMessage = QString("Unsupported language: %1").arg(scriptLanguage);
            Terminal::instance()->cerr(errMessage);
            qWarning("%s", qPrintable(errMessage));
            return false;
        }

        // Create the REPL: it will launch itself, no need to store this variable.
        REPL::getInstance(m_page->mainFrame(), this);
    } else {                                                            // Load the User Script
        qDebug() << "Phantom - execute: Starting normal mode";

        if (m_config.debug()) {
            // Debug enabled
            if (!Utils::loadJSForDebug(m_config.scriptFile(), m_config.scriptLanguage(), m_scriptFileEnc, QDir::currentPath(), m_page->mainFrame(), m_config.remoteDebugAutorun())) {
                m_returnValue = -1;
                return false;
            }
            m_page->showInspector(m_config.remoteDebugPort());
        } else {
            if (!Utils::injectJsInFrame(m_config.scriptFile(), m_config.scriptLanguage(), m_scriptFileEnc, QDir::currentPath(), m_page->mainFrame(), true)) {
                m_returnValue = -1;
                return false;
            }
        }
    }

    return !m_terminated;
}
Example #17
0
void VtkVisPointSetItem::Initialize(vtkRenderer* renderer)
{
    // TODO vtkTransformFilter creates a new copy of the point coordinates which
    // conflicts with VtkMappedMeshSource. Find a workaround!
    _transformFilter = vtkTransformFilter::New();
    vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
    transform->Identity();
    _transformFilter->SetTransform(transform);

    _transformFilter->SetInputConnection(_algorithm->GetOutputPort());
    _transformFilter->Update();

    _renderer = renderer;
    _mapper = QVtkDataSetMapper::New();
    _mapper->InterpolateScalarsBeforeMappingOff();
    _mapper->SetColorModeToMapScalars();

    _mapper->SetInputConnection(_transformFilter->GetOutputPort());
    _actor = vtkActor::New();
    static_cast<vtkActor*>(_actor)->SetMapper(_mapper);
    _renderer->AddActor(_actor);

    // Determine the right pre-set properties
    // Order is: _algorithm, _compositeFilter, create a new one with props copied from parent
    VtkAlgorithmProperties* vtkProps = dynamic_cast<VtkAlgorithmProperties*>(_algorithm);
    if (!vtkProps)
    {
        vtkProps = dynamic_cast<VtkAlgorithmProperties*>(_compositeFilter);

        // Copy properties from parent or create a new VtkAlgorithmProperties
        if (!vtkProps)
        {
            VtkVisPipelineItem* parentItem = dynamic_cast<VtkVisPipelineItem*>(this->parentItem());
            while (parentItem)
            {
                VtkAlgorithmProperties* parentProps = nullptr;
                if(dynamic_cast<VtkVisPointSetItem*>(parentItem))
                    parentProps = dynamic_cast<VtkVisPointSetItem*>(parentItem)->getVtkProperties();
                if (parentProps)
                {
                    vtkProps = new VtkAlgorithmProperties(); // TODO memory leak?
                    vtkProps->SetScalarVisibility(parentProps->GetScalarVisibility());
                    vtkProps->SetTexture(parentProps->GetTexture());
                    vtkProps->SetActiveAttribute(parentProps->GetActiveAttribute());
                    parentItem = nullptr;
                }
                else
                    parentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem->parentItem());
            }

            // Has no parents
            if (!vtkProps)
                vtkProps = new VtkAlgorithmProperties(); // TODO memory leak?
        }
    }
    _vtkProps = vtkProps;

    if (vtkProps->GetActiveAttribute().length() == 0)
    {
        // Get first scalar and set it to active
        QStringList arrayNames = this->getScalarArrayNames();
        if (arrayNames.length() > 0)
            vtkProps->SetActiveAttribute(arrayNames[0]);
        else
            vtkProps->SetActiveAttribute("Solid Color");
    }
    this->setVtkProperties(vtkProps);
    this->SetActiveAttribute(vtkProps->GetActiveAttribute());


    // Set global backface culling
    QSettings settings;
    bool backfaceCulling = settings.value("globalCullBackfaces", 0).toBool();
    this->setBackfaceCulling(backfaceCulling);

    // Set the correct threshold range
    if (dynamic_cast<VtkCompositeThresholdFilter*>(this->_compositeFilter) )
    {
        double range[2];
        this->GetRangeForActiveAttribute(range);
        QList<QVariant> thresholdRangeList;
        thresholdRangeList.push_back(range[0]);
        thresholdRangeList.push_back(range[1]);
        dynamic_cast<VtkCompositeFilter*>(this->_compositeFilter)
            ->SetUserVectorProperty("Range", thresholdRangeList);
    }

    // Show edges on meshes
    if (dynamic_cast<MeshLib::VtkMappedMeshSource*>(this->_algorithm))
        _vtkProps->GetProperties()->SetEdgeVisibility(1);
}
Example #18
0
/**
 * process data string from flight simulator
 */
void IL2Simulator::processUpdate(const QByteArray& inp)
{
    // save old flight data to calculate delta's later
    old=current;
    QString data(inp);
    // Split
    QStringList fields = data.split("/");

    // split up response string
    int t;
    for (t=0; t<fields.length(); t++) {
        QStringList values = fields[t].split("\\");
        // parse values
        if (values.length()>=2) {
            int id = values[0].toInt();
            float value = values[1].toFloat();
            switch (id) {
            case 30:
                current.cas=value * KM_PER_HOUR2METERS_PER_SECOND;
                break;
            case 32:
                current.dZ=value;
                break;
            case 40:
                current.Z=value;
                break;
            case 42:
                current.azimuth=value;
                break;
            case 46:
                current.roll=-value;
                break;
            case 48:
                current.pitch=value;
                break;
            }
        }
    }

    // measure time
    current.dT = ((float)time->restart()) / 1000.0;
    if (current.dT<0.001)  current.dT=0.001;
    current.T = old.T+current.dT;
    current.i = old.i+1;
    if (current.i==1) {
        old.dRoll=0;
        old.dPitch=0;
        old.dAzimuth=0;
        old.ddX=0;
        old.ddX=0;
        old.ddX=0;
    }

    // calculate TAS from alt and CAS
    current.tas = cas2tas(current.cas, current.Z, airParameters, GRAVITY);

    // assume the plane actually flies straight and no wind
    // groundspeed is horizontal vector of TAS
    current.groundspeed = current.tas*cos(current.pitch*DEG2RAD);
    // x and y vector components
    current.dX = current.groundspeed*sin(current.azimuth*DEG2RAD);
    current.dY = current.groundspeed*cos(current.azimuth*DEG2RAD);

    // simple IMS - integration over time the easy way...
    current.X = old.X + (current.dX*current.dT);
    current.Y = old.Y + (current.dY*current.dT);

    // accelerations (filtered)
    if (isnan(old.ddX) || isinf(old.ddX)) old.ddX=0;
    if (isnan(old.ddY) || isinf(old.ddY)) old.ddY=0;
    if (isnan(old.ddZ) || isinf(old.ddZ)) old.ddZ=0;
#define SPEED_FILTER 10
    current.ddX = ((current.dX-old.dX)/current.dT + SPEED_FILTER * (old.ddX)) / (SPEED_FILTER+1);
    current.ddY = ((current.dY-old.dY)/current.dT + SPEED_FILTER * (old.ddY)) / (SPEED_FILTER+1);
    current.ddZ = ((current.dZ-old.dZ)/current.dT + SPEED_FILTER * (old.ddZ)) / (SPEED_FILTER+1);

#define TURN_FILTER 10
    // turn speeds (filtered)
    if (isnan(old.dAzimuth) || isinf(old.dAzimuth)) old.dAzimuth=0;
    if (isnan(old.dPitch) || isinf(old.dPitch)) old.dPitch=0;
    if (isnan(old.dRoll) || isinf(old.dRoll)) old.dRoll=0;
    current.dAzimuth = (angleDifference(current.azimuth,old.azimuth)/current.dT + TURN_FILTER * (old.dAzimuth)) / (TURN_FILTER+1);
    current.dPitch   = (angleDifference(current.pitch,old.pitch)/current.dT     + TURN_FILTER * (old.dPitch))   / (TURN_FILTER+1);
    current.dRoll    = (angleDifference(current.roll,old.roll)/current.dT       + TURN_FILTER * (old.dRoll))    / (TURN_FILTER+1);

    ///////
    // Output formatting
    ///////
    Output2Hardware out;
    memset(&out, 0, sizeof(Output2Hardware));

    // Compute rotation matrix, for later calculations
    float Rbe[3][3];
    float rpy[3];
    float quat[4];
    rpy[0]=current.roll;
    rpy[1]=current.pitch;
    rpy[2]=current.azimuth;
    Utils::CoordinateConversions().RPY2Quaternion(rpy,quat);
    Utils::CoordinateConversions().Quaternion2R(quat,Rbe);

    // Update GPS Position objects, convertin from the current NED position
    // to LLA
    double HomeLLA[3];
    double LLA[3];
    double NED[3];
    HomeLLA[0]=settings.latitude.toFloat();
    HomeLLA[1]=settings.longitude.toFloat();
    HomeLLA[2]=0;
    NED[0] = current.Y;
    NED[1] = current.X;
    NED[2] = -current.Z;
    Utils::CoordinateConversions().NED2LLA_HomeLLA(HomeLLA, NED, LLA);
    out.latitude = LLA[0];
    out.longitude = LLA[1];
    out.groundspeed = current.groundspeed;

    out.calibratedAirspeed = current.cas;
    out.trueAirspeed=cas2tas(current.cas, current.Z, airParameters, GRAVITY);

    out.dstN=current.Y;
    out.dstE=current.X;
    out.dstD=-current.Z;

    // Update BaroAltitude object
    out.altitude = current.Z;
    out.agl = current.Z;
    out.temperature = airParameters.groundTemp + (current.Z * airParameters.tempLapseRate) - 273.0;
    out.pressure = airPressureFromAltitude(current.Z, airParameters, GRAVITY) ; // kpa


    // Update attActual object
    out.roll = current.roll;   //roll;
    out.pitch = current.pitch;  // pitch
    out.heading = current.azimuth; // yaw


    // Update VelocityActual.{North,East,Down}
    out.velNorth = current.dY;
    out.velEast = current.dX;
    out.velDown = -current.dZ;

    // rotate turn rates and accelerations into body frame
    // (note: rotation deltas are NOT in NED frame but in RPY - manual conversion!)
    out.rollRate = current.dRoll;
    out.pitchRate = cos(DEG2RAD * current.roll) * current.dPitch + sin(DEG2RAD * current.roll) * current.dAzimuth;
    out.yawRate = cos(DEG2RAD * current.roll) * current.dAzimuth - sin(DEG2RAD * current.roll) * current.dPitch;

    //Update accelerometer sensor data
    out.accX = current.ddX*Rbe[0][0]
            +current.ddY*Rbe[0][1]
            +(current.ddZ+GRAVITY)*Rbe[0][2];
    out.accY = current.ddX*Rbe[1][0]
            +current.ddY*Rbe[1][1]
            +(current.ddZ+GRAVITY)*Rbe[1][2];
    out.accZ = - (current.ddX*Rbe[2][0]
                     +current.ddY*Rbe[2][1]
                     +(current.ddZ+GRAVITY)*Rbe[2][2]);

    updateUAVOs(out);
}
Example #19
0
void PluginManager::loadAllPlugins(EnvisionManager& envisionManager)
{
	int lastCountLoaded = -1;

	// Holds the ids of plugins which are not yet loaded.
	QStringList plugins;
	for (auto p_meta : pluginMetaData)
		plugins.append(p_meta.id);

	QTextStream out(stdout);

	while ( lastCountLoaded != loadedPlugins.length() && loadedPlugins.length() < pluginMetaData.length() )
	{
		lastCountLoaded = loadedPlugins.length();

		for (int i = plugins.length() - 1; i >= 0; i--)
		{
			QList<PluginDependency> depList = idToMetaDataMap.value(plugins.at(i))->dependencies;

			bool allDependenciesLoaded = true;
			for (QList<PluginDependency>::iterator dep = depList.begin(); dep != depList.end(); dep++)
			{
				// Check if this dependency is already loaded
				if ( idToPluginLoaderMap.contains(dep->id) == false )
				{
					allDependenciesLoaded = false;
					break;
				}

				// Check if the version of the non-dependent plugin matches the version the current plugin depends on
				if ( !idToMetaDataMap.value(dep->id)->version.startsWith(dep->majorVersion + ".", Qt::CaseSensitive) )
					throw EnvisionException("Plugin " + plugins.at(i) + " depends on version " + dep->majorVersion
							+ " of " + dep->id + " but a different version is installed.");
			}

			if ( allDependenciesLoaded )
			{
				out << "Loading plug-in " << plugins.at(i) << "... " << endl;

				QPluginLoader* plugin = new QPluginLoader(pluginsDir.absoluteFilePath(getLibraryFileName(plugins.at(i))));
				plugin->setLoadHints(QLibrary::ExportExternalSymbolsHint);

				plugin->load();

				if ( plugin->isLoaded() == false )
					throw EnvisionException("Could not load plugin: " + plugin->errorString());

				EnvisionPlugin* p = qobject_cast<EnvisionPlugin*> (plugin->instance());
				p->initialize(envisionManager);

				out << plugins.at(i) << " loaded OK" << endl;

				loadedPlugins.append(plugin);
				idToPluginLoaderMap.insert(plugins.at(i), plugin);
				plugins.removeAt(i);
			}
		}
	}

	// Check if there are any plug-ins with unmet dependencies
	if (plugins.size() > 0)
	{
		out<< "Warning: The following plug-ins have not been loaded because their dependencies are not satisfied" << endl;
		for (int i = 0; i< plugins.size(); ++i) out << "  " << plugins.at(i) << endl;
	}
	else out << "All plug-ins loaded." << endl;
}
Example #20
0
bool WebSocketWorker::ProcessHandshake(QTcpSocket *socket)
{
    QByteArray line;

    // Minimum length of the request line is 16
    // i.e. "GET / HTTP/1.1\r\n"
    while (socket->bytesAvailable() < 16)
    {
        if (!socket->waitForReadyRead(5000)) // 5 second timeout
            return false;
    }

    // Set a maximum length for a request line of 255 bytes, it's an
    // arbitrary limit but a reasonable one for now
    line = socket->readLine(255).trimmed(); // Strip newline
    if (line.isEmpty())
        return false;

    QStringList tokens = QString(line).split(' ', QString::SkipEmptyParts);

    if (tokens.length() != 3) // Anything but 3 is invalid - {METHOD} {HOST/PATH} {PROTOCOL}
    {
        LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Invalid number of tokens in Request line");
        return false;
    }

    if (tokens[0] != "GET") // RFC 6455 - Request method MUST be GET
    {
        LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Invalid method: %1").arg(tokens[0]));
        return false;
    }

    QString path = tokens[1];

    if (path.contains('#')) // RFC 6455 - Fragments MUST NOT be used
    {
        LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Path contains illegal fragment");
        return false;
    }

    if (!tokens[2].startsWith("HTTP/")) // Must be HTTP
    {
        LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Invalid protocol: %1").arg(tokens[2]));
        return false;
    }

    QString versionStr = tokens[2].section('/', 1, 1);

    int majorVersion = versionStr.section('.', 0, 0).toInt();
    int minorVersion = versionStr.section('.', 1, 1).toInt();

    if ((majorVersion < 1) || (minorVersion < 1)) // RFC 6455 - HTTP version MUST be at least 1.1
    {
        LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Invalid HTTP version: %1.%2").arg(majorVersion).arg(minorVersion));
        return false;
    }

    // Read Header
    line = socket->readLine(2000).trimmed(); // 2KB Maximum

    QMap<QString, QString> requestHeaders;
    while (!line.isEmpty())
    {
        QString strLine = QString(line);
        QString sName  = strLine.section( ':', 0, 0 ).trimmed();
        QString sValue = strLine.section( ':', 1 ).trimmed();
        sValue.replace(" ",""); // Remove all internal whitespace

        if (!sName.isEmpty() && !sValue.isEmpty())
            requestHeaders.insert(sName.toLower(), sValue);

        line = socket->readLine(2000).trimmed(); // 2KB Maximum
    }

    // Dump request header
    QMap<QString, QString>::iterator it;
    for ( it = requestHeaders.begin();
          it != requestHeaders.end();
          ++it )
    {
        LOG(VB_HTTP, LOG_INFO, QString("(Request Header) %1: %2")
                                        .arg(it.key()).arg(*it));
    }

    if (!requestHeaders.contains("connection")) // RFC 6455 - 1.3. Opening Handshake
    {
        LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing 'Connection' header");
        return false;
    }

    QStringList connectionValues = requestHeaders["connection"].split(',', QString::SkipEmptyParts);
    if (!connectionValues.contains("Upgrade", Qt::CaseInsensitive)) // RFC 6455 - 1.3. Opening Handshake
    {
        LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Invalid 'Connection' header");
        return false;
    }

    if (!requestHeaders.contains("upgrade") ||
        requestHeaders["upgrade"].toLower() != "websocket") // RFC 6455 - 1.3. Opening Handshake
    {
        LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing or invalid 'Upgrade' header");
        return false;
    }

    if (!requestHeaders.contains("sec-websocket-version")) // RFC 6455 - 1.3. Opening Handshake
    {
        LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing 'Sec-WebSocket-Version' header");
        return false;
    }

    if (requestHeaders["sec-websocket-version"] != "13") // RFC 6455 - 1.3. Opening Handshake
    {
        LOG(VB_GENERAL, LOG_ERR, QString("WebSocketWorker::ProcessHandshake() - Unsupported WebSocket protocol "
                                      "version. We speak '13' the client speaks '%1'")
                                            .arg(requestHeaders["sec-websocket-version"]));
        return false;
    }

    if (!requestHeaders.contains("sec-websocket-key") ||
        QByteArray::fromBase64(requestHeaders["sec-websocket-key"].toLatin1()).length() != 16) // RFC 6455 - 1.3. Opening Handshake
    {
        LOG(VB_GENERAL, LOG_ERR, "WebSocketWorker::ProcessHandshake() - Missing or invalid 'sec-websocket-key' header");
        return false;
    }

    // If we're running the Autobahn fuzz/unit tester then we need to disable
    // the heartbeat and 'echo' text/binary frames back to the sender
    if (requestHeaders.contains("user-agent") &&
        requestHeaders["user-agent"].contains("AutobahnTestSuite"))
        m_fuzzTesting = true;

    QString key = requestHeaders["sec-websocket-key"];
    const QString magicString = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    // Response token - Watch very closely, there's a lot happening here
    QString acceptToken = QCryptographicHash::hash(key.append(magicString).toUtf8(),
                                                   QCryptographicHash::Sha1).toBase64();

    QMap<QString, QString> responseHeaders;
    responseHeaders.insert("Connection", "Upgrade");
    responseHeaders.insert("Upgrade", "websocket");
    responseHeaders.insert("Sec-WebSocket-Accept", acceptToken);

    socket->write("HTTP/1.1 101 Switching Protocols\r\n");

    QString header("%1: %2\r\n");
    for (it = responseHeaders.begin(); it != responseHeaders.end(); ++it)
    {
        socket->write(header.arg(it.key()).arg(*it).toLatin1().constData());
        LOG(VB_HTTP, LOG_INFO, QString("(Response Header) %1: %2")
                                        .arg(it.key()).arg(*it));
    }

    socket->write("\r\n");
    socket->waitForBytesWritten();

    m_webSocketMode = true;
    // Start the heart beat
    if (!m_fuzzTesting)
        m_heartBeat->start();

    return true;
}
Example #21
0
bool ApplicationList::LoadSettings()
{
    QSettings settings;
    QStringList names = settings.value(SETTINGS_APPLICATION_NAMES, QStringList()).toStringList();
    QStringList paths = settings.value(SETTINGS_APPLICATION_PATHS, QStringList()).toStringList();
    QStringList params = settings.value(SETTINGS_APPLICATION_PARAMS, QStringList()).toStringList();
    int defapp = settings.value(SETTINGS_APPLICATION_DEFAULT, -1).toInt();

    // Params will be empty first time starting with the new setting.
    // Return false and inform user about problem with application settings.
    bool succeeded = true;
    if (!names.empty() && !paths.empty() && params.empty()) {
        for (int i = 0; i < paths.length(); i++)
            params << "";
        succeeded = false;
    }

    if (names.empty() && paths.empty() && params.empty()) {
        do {
            // use as default for gnome environments
            if (QFileInfo("/usr/bin/gedit").isExecutable()) {
                Application app;
                app.setName("gedit");
                app.setPath("/usr/bin/gedit");
                app.setParameters("+(line) (file)");
                AddApplication(app);
                defapp = 0;
                break;
            }
            // use as default for kde environments
            if (QFileInfo("/usr/bin/kate").isExecutable()) {
                Application app;
                app.setName("kate");
                app.setPath("/usr/bin/kate");
                app.setParameters("-l(line) (file)");
                AddApplication(app);
                defapp = 0;
                break;
            }
            if (FindDefaultWindowsEditor()) {
                defapp = 0;
                break;
            }
        } while (0);
    }

    if (names.size() > 0 && (names.size() == paths.size())) {
        for (int i = 0; i < names.size(); i++) {
            const Application app(names[i], paths[i], params[i]);
            AddApplication(app);
        }

        if (defapp == -1)
            mDefaultApplicationIndex = 0;
        else if (defapp < names.size())
            mDefaultApplicationIndex = defapp;
        else
            mDefaultApplicationIndex = 0;
    }
    return succeeded;
}
Example #22
0
void MainWindow::showDetails(QModelIndex index)
{
    QStringList listAttr;
    index = index.sibling(index.row(), 0);

    nodeName = model->itemFromIndex(index)->text();
    currentIndex = index;
    buttonAddParam->show();
    buttonInsert->show();

    signalMapper = new QSignalMapper(this);

    //Clear formLayout to remove the parameter related to the last element selected
    clearFormLayout();

    label->setText("Edit " + nodeName);
    if(nodeName.compare(root) != 0)
    {
        //Store the list of attribute for the selected element
        for(int i = 1; i < model->itemFromIndex(index)->parent()->columnCount(); i++)
        {
            index = index.sibling(index.row(), i);
            if(i == 1)
            {
                listAttr.append("TextNode");
                listAttr.append(model->itemFromIndex(index)->text());
            }
            else
            {
                if(model->itemFromIndex(index)->text() != "")
                {
                    listAttr.append(model->itemFromIndex(index)->text().section(":",0,0));
                    listAttr.append(model->itemFromIndex(index)->text().section(":",1));
                }
            }
        }

        //Add all attributes in formLayout to display them and store them so we'll be able to remove them from formLayout later
        //The QHBoxLayout is used to display the name and the value of the attribute on the same line
        QHBoxLayout *horizontalLayout;
        //if(!currentDocument->elementsByTagName(nodeName).item(0).childNodes().item(0).isElement() && currentDocument->elementsByTagName(nodeName).item(0).hasChildNodes())
        if(listAttr[1] != "")
        {
            horizontalLayout = new QHBoxLayout();
            list.push_front(new QLineEdit(listAttr[1]));
            list.push_front(new QLineEdit(listAttr[0]));
            horizontalLayout->addWidget(list[0]);
            horizontalLayout->addWidget(list[1]);
            listLayout.push_front(horizontalLayout);
            formLayout->addRow(horizontalLayout);
        }


        for(int i = 2; i < listAttr.length(); i+=2)
        {
            horizontalLayout = new QHBoxLayout();
            list.push_front(new QLineEdit(listAttr[i+1]));
            list.push_front(new QLineEdit(listAttr[i]));
            listButton.push_front(new QPushButton("-"));
            horizontalLayout->addWidget(list[0]);
            horizontalLayout->addWidget(list[1]);
            QObject::connect(listButton[0], SIGNAL(clicked()), signalMapper, SLOT(map()));
            signalMapper->setMapping(listButton[0], listAttr[i]);
            horizontalLayout->addWidget(listButton[0]);
            listLayout.push_front(horizontalLayout);
            formLayout->addRow(horizontalLayout);
        }
        QObject::connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(deleteAttribute(QString)));
    }
}
QStringList Manager::newMove(const QString &indexString, const int &level) {
    QTextStream cout(stdout); // set cout for console debug

    QStringList array;

    cout << QDir::setCurrent("/usr/share/harbour-pocketmonsters/qml/pages/xmls/") << endl;
    QFile pokedex( indexString + ".xml");

    cout << pokedex.open(QIODevice::ReadOnly) << endl;

    QXmlStreamReader xml(&pokedex);

    QString newMoveId;

    while (!xml.atEnd() && !xml.hasError()) {

        xml.readNext();

        if ( xml.isStartElement() && xml.name().toString() == "move" &&
             xml.attributes().value("level").toString() == QString::number(level) ) {
            cout << "found :" << xml.attributes().value("id").toString() << endl;
            newMoveId = xml.attributes().value("id").toString();
        }

    }

    if (xml.hasError())
    {
        cout << "XML error: " << xml.errorString() << "line:column - " << xml.lineNumber() << ":" << xml.columnNumber() << endl;
    }
    else if (xml.atEnd())
    {
        cout << "Reached end, done" << endl;
    }

    cout << QDir::setCurrent("/usr/share/harbour-pocketmonsters/qml/pages/xmls/") << endl;

    QFile movedex( "movedex.xml");

    cout << movedex.open(QIODevice::ReadOnly) << endl;

    QXmlStreamReader xml2(&movedex);

    bool found = false;
    while (!xml2.atEnd() && !xml2.hasError()) {
        xml2.readNext();
        QXmlStreamAttributes attributes = xml2.attributes();
        QString name = xml2.name().toString();
        if ( !found && xml2.isStartElement() && name == "index" && attributes.value("id").toString() == newMoveId ) {
            array.append(attributes.value("id").toString());
            found = true;
        }
        if ( found && xml2.isEndElement() && name == "index")
            found = false;
        if ( found && xml2.isStartElement() && name != "index")
            array.append(xml2.readElementText());
    }

    if (xml2.hasError()) {
        cout << "XML error: " << xml2.errorString() << " - line:column - " << xml2.lineNumber() << ":" << xml2.columnNumber() << endl;
    } else if (xml2.atEnd()) {
        cout << "Reached end, done" << endl;
    }

    for ( int i = 0; i < array.length(); i++)
        cout << array[i] << ":";

    cout << endl;

    return array;

}
Example #24
0
void MainWindow::insert()
{
    QString attrName, attrValue;
    QStringList *listAttr = new QStringList();
    int ii = 0;
    QList<int> *indexToDelete = new QList<int>();
    bool indexToDeleteFound = false;

    //the function elementsByTagName returns a list, so to get the good index in this list we need to count how many nodes
    //have a tag different from the one which is selected
    int countDiff = 0;
    for(int i = 1; i <= treeView->currentIndex().row(); i++)
    {
        if(model->itemFromIndex(treeView->currentIndex().sibling(treeView->currentIndex().row()-i,0))->text() != model->itemFromIndex(treeView->currentIndex().sibling(treeView->currentIndex().row(),0))->text())
        {
            countDiff++;
        }
    }

    for(int i = 0; i < currentDocument->elementsByTagName(nodeName).item(treeView->currentIndex().row() - countDiff).attributes().length(); i++)
    {
        listAttr->append(currentDocument->elementsByTagName(nodeName).item(treeView->currentIndex().row() - countDiff).attributes().item(i).toAttr().name().trimmed());
    }

    //If the name of existing attributes are modified, first we need to delete them from the document and add them with their new name
    //The firsts elements in list are the ones which were added so we need to start at the first "old attribute"
    ii = (list.length()/2-listAttr->length())*2;

    //get the index of existing attributes if their name is modified
    for(int i = 0; i < listAttr->length(); i++)
    {
        while(ii < list.length() && !indexToDeleteFound)
        {
            if(((QLineEdit*)list[ii])->text().trimmed() == listAttr->at(i))
            {
                indexToDeleteFound = true;
            }
            ii += 2;
        }
        if(!indexToDeleteFound)
        {
            indexToDelete->append(i);
        }
        ii = (list.length()/2-listAttr->length())*2;;
        indexToDeleteFound = false;
    }
    //delete the attributes if their name is modified
    for(int i = 0; i < indexToDelete->length(); i++)
    {
        currentDocument->elementsByTagName(nodeName).item(treeView->currentIndex().row() - countDiff).toElement().removeAttribute(listAttr->at(indexToDelete->at(i)));
    }

    //add the attributes to the document
    for(int i = 0; i < list.length(); i += 2)
    {
        attrName = ((QLineEdit*)list[i])->text().trimmed();
        attrValue = ((QLineEdit*)list[i+1])->text().trimmed();

        currentDocument->elementsByTagName(nodeName).item(treeView->currentIndex().row() - countDiff).toElement().setAttribute(attrName, attrValue);
    }

    updateTree();
}
Example #25
0
void InputOutputPatchEditor::fillMappingTree()
{
    /* Disable check state change tracking when the tree is filled */
    disconnect(m_mapTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
               this, SLOT(slotMapItemChanged(QTreeWidgetItem*, int)));

    m_mapTree->clear();

    qDebug() << "[InputOutputPatchEditor] Fill tree for universe: " << m_universe;

    // Build a complete list of Input/Output plugins
    QStringList IOplugins = m_inputMap->pluginNames();
    foreach (QString out, m_outputMap->pluginNames())
        if (IOplugins.contains(out) == false)
            IOplugins.append(out);

    // cycle through available plugins
    foreach (QString pluginName, IOplugins)
    {
        quint32 inputId = 0;
        quint32 outputId = 0;
        QStringList inputs = m_inputMap->pluginInputs(pluginName);
        QStringList outputs = m_outputMap->pluginOutputs(pluginName);

        // 1st case: this plugin has no input or output
        if (inputs.length() == 0 && outputs.length() == 0)
        {
            QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
            pitem->setText(KMapColumnPluginName, pluginName);
            pitem->setText(KMapColumnDeviceName, KInputNone);
            pitem->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
            pitem->setText(KMapColumnOutputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
        }
        else
        {
            // 2nd case: plugin with an input and maybe an output
            for (int l = 0; l < inputs.length(); l++)
            {
                quint32 uni = m_inputMap->mapping(pluginName, inputId);
                //qDebug() << "Plugin: " << pluginName << ", input: " << id << ", universe:" << uni;
                if (uni == InputMap::invalidUniverse() || uni == m_universe)
                {
                    QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
                    pitem->setText(KMapColumnPluginName, pluginName);
                    pitem->setText(KMapColumnDeviceName, inputs.at(l));
                    pitem->setFlags(pitem->flags() | Qt::ItemIsUserCheckable);
                    if (m_currentInputPluginName == pluginName && m_currentInput == inputId)
                        pitem->setCheckState(KMapColumnHasInput, Qt::Checked);
                    else
                        pitem->setCheckState(KMapColumnHasInput, Qt::Unchecked);
                    pitem->setTextAlignment(KMapColumnHasInput, Qt::AlignHCenter);
                    pitem->setText(KMapColumnInputLine, QString("%1").arg(inputId));
                    pitem->setText(KMapColumnOutputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
                    // check if this plugin has also an output
                    if (outputs.contains(inputs.at(l)))
                    {
                        quint32 outUni = m_outputMap->mapping(pluginName, outputId);
                        if (outUni == OutputMap::invalidUniverse() || outUni == m_universe)
                        {
                            if (m_currentOutputPluginName == pluginName && m_currentOutput == outputId)
                                pitem->setCheckState(KMapColumnHasOutput, Qt::Checked);
                            else
                                pitem->setCheckState(KMapColumnHasOutput, Qt::Unchecked);
                            pitem->setText(KMapColumnOutputLine, QString("%1").arg(outputId));
                            // add feedback
                            if (pluginName == "MIDI" || pluginName == "OSC")
                            {
                                if (m_currentFeedbackPluginName == pluginName && m_currentFeedback == outputId)
                                    pitem->setCheckState(KMapColumnHasFeedback, Qt::Checked);
                                else
                                    pitem->setCheckState(KMapColumnHasFeedback, Qt::Unchecked);
                            }
                        }
                        outputId++;
                    }
                }
                inputId++;
            }
            // 3rd case: output only plugins
            for (int o = 0; o < outputs.length(); o++)
            {
                if (inputs.contains(outputs.at(o)) == false)
                {
                    quint32 outUni = m_outputMap->mapping(pluginName, outputId);
                    if (outUni == OutputMap::invalidUniverse() || outUni == m_universe)
                    {
                        //qDebug() << "Plugin: " << pluginName << ", output: " << id << ", universe:" << outUni;
                        QTreeWidgetItem* pitem = new QTreeWidgetItem(m_mapTree);
                        pitem->setText(KMapColumnPluginName, pluginName);
                        pitem->setText(KMapColumnDeviceName, outputs.at(o));
                        pitem->setFlags(pitem->flags() | Qt::ItemIsUserCheckable);
                        if (m_currentOutputPluginName == pluginName && m_currentOutput == outputId)
                            pitem->setCheckState(KMapColumnHasOutput, Qt::Checked);
                        else
                            pitem->setCheckState(KMapColumnHasOutput, Qt::Unchecked);
                        // add feedback
                        if (pluginName == "MIDI" || pluginName == "OSC")
                        {
                            if (m_currentFeedbackPluginName == pluginName && m_currentFeedback == outputId)
                                pitem->setCheckState(KMapColumnHasFeedback, Qt::Checked);
                            else
                                pitem->setCheckState(KMapColumnHasFeedback, Qt::Unchecked);
                        }
                        pitem->setText(KMapColumnOutputLine, QString("%1").arg(outputId));
                        pitem->setText(KMapColumnInputLine, QString("%1").arg(QLCIOPlugin::invalidLine()));
                    }
                    outputId++;
                }
            }
        }
    }
Example #26
0
int main(int argc, char *argv[])
{
    ///SSP/////////////////////////////////


    /////////////////////////////////////////////
    QCoreApplication a(argc, argv);

// argc=4;
// argv[1]="-ls";
// argv[2]="-t";
// argv[3]="COM3";
    if (argc > 1 || !PRIVATE) {
        bool use_serial = false;
        bool verify;
        bool debug = false;
        bool umodereset = false;
        OP_DFU::Actions action;
        QString file;
        QString serialport;
        QString description;
        int device = -1;
        QStringList args;
        for (int i = 0; i < argc; ++i) {
            args << argv[i];
        }
        if (args.contains("-debug")) {
            debug = true;
        }
        if (args.contains("-ur")) {
            umodereset = true;
        }
        if (args.contains("-?") || (!PRIVATE && argc == 1)) {
            cout << "_________________________________________________________________________\n";
            cout << "| Commands                                                               |\n";
            cout << "|                                                                        |\n";
            cout << "| -ls                  : lists available devices                         |\n";
            cout << "| -p <file>            : program hw (requires:-d - optionals:-v,-w)      |\n";
            cout << "| -v                   : verify     (requires:-d)                        |\n";
            cout << "| -dn <file>           : download firmware to file (requires:-d)         |\n";
            // cout<<"| -dd <file>           : download discription (requires:-d)         |\n";
            cout << "| -d <number Of Device : (requires: -p or -dn)                           |\n";
            cout << "| -w <description>     : (requires: -p)                                  |\n";
            cout << "| -ca <file>           : compares byte by byte current firmware with file|\n";
            cout << "| -cc <file>           : compares CRC  of current firmware with file     |\n";
            cout << "| -s                   : requests status of device                       |\n";
            cout << "| -r                   : resets the device                               |\n";
            cout << "| -j                   : exits bootloader and jumps to user FW           |\n";
            cout << "| -debug               : prints debug information                        |\n";
            cout << "| -t <port>            : uses serial port(requires:-ur)                  |\n";
            cout << "| -ur <port>           : user mode reset*                                |\n";
            cout << "|                                                                        |\n";
            cout << "| examples:                                                              |\n";
            cout << "|                                                                        |\n";
            cout << "| program and verify device #0                                           |\n";
            cout << "| OPUploadTool -p c:/OpenPilot.bin -w \"OpenPilot Firmware\" -v -d 0     |\n";
            cout << "|                                                                        |\n";
            cout << "| Perform a quick compare of FW in file with FW in device #1             |\n";
            cout << "| OPUploadTool -ch c:/OpenPilot2.bin -d 2                                |\n";
            cout << "|                                                                        |\n";
            cout << "| *requires valid user space firmwares already running                   |\n";
            cout << "|________________________________________________________________________|\n";
            return 0;
        } else if (args.contains(PROGRAMFW)) {
            if (args.contains(VERIFY)) {
                verify = true;
            } else {
                verify = false;
            }
            if (args.contains(PROGRAMDESC)) {
                if (args.indexOf(PROGRAMDESC) + 1 < args.length()) {
                    description = (args[args.indexOf(PROGRAMDESC) + 1]);
                }
            }
            action = OP_DFU::actionProgram;
            if (args.contains(DEVICE)) {
                if (args.indexOf(DEVICE) + 1 < args.length()) {
                    device = (args[args.indexOf(DEVICE) + 1]).toInt();
                }
                if (args.indexOf(PROGRAMFW) + 1 < args.length()) {
                    file = args[args.indexOf(PROGRAMFW) + 1];
                }
            } else {
                cout << ("Device not specified\n");
                return -1;
            }
        } else if (args.contains(COMPARECRC) || args.contains(COMPAREALL)) {
            int index;
            if (args.contains(COMPARECRC)) {
                index  = args.indexOf(COMPARECRC);
                action = OP_DFU::actionCompareCrc;
            } else {
                index  = args.indexOf(COMPAREALL);
                action = OP_DFU::actionCompareAll;
            }
            if (args.contains(DEVICE)) {
                if (args.indexOf(DEVICE) + 1 < args.length()) {
                    device = (args[args.indexOf(DEVICE) + 1]).toInt();
                }
                if (index + 1 < args.length()) {
                    file = args[index + 1];
                }
            } else {
                cout << "Device not specified";
                return -1;
            }
        } else if (args.contains(DOWNLOAD)) {
            int index;
            index  = args.indexOf(DOWNLOAD);
            action = OP_DFU::actionDownload;

            if (args.contains(DEVICE)) {
                if (args.indexOf(DEVICE) + 1 < args.length()) {
                    device = (args[args.indexOf(DEVICE) + 1]).toInt();
                }
                if (index + 1 < args.length()) {
                    file = args[index + 1];
                }
            } else {
                cout << "Device not specified";
                return -1;
            }
        } else if (args.contains(STATUSREQUEST)) {
            action = OP_DFU::actionStatusReq;
        } else if (args.contains(RESET)) {
            action = OP_DFU::actionReset;
        } else if (args.contains(JUMP)) {
            action = OP_DFU::actionJump;
        } else if (args.contains(LISTDEVICES)) {
            action = OP_DFU::actionListDevs;
        }
        if ((file.isEmpty() || device == -1) && action != OP_DFU::actionReset && action != OP_DFU::actionStatusReq && action != OP_DFU::actionListDevs && action != OP_DFU::actionJump) {
            cout << "wrong parameters";
            return -1;
        }
        if (args.contains(USE_SERIAL)) {
            if (args.indexOf(USE_SERIAL) + 1 < args.length()) {
                serialport = (args[args.indexOf(USE_SERIAL) + 1]);
                use_serial = true;
            }
        }
        if (debug) {
            qDebug() << "Action=" << (int)action;
            qDebug() << "File=" << file;
            qDebug() << "Device=" << device;
            qDebug() << "Action=" << action;
            qDebug() << "Desctription" << description;
            qDebug() << "Use Serial port" << use_serial;
            if (use_serial) {
                qDebug() << "Port Name" << serialport;
            }
        }

        ///////////////////////////////////ACTIONS START///////////////////////////////////////////////////
        OP_DFU dfu(debug, use_serial, serialport, umodereset);
        if (!dfu.ready()) {
            return -1;
        }

        dfu.AbortOperation();
        if (!dfu.enterDFU(0)) {
            cout << "Could not enter DFU mode\n";
            return -1;
        }
        if (debug) {
            OP_DFU::Status ret = dfu.StatusRequest();
            qDebug() << dfu.StatusToString(ret);
        }
        if (!(action == OP_DFU::actionStatusReq || action == OP_DFU::actionReset || action == OP_DFU::actionJump)) {
            dfu.findDevices();
            if (action == OP_DFU::actionListDevs) {
                cout << "Found " << dfu.numberOfDevices << "\n";
                for (int x = 0; x < dfu.numberOfDevices; ++x) {
                    cout << "Device #" << x << "\n";
                    cout << "Device ID=" << dfu.devices[x].ID << "\n";
                    cout << "Device Readable=" << dfu.devices[x].Readable << "\n";
                    cout << "Device Writable=" << dfu.devices[x].Writable << "\n";
                    cout << "Device SizeOfCode=" << dfu.devices[x].SizeOfCode << "\n";
                    cout << "BL Version=" << dfu.devices[x].BL_Version << "\n";
                    cout << "Device SizeOfDesc=" << dfu.devices[x].SizeOfDesc << "\n";
                    cout << "FW CRC=" << dfu.devices[x].FW_CRC << "\n";

                    int size = ((OP_DFU::device)dfu.devices[x]).SizeOfDesc;
                    dfu.enterDFU(x);
                    cout << "Description:" << dfu.DownloadDescription(size).toLatin1().data() << "\n";
                    cout << "\n";
                }
                return 0;
            }
            if (device > dfu.numberOfDevices - 1) {
                cout << "Error:Invalid Device";
                return -1;
            }
// if(dfu.numberOfDevices==1)
// dfu.use_delay=false;
            if (!dfu.enterDFU(device)) {
                cout << "Error:Could not enter DFU mode\n";
                return -1;
            }
            if (action == OP_DFU::actionProgram) {
                if (((OP_DFU::device)dfu.devices[device]).Writable == false) {
                    cout << "ERROR device not Writable\n";
                    return false;
                }

                OP_DFU::Status retstatus = dfu.UploadFirmware(file.toAscii(), verify, device);
                if (retstatus != OP_DFU::Last_operation_Success) {
                    cout << "Upload failed with code:" << dfu.StatusToString(retstatus).toLatin1().data();
                    return -1;
                }
                if (!description.isEmpty()) {
                    retstatus = dfu.UploadDescription(description);
                    if (retstatus != OP_DFU::Last_operation_Success) {
                        cout << "Upload failed with code:" << dfu.StatusToString(retstatus).toLatin1().data();
                        return -1;
                    }
                }
                cout << "Uploading Succeded!\n";
            } else if (action == OP_DFU::actionDownload) {
                if (((OP_DFU::device)dfu.devices[device]).Readable == false) {
                    cout << "ERROR device not readable\n";
                    return false;
                }
                qint32 size = ((OP_DFU::device)dfu.devices[device]).SizeOfCode;
                bool ret    = dfu.SaveByteArrayToFile(file.toAscii(), dfu.StartDownload(size, OP_DFU::FW));
                return ret;
            } else if (action == OP_DFU::actionCompareCrc) {
                dfu.CompareFirmware(file.toAscii(), OP_DFU::crccompare, device);
                return 1;
            } else if (action == OP_DFU::actionCompareAll) {
                if (((OP_DFU::device)dfu.devices[device]).Readable == false) {
                    cout << "ERROR device not readable\n";
                    return false;
                }
                dfu.CompareFirmware(file.toAscii(), OP_DFU::bytetobytecompare, device);
                return 1;
            }
        } else if (action == OP_DFU::actionStatusReq) {
            cout << "Current device status=" << dfu.StatusToString(dfu.StatusRequest()).toLatin1().data() << "\n";
        } else if (action == OP_DFU::actionReset) {
            dfu.ResetDevice();
        } else if (action == OP_DFU::actionJump) {
            dfu.JumpToApp();
        }

        return 0;
    }
    return a.exec();
}
Example #27
0
void MakeConfig::onDataAvailable()
{
    QMutexLocker mtxlock(mtx);
    QByteArray data =  port->readAll();
    if(data[0]==13 || data[0]==10) return;

    buf.append(data);
qDebug()<<"state"<<state<<"buf="<<buf;
    if (state == stNone) return;
    if (state == stReadCurState) {
        ui->statusBar->showMessage(QString::fromLocal8Bit("Получение текущего состояния..."));
        if (!buf.contains(";")) return;
        ui->statusBar->showMessage(QString::fromLocal8Bit("Дешифровка текущего состояния..."));
        QString s = QString(buf);
        QStringList devs = s.split(QString(","));
        if (devs.count() < 2) {
            state = stNone;
            qDebug()<<"no sensor devices found";
            buf.clear();
            return;
        }
        QString cmd;
        for (int i=0; i< devs.count()-1; ++i ) {
            cmd.append(QString("iic %1,*;").arg(devs[i]));
        }
        qDebug()<<"iic cmd: "<<cmd;
        buf.clear();
        port->write(cmd.toLocal8Bit());
        state = stReadCurState2;
        return;
    } else if (state == stReadCurState2) {
        if (!buf.contains(";")) {
            return;
        }
        qDebug()<<"got iic data:"<<buf;
        QString data(buf.trimmed());
        data.chop(1);
        QStringList parts = data.split(",");
        if (parts.length() < 3) {
            qDebug()<<"bad data:"<<data;
            buf.clear();
            return;
        }
        int r=0;
        while (r < this->ui->tblConfig->rowCount()) {
            if (! (ui->tblConfig->item(r, 2) && ui->tblConfig->item(r, 3))) {
                ++r;
                continue;
            }
            if ( (ui->tblConfig->item(r, 3)->text() == parts[1]) && (ui->tblConfig->item(r, 2)->text() == parts[0]) ) {

                QTableWidgetItem *item= new QTableWidgetItem(parts[2]);
                ui->tblConfig->setItem(r, 10, item);
                break;
            }
            ++r;
        }//while
        buf = buf.remove(0, buf.indexOf(";") + 1);
    } else if (state == stSendConfigLines) {
        //qDebug()<<buf.contains("OK");
        if (buf.contains("OK")) {
            buf.clear();
            ui->statusBar->showMessage(QString::fromLocal8Bit("Отправляем строку конфигурации №%1").arg(lsi+1));
            this->sendConfigLine(++lsi);
        } else if (buf.contains("setup()")) {
            buf.clear();
            this->sendConfigLine(lsi);
        }
        return;
    }else if (stSendSensorsCount == state) {
        //qDebug()<<buf.contains("SET");
        if (buf.contains(("SET"))) {
            state = stSendPlantNames;
            this->lsi  = 0;
            ui->statusBar->showMessage(QString::fromLocal8Bit("Начинаем отправку названий растений..."));
            this->port->write("\7");
            this->port->flush();
            sleep(1);
            this->sendPlantName(lsi);
        }
        return;
    } else if (state == stSendPlantNames) {
        //qDebug()<<buf.contains("OK");
        if (buf.contains("OK")) {
            buf.clear();
            ui->statusBar->showMessage(QString::fromLocal8Bit("Отправка названия из строки %1").arg(lsi+1));
            this->sendPlantName(++lsi);
        }
        return;
    } else if (state == stGetW2Dsizes) {
        if (buf.contains(";")) {
            QRegExp re("^.*(\\d+)\\s*\\,\\s*(\\d+).*$");
            if (re.indexIn(buf) > -1) {
                qDebug()<<re.cap(1)<< re.cap(1).toInt()<<re.cap(2)<< re.cap(2).toInt();
                ui->spinX->setMaximum(re.cap(1).toInt());
                ui->spinY->setMaximum(re.cap(2).toInt());
            } else {
                qDebug()<<"not matched";
            }
            state = stNone;
        }
    } else if (state == stReadConfig) {
        if (buf.contains(";")) {
            if (last_index == -1) {
                qDebug()<<"got pot cnt";
                buf = buf.trimmed();
                buf.chop(1);
                pots_total = buf.toInt();
                last_index = 0;
                buf.clear();
                this->port->write(QString("pot get %1;\r\n").arg(last_index).toLocal8Bit());
                this->ui->tblConfig->setRowCount(0);
                this->ui->tblConfig->setRowCount(pots_total);
            } else if (buf.length() > 10 && buf.contains(",")) {
                buf = buf.trimmed();
                buf.chop(1);
                QStringList parts = buf.split(",");
                if (parts.length() >=14) {
                    QTableWidgetItem*item;
                    SETITEM(last_index, 0, parts[1]);//флаги
                    SETITEM(last_index, 1, parts[2]);//растение
                    SETITEM(last_index, 2, parts[3]);//чип
                    SETITEM(last_index, 3, parts[4]);//пин
                    SETITEM(last_index, 4, parts[5]);// Х
                    SETITEM(last_index, 5, parts[6]);// У
                    SETITEM(last_index, 6, parts[7]);// доза
                    SETITEM(last_index, 7, parts[8]);// программа
                    SETITEM(last_index, 8, parts[9]);// мин
                    SETITEM(last_index, 9, parts[10]);// макс
                    SETITEM(last_index, 10, QString("?"));// тек.знач-ие
                    SETITEM(last_index, 11, parts[13]);// вкл/выкл
                    SETITEM(last_index, 12, (parts[12]=="1"?QString::fromLocal8Bit("сушим"):QString::fromLocal8Bit("льём")));// состояние(полив/подсушка)
                    SETITEM(last_index, 13, parts[14]);// вылито
                    ++last_index;
                    PlantData pd;
                    pd.index = parts[0].toInt();
                    pd.flags = parts[1].toInt();
                    pd.name = parts[2];
                    pd.chip = parts[3].toInt();
                    pd.pin = parts[4].toInt();
                    pd.X = parts[5].toInt();
                    pd.Y = parts[6].toInt();
                    pd.portion = parts[7].toInt();
                    pd.pgm = parts[8].toInt();
                    pd.min = parts[9].toInt();
                    pd.max = parts[10].toInt();
                    pd.en = parts[13].toInt();
                    this->pots_data.push_back(pd);
                } else {
                    qDebug()<<"re-query pot "<<last_index;
                }
                buf.clear();
                if (last_index < pots_total) {
                    qDebug()<<"query pot "<<last_index;
                    this->port->write(QString("pot get %1;\r\n").arg(last_index).toLocal8Bit());
                    //this->port->flush();
                } else {
                    state = stGetW2Dsizes;
                    this->port->write("WSZ;\r\n");
                }
            } else {
                this->port->write(QString("pot get %1;\r\n").arg(last_index).toLocal8Bit());
                buf.clear();
            }
            return;
        } else {
            return;
        }
        if (!buf.contains(";;")) return;
        buf = buf.trimmed();
        qDebug()<<"READ CONFIG"<<"\n----\n"<<buf<<"\n-----";
        QRegExp re("\\{(\\d+)\\};");
        re.indexIn(buf);
        int n_rows = re.cap(1).toInt();
        this->ui->tblConfig->setRowCount(0);
        this->ui->tblConfig->setRowCount(n_rows);

        buf= buf.replace(re, "").trimmed();
        QStringList list = buf.split(";");
        qDebug()<<list;
        QRegExp il("^(.*)\\[(.*)\\]$");
        int r = 0;
        for (int i = 0; i < list.length(); ++i) {
            //qDebug()<<list[i];
            if (il.indexIn(list[i].trimmed()) > -1) {
                QString nums = il.cap(1), name = il.cap(2);
                nums = nums.replace(QRegExp("\\s+"), "");
                //qDebug()<<"nums:"<<nums;
                QStringList numz = nums.split(",");
                QTableWidgetItem*item;
                SETITEM(r, 0, name);
                SETITEM(r, 1, numz[0]);
                SETITEM(r, 2, numz[1]);
                SETITEM(r, 3, numz[2]);
                SETITEM(r, 4, numz[3]);
                SETITEM(r, 5, numz[4]);
                SETITEM(r, 6, numz[5]);
                SETITEM(r, 7, numz[6]);
                SETITEM(r, 8, numz[7]);
                ++r;
             //   qDebug()<<numz;
            }
        }
        buf.clear();
        state = stNone;
        return;
    }
    //QStringList lines = buf.split("\n");
    //first line -- cmd echo
    //qDebug()<<data<<data.contains(';');
    if (buf.contains(';')) {
        buf = buf.trimmed();
        //qDebug()<<buf;
        if (state == stDetectPinStep1) {
            //test1.resize(0);
        } else if(state == stDetectPinStep2) {
            //test2.resize(0);
        } else {
            ui->statusBar->showMessage(QString::fromLocal8Bit("Неправильный код состояния. Возможно, идёт отсылка/приём данных..."));
            data.clear();
            return;
        }
            QString str = QString(buf);
            QTextStream st(&str,  QIODevice::ReadOnly);
            int n;
            st>>n;
            //qDebug() << "n="<<n;
            for (int i = 0; i < n; ++i) {
                int val;
                st>>val;
                if (state == stDetectPinStep1) {
                    //test1.push_back(val);
                } else if (state ==stDetectPinStep2) {
                    //test2.push_back(val);
                }
            }
            if (state == stDetectPinStep1) {
                ui->statusBar->showMessage(QString::fromLocal8Bit("Готов к шагу 2"));
            } else if (state == stDetectPinStep2) {
                qDebug()<<"state"<<state<<"buf="<<buf;
              /*  if (test1.size()!=test2.size()) {
                    ui->statusBar->showMessage(QString::fromLocal8Bit("Ошибка: не совпадает размер данных"));
                    buf.clear();
                    //qDebug()<<"state=0, ln 216";
                    state = stNone;
                    return;
                }
                int max_df = 0, max_index=-1, _cdf;
                for (int i=0;i<test1.size(); ++i) {
                    _cdf = abs(test1.at(i)-test2.at(i));
                    if (_cdf > max_df) {
                        qDebug()<<"delta: "<<_cdf;
                        max_index = i;
                        max_df = _cdf;
                    }
                }
                if (max_index >=0 ) {
                    qDebug()<<"max_index "<<max_index;
                    int pins = ui->cbChipType->itemData((ui->cbChipType->currentIndex())).toInt();
                    qDebug()<<"max_index "<<max_index;
                    ui->statusBar->showMessage(QString::fromLocal8Bit("Чип %1 пин %2").arg(max_index/pins).arg(max_index%pins));
                    this->last_found = max_index;
                }
                state = stNone;
                //qDebug()<<"state=0, ln234";
                */
            }
    }
Example #28
0
void MainWindow::buttonEvent(int button) {
    switch (button) {
    case 0: {
        QFile advFile("advice.dat");
        if (!advFile.open(QIODevice::ReadOnly))
            qDebug() << "Error: Unable to open file";
        QStringList fileLines = getLinesWithBreaks(advFile);
        int numLines = fileLines.length();
        int randLine = rand() % numLines;
        QString myMessage = "Advice: " + fileLines.at(randLine);
        myTextEdit->append(myMessage);
        break;
    }
    case 1: {
        QFile wthrFile("weather.dat");
        if (!wthrFile.open(QIODevice::ReadOnly))
            qDebug() << "Error: Unable to open file";
        QStringList fileLines = getLinesWithBreaks(wthrFile);
        int numLines = fileLines.length();
        int randLine = rand() % numLines;
        QString myMessage = "Weather: " + fileLines.at(randLine);
        myTextEdit->append(myMessage);
        break;
    }
    case 2: {
        QFile rmndFile("reminder.dat");
        if (!rmndFile.open(QIODevice::ReadOnly))
            qDebug() << "Error: Unable to open file";
        QStringList fileLines = getLinesWithBreaks(rmndFile);
        int numLines = fileLines.length();
        int randLine = rand() % numLines;
        QString message = fileLines.at(randLine);
        QMessageBox *myReminderBox = new QMessageBox(this);

        prompt->blockSignals(true);
        myReminderBox->addButton(prompt, QMessageBox::ActionRole);
        myReminderBox->addButton("OK", QMessageBox::RejectRole);
        myReminderBox->setIcon(QMessageBox::Information);
        myReminderBox->setModal(true);

        while (alreadyDisplayed.contains(message) && alreadyDisplayed.length() != numLines) {
            numLines = fileLines.length();
            randLine = rand() % numLines;
            message = fileLines.at(randLine);
        }
        if (alreadyDisplayed.length() != numLines) {
            prompt->setChecked(true);
            myReminderBox->setText(message);
            myReminderBox->exec();
            if (prompt->checkState() == Qt::Unchecked) {
                alreadyDisplayed.append(message);
            }
        }
        else
            myTextEdit->append("There are no more reminders.");
        break;
    }
    case 3: {
        QMessageBox *closeBox = new QMessageBox(this);
        closeBox->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        closeBox->setText("Are you sure you want to quit?");
        closeBox->setIcon(QMessageBox::Question);
        closeBox->setModal(true);
        int clicked = closeBox->exec();
        if (clicked == 16384)
            QApplication::quit();
    }
    }
}
void LH_CursorController::updateLocation(int xMod, int yMod, bool absolute)
{
    QStringList boundsList = setup_boundry_->value().split(',');
    QStringList badPoints = setup_invalid_coordinates_->value().split(';');

    bool moved = false;

    int newX = cursor_data_.x;
    int newY = cursor_data_.y;

    if (boundsList.length()>=4)
    {
        cursor_data_.range.x = (minmax){boundsList.at(0).toInt(), boundsList.at(2).toInt()};
        cursor_data_.range.y = (minmax){boundsList.at(1).toInt(), boundsList.at(3).toInt()};

        if (absolute)
        {
            if(xMod >= cursor_data_.range.x.min &&
               xMod <= cursor_data_.range.x.max &&
               yMod >= cursor_data_.range.y.min &&
               yMod <= cursor_data_.range.y.max
               )
            {
                newX = xMod;
                newY = yMod;
                QString point = QString::number(newX) + "," + QString::number(newY);
                if(!badPoints.contains(point)) moved = true;
            }
        } else
        if(xMod!=0 || yMod!=0)
        {
            int loops = 0;
            while (loops<=1 && !moved)
            {
                loops++;
                while(!moved &&
                      newX+xMod >= cursor_data_.range.x.min &&
                      newX+xMod <= cursor_data_.range.x.max &&
                      newY+yMod >= cursor_data_.range.y.min &&
                      newY+yMod <= cursor_data_.range.y.max
                      )
                {
                    newX += xMod;
                    newY += yMod;
                    QString point = QString::number(newX) + "," + QString::number(newY);
                    if(!badPoints.contains(point)) moved = true;
                    if(!setup_jump_invalid_->value()) break;


                }
                if(!setup_boundry_loop_->value()) break;
                else if(!moved)
                {
                    if(xMod==1)  newX = cursor_data_.range.x.min - xMod;
                    if(xMod==-1) newX = cursor_data_.range.x.max - xMod;
                    if(yMod==1)  newY = cursor_data_.range.y.min - yMod;
                    if(yMod==-1) newY = cursor_data_.range.y.max - yMod;
                }
            }
        }
    }

    if(moved) {
        cursor_data_.x = newX;
        cursor_data_.y = newY;
        if(setup_mode_->value()!=-1)
            if(cursorModes[setup_mode_->value()].select==smNone) doSelect("",0,0);
    }

    persistSelection();
    updateLinkData();

    setup_coordinate_->setValue(QString("%1,%2").arg(cursor_data_.x).arg(cursor_data_.y));
}
Example #30
0
//Reset current screen config to match previously-saved settings
void RRSettings::ApplyPrevious(){
  QSettings set("lumina-desktop","lumina-xconfig");
  set.beginGroup("MonitorSettings");
  //Setup a couple lists
  QStringList devs = set.childGroups(); //known/saved devices
  QList<ScreenInfo> screens = RRSettings::CurrentScreens();
  QStringList lastactive = set.value("lastActive",QStringList()).toStringList();
  //Now go through all the saved settings and put that info into the array
  QString primary;
  QStringList avail;
  for(int i=0; i<screens.length(); i++){
    //if(screens[i].order>=0){screens[i].order = -1; } //reset all screen orders (need to re-check all)
    if(devs.contains(screens[i].ID) && screens[i].isavailable){ //only load settings for monitors which are currently attached
      set.beginGroup(screens[i].ID);
        screens[i].geom = set.value("geometry", QRect()).toRect();
        screens[i].isprimary = set.value("isprimary", false).toBool();
        if(screens[i].isprimary){ primary = screens[i].ID; }
        screens[i].isactive = lastactive.contains(screens[i].ID);
        screens[i].order = (screens[i].isactive ? -1 : -3); //check/ignore
      set.endGroup();
    }else if(screens[i].isavailable){
      screens[i].order = -2; //needs activation/placement
    }else{
      screens[i].order = -3; //ignored
    }
    //Now clean up the list as needed
    if(screens[i].order < -2){ screens.removeAt(i); i--; } //just remove it (less to loop through later)
    else{ avail << screens[i].ID; } //needed for some checks later - make it simple
  }
  //NOTE ABOUT orders: -1: check geom, -2: auto-add to end, -3: ignored
  
  //Quick checks for simple systems - just use current X config as-is
  if(devs.isEmpty() && (avail.filter("LVDS").isEmpty() || screens.length()==1) ){ return; } 

  //Typical ID's: LVDS-[], DVI-I-[], DP-[], HDMI-[], VGA-[]
  //"LVDS" is the built-in laptop display normally
  if(primary.isEmpty()){
    QStringList priority; priority << "LVDS" << "DP" << "HDMI" << "DVI" << "VGA";
    for(int i=0; i<priority.length() && primary.isEmpty(); i++){
      QStringList filter = avail.filter(priority[i]);
      if(!filter.isEmpty()){ filter.sort(); primary = filter.first(); }
    }
    if(primary.isEmpty()){ primary = avail.first(); }
  }
  //Ensure only one monitor is primary, and reset a few flags
  for(int i=0; i<screens.length(); i++){  
    if(screens[i].ID!=primary){ screens[i].isprimary = false; }  
    screens[i].isactive = true; //we want all these monitors to be active eventually
  }
  // Handle all the available monitors
  int handled = 0;
  int cx = 0; //current x point
  while(handled<screens.length()){
    //Go through horizontally and place monitors (TO-DO: Vertical placement not handled yet)
    int next = -1;
    int diff = -1;
    for(int i=0; i<screens.length(); i++){
      if(screens[i].order==-1){
        if(diff<0 || ((screens[i].geom.x()-cx) < diff)){
          diff = screens[i].geom.x()-cx;
          next = i;
        }
      }
    }//end loop over screens
    if(next<0){
      //Go through and start adding the non-assigned screens to the end
      for(int i=0; i<screens.length(); i++){
        if(screens[i].order==-2){
          if(diff<0 || ((screens[i].geom.x()-cx) < diff)){
            diff = screens[i].geom.x()-cx;
            next = i;
          }
        }
      } //end loop over screens
    }
    if(next>=0){ 
      cx+=screens[next].geom.width();
      screens[next].order = handled; handled++; 
    }else{
      //Still missing monitors (vertical alignment?)
      qDebug() << "Unhandled Monitors:" << screens.length()-handled;
      break;
    }
  }
  //Now reset the display with xrandr
  RRSettings::Apply(screens);
}