Beispiel #1
0
void DistroMesas::importXML(const QString val) {
  QFile file ( g_confpr->value( CONF_DIR_USER ) + "distromesas_" + mainCompany()->dbName() + ".cfn" );

    if (file.exists()) {
        if ( !file.open ( QIODevice::ReadOnly ) ) {
            
            return;
        } // end if
        QString result (file.readAll());
        file.close(); 


    QDomDocument doc ( "mydocument" );

    if ( !doc.setContent ( result ) ) {
	
        return;
    } // end if

    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "BACKGROUND" );
    m_background = principal.text();

    principal = docElem.firstChildElement ( "ESCALA" );
    g_escala = principal.text().toInt();


    QDomNodeList nodos = docElem.elementsByTagName ( "MESA" );
    int i = 0;
    while (i < nodos.count() ) {
        QDomNode ventana = nodos.item ( i++ );
        QDomElement e1 = ventana.toElement(); /// try to convert the node to an element.
        if ( !e1.isNull() ) { /// the node was really an element.
            QString nodoText = e1.text();
            /// Pasamos el XML a texto para poder procesarlo como tal.
            QString result;
            QTextStream stream ( &result );
            ventana.save(stream,5);

            Mesa *mesa = new Mesa((BtCompany *) mainCompany(), mui_widget);
            mesa->importXML(result);
	    
	    if (! m_listapantallas.contains(mesa->m_pantalla)) {
	        if (m_pantallaactual == "") {
		    m_pantallaactual = mesa->m_pantalla;
		} // end if
		m_listapantallas.append(mesa->m_pantalla);
		QToolButton *but = new QToolButton(this);
		but->setObjectName("p_"+mesa->m_pantalla);
		but->setText(mesa->m_pantalla);
		but->setMinimumHeight(42);
		but->setMinimumWidth(42);
		but->setCheckable(TRUE);
		mui_espaciopantallas->addWidget(but);
		connect(but, SIGNAL(clicked()), this, SLOT(cambiarPantalla()));
	    } // end if
	    if (mesa->m_pantalla == m_pantallaactual) 
		mesa->show();

        } // end if
    } // end while

} // end if

}
Beispiel #2
0
bool MachConf::read()
 {
     QString errorStr;
     int errorLine;
     int errorColumn;
     QFile *device = new QFile(_fileName);
     if (!device->open(QIODevice::ReadOnly))
        return false;
     if (!domDocument.setContent(device, true, &errorStr, &errorLine,
                                 &errorColumn)) {

         return false;
     }

     QDomElement root = domDocument.documentElement();

    //Console *console =
     //cout <<
     //std::basic_ostream<<root.tagName()<<endl;

    Console * console = SkyMain::getUartConsole();
    DevTreeView *treeView = SkyMain::getDevTreeView();

    //QDomElement child = root.firstChildElement("arch");
    if(root.tagName() != "machine"){        
         return false;
    }
    else{
        QDomAttr attr = root.attributeNode(QString("name"));
        treeView->insertMachine(attr.value());
    }
    QDomElement board = root.firstChildElement("board");

    //console->insertPlainText(attr.value());
    console->insertPlainText("\n");
    //console->insertPlainText(child);

    //console->insertPlainText(QString("ljklkjkejlwer"));

       /*
     if (root.tagName() != "xbel") {
         QMessageBox::information(window(), tr("DOM Bookmarks"),
                                  tr("The file is not an XBEL file."));
         return false;
     } else if (root.hasAttribute("version")
                && root.attribute("version") != "1.0") {
         QMessageBox::information(window(), tr("DOM Bookmarks"),
                                  tr("The file is not an XBEL version 1.0 "
                                     "file."));
         return false;
     }

     clear();

     disconnect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
                this, SLOT(updateDomElement(QTreeWidgetItem *, int)));

     QDomElement child = root.firstChildElement("folder");
     while (!child.isNull()) {
         parseFolderElement(child);
         child = child.nextSiblingElement("folder");
     }

     connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
             this, SLOT(updateDomElement(QTreeWidgetItem *, int)));
    */
     return true;
}
Beispiel #3
0
//---------------------------------------------------------------------------------
void
MagicRules::initialize(const QString& p_jsonFile)
{
    // Read the JSON file
    QString val;
    QFile file;
    file.setFileName(p_jsonFile);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    val = file.readAll();
    file.close();

    // Read document
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8(), &error);
    if (error.error != QJsonParseError::NoError)
    {
        qCritical() << QString("Error while reading file: %1\nError: %2").arg(p_jsonFile, error.errorString());
        return;
    }

    // Parse each magic type and add to the rules
    QJsonArray magicTypesArray = doc.object().value("magic_types").toArray();
    QJsonObject currentType;
    MagicTypeDefinition* typeDef = 0;
    MagicTypePriorityDefinition* prioDef = 0;
    QJsonArray tempArray;
    QJsonObject tempObject;
    QJsonObject tempObject2;
    for (int i = 0; i < magicTypesArray.size(); ++i)
    {
        currentType = magicTypesArray.at(i).toObject();

        // Add type definition
        typeDef = new MagicTypeDefinition();

        // Translations
        tempObject = currentType["translations"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            typeDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString();
        }

        // Types
        tempArray = currentType["types"].toArray();
        for (int j = 0; j < tempArray.size(); ++j)
        {
            typeDef->types.push_back(tempArray.at(j).toString());
        }

        // Priorities
        tempObject = currentType["priorities"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            tempObject2 = tempObject[tempObject.keys().at(j)].toObject();

            prioDef = new MagicTypePriorityDefinition();

            // Starting magic
            if (tempObject2.contains("starting_magic"))
            {
                prioDef->startingMagic = tempObject2.value("starting_magic").toString().toInt();
            }

            // Free spells
            if (tempObject2.contains("free_spells"))
            {
                prioDef->freeSpells = tempObject2.value("free_spells").toString().toInt();
            }

            // Free skills
            if (tempObject2.contains("free_skills"))
            {
                prioDef->freeSkills.first = tempObject2.value("free_skills").toArray().at(0).toString().toInt();
                prioDef->freeSkills.second = tempObject2.value("free_skills").toArray().at(1).toString().toInt();
            }

            // Forced skill group
            if (tempObject2.contains("free_skill_groups"))
            {
                prioDef->freeSkillGroup.first = tempObject2.value("free_skill_groups").toArray().at(0).toString().toInt();
                prioDef->freeSkillGroup.second = tempObject2.value("free_skill_groups").toArray().at(1).toString().toInt();
            }

            // Store priority
            typeDef->priorities[tempObject.keys().at(j).toInt()] = prioDef;
        }

        // Make sure the definition doesn't already exist
        if (_typeDefinitions.contains(currentType["unique_id"].toString()))
        {
            qCritical() << "Magic type \"" << currentType["unique_id"].toString() << "\" already exists. Parsing aborted.";
            return;
        }

        _typeDefinitions[currentType["unique_id"].toString()] = typeDef;
    }// END magic types

    // Parse spell category strings
    QJsonArray categoryArray = doc.object().value("spell_categories").toArray();
    QJsonObject currentCat;
    SpellDefinition* spellCat = NULL;
    MagicAbilityDefinition* category = NULL;
    MagicAbilityDefinition* abilityDef = NULL;
    QString tempString;
    QString uniqueId = "";
    for (int i = 0; i < categoryArray.size(); ++i)
    {
        currentCat = categoryArray.at(i).toObject();

        uniqueId = currentCat["unique_id"].toString();

        // Make sure the definition doesn't already exist
        if (_spellCategoryDefinitions.contains(uniqueId))
        {
            qCritical() << "Spell category \"" << uniqueId << "\" already exists. Parsing aborted.";
            return;
        }

        // Get correct category
        category = _rootItem->children[MAGICABILITYTYPE_SPELL];

        // Add spell definition
        abilityDef = new MagicAbilityDefinition(category);
        abilityDef->id = uniqueId;
        abilityDef->abilityType = MAGICABILITYTYPE_SPELL;
        spellCat = new SpellDefinition();
        abilityDef->spell = spellCat;
        abilityDef->spell->isSpellCategory = true;
        category->children.push_back(abilityDef);

        // Translations
        tempObject = currentCat["translations"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString();
        }

        _definitions[uniqueId] = abilityDef;
        _spellCategoryDefinitions[uniqueId] = spellCat;
    }

    // Parse each spell and add to the rules
    QJsonArray spellsArray = doc.object().value("spells").toArray();
    QJsonObject currentSpell;
    SpellDefinition* spellDef = 0;
    for (int i = 0; i < spellsArray.size(); ++i)
    {
        currentSpell = spellsArray.at(i).toObject();

        uniqueId = currentSpell["unique_id"].toString();

        // Make sure the definition doesn't already exist
        if (_spellDefinitions.contains(uniqueId))
        {
            qCritical() << "Spell \"" << uniqueId << "\" already exists. Parsing aborted.";
            return;
        }

        // Add spell definition
        abilityDef = new MagicAbilityDefinition();
        abilityDef->id = uniqueId;
        abilityDef->abilityType = MAGICABILITYTYPE_SPELL;
        spellDef = new SpellDefinition();
        abilityDef->spell = spellDef;

        // Translations
        tempObject = currentSpell["translations"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString();
        }

        // Category
        spellDef->category = currentSpell["category"].toString();
        if (!_spellCategoryDefinitions.contains(spellDef->category))
        {
            qCritical() << "Spell \"" << currentSpell["unique_id"].toString() << "\" of non existing category \""
                           << spellDef->category << "\". Parsing aborted.";
            return;
        }

        // Get correct spell category and add to it
        category = _definitions[spellDef->category];
        abilityDef->parent = category;
        category->children.push_back(abilityDef);

        // Type
        tempString = currentSpell["type"].toString();
        if (tempString == "P")
        {
            spellDef->type = SPELLTYPE_PHYSICAL;
        }
        else if (tempString == "M")
        {
            spellDef->type = SPELLTYPE_MAGICAL;
        }

        // Range
        tempString = currentSpell["range"].toString();
        if (tempString == "T")
        {
            spellDef->range = SPELLRANGE_TOUCH;
        }
        else if (tempString == "LOS")
        {
            spellDef->range = SPELLRANGE_LOS;
        }
        else if (tempString == "LOS(A)")
        {
            spellDef->range = SPELLRANGE_LOS_AREA;
        }

        // Damage (optional)
        if (currentSpell.contains("damage"))
        {
            tempString = currentSpell["damage"].toString();
            if (tempString == "P")
            {
                spellDef->damageType = SPELLDAMAGE_PHYSICAL;
            }
            else if (tempString == "M")
            {
                spellDef->damageType = SPELLDAMAGE_MENTAL;
            }
        }

        // Duration
        tempString = currentSpell["duration"].toString();
        if (tempString == "I")
        {
            spellDef->duration = SPELLDURATION_INSTANT;
        }
        else if (tempString == "S")
        {
            spellDef->duration = SPELLDURATION_SUSTAINED;
        }
        else if (tempString == "P")
        {
            spellDef->duration = SPELLDURATION_PERMANENT;
        }

        // Drain
        spellDef->drain = currentSpell["drain"].toString();

        // Descriptors (optional)
        if (currentSpell.contains("descriptors"))
        {
            QVariantList list = currentSpell["descriptors"].toArray().toVariantList();
            QListIterator<QVariant> i(list);
            while (i.hasNext())
            {
                spellDef->descriptors << i.next().toString();
            }
        }

        // Does this spell require a custom choice?
        if (currentSpell.contains("requires_custom"))
        {
            abilityDef->requiresCustom = currentSpell["requires_custom"].toString() == "true";
            if (currentSpell.contains("custom_choices"))
            {
                QJsonObject obj = currentSpell["custom_choices"].toObject();
                abilityDef->customChoices = new CustomChoice(&obj);
            }
        }

        // Is this spell affected by the essence value?
        if (currentSpell.contains("essence_effect"))
        {
            spellDef->essenceEffect = currentSpell["essence_effect"].toString() == "true";
        }

        _definitions[uniqueId] = abilityDef;
        _spellDefinitions[uniqueId] = spellDef;
    }// END spells

    // Parse each adept power and add to the rules
    QJsonArray powersArray = doc.object().value("adept_powers").toArray();
    QJsonObject currentPower;
    AdeptPowerDefinition* powerDef = 0;
    for (int i = 0; i < powersArray.size(); ++i)
    {
        currentPower = powersArray.at(i).toObject();

        uniqueId = currentPower["unique_id"].toString();

        // Make sure the definition doesn't already exist
        if (_adeptPowerDefinitions.contains(uniqueId))
        {
            qCritical() << "Adept Power \"" << uniqueId << "\" already exists. Parsing aborted.";
            return;
        }

        // Add type definition
        abilityDef = new MagicAbilityDefinition();
        abilityDef->id = uniqueId;
        abilityDef->abilityType = MAGICABILITYTYPE_ADEPT_POWER;
        powerDef = new AdeptPowerDefinition();
        abilityDef->adeptPower = powerDef;

        // Get correct spell category and add to it
        category = _rootItem->children[MAGICABILITYTYPE_ADEPT_POWER];
        abilityDef->parent = category;
        category->children.push_back(abilityDef);

        // Translations
        tempObject = currentPower["translations"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString();
        }

        // Cost
        if (currentPower.contains("cost_per_level"))
        {
            powerDef->costType = COSTTYPE_PER_LEVEL;
            powerDef->costArray.push_back(currentPower["cost_per_level"].toString().toDouble());
        }
        else if (currentPower.contains("cost"))
        {
            QJsonValue::Type type = currentPower["cost"].type();

            // Normal cost or array
            if (type != QJsonValue::Array)
            {
                powerDef->costType = COSTTYPE_NORMAL;
                powerDef->costArray.push_back(currentPower["cost"].toString().toDouble());
            }
            else
            {
                powerDef->costType = COSTTYPE_ARRAY;
                tempArray = currentPower["cost"].toArray();

                // Add each array entry
                for (int j = 0; j < tempArray.size(); ++j)
                {
                    powerDef->costArray.push_back(tempArray[j].toString().toDouble());
                }
            }
        }

        // Activation (optional)
        if (currentPower.contains("activation"))
        {
            tempString = currentPower["activation"].toString();
            if (tempString == "interrupt")
            {
                powerDef->activationType = ACTIVATIONTYPE_INTERRUPT;
            }
            else if (tempString == "free")
            {
                powerDef->activationType = ACTIVATIONTYPE_FREE;
            }
            else if (tempString == "simple")
            {
                powerDef->activationType = ACTIVATIONTYPE_SIMPLE;
            }
        }

        // Does this power require a custom choice?
        if (currentPower.contains("requires_custom"))
        {
            abilityDef->requiresCustom = currentPower["requires_custom"].toString() == "true";
            if (currentPower.contains("custom_choices"))
            {
                QJsonObject obj = currentPower["custom_choices"].toObject();
                abilityDef->customChoices = new CustomChoice(&obj);
            }
        }

        // Does this power have effects?
        if (currentPower.contains("effects"))
        {
            tempArray = currentPower["effects"].toArray();
            for (int j = 0; j < tempArray.size(); ++j)
            {
                QJsonValueRef obj = tempArray[j];
                EffectSource source;
                source.magicAbility = abilityDef;
                abilityDef->effects.push_back(new Effect(&obj, source));
            }
        }

        _definitions[uniqueId] = abilityDef;
        _adeptPowerDefinitions[uniqueId] = powerDef;
    } // END adept powers

    // Parse each complex form and add to the rules
    QJsonArray formsArray = doc.object().value("complex_forms").toArray();
    QJsonObject currentForm;
    ComplexFormDefinition* formDef = 0;
    for (int i = 0; i < formsArray.size(); ++i)
    {
        currentForm = formsArray.at(i).toObject();

        uniqueId = currentForm["unique_id"].toString();

        // Make sure the definition doesn't already exist
        if (_complexFormDefinitions.contains(uniqueId))
        {
            qCritical() << "Complex Form \"" << uniqueId << "\" already exists. Parsing aborted.";
            return;
        }

        // Add form definition
        abilityDef = new MagicAbilityDefinition();
        abilityDef->id = uniqueId;
        abilityDef->abilityType = MAGICABILITYTYPE_COMPLEX_FORM;
        formDef = new ComplexFormDefinition();
        abilityDef->complexForm = formDef;

        // Get correct spell category and add to it
        category = _rootItem->children[MAGICABILITYTYPE_COMPLEX_FORM];
        abilityDef->parent = category;
        category->children.push_back(abilityDef);

        // Translations
        tempObject = currentForm["translations"].toObject();
        for (int j = 0; j < tempObject.keys().size(); ++j)
        {
            abilityDef->translations[tempObject.keys().at(j)] = tempObject[tempObject.keys().at(j)].toString();
        }

        // Target
        tempString = currentForm["target"].toString();
        if (tempString == "persona")
        {
            formDef->targetType = TARGETTYPE_PERSONA;
        }
        else if (tempString == "device")
        {
            formDef->targetType = TARGETTYPE_DEVICE;
        }
        else if (tempString == "file")
        {
            formDef->targetType = TARGETTYPE_FILE;
        }
        else if (tempString == "sprite")
        {
            formDef->targetType = TARGETTYPE_SPRITE;
        }

        // Duration
        tempString = currentForm["duration"].toString();
        if (tempString == "I")
        {
            formDef->duration = SPELLDURATION_INSTANT;
        }
        else if (tempString == "S")
        {
            formDef->duration = SPELLDURATION_SUSTAINED;
        }
        else if (tempString == "P")
        {
            formDef->duration = SPELLDURATION_PERMANENT;
        }

        // Fading Value
        formDef->fadingValue = currentForm["fading_value"].toString();

        // Does this form require a custom choice?
        if (currentForm.contains("requires_custom"))
        {
            abilityDef->requiresCustom = currentForm["requires_custom"].toString() == "true";
            if (currentForm.contains("custom_choices"))
            {
                QJsonObject obj = currentForm["custom_choices"].toObject();
                abilityDef->customChoices = new CustomChoice(&obj);
            }
        }

        _definitions[uniqueId] = abilityDef;
        _complexFormDefinitions[uniqueId] = formDef;
    } // END complex forms
}
Beispiel #4
0
void jsBridge::dragResource(QString hash) {

    Resource *res = Resource::fromHash(hash);
    if (res == NULL)
        return;

    QString mime = res->mimeType();
    QString fileName = res->getFileName();
    QByteArray data = res->getData();

    QPixmap pix;
    if (res->isImage()) {
        pix.loadFromData(data);
    } else if (res->isPDF()) {
        pix.load(":/img/application-pdf.png");
    } else {
        pix.load(":/img/application-octet-stream.png");
    }

    delete res;

    if (fileName.isEmpty())
        fileName = hash;

    if (mime == "application/pdf") {
        if (!fileName.endsWith(".pdf", Qt::CaseInsensitive))
            fileName += ".pdf";
    } else if (mime == "image/jpeg") {
        if (!fileName.endsWith(".jpg", Qt::CaseInsensitive) && !fileName.endsWith(".jpeg", Qt::CaseInsensitive))
            fileName += ".jpg";
    } else if (mime == "image/png") {
        if (!fileName.endsWith(".png", Qt::CaseInsensitive))
            fileName += ".png";
    } else if (mime == "image/gif") {
        if (!fileName.endsWith(".gif", Qt::CaseInsensitive))
            fileName += ".gif";
    }

    QString tmpl = QDir::tempPath() + QDir::separator() + fileName;

    QFile* f = new QFile(tmpl);

    if (!f->open(QIODevice::WriteOnly))
        return;

    f->write(data);
    f->close();
    files.enqueue(f);

    QTimer::singleShot(60000, this, SLOT(removeTmpFile()));

    QDrag *drag = new QDrag(new QWidget());
    QMimeData *mimeData = new QMimeData;

    QFileInfo fileInfo(tmpl);
    QUrl url = QUrl::fromLocalFile(fileInfo.absoluteFilePath());
    mimeData->setUrls(QList<QUrl>() << url);

    drag->setMimeData(mimeData);

    if (!pix.isNull())
        drag->setPixmap(pix.scaled(128,128, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    drag->exec(Qt::CopyAction | Qt::MoveAction);
}
QString htmlizedTextPart(const QModelIndex &partIndex, const QFontInfo &font, const QColor &backgroundColor, const QColor &textColor,
                         const QColor &linkColor, const QColor &visitedLinkColor)
{
    static const QString defaultStyle = QString::fromUtf8(
        "pre{word-wrap: break-word; white-space: pre-wrap;}"
        // The following line, sadly, produces a warning "QFont::setPixelSize: Pixel size <= 0 (0)".
        // However, if it is not in place or if the font size is set higher, even to 0.1px, WebKit reserves space for the
        // quotation characters and therefore a weird white area appears. Even width: 0px doesn't help, so it looks like
        // we will have to live with this warning for the time being.
        ".quotemarks{color:transparent;font-size:0px;}"

        // Cannot really use the :dir(rtl) selector for putting the quote indicator to the "correct" side.
        // It's CSS4 and it isn't supported yet.
        "blockquote{font-size:90%; margin: 4pt 0 4pt 0; padding: 0 0 0 1em; border-left: 2px solid %1; unicode-bidi: -webkit-plaintext}"

        // Stop the font size from getting smaller after reaching two levels of quotes
        // (ie. starting on the third level, don't make the size any smaller than what it already is)
        "blockquote blockquote blockquote {font-size: 100%}"
        ".signature{opacity: 0.6;}"

        // Dynamic quote collapsing via pure CSS, yay
        "input {display: none}"
        "input ~ span.full {display: block}"
        "input ~ span.short {display: none}"
        "input:checked ~ span.full {display: none}"
        "input:checked ~ span.short {display: block}"
        "label {border: 1px solid %2; border-radius: 5px; padding: 0px 4px 0px 4px; white-space: nowrap}"
        // BLACK UP-POINTING SMALL TRIANGLE (U+25B4)
        // BLACK DOWN-POINTING SMALL TRIANGLE (U+25BE)
        "span.full > blockquote > label:before {content: \"\u25b4\"}"
        "span.short > blockquote > label:after {content: \" \u25be\"}"
        "span.shortquote > blockquote > label {display: none}"
    );

    QString fontSpecification(QStringLiteral("pre{"));
    if (font.italic())
        fontSpecification += QLatin1String("font-style: italic; ");
    if (font.bold())
        fontSpecification += QLatin1String("font-weight: bold; ");
    fontSpecification += QStringLiteral("font-size: %1px; font-family: \"%2\", monospace }").arg(
                QString::number(font.pixelSize()), font.family());

    QString textColors = QString::fromUtf8("body { background-color: %1; color: %2 }"
                                           "a:link { color: %3 } a:visited { color: %4 } a:hover { color: %3 }").arg(
                backgroundColor.name(), textColor.name(), linkColor.name(), visitedLinkColor.name());
    // looks like there's no special color for hovered links in Qt

    // build stylesheet and html header
    QColor tintForQuoteIndicator = backgroundColor;
    tintForQuoteIndicator.setAlpha(0x66);
    static QString stylesheet = defaultStyle.arg(linkColor.name(),
                                                 tintColor(textColor, tintForQuoteIndicator).name());
    static QFile file(Common::writablePath(Common::LOCATION_DATA) + QLatin1String("message.css"));
    static QDateTime lastVersion;
    QDateTime lastTouched(file.exists() ? QFileInfo(file).lastModified() : QDateTime());
    if (lastVersion < lastTouched) {
        stylesheet = defaultStyle;
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            const QString userSheet = QString::fromLocal8Bit(file.readAll().data());
            lastVersion = lastTouched;
            stylesheet += QLatin1Char('\n') + userSheet;
            file.close();
        }
    }

    // The dir="auto" is required for WebKit to treat all paragraphs as entities with possibly different text direction.
    // The individual paragraphs unfortunately share the same text alignment, though, as per
    // https://bugs.webkit.org/show_bug.cgi?id=71194 (fixed in Blink already).
    QString htmlHeader(QLatin1String("<html><head><style type=\"text/css\"><!--") + textColors + fontSpecification + stylesheet +
                       QLatin1String("--></style></head><body><pre dir=\"auto\">"));
    static QString htmlFooter(QStringLiteral("\n</pre></body></html>"));


    // We cannot rely on the QWebFrame's toPlainText because of https://bugs.kde.org/show_bug.cgi?id=321160
    QString markup = plainTextToHtml(partIndex.data(Imap::Mailbox::RolePartUnicodeText).toString(), flowedFormatForPart(partIndex));

    return htmlHeader + markup + htmlFooter;
}
Beispiel #6
0
QFile* Snapshot::savedFileForSnapshot(bool isTemporary) {
    auto glCanvas = DependencyManager::get<GLCanvas>();
    QImage shot = glCanvas->grabFrameBuffer();
    
    Avatar* avatar = Application::getInstance()->getAvatar();
    
    glm::vec3 location = avatar->getPosition();
    glm::quat orientation = avatar->getHead()->getOrientation();
    
    // add metadata
    shot.setText(LOCATION_X, QString::number(location.x));
    shot.setText(LOCATION_Y, QString::number(location.y));
    shot.setText(LOCATION_Z, QString::number(location.z));
    
    shot.setText(ORIENTATION_X, QString::number(orientation.x));
    shot.setText(ORIENTATION_Y, QString::number(orientation.y));
    shot.setText(ORIENTATION_Z, QString::number(orientation.z));
    shot.setText(ORIENTATION_W, QString::number(orientation.w));
    
    shot.setText(DOMAIN_KEY, DependencyManager::get<NodeList>()->getDomainHandler().getHostname());

    QString formattedLocation = QString("%1_%2_%3").arg(location.x).arg(location.y).arg(location.z);
    // replace decimal . with '-'
    formattedLocation.replace('.', '-');
    
    QString username = AccountManager::getInstance().getAccountInfo().getUsername();
    // normalize username, replace all non alphanumeric with '-'
    username.replace(QRegExp("[^A-Za-z0-9_]"), "-");
    
    QDateTime now = QDateTime::currentDateTime();
    
    QString filename = FILENAME_PATH_FORMAT.arg(username, now.toString(DATETIME_FORMAT), formattedLocation);
    
    const int IMAGE_QUALITY = 100;
    
    if (!isTemporary) {
        QString snapshotFullPath = Menu::getInstance()->getSnapshotsLocation();
        
        if (!snapshotFullPath.endsWith(QDir::separator())) {
            snapshotFullPath.append(QDir::separator());
        }
        
        snapshotFullPath.append(filename);
        
        QFile* imageFile = new QFile(snapshotFullPath);
        imageFile->open(QIODevice::WriteOnly);
        
        shot.save(imageFile, 0, IMAGE_QUALITY);
        imageFile->close();
        
        return imageFile;
    } else {
        QTemporaryFile* imageTempFile = new QTemporaryFile(QDir::tempPath() + "/XXXXXX-" + filename);
        
        if (!imageTempFile->open()) {
            qDebug() << "Unable to open QTemporaryFile for temp snapshot. Will not save.";
            return NULL;
        }
        
        shot.save(imageTempFile, 0, IMAGE_QUALITY);
        imageTempFile->close();
        
        return imageTempFile;
    }
}
Sequence::Sequence(
                        //CAMERASET
                          QString INPUT_PATH_CAMERA_SET_IN,

                        //MODEL
                          QString INPUT_BasePath_OutPut_IN,
                          QString INPUT_dynamicStringPart_IN,
                          QString INPUT_EXTENSSS_Mesh_IN,
                          QString INPUT_EXTENSSS_Skeleton_IN,
                          QString INPUT_EXTENSSS_Skin_IN,
                          QString INPUT_PATH_MODELS_INFO_IN,

                        //ANIMATION
                          QString PATH_OutputBase_IN,
                          QString PATH_FolderName_INPUT_IN,
                          QString INPUT_EXTENSSS_Motion_IN,
                          QString PATH_INDEX_BOUNDS_IN,

                        //SEQUENCE
                          QString PATH_INDEX_BOUNDS_INNN,
                          QString RadioSequenceID_String_IN,

                          bool printEnabled
                  )
{

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        cameraSet = CameraSet( INPUT_PATH_CAMERA_SET_IN );

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        Animation animSource = Animation(
                                              //MODEL
                                                INPUT_BasePath_OutPut_IN,
                                                INPUT_dynamicStringPart_IN,
                                                INPUT_EXTENSSS_Mesh_IN,
                                                INPUT_EXTENSSS_Skeleton_IN,
                                                INPUT_EXTENSSS_Skin_IN,
                                                INPUT_PATH_MODELS_INFO_IN,

                                              //ANIMATION
                                                PATH_OutputBase_IN,
                                                PATH_FolderName_INPUT_IN,
                                                INPUT_EXTENSSS_Motion_IN,
                                                PATH_INDEX_BOUNDS_IN,
                                                "Source_Animation",

                                                printEnabled
                                        );

        Animation animTarget = Animation(
                                              //MODEL
                                                INPUT_BasePath_OutPut_IN,
                                                INPUT_dynamicStringPart_IN,
                                                INPUT_EXTENSSS_Mesh_IN,
                                                INPUT_EXTENSSS_Skeleton_IN,
                                                INPUT_EXTENSSS_Skin_IN,
                                                INPUT_PATH_MODELS_INFO_IN,

                                              //ANIMATION
                                                PATH_OutputBase_IN,
                                                PATH_FolderName_INPUT_IN,
                                                INPUT_EXTENSSS_Motion_IN,
                                                PATH_INDEX_BOUNDS_IN,
                                                "Target_Animation",

                                                printEnabled
                                        );

        posedAnimations.append( animSource );
        posedAnimations.append( animTarget );

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        currentFrameNumber_Source = 0;
        currentFrameNumber_Target = 0;

        sequenceID_String = RadioSequenceID_String_IN;
        sequenceID        = sequenceID_String.toInt() - 1;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        QFile myFile ( PATH_INDEX_BOUNDS_INNN );

        myFile.open(QIODevice::ReadOnly);

        if( !myFile.isOpen() )
        {
            qDebug() << "\n\n\n   Sequence::Sequence - ERROR, unable to open **" << PATH_INDEX_BOUNDS_INNN << "** for IndexCheat Input \n\n\n";
            return;
        }

        QTextStream myStream(&myFile);

        QString dummyDescr;

        myStream >> dummyDescr;       myStream >> totalAllignedFrames;      posedAnimations[0].totalAllignedFrames = totalAllignedFrames;
        myStream >> dummyDescr;       myStream >> motionOffset;             posedAnimations[0].motionOffset        = motionOffset;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /////////////////////////////////////////
        /////////////////////////////////////////
        if (printEnabled)   printAnimationINFO();
        /////////////////////////////////////////
        /////////////////////////////////////////

}
Beispiel #8
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ArrayInit();

    QFile file;//загрузка jquery и добавление ноу конфликт
    file.setFileName(":/jquery-1.11.3.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
    file.close();

    ServIP="127.0.0.1";


    QFile htmlF;//подгрузка html
    htmlF.setFileName(":/page.html");
    htmlF.open(QFile::ReadOnly);
    Html = htmlF.readAll();
    htmlF.close();

    QFile styleF;//подгрузка стилей
    styleF.setFileName("://style.qss");
    styleF.open(QFile::ReadOnly);
    QString qssStr = styleF.readAll();
    qApp->setStyleSheet(qssStr);
    styleF.close();

     QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
     QWebSettings::globalSettings()->setAttribute(QWebSettings::AutoLoadImages, true);
     QWebSettings::globalSettings()->setAttribute(QWebSettings::JavascriptEnabled, true);
     connect(ui->webView,SIGNAL(loadFinished(bool)),this,SLOT(UIloadFinished(bool)));
     ui->webView->load(QUrl("http://free-filmy.ru/"));

    connect(this,SIGNAL (phase2(QString)),this ,SLOT(Phase2Do(QString)));
    wb1=new QWebView();
    connect(wb1,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished(bool)));
    connect(wb1,SIGNAL(loadProgress(int)),this, SLOT(changeProgress(int)));
    wb2=new QWebView();
    connect(wb2,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished2(bool)));

    dial=new QDialog;
    wb3=new QWebView();
    pb=new QPushButton();
    pb->setText("OK");
    VBox=new QVBoxLayout;
    VBox->addWidget(wb3);
    VBox->addWidget(pb);
    HBox=new QHBoxLayout;
    HBox->addLayout(VBox);
    dial->setLayout(HBox);

    dial2=new QDialog;
    wb4=new QWebView();
    VBox2=new QVBoxLayout;
    VBox2->addWidget(wb4);
    HBox2=new QHBoxLayout;
    HBox2->addLayout(VBox2);
    dial2->setLayout(HBox2);


  connect(pb,SIGNAL(clicked(bool)),this,SLOT(pb_click(bool)));
  connect(wb3->page()->mainFrame(),SIGNAL(titleChanged(QString)),this,SLOT(img_put(QString)));

  done2=true;

}
Beispiel #9
0
// ---------------------------------------------------
// Converts a spice netlist into Qucs format and outputs it.
void SimMessage::nextSPICE()
{
  QString Line;
  for(;;) {  // search for next SPICE component
    Line = *(Collect.begin());
    Collect.remove(Collect.begin());
    if(Line == "*") {  // worked on all components ?
      startSimulator(); // <<<<<================== go on ===
      return;
    }
// FIXME #warning SPICE section below not being covered?
    qDebug() << "goin thru SPICE branch on simmmessage.cpp";
    if(Line.left(5) == "SPICE") {
      if(Line.at(5) != 'o') insertSim = true;
      else insertSim = false;
      break;
    }
    Collect.append(Line);
  }


  QString FileName = Line.section('"', 1,1);
  Line = Line.section('"', 2);  // port nodes
  if(Line.isEmpty())  makeSubcircuit = false;
  else  makeSubcircuit = true;

  QString prog;
  QStringList com;
  prog = QucsSettings.BinDir + "qucsconv";
  if(makeSubcircuit)
    com << "-g" << "_ref";
  com << "-if" << "spice" << "-of" << "qucs";

  QFile SpiceFile;
  if(FileName.find(QDir::separator()) < 0)  // add path ?
    SpiceFile.setName(QucsSettings.QucsWorkDir.path() + QDir::separator() + FileName);
  else
    SpiceFile.setName(FileName);
  if(!SpiceFile.open(QIODevice::ReadOnly)) {
    ErrText->insert(tr("ERROR: Cannot open SPICE file \"%1\".").arg(FileName));
    FinishSimulation(-1);
    return;
  }

  if(makeSubcircuit) {
    Stream << "\n.Def:" << properName(FileName) << " ";

    Line.replace(',', ' ');
    Stream << Line;
    if(!Line.isEmpty()) Stream << " _ref";
  }
  Stream << "\n";

  ProgressText = "";

  qDebug() << "start QucsConv" << prog << com.join(" ");
  SimProcess.start(prog, com);

  if(!SimProcess.Running) {
    ErrText->insert(tr("ERROR: Cannot start QucsConv!"));
    FinishSimulation(-1);
    return;
  }

  QByteArray SpiceContent = SpiceFile.readAll();
  SpiceFile.close();
  QString command(SpiceContent); //to convert byte array to string
  SimProcess.setStandardInputFile(command);  //? FIXME works?
  qDebug() << command;
  connect(&SimProcess, SIGNAL(wroteToStdin()), SLOT(slotCloseStdin()));
}
void
VeloHeroUploader::requestUpload()
{
    assert(sessionId.length() > 0 );

    parent->progressLabel->setText(tr("preparing VeloHero data ..."));

    QHttpMultiPart *body = new QHttpMultiPart( QHttpMultiPart::FormDataType );

    QHttpPart textPart;
    textPart.setHeader(QNetworkRequest::ContentDispositionHeader,
    QVariant("form-data; name=\"upload_submit\""));
    textPart.setBody("hrm");
    body->append( textPart );

    QString fname = context->athlete->home->temp().absoluteFilePath(".velohero-upload.pwx" );
    QFile *uploadFile = new QFile( fname );
    uploadFile->setParent(body);

    PwxFileReader reader;
    reader.writeRideFile(context, ride->ride(), *uploadFile );
    parent->progressBar->setValue(parent->progressBar->value()+20/parent->shareSiteCount);

    int limit = 16777216; // 16MB
    if( uploadFile->size() >= limit ){
        parent->errorLabel->setText(tr("temporary file too large for upload: %1 > %1 bytes")
            .arg(uploadFile->size())
            .arg(limit) );

        eventLoop.quit();
        return;
    }

    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentTypeHeader,
    QVariant("application/occtet-stream"));
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
    QVariant("form-data; name=\"file\"; filename=\"gc-upload-velohero.pwx\""));
    uploadFile->open(QIODevice::ReadOnly);
    filePart.setBodyDevice(uploadFile);
    body->append( filePart );


    parent->progressLabel->setText(tr("sending to VeloHero..."));

    currentRequest = reqUpload;

#if QT_VERSION > 0x050000
    QUrlQuery urlquery( VELOHERO_URL + "/upload/file" );
#else
    QUrl urlquery( VELOHERO_URL + "/upload/file" );
#endif
    urlquery.addQueryItem( "view", "xml" );
    urlquery.addQueryItem( "sso", sessionId );

#if QT_VERSION > 0x050000
    QUrl url;
    url.setQuery(urlquery);
    QNetworkRequest request = QNetworkRequest(url);
#else
    QNetworkRequest request = QNetworkRequest(urlquery);
#endif

    request.setRawHeader( "Accept-Encoding", "identity" );
    request.setRawHeader( "Accept", "application/xml" );
    request.setRawHeader( "Accept-Charset", "utf-8" );

    QNetworkReply *reply = networkMgr.post( request, body );
    body->setParent( reply );

}
Beispiel #11
0
bool SGFParser::parseASCII(const QString &fileName, ASCII_Import *charset, bool isFilename)
{
	QTextStream *txt = NULL;
	bool result = false;
	asciiOffsetX = asciiOffsetY = 0;
	
#if 0
	qDebug("BLACK STONE CHAR %c\n"
		"WHITE STONE CHAR %c\n"
		"STAR POINT  CHAR %c\n"
		"EMPTY POINT CHAR %c\n"
		"HOR BORDER CHAR %c\n"
		"VER BORDER CHAR %c\n",
		charset->blackStone,
		charset->whiteStone,
		charset->starPoint,
		charset->emptyPoint,
		charset->hBorder,
		charset->vBorder);
#endif
	
	if (isFilename)  // Load from file
	{
		QFile file;
		
		if (fileName.isNull() || fileName.isEmpty())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("No filename given!"));
			delete txt;
			return false;
		}
		
		file.setName(fileName);
		if (!file.exists())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Could not find file:") + " " + fileName);
			delete txt;
			return false;
		}
		
		if (!file.open(IO_ReadOnly))
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Could not open file:") + " " + fileName);
			delete txt;
			return false;
		}
		
		txt = new QTextStream(&file);
		if (!initStream(txt))
		{
			QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
			delete txt;
			return false;
		}
		
		result = parseASCIIStream(txt, charset);
		file.close();
	}
	else  // a string was passed instead of a filename, copy from clipboard
	{
		if (fileName.isNull() || fileName.isEmpty())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Importing ASCII failed. Clipboard empty?"));
			delete txt;
			return false;
		}
		
		QString buf(fileName);
		txt = new QTextStream(buf, IO_ReadOnly);
		if (!initStream(txt))
		{
			QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
			delete txt;
			return false;
		}
		
		result = parseASCIIStream(txt, charset);
	}
	
	delete txt;
	return result;
}
Beispiel #12
0
void atlasMap::sHandleAtlas()
{
  _map->clear();

  if (_atlas->text().isEmpty())
    return;

  if (DEBUG)
    qDebug("atlasMap::sHandleAtlas() entered with %s and %s",
           qPrintable(_atlas->text()), qPrintable(_defaultDir));

  if (! _defaultDir.isEmpty() && _atlas->text().startsWith(_defaultDir))
    _atlas->setText(_atlas->text().remove(0, _defaultDir.length() + 1));

  QFile atlasfile;
  if (QFile::exists(_atlas->text()))
    atlasfile.setFileName(_atlas->text());
  else if (QFile::exists(_defaultDir + QDir::separator() + _atlas->text()))
    atlasfile.setFileName(_defaultDir + QDir::separator() + _atlas->text());
  else
  {
    QMessageBox::warning(this, tr("Could not find Atlas"),
                         tr("<p>Could not find the Atlas file to open to look "
                            "for CSV import Maps."));
    return;
  }

  if (! atlasfile.open(QIODevice::ReadOnly))
  {
    QMessageBox::critical(this, tr("Could not open Atlas"),
                          tr("<p>Could not open the Atlas file %1 (error %2).")
                          .arg(atlasfile.fileName(), atlasfile.errorString()));
    return;
  }

  QXmlQuery mapq;
  mapq.setMessageHandler(_msghandler);

  if (! mapq.setFocus(&atlasfile))
  {
    QMessageBox::critical(this, tr("No Focus"),
                          tr("<p>Could not set focus on the Atlas %1")
                          .arg(atlasfile.fileName()));
    return;
  }

  // string() at the end tells the query to generate a sequence of values
  mapq.setQuery("/CSVAtlas/CSVMap/Name/text()/string()");
  if (! mapq.isValid())
  {
    QMessageBox::critical(this, tr("Invalid Query"),
                          tr("<p>The query is not valid for some reason"));
    return;
  }

  QStringList maplist;
  if (! mapq.evaluateTo(&maplist))
  {
    QMessageBox::warning(this, tr("No Maps"),
                         tr("<p>Could not find any Maps in the Atlas %1")
                         .arg(atlasfile.fileName()));
    return;
  }
  else
    for (int i = 0; i < maplist.size(); i++)
      _map->append(i, maplist.at(i));
}
Beispiel #13
0
QPair<QString, QString> GetOSNameSplit ()
{
#if defined(Q_OS_MAC)
    QSysInfo::MacVersion v = QSysInfo::MacintoshVersion;
    if (v == QSysInfo::MV_10_3)
        return SplitInfo_t ("Mac OS X", "10.3");
    else if (v == QSysInfo::MV_10_4)
        return SplitInfo_t ("Mac OS X", "10.4");
    else if (v == QSysInfo::MV_10_5)
        return SplitInfo_t ("Mac OS X", "10.5");
    else if (v == QSysInfo::MV_10_6)
        return SplitInfo_t ("Mac OS X", "10.6");
    else if (v == QSysInfo::MV_10_7)
        return SplitInfo_t ("Mac OS X", "10.7");
    else
        return SplitInfo_t ("Mac OS X", "Unknown version");
#elif defined(Q_OS_WIN32)
    QSysInfo::WinVersion v = QSysInfo::WindowsVersion;
    if (v == QSysInfo::WV_95)
        return SplitInfo_t ("Windows", "95");
    else if (v == QSysInfo::WV_98)
        return SplitInfo_t ("Windows", "98");
    else if (v == QSysInfo::WV_Me)
        return SplitInfo_t ("Windows", "Me");
    else if (v == QSysInfo::WV_DOS_based)
        return SplitInfo_t ("Windows", "9x/Me");
    else if (v == QSysInfo::WV_NT)
        return SplitInfo_t ("Windows", "NT 4.x");
    else if (v == QSysInfo::WV_2000)
        return SplitInfo_t ("Windows", "2000");
    else if (v == QSysInfo::WV_XP)
        return SplitInfo_t ("Windows", "XP");
    else if (v == QSysInfo::WV_2003)
        return SplitInfo_t ("Windows", "2003");
    else if (v == QSysInfo::WV_VISTA)
        return SplitInfo_t ("Windows", "Vista");
    else if (v == QSysInfo::WV_WINDOWS7)
        return SplitInfo_t ("Windows", "7");
    else if (v == 0x00a0)
        return SplitInfo_t ("Windows", "8");
    else if (v == QSysInfo::WV_NT_based)
        return SplitInfo_t ("Windows", "NT-based");
#else
    QString osName;

    QProcess proc;
    proc.start (QString ("/bin/sh"),
                QStringList ("-c") << "lsb_release -ds", QIODevice::ReadOnly);
    if (proc.waitForStarted ())
    {
        QTextStream stream (&proc);
        QString ret;
        while (proc.waitForReadyRead ())
            ret += stream.readAll ();
        proc.close ();
        if (!ret.isEmpty ())
            osName = ret.remove ('"').trimmed ();
    }

    if (osName.isEmpty ())
    {
        struct OsInfo_t
        {
            QString path;
            QString name;
        } OsInfo [] =
        {
            { "/etc/mandrake-release", "Mandrake Linux" },
            { "/etc/debian_version", "Debian GNU/Linux" },
            { "/etc/gentoo-release", "Gentoo Linux" },
            { "/etc/exherbo-release", "Exherbo" },
            { "/etc/arch-release", "Arch Linux" },
            { "/etc/slackware-version", "Slackware Linux" },
            { "/etc/pld-release", "" },
            { "/etc/lfs-release", "LFS" },
            { "/etc/SuSE-release", "SuSE linux" },
            { "/etc/conectiva-release", "Connectiva" },
            { "/etc/.installed", "" },
            { "/etc/redhat-release", "" },
            { "", "" }
        };
        OsInfo_t *osptr = OsInfo;
        while (!osptr->path.isEmpty ())
        {
            QFileInfo fi (osptr->path);
            if (fi.exists ())
            {
                QFile f (osptr->path);
                f.open (QIODevice::ReadOnly);
                QString data = QString (f.read (1024)).trimmed ();
                if (osptr->name.isEmpty ())
                    osName = data;
                else
                    osName = QString ("%1 (%2)")
                             .arg (osptr->name)
                             .arg (data);
                break;
            }
            ++osptr;
        }
    }

    utsname u;
    uname (&u);

    return qMakePair (osName.isEmpty () ? QString (u.sysname) : osName,
                      QString ("%1 %2 %3").arg (u.machine, u.release, u.version));
#endif

    return qMakePair (QString ("Unknown OS"), QString ("Unknown version"));
}
Beispiel #14
0
int main(int argc, char *argv[])
{
    enum ExitCode
    {
        Success,
        ParseFailure,
        ArgumentError,
        WriteError,
        FileFailure
    };

    QCoreApplication app(argc, argv);

    QTextStream errorStream(stderr);

    if (argc != 2)
    {
        errorStream << PrettyPrint::tr(
                       "Usage: prettyprint <path to XML file>\n");
        return ArgumentError;
    }

    QString inputFilePath(QCoreApplication::arguments().at(1));
    QFile inputFile(inputFilePath);

    if (!QFile::exists(inputFilePath))
    {
        errorStream << PrettyPrint::tr(
                       "File %1 does not exist.\n").arg(inputFilePath);
        return FileFailure;

    } else if (!inputFile.open(QIODevice::ReadOnly)) {
        errorStream << PrettyPrint::tr(
                       "Failed to open file %1.\n").arg(inputFilePath);
        return FileFailure;
    }

    QFile outputFile;
    if (!outputFile.open(stdout, QIODevice::WriteOnly))
    {
        QTextStream(stderr) << PrettyPrint::tr("Failed to open stdout.");
        return WriteError;
    }

    QXmlStreamReader reader(&inputFile);
    int indentation = 0;
    QHash<int,QPair<int, int> > indentationStack;

    while (!reader.atEnd())
    {
        reader.readNext();
        if (reader.isStartElement()) {
            indentationStack[indentation] = QPair<int,int>(
                reader.lineNumber(), reader.columnNumber());
            indentation += 1;
        } else if (reader.isEndElement()) {
            indentationStack.remove(indentation);
            indentation -= 1;
        }

        if (reader.error())
        {
            errorStream << PrettyPrint::tr(
                           "Error: %1 in file %2 at line %3, column %4.\n").arg(
                               reader.errorString(), inputFilePath,
                               QString::number(reader.lineNumber()),
                               QString::number(reader.columnNumber()));
            if (indentationStack.contains(indentation-1)) {
                int line = indentationStack[indentation-1].first;
                int column = indentationStack[indentation-1].second;
                errorStream << PrettyPrint::tr(
                               "Opened at line %1, column %2.\n").arg(
                                   QString::number(line),
                                   QString::number(column));
            }
            return ParseFailure;

        } else if (reader.isStartElement() && !reader.name().isEmpty()) {
            outputFile.write(QByteArray().fill(' ', indentation));
            outputFile.write(reader.name().toString().toLocal8Bit());
            outputFile.write(QString(" line %1, column %2\n").arg(
                reader.lineNumber()).arg(reader.columnNumber()).toLocal8Bit());
        }
    }

    return Success;
}
Beispiel #15
0
void ShortLocater::Initializations(){

	IPsoc->resetRelays();
	IPsoc->srcImpedanceSelection(SRC_IMP_0E);
//	IPsoc->shLocatorDetection();
    m_nADCtimer = new QTimer(this);

    IBackPlane->writeBackPlaneRegister(0x0FFF,0x001E);//clear all interrupts
    IBackPlane->writeBackPlaneRegister(0x0000,0x0020);//disable all interrupts
    IBackPlane->writeBackPlaneRegister(0x0000,0x0024);//disable global interrupt
    IBackPlane->writeBackPlaneRegister(0x0100,0x0020);//enabling psoc INT0embedded key interrupt)

    IPTKeyEvent->InvokeGPIOEvent(this,"/dev/input/event2","pt_kpp",&m_nPTKeyCode);
    IGPIOEvent->InvokeGPIOEvent(this,"/dev/input/event7","gpioevent",&m_nGPIOCode);
    IBackPlane->writeBackPlaneRegister(0x0001,0x0024);

    //        IBackPlane->writeBackPlaneRegister();
    ohms=QChar(0x2126);
    micro=QChar(0x00B5);

    //~~~~~~~~~~~~~Reading Short Values from File~~~~~~~~~~~~~~~~~~~~~~
	QStringList stringList;
	bool ok=true;
	QFile textFile;
   	textFile.setFileName("shortValuesI.txt");

    if (textFile.open(QIODevice::ReadOnly))
    {
        QTextStream textStream(&textFile);
        while (!textStream.atEnd())
        {
            stringList.append(textStream.readLine());
        }
        r200EShortValue=stringList.value(0).toDouble(&ok);
        qDebug()<<"200E Short Value:"<<r200EShortValue;
        r2EShortValue=stringList.value(1).toDouble(&ok);
        qDebug()<<"2E Short Value:"<<r2EShortValue;
       	r200mEShortValue=stringList.value(2).toDouble(&ok);
        qDebug()<<"200mE Short Value:"<<r200mEShortValue;
    }else{
        r200EShortValue=r200mEShortValue=r2EShortValue=0.0;
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //~~~~~~~~Check for debug panel~~~~~~~~~~~~~~~~~~~~~~~~
    QStringList debugPanel;
    QFile textFile2("debugPanel.txt");
    if (textFile2.open(QIODevice::ReadOnly))
    {
        QTextStream textStream(&textFile2);
        while (!textStream.atEnd())
        {
            debugPanel.append(textStream.readLine());
            if(debugPanel.value(0)=="1")
                ToolBox(true);
            else
                ToolBox(false);
        }
    }else{
        ToolBox(false);
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    IDMMLib->ApplyDACOffset(false);

    dis->setValue("OL");
    IBackPlane->writeBackPlaneRegister(0x0,0x16);
    //	Beep(false);

    AutoFlag=false;
    on_Auto_clicked();

    OffsetFlag=false;
    BuzzerFlag=false;
    msgBoxLive=false;

    ui.progressBar_2->setValue(0);
    for(int i=0;i<100;i++)
        avgRetval[i]=0.0;

    retval=retval2=retval3=0.0;
    nullify=0.0;
    nullit=0.0;
    avg=0;

    noOFsamples=1;

    rangePrevValue=33;

    ui.uE->setText(micro+ohms);

    on_r200But_clicked();
    ui.holdCap->setVisible(false);
    runFlag=true;
    startStop();

	ui.openShortEnable->setChecked(true);

	m_nAvgCount=0;
	movingAverage=5;

	ui.splashWidget->setVisible(false);
		usleep(1000);

}
Beispiel #16
0
/*!
 * \brief SimMessage::startSimulator simulates the document in view.
 */
void SimMessage::startSimulator()
{
  // Using the Doc pointer here is risky as the user may have closed
  // the schematic, but converting the SPICE netlists is (hopefully)
  // faster than the user (I have no other idea).

  QString SimTime;
  QString Program;
  QStringList Arguments;
  QString SimPath = QDir::convertSeparators (QucsSettings.QucsHomeDir.absPath());
#ifdef __MINGW32__
  QString QucsDigiLib = "qucsdigilib.bat";
  QString QucsDigi = "qucsdigi.bat";
  QString QucsVeri = "qucsveri.bat";
#else
  QString QucsDigiLib = "qucsdigilib";
  QString QucsDigi = "qucsdigi";
  QString QucsVeri = "qucsveri";
#endif
  SimOpt = NULL;
  bool isVerilog = false;

  // Simulate text window.
  if(DocWidget->inherits("QTextEdit")) {

    TextDoc * Doc = (TextDoc*)DocWidget;

    // Take VHDL file in memory as it could contain unsaved changes.
    Stream << Doc->toPlainText();
    NetlistFile.close();
    ProgText->insert(tr("done.")+"\n");  // of "creating netlist...

    // Simulation.
    if (Doc->simulation) {
      SimTime = Doc->SimTime;
      QString libs = Doc->Libraries.lower();
      /// \todo \bug error: unrecognized command line option '-Wl'
#ifdef __MINGW32__
      if(libs.isEmpty()) {
        libs = "";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-Wl,-l" + libs;
      }
#else
      if(libs.isEmpty()) {
        libs = "-c";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-c,-l" + libs;
      }
#endif
      Program = pathName(QucsSettings.BinDir + QucsDigi);
      Arguments  << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                 << DataSet << SimTime << pathName(SimPath)
                 << pathName(QucsSettings.BinDir) << libs;
    }
    // Module.
    else {
      QString text = Doc->toPlainText();
      VHDL_File_Info VInfo (text);
      QString entity = VInfo.EntityName.lower();
      QString lib = Doc->Library.lower();
      if (lib.isEmpty()) lib = "work";
      QString dir = QDir::convertSeparators (QucsSettings.QucsHomeDir.path());
      QDir vhdlDir(dir);
      if(!vhdlDir.exists("vhdl"))
	if(!vhdlDir.mkdir("vhdl")) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/vhdl"));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/vhdl");
      if(!vhdlDir.exists(lib))
	if(!vhdlDir.mkdir(lib)) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/"+lib));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/"+lib);
      QFile destFile;
      destFile.setName(vhdlDir.filePath(entity+".vhdl"));
      if(!destFile.open(QIODevice::WriteOnly)) {
	ErrText->insert(tr("ERROR: Cannot create \"%1\"!")
			.arg(destFile.name()));
	return;
      }
      destFile.writeBlock(text.ascii(), text.length());
      destFile.close();
      Program = pathName(QucsSettings.BinDir + QucsDigiLib);
      Arguments << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                << pathName(SimPath)
                << entity
                << lib;
    }
  }
  // Simulate schematic window.
  else {
    // output NodeSets, SPICE simulations etc.
    for(QStringList::Iterator it = Collect.begin();
	it != Collect.end(); ++it) {
      // don't put library includes into netlist...
      if ((*it).right(4) != ".lst" &&
	  (*it).right(5) != ".vhdl" &&
	  (*it).right(4) != ".vhd" &&
	  (*it).right(2) != ".v") {
	Stream << *it << '\n';
      }
    }
    Stream << '\n';

    isVerilog = ((Schematic*)DocWidget)->isVerilog;
    SimTime = ((Schematic*)DocWidget)->createNetlist(Stream, SimPorts);
    if(SimTime.length()>0&&SimTime.at(0) == '\xA7') {
      NetlistFile.close();
      ErrText->insert(SimTime.mid(1));
      FinishSimulation(-1);
      return;
    }
    if (isVerilog) {
      Stream << "\n"
	     << "  initial begin\n"
	     << "    $dumpfile(\"digi.vcd\");\n"
	     << "    $dumpvars();\n"
	     << "    #" << SimTime << " $finish;\n"
	     << "  end\n\n"
	     << "endmodule // TestBench\n";
    }
    NetlistFile.close();
    ProgText->insert(tr("done.")+"\n");  // of "creating netlist...

    if(SimPorts < 0) {

      // append command arguments
      // append netlist with same arguments
      if (! Module::vaComponents.isEmpty()) {

          /*! Only pass modules to Qucsator that are indeed used on
           * the schematic,it might be the case that the user loaded the icons,
           * but did not compiled the module. Qucsator will not find the library.
           *
           * Check if used symbols have corresponing lib before running
           * Qucsator? Need to search on the netlis.txt? Is there other data
           * structure containig the netlist?
           *
          */
          QStringList usedComponents;

          if (!NetlistFile.open(QIODevice::ReadOnly))
             QMessageBox::critical(this, tr("Error"), tr("Cannot read netlist!"));
          else {
             QString net = QString(NetlistFile.readAll());

             QMapIterator<QString, QString> i(Module::vaComponents);
             while (i.hasNext()) {
                 i.next();
                 if (net.contains(i.key()))
                     usedComponents << i.key();
             }
             NetlistFile.close();
          }

          if (! usedComponents.isEmpty()) {


            // \todo remvoe the command line arguments? use only netlist annotation?
            //Arguments << "-p" << QucsSettings.QucsWorkDir.absolutePath()
            //          << "-m" << usedComponents;
            //qDebug() << "Command :" << Program << Arguments.join(" ");

            /// Anotate netlist with Verilog-A dynamic path and module names
            ///
            if (!NetlistFile.open(QFile::Append | QFile::Text))
               QMessageBox::critical(this, tr("Error"), tr("Cannot read netlist!"));
            else {
               QTextStream out(&NetlistFile);
               out << "\n";
               out << "# --path=" << QucsSettings.QucsWorkDir.absolutePath() << "\n";
               out << "# --module=" << usedComponents.join(" ") << "\n";

               NetlistFile.close();
            }
          }
      } // vaComponents not empty

      if((SimOpt = findOptimization((Schematic*)DocWidget))) {
	    ((Optimize_Sim*)SimOpt)->createASCOnetlist();

        Program = QucsSettings.AscoBinDir.canonicalPath();
        Program = QDir::toNativeSeparators(Program+"/"+"asco"+QString(executableSuffix));
        Arguments << "-qucs" << QucsSettings.QucsHomeDir.filePath("asco_netlist.txt")
                  << "-o" << "asco_out";
      }
      else {
        Program = QucsSettings.BinDir + "qucsator" + executableSuffix;
        Arguments << "-b" << "-g" << "-i"
                  << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                  << "-o" << DataSet;
      }
    }
    else {
      if (isVerilog) {
          Program = QDir::toNativeSeparators(QucsSettings.BinDir + QucsVeri);
          Arguments << QDir::toNativeSeparators(QucsSettings.QucsHomeDir.filePath("netlist.txt"))
                    << DataSet
                    << SimTime
                    << QDir::toNativeSeparators(SimPath)
                    << QDir::toNativeSeparators(QucsSettings.BinDir)
                    << "-c";
      } else {
/// \todo \bug error: unrecognized command line option '-Wl'
#ifdef __MINGW32__
    Program = QDir::toNativeSeparators(pathName(QucsSettings.BinDir + QucsDigi));
    Arguments << QDir::toNativeSeparators(QucsSettings.QucsHomeDir.filePath("netlist.txt"))
              << DataSet
              << SimTime
              << QDir::toNativeSeparators(SimPath)
              << QDir::toNativeSeparators(QucsSettings.BinDir) << "-Wall" << "-c";
#else
    Program = QDir::toNativeSeparators(pathName(QucsSettings.BinDir + QucsDigi));
    Arguments << QucsSettings.QucsHomeDir.filePath("netlist.txt")
              << DataSet << SimTime << pathName(SimPath)
		      << pathName(QucsSettings.BinDir) << "-Wall" << "-c";

#endif
      }
    }
  }

  disconnect(&SimProcess, 0, 0, 0);
  connect(&SimProcess, SIGNAL(readyReadStandardError()), SLOT(slotDisplayErr()));
  connect(&SimProcess, SIGNAL(readyReadStandardOutput()), SLOT(slotDisplayMsg()));
  connect(&SimProcess, SIGNAL(finished(int)), SLOT(slotSimEnded(int)));

#ifdef SPEEDUP_PROGRESSBAR
  waitForUpdate = false;
#endif
  wasLF = false;

  ProgressText = "";

#ifdef __MINGW32__
  QString sep(";"); // path separator
#else
  QString sep(":");
#endif

  // append process PATH
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  // insert Qucs bin dir, so ASCO can find qucsator
  env.insert("PATH", env.value("PATH") + sep + QucsSettings.BinDir );
  SimProcess.setProcessEnvironment(env);
  QFile file(Program);
  if ( !file.exists() ){
    ErrText->insert(tr("ERROR: Program not found: %1").arg(Program));
    FinishSimulation(-1);
    return;
  }
  else
    file.close();

  qDebug() << "Command :" << Program << Arguments.join(" ");
  SimProcess.start(Program, Arguments); // launch the program

  if(!SimProcess.Running) {
    ErrText->insert(tr("ERROR: Cannot start simulator!"));
    FinishSimulation(-1);
    return;
  }

}
Beispiel #17
0
void QJDMainWindow::creatNewLine(QString lineName)
{
    QString lowerCaseLineName;
    lowerCaseLineName=lineName.toLower();
    lowerCaseLineName.simplified();
    lowerCaseLineName.remove(" ");
    qDebug()<<"creatNewLine::"<<lineName<<lowerCaseLineName;  // 所有大写阿,带空格的之类的统一小写,并且去空格

    //1. 创建文件夹,需要获取当前area文件夹名称,通过当前的名称获取
    QDir newDir;
    newDir.setPath(areaWidget->getAbsolutePath());
    if(newDir.exists(lowerCaseLineName))
    {
        QMessageBox::warning(this,"Warning!","Do not creat the same LINE again!");
        return;
    }

    if(!newDir.mkdir(lowerCaseLineName))
        qDebug()<<"Creat New Line Dir failed";

    //2. 创建.Line Desc
    QFile newDesc;
    newDesc.setFileName(newDir.path()+"/"+lowerCaseLineName+"/DescName");
    if(!newDesc.open(QFile::WriteOnly))
    {
        qDebug()<<"creat new desc open failed";
    }
    QTextStream ts(&newDesc);
    ts<<lineName<<"\n";
    newDesc.close();

    // 3. 创建Data文件夹
    QDir dataDir;
    QString dataDirPath=areaWidget->getAbsolutePath()+"/"+lowerCaseLineName;
    dataDir.setPath(dataDirPath);
    if(dataDir.exists("Data"))
    {
        QMessageBox::warning(this,"Warning!","Can not creat the Data Dir for this LINE!");
        return;
    }

    if(!dataDir.mkdir("Data"))
        qDebug()<<"Creat Line Data Dir failed";

    QFile dataDesc;
    dataDesc.setFileName(dataDir.path()+"/Data/DescName");
    if(!dataDesc.open(QFile::WriteOnly))
    {
        qDebug()<<"creat data dir desc open failed";
    }
    QTextStream datats(&dataDesc);
    datats<<"Data\n";
    dataDesc.close();

    // 4. 创建各个类型文件的文件夹
    QStringList fileTypeList=settings.value("FileType").toStringList();
    for(int i=0; i<fileTypeList.size(); i++)
    {
        QDir typeDir;
        QString typeDirPath=dataDirPath+"/Data";
        typeDir.setPath(typeDirPath);
        if(typeDir.exists(fileTypeList.at(i)))
        {
            QMessageBox::warning(this,"Warning!","Can not creat the Same Type Dir for this LINE Data!");
            return;
        }

        if(!typeDir.mkdir(fileTypeList.at(i)))
            qDebug()<<"Creat Line Data Dir failed";
    }


    setHomeDir(getHomeDir());
    areaWidget->expandToDepth(1);
}
Beispiel #18
0
void startCrashHandler(int signal)
{
	QFile output;
	QString lin, cmd;

	/** At the moment the backtrace function does not exists on MingW (Windows) this way
		 the code that generates the stacktrace is available only on Linux/Unix systems */
	#ifndef Q_OS_WIN
		void *stack[20];
		size_t stack_size, i;
		char **symbols=nullptr;
		stack_size = backtrace(stack, 20);
		symbols = backtrace_symbols(stack, stack_size);
	#endif

	#ifdef Q_OS_MAC
		cmd=QApplication::applicationDirPath() + GlobalAttributes::DIR_SEPARATOR +
				GlobalAttributes::CRASH_HANDLER_PATH + " -style " + GlobalAttributes::DEFAULT_QT_STYLE;
	#else
		cmd=GlobalAttributes::CRASH_HANDLER_PATH + " -style " + GlobalAttributes::DEFAULT_QT_STYLE;
	#endif

	//Creates the stacktrace file
	output.setFileName(GlobalAttributes::TEMPORARY_DIR +
										 GlobalAttributes::DIR_SEPARATOR +
										 GlobalAttributes::STACKTRACE_FILE);
	output.open(QFile::WriteOnly);

	if(output.isOpen())
	{
    lin=QString("** pgModeler crashed after receive signal: %1 **\n\nDate/Time: %2 \nVersion: %3 \nBuild: %4 \n")
        .arg(signal)
        .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
        .arg(GlobalAttributes::PGMODELER_VERSION)
        .arg(GlobalAttributes::PGMODELER_BUILD_NUMBER);

		lin+=QString("Compilation Qt version: %1\nRunning Qt version: %2\n\n")
				 .arg(QT_VERSION_STR)
				 .arg(qVersion());

		output.write(lin.toStdString().c_str(), lin.size());

		#ifndef Q_OS_WIN
			for(i=0; i < stack_size; i++)
			{
				lin=QString(symbols[i]) + QString("\n");
				output.write(lin.toStdString().c_str(), lin.size());
			}
			free(symbols);
		#else
			lin=QString("** Stack trace unavailable on Windows system **");
			output.write(lin.toStdString().c_str(), lin.size());
		#endif

		output.close();
	}

	/* Changing the working dir to the main executable in order to call the crash handler
	if the PGMODELER_CHANDLER_PATH isn't set */
	QDir dir;
	dir.cd(QApplication::applicationDirPath());

	exit(1 + system(cmd.toStdString().c_str()));
}
/**OK
 * Estrae il file fileName, contenuto nell'oggetto zip, con il nome fileDest.
 * Se la funzione fallisce restituisce false e cancella il file che si e tentato di estrarre.
 *
 * La funzione fallisce se:
 * * zip==NULL;
 * * l'oggetto zip e stato aperto in una modalita non compatibile con l'estrazione di file;
 * * non e possibile aprire il file all'interno dell'oggetto zip;
 * * non e possibile creare il file estratto;
 * * si e rilevato un errore nella copia dei dati (1);
 * * non e stato possibile chiudere il file all'interno dell'oggetto zip (1);
 *
 * (1): prima di uscire dalla funzione cancella il file estratto.
 */
bool JlCompress::extractFile(QuaZip* zip, QString fileName, QString fileDest) {
    // zip: oggetto dove aggiungere il file
    // filename: nome del file reale
    // fileincompress: nome del file all'interno del file compresso

    // Controllo l'apertura dello zip
    if (!zip) return false;
    if (zip->getMode()!=QuaZip::mdUnzip) return false;

    // Apro il file compresso
    if (!fileName.isEmpty())
        zip->setCurrentFile(fileName);
    QuaZipFile inFile(zip);
    if(!inFile.open(QIODevice::ReadOnly) || inFile.getZipError()!=UNZ_OK) return false;

    // Controllo esistenza cartella file risultato
    QDir curDir;
    if (fileDest.endsWith('/')) {
        if (!curDir.mkpath(fileDest)) {
            return false;
        }
    } else {
        if (!curDir.mkpath(QFileInfo(fileDest).absolutePath())) {
            return false;
        }
    }

    QuaZipFileInfo64 info;
    if (!zip->getCurrentFileInfo(&info))
        return false;

    QFile::Permissions srcPerm = info.getPermissions();
    if (fileDest.endsWith('/') && QFileInfo(fileDest).isDir()) {
        if (srcPerm != 0) {
            QFile(fileDest).setPermissions(srcPerm);
        }
        return true;
    }

    // Apro il file risultato
    QFile outFile;
    outFile.setFileName(fileDest);
    if(!outFile.open(QIODevice::WriteOnly)) return false;

    // Copio i dati
    if (!copyData(inFile, outFile) || inFile.getZipError()!=UNZ_OK) {
        outFile.close();
        removeFile(QStringList(fileDest));
        return false;
    }
    outFile.close();

    // Chiudo i file
    inFile.close();
    if (inFile.getZipError()!=UNZ_OK) {
        removeFile(QStringList(fileDest));
        return false;
    }

    if (srcPerm != 0) {
        outFile.setPermissions(srcPerm);
    }
    return true;
}
Beispiel #20
0
static QString acquire_base_path (void)
{
  QString proc_path = "/proc/";
  QString maps_file = "/maps";

  QString pid_as_string = QString::number (getpid ());
  
  QString the_maps = proc_path % pid_as_string % maps_file;
  
  QFile file (the_maps);

  if (!file.open (QIODevice::ReadOnly | QIODevice::Text))
    {
      qDebug () << "FATAL: Don't know how to open: " << the_maps;
      exit (1);
    }

  QString base_path;

  QTextStream in (&file);

  QRegExp splitter ("^[^\\s]+\\s+[^\\s]+\\s+[^\\s]+\\s+[^\\s]+\\s+[^\\s]+\\s+");
  QString line;
  
  do
    {
      line = in.readLine ();
      
      if (line.isNull ())
	{
	  qDebug () << "FATAL: Can't determine base path";
	  exit (1);
	}

      // Find if line contains our library name (librfgis_android_wrap.so)
      
      QString end = line.split (splitter).last ();

      QStringList path_elements = end.split ("/");

      if (path_elements.last () == "librfgis.so")
	{
	  qDebug() << "Found ourselves: " << end;
	  int max_elements = path_elements.size () - 2;
	  for (int i = 0; i < max_elements; i++)
	    {
	      if (i + 1 == max_elements)
		{
		  base_path = base_path % path_elements [i];
		}
	      else
		{
		  base_path = base_path % path_elements [i] % "/";
		}
	    }
	  break;
	}
    }
  while (!line.isNull ());

  return base_path;
}
bool LzNTunnelsSynthesis::loadBaseClearanceTemplateData(OutputClearanceImageType type)
{
    hasinitBaseClearanceData = false;
    baseClearandeData.initMaps();

    QFile file;
    QString in;

    QString typefilename = "";
    switch (type)
    {
        case OutputClearanceImageType::OutType_B_NeiRan: typefilename = "BaseClearance_B_NeiRan.sec"; break;
        case OutputClearanceImageType::OutType_B_DianLi: typefilename = "BaseClearance_B_DianLi.sec"; break;
        case OutputClearanceImageType::OutType_D_NeiRan: typefilename = "BaseClearance_D_NeiRan.sec"; break;
        case OutputClearanceImageType::OutType_D_DianLi: typefilename = "BaseClearance_D_DianLi.sec"; break;
        default: typefilename = "BaseClearance_B_DianLi.sec"; break;
    }

    QString filename = QString::fromLocal8Bit(templatepath.c_str()) + "/" + typefilename;
    qDebug() << "filename " << filename;
    file.setFileName(filename);

    // Currently here for debugging purposes
    qDebug() << "Reading file: " << filename.toLocal8Bit().data() << endl;

    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream inStream(&file);
        
        // readfile
        
        in = inStream.readLine();

        int height;
        int left;
        int right;

        while(!(in.isNull()))
        {
            height = in.section("\t",0,0).toInt();
            left = in.section("\t",1,1).toInt();
            // Reads in fifth column: signal-to-noise ratio
            right = in.section("\t",2,2).toInt();
            
            baseClearandeData.updateToMapVals(height, (float)left, (float)right);

            in = inStream.readLine();
        }

        file.close();

        qDebug() << "read_end" << endl;
        hasinitBaseClearanceData = true;
        return true;
    }
    // Do some proper debugging here at some point...
    else 
    {
        std::cout << "Problem reading file: " << filename.toLocal8Bit().data() << std::endl;
        hasinitBaseClearanceData = false;
        return false;
    }
}
Beispiel #22
0
QString MyString::dataToPullbackDotString(Data *data)
{
    QString buffer;

    //exp
    buffer += MyString::stateVectorToPullbackString(data->affordanceStates);
    buffer += MyString::arrowVectorToPullbackString(data->affordanceEdges);
    buffer += MyString::stateVectorToPullbackString(data->actionStates);
    buffer += MyString::arrowVectorToPullbackString(data->actionEdges);
    buffer += MyString::stateVectorToPullbackString(data->abstractStates);
    buffer += MyString::arrowVectorToPullbackString(data->abstractEdges);

    buffer += MyString::stateMappingsToPullbackString(data->mapAffordanceToAbstractNodes); //separate collection for states needed?
    buffer += "\n";
    buffer += MyString::edgeMappingsToPullbackString(data->mapAffordanceToAbstractEdges);
    buffer += "\n";
    buffer += MyString::stateMappingsToPullbackString(data->mapActionToAbstractNodes);
    buffer += "\n";
    buffer += MyString::edgeMappingsToPullbackString(data->mapActionToAbstractEdges);
    buffer += "\n";

    //fetch dot file from Haskell routine
    QString tempPath = QDir::tempPath();

    QString serializePath, dotPath;

    for (int i = 0; ; i++)
    {
        serializePath = tempPath;
        serializePath += "/uic";
        serializePath += QString::number(i);
        serializePath += + ".txt";
        if (!QFile::exists(serializePath))
            break;
    }

    for (int j = 0; ; j++)
    {
        dotPath = tempPath;
        dotPath += "/uic";
        dotPath += QString::number(j);
        dotPath += ".dot";
        if (!QFile::exists(dotPath))
            break;
    }

    QFile serializeFile(serializePath);
    serializeFile.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&serializeFile);
    out << buffer;
    serializeFile.close();

    //qDebug() << "Wrote string:\n" << buffer << "to file: " << serializePath;

#ifdef Q_OS_LINUX
    QProcess::execute("cd /tmp");
#endif

    QString haskellCmd;
    haskellCmd += QCoreApplication::applicationDirPath();
    haskellCmd += "/bin/pullbacks_first ";
    haskellCmd += serializePath;
    haskellCmd += " ";
    haskellCmd += dotPath;

    qDebug() << haskellCmd;
    int ret = QProcess::execute(haskellCmd);

    if (ret)
    {
        qDebug() << "Haskell command returned error value";
        qDebug() << "Wrote string:\n" << buffer << "to file: " << serializePath;
        return "";
    }

    //read dot file
    QString dot;

    QFile file;
    file.setFileName(dotPath);
    file.open(QIODevice::ReadOnly);
    dot = file.readAll();
    file.close();

    return dot;
}
Beispiel #23
0
int main(int argc, char *argv[])
{
  QMap<QString,ParamPair> paramList;
  QString username  = "";
  QString filename;
  QString printerName;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    print           = FALSE;
  bool    printPreview    = FALSE;
  bool    close           = FALSE;
  int     numCopies       = 1;
  // BVI::Sednacom
  // new options
  bool    pdfOutput = FALSE;
  QString pdfFileName;
  // BVI::Sednacom

  QString databaseURL = "";
  QString loadFromDB = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");

  OpenRPT::languages.addTranslationToDefault(":/common.qm");
  OpenRPT::languages.addTranslationToDefault(":/wrtembed.qm");
  OpenRPT::languages.addTranslationToDefault(":/renderer.qm");
  OpenRPT::languages.addTranslationToDefault(":/renderapp.qm");
  OpenRPT::languages.installSelected();

  if (app.argc() > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd          = FALSE;
    QString passwd              = "";

    QStringList arguments;
    QString firstArgument = QString( app.argv()[ 1 ] );

    if( firstArgument.startsWith("-fromStdin=", Qt::CaseInsensitive) ){
      QFile file;
      file.open(stdin, QIODevice::ReadOnly);
      QTextStream in(&file);
      in.setCodec( firstArgument.right( firstArgument.length() - 11 ).toAscii() ); 
      QString arg;
      while( arg.compare("-launch") !=0 ){
        arg = in.readLine();
        arguments << arg;
      }
      file.close();
    }
    else{
      for (int intCounter = 1; intCounter < app.argc(); intCounter++){
        arguments << QString (app.argv()[intCounter]);
      }
    }

    for ( QStringList::Iterator it = arguments.begin(); it != arguments.end(); ++it ) {
      QString argument( *it );

      if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive)) {
        haveDatabaseURL = TRUE;
        databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-noauth")
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      }
      else if (argument.startsWith("-numCopies=", Qt::CaseInsensitive)){
        numCopies = argument.right( argument.length() - 11).toInt();
      }
      else if (argument.toLower() == "-print")
        print = true;
      else if (argument.toLower() == "-printpreview")
        printPreview = true;
      else if (argument.toLower() == "-close")
        close = true;
      else if (argument.startsWith("-printerName=", Qt::CaseInsensitive))
        printerName = argument.right(argument.length() - 13);
      else if (argument.startsWith("-param=", Qt::CaseInsensitive))
      {
        QString str = argument.right(argument.length() - 7);
        bool active = true;
        QString name;
        QString type;
        QString value;
        QVariant var;
        int sep = str.indexOf('=');
        if(sep == -1)
          name = str;
        else
        {
          name = str.left(sep);
          value = str.right(str.length() - (sep + 1));
        }
        str = name;
        sep = str.indexOf(':');
        if(sep != -1)
        {
          name = str.left(sep);
          type = str.right(str.length() - (sep + 1));
        }
        if(name.startsWith("-"))
        {
          name = name.right(name.length() - 1);
          active = false;
        }
        else if(name.startsWith("+"))
          name = name.right(name.length() - 1);
        if(!value.isEmpty())
          var = XVariant::decode(type, value);
        paramList[name] = ParamPair(active, var);
      }
      // BVI::Sednacom
      // manage new arguments for CLI
      else if (argument.startsWith("-pdf", Qt::CaseInsensitive)) {
        pdfOutput = true ;
      }
      else if (argument.startsWith("-outpdf=", Qt::CaseInsensitive)) {
        pdfFileName = argument.right(argument.length() - 8 ) ;
      }
      // BVI::Sednacom
      else if (argument.startsWith("-loadfromdb=", Qt::CaseInsensitive))
        loadFromDB = argument.right(argument.length() - 12);
      else if (argument.toLower() == "-e")
        XSqlQuery::setNameErrorValue("Missing");
      else if(!argument.startsWith("-"))
        filename = argument;
    }

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
    {
      QSqlDatabase db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the database driver. Please contact your systems administrator."));
        QApplication::exit(-1);
      }

      db.setUserName(username);
      db.setPassword(passwd);

      if (!db.open())
      {
        QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information."));
        QApplication::exit(-1);
      }
      else
        loggedIn = TRUE;
    }

  }

  if(!loggedIn)
  {
    ParameterList params;
    params.append("name",      RenderWindow::name());
    params.append("copyright", OpenRPT::copyright);
    params.append("version",   OpenRPT::version);
    params.append("build",     OpenRPT::build);

    if (haveUsername)
      params.append("username", username);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    login newdlg(0, "", TRUE);
    newdlg.set(params, 0);

    if (newdlg.exec() == QDialog::Rejected)
      return -1;
  }

  // The following is code that works specifically with the xTuple ERP database
  // This should be expanded to be usefull when not connecting to an xTuple ERP
  // database as well. Command line option maybe?
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList paths;
    paths << "dict";
    paths << "";
    paths << "../dict";
    paths << app.applicationDirPath() + "/dict";
    paths << app.applicationDirPath();
    paths << app.applicationDirPath() + "/../dict";
#if defined Q_WS_MACX
    paths << app.applicationDirPath() + "/../../../dict";
    paths << app.applicationDirPath() + "/../../..";
#endif

    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    QString langext;
    if (!langq.value("lang_abbr2").toString().isEmpty() &&
        !langq.value("country_abbr").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString() + "_" +
                langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString();
    }

    if(!langext.isEmpty())
    {
      files << "reports." + langext;

      XSqlQuery pkglist("SELECT pkghead_name FROM pkghead WHERE packageIsEnabled(pkghead_name);");
      while(pkglist.next())
      {
        files << pkglist.value("pkghead_name").toString() + "." + langext;
      }
    }

    if (files.size() > 0)
    {
      QTranslator *translator = new QTranslator(&app);
      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit)
        {
          qDebug("looking for %s in %s", (*fit).toAscii().data(), (*pit).toAscii().data());
          if (translator->load(*fit, *pit))
          {
            app.installTranslator(translator);
            qDebug("installed %s/%s", (*pit).toAscii().data(), (*fit).toAscii().data());
            translator = new QTranslator(&app);
            break;
          }
        }
      }
    }
  }
  // END language loading code

  RenderWindow mainwin;

  mainwin._printerName = printerName;

  if(!filename.isEmpty())
    mainwin.fileOpen(filename);
  if(!loadFromDB.isEmpty())
    mainwin.fileLoad(loadFromDB);

  QMap<QString,ParamPair>::Iterator it;
  for ( it = paramList.begin(); it != paramList.end(); ++it ) {
    mainwin.updateParam(it.key(), it.value().second, it.value().first);
  }

  // BVI::Sednacom
  // do not display window for PDF output
  if (!pdfOutput)
    mainwin.show();
  // BVI::Sednacom

  if(print)
    mainwin.filePrint( numCopies );

  if(printPreview)
    mainwin.filePreview( numCopies );

  // BVI::Sednacom
  // generate the PDF
  if (pdfOutput)
    mainwin.filePrintToPDF(pdfFileName);  
  // BVI::Sednacom

  if(close)
  {
    mainwin.fileExit();
    return 0;
  }

  return app.exec();
}
Beispiel #24
0
bool RC2UI::makeDialog()
{
    line = in->readLine();
    do {
        QFile fileOut;
	QString buffer;
	int count;
	QCString className;
	uint x, y, w, h;
	uint endDesc;
	bool space = FALSE;
	for ( endDesc = 0; endDesc < line.length() ; endDesc++ ) {
	    char c = (QChar)line.at(endDesc);
	    if ( space && (c >= '0') && (c <= '9') )
		break;
	    space = c==' ';
	}

	QString desc = line.left(endDesc-1);
	line = line.right( line.length() - endDesc );

	className = parseNext( desc, ' ' );

 	count = sscanf( line, "%u, %u, %u, %u", &x, &y, &w, &h );

	if ( !count && count == EOF )
	    return FALSE;

	char property[256];
	QStringList styles;
	QStringList extendedStyles;
	QString caption = "";
	QString baseClass = "";
	QString widgetType;
	QString widgetName;
	QString arguments;
	int pointsize = 10;
	QString fontname;
	do {
	    line = "";
	    do {
		if ( in->eof() )
		    return TRUE;
		line += in->readLine();
	    } while ( line[(int)line.length()-1] == '|' ||
		      line[(int)line.length()-1] == ',' );
	    count = sscanf( line, "%s", property );
	    line = line.right( line.length() - line.find(" ") -1 );
	    if ( QString(property) == "STYLE" ) {
		styles = splitStyles(line);
		if ( styles.contains( "WS_CAPTION" ) )
		    baseClass = "QDialog";
		else
		    baseClass = "QWidget";
	    } else if ( QString(property) == "CAPTION" ) {
		caption = stripQM( line );
	    } else if ( QString(property) == "FONT" ) {
		QString pt = line.left( line.find(",") );
		pointsize = pt.toInt();
		fontname = stripQM(line.right( line.length() - line.find(",") - 2 ));
	    }
	} while ( line != "BEGIN" );

	if ( writeToFile ) {

	    QString outputFile = QString(className) + ".ui";
	    fileOut.setName( outputFile );
	    if (!fileOut.open( IO_WriteOnly ) )
		qFatal( "rc2ui: Could not open output file '%s'", outputFile.latin1() );
	    out = new QTextStream( &fileOut );
	    targetFiles.append( outputFile );
	} else {
	    out = new QTextStream( &buffer, IO_WriteOnly );
	}

	*out << "<!DOCTYPE UI><UI>" << endl;
	writeClass( className );
	wi(); *out << "<widget>"<< endl; indent();
	writeClass( baseClass );
	writeCString( "name", className );
	writeRect( "geometry", x, y, w, h );
	writeString( "caption", caption );
	writeFont( fontname, pointsize );

	do {
	    if ( in->eof() )
		return TRUE;

	    line = in->readLine().stripWhiteSpace();
	    if ( line == "END" )
		continue;

	    widgetType = parseNext(line, ' ');
	    arguments = line.stripWhiteSpace();
	    while ( arguments[(int)arguments.length()-1] == ',' ||
		    arguments[(int)arguments.length()-1] == '|'  )
		arguments += " "+in->readLine().stripWhiteSpace();

	    wi(); *out << "<widget>" << endl; indent();

	    WidgetType ID = IDUnknown;
	    QString controlType;
	    QString widgetID;
	    QString widgetText;
	    bool hasText = FALSE;
	    bool isControl = FALSE;
	    bool isFrame = FALSE;

	    if ( widgetType == "PUSHBUTTON" ) {
		ID = IDPushButton;
		hasText = TRUE;
	    } else if ( widgetType == "DEFPUSHBUTTON" ) {
		ID = IDPushButton;
		hasText = TRUE;
	    } else if ( widgetType == "LTEXT" ) {
		ID = IDLabel;
		hasText = TRUE;
	    } else if ( widgetType == "CTEXT" ) {
		ID = IDLabel;
		hasText = TRUE;
	    } else if ( widgetType == "RTEXT" ) {
		ID = IDLabel;
		hasText = TRUE;
	    } else if ( widgetType == "EDITTEXT" ) {
		ID = IDLineEdit;
	    } else if ( widgetType == "GROUPBOX" ) {
		ID = IDGroupBox;
		hasText = TRUE;
	    } else if ( widgetType == "COMBOBOX" ) {
		ID = IDComboBox;
	    } else if ( widgetType == "LISTBOX" ) {
		ID = IDListBox;
	    } else if ( widgetType == "SCROLLBAR" ) {
		ID = IDScrollBar;
	    } else if ( widgetType == "CHECKBOX" ) {
		ID = IDCheckBox;
		hasText = TRUE;
	    } else if ( widgetType == "RADIOBUTTON" ) {
		ID = IDRadioButton;
		hasText = TRUE;
	    } else if ( widgetType == "CONTROL" ) {
		isControl = TRUE;
		widgetText = stripQM(parseNext( arguments ));
		widgetID = parseNext( arguments );
		controlType = stripQM(parseNext( arguments ));
		styles = splitStyles(parseNext( arguments ));

		if ( controlType == "Static" ) {
		    ID = IDLabel;
		} else if ( controlType == "Button" ) {
		    if ( styles.contains("BS_AUTOCHECKBOX") ||
			 styles.contains("BS_3STATE") )
			ID = IDCheckBox;
		    else if ( styles.contains("BS_AUTORADIOBUTTON") )
			ID = IDRadioButton;
		} else if ( controlType == "msctls_updown32" ) {
		    ID = IDSpinBox;
		} else if ( controlType == "msctls_progress32" ) {
		    ID = IDProgressBar;
		} else if ( controlType == "msctls_trackbar32" ) {
		    ID = IDSlider;
		} else if ( controlType == "SysListView32" ) {
		    ID = IDIconView;
		} else if ( controlType == "SysTreeView32" ) {
		    ID = IDListView;
		} else if ( controlType == "SysTabControl32" ) {
		    ID = IDTabWidget;
		} else if ( controlType == "SysAnimate32" ) {
		    ID = IDLabel;
		} else if ( controlType == "RICHEDIT" ) {
		    ID = IDMultiLineEdit;
		} else if ( controlType == "ComboBoxEx32" ) {
		    ID = IDComboBox;
		} else if ( controlType == "" ) {
		    ID = IDCustom;
		} else {
		    ID = IDUnknown;
		}
	    } else
		ID = IDUnknown;

	    if ( hasText )
		widgetText = stripQM(parseNext( arguments ));

	    if ( isControl ) {
		x = parseNext( arguments ).toInt();
		y = parseNext( arguments ).toInt();
		w = parseNext( arguments ).toInt();
		h = parseNext( arguments ).toInt();
	    } else {
		widgetID = parseNext( arguments );
		x = parseNext( arguments ).toInt();
		y = parseNext( arguments ).toInt();
		w = parseNext( arguments ).toInt();
		h = parseNext( arguments ).toInt();
		styles.clear();
	    }

	    do {
		extendedStyles = splitStyles(parseNext( arguments ));
		for ( uint i = 0; i < extendedStyles.count(); i++ )
		    styles << (*extendedStyles.at(i));
	    } while ( arguments.find(',') > -1 );

	    switch ( ID ) {
	    case IDWidget:
		break;
	    case IDPushButton:
		{
		    writeClass("QPushButton");
		    writeCString( "name", useName("PushButton_"+widgetID) );
		    writeRect( "geometry", x, y, w, h );
		    writeString( "text", widgetText );
		    if ( widgetType == "DEFPUSHBUTTON" )
			writeBool( "default", TRUE );
		}
		break;
	    case IDLabel:
		{
		    isFrame = TRUE,
		    writeClass("QLabel");
		    writeCString( "name", useName("Label_"+widgetID) );
		    writeRect( "geometry", x,y,w,h );
		    writeString( "text", widgetText );
		    QString align;
		    if ( !styles.contains("SS_CENTERIMAGE") )
			align += "|AlignTop";
		    else
			align += "|AlignVCenter";
		    if ( widgetType == "LTEXT" ) {
			align += "|AlignLeft";
		    } else if ( widgetType == "CTEXT") {
			align += "|AlignHCenter";
		    } else if ( widgetType == "RTEXT") {
			align += "|AlignRight";
		    }
		    writeSet("alignment", align );
		}
		break;
	    case IDCheckBox:
		{
		    writeClass("QCheckBox");
		    writeCString("name", useName("CheckBox_"+widgetID) );
		    writeRect("geometry", x,y,w,h);
		    writeString("text", widgetText );
		    if ( styles.contains( "BS_3STATE" ) )
			writeBool( "tristate", TRUE );
		}
		break;
	    case IDRadioButton:
		{
		    writeClass("QRadioButton");
		    writeCString("name", useName("RadioButton_"+widgetID) );
		    writeRect("geometry", x,y,w,h);
		    writeString("text", widgetText );
		}
		break;
	    case IDGroupBox:
		{
		    isFrame = TRUE;
		    writeClass("QGroupBox");
		    writeCString( "name", useName("GroupBox_"+widgetID) );
		    writeRect( "geometry", x,y,w,h );
		    writeString( "title", widgetText );
		    if ( !styles.contains( "WS_BORDER" ) )
			styles.append( "WS_BORDER" );
		}
		break;
	    case IDLineEdit:
		{
		    if ( !styles.contains("ES_MULTILINE") ) {
			writeClass("QLineEdit");
			writeCString( "name", useName("LineEdit_"+widgetID) );
		    } else {
			writeClass("QMultiLineEdit");
			writeCString( "name", useName("MultiLineEdit_"+widgetID) );
		    }
		    writeRect( "geometry", x,y,w,h );
		    QString align = "AlignTop";
		    if ( styles.contains("ES_CENTER") )
			align+="|AlignHCenter";
		    else if ( styles.contains("ES_RIGHT") )
			align+="|AlignRight";
		    else
			align+="|AlignLeft";
		    writeSet("alignment", align);
		}
		break;
	    case IDMultiLineEdit:
		{
		    writeClass("QMultiLineEdit");
		    writeCString("name", useName("MultiLineEdit_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		}
		break;
	    case IDIconView:
		{
		    isFrame = TRUE;
		    writeClass("QIconView");
		    writeCString("name", useName("IconView_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( !styles.contains( "LVS_SINGLESEL" ) )
			writeEnum( "selectionMode", "Extended" );
		    if ( styles.contains( "LVS_NOLABELWRAP" ) )
			writeBool("wordWrapIconText", FALSE );
		}
		break;
	    case IDListView:
		{
		    isFrame = TRUE;
		    writeClass("QListView");
		    writeCString("name", useName("ListView_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains( "TVS_LINESATROOT" ) )
			writeBool( "rootIsDecorated", TRUE );
		    if ( styles.contains( "TVS_FULLROWSELECT" ) )
			writeBool( "allColumnsShowFocus", TRUE );
		}
		break;
	    case IDProgressBar:
		{
		    isFrame = TRUE;
		    writeClass("QProgressBar");
		    writeCString("name", useName("ProgressBar_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains("TBS_VERT") )
			writeEnum("orientation", "Vertical");
		    else
			writeEnum("orientation", "Horizontal");
		}
		break;
	    case IDTabWidget:
		{
		    writeClass("QTabWidget");
		    writeCString("name", useName("TabWidget_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    wi(); *out << "<widget>" << endl; indent();
		    writeClass("QWidget");
		    wi(); *out << "<attribute>" << endl; indent();
		    wi(); *out << "<name>title</name>" << endl;
		    wi(); *out << "<string>Tab1</string>" << endl; undent();
		    wi(); *out << "</attribute>" << endl; undent();
		    wi(); *out << "</widget>" << endl;
		}
		break;
	    case IDSpinBox:
		{
		    isFrame = TRUE;
		    writeClass("QSpinBox");
		    writeCString("name", useName("SpinBox_"+widgetID) );
		    writeRect("geometry", x,y,w,h);
		}
		break;
	    case IDSlider:
		{
		    writeClass("QSlider");
		    writeCString("name", useName("Slider_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains("TBS_VERT") )
			writeEnum("orientation", "Vertical");
		    else
			writeEnum("orientation", "Horizontal");
		    if ( !styles.contains("TBS_NOTICKS") )
			writeEnum("tickmarks", "Left" );
		}
		break;
	    case IDComboBox:
		{
		    writeClass("QComboBox");
		    writeCString("name", useName("ComboBox_"+widgetID) );
		    if ( isControl )
			writeRect( "geometry", x,y,w,14 );
		    else
			writeRect( "geometry", x,y,w,h );
		}
		break;
	    case IDListBox:
		{
		    isFrame = TRUE;
		    writeClass("QListBox");
		    writeCString("name", useName("ListBox_"+widgetID) );
		    writeRect( "geometry", x,y,w,h );
		    if ( styles.contains("WS_HSCROLL") )
			writeEnum("hScrollBarMode", "Auto");
		    else
			writeEnum("hScrollBarMode", "AlwaysOff");
		    if ( styles.contains("WS_VSCROLL") )
			writeEnum("vScrollBarMode", "Auto");
		    else
			writeEnum("vScrollBarMode", "AlwaysOff");
		    if ( styles.contains("LBS_EXTENDEDSEL") )
			writeEnum("selectionMode", "Extended");
		    else if ( styles.contains("LBS_MULTIPLESEL") )
			writeEnum("selectionMode", "Multi");
		    else if ( styles.contains("LBS_NOSEL") )
			writeEnum("selectionMode", "NoSelection");
		    else
			writeEnum("selectionMode", "Single");
		    if ( !styles.contains( "NO WS_BORDER" ) )
			styles.append( "WS_BORDER" );
		}
		break;
	    case IDScrollBar:
		{
		    writeClass("QScrollBar");
		    writeCString("name", useName("ScrollBar_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains("SBS_VERT") )
			writeEnum("orientation", "Vertical");
		    else
			writeEnum("orientation", "Horizontal");
		}
		break;
	    case IDCustom:
		{
		    writeClass("QLabel");
		    writeCString("name", useName("Custom_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    writeString("text", "Create a custom widget and place it here." );
		}
	    default:
		{
		    writeClass("QLabel");
		    writeCString("name", useName("Unknown_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    writeString("text", QString("No support for %1.").arg(controlType) );
		}
		break;
	    }

	    writeStyles( styles, isFrame );

	    styles.clear();

	    undent();
	    wi(); *out << "</widget>" << endl;
	} while ( line != "END" );

	undent();
	wi(); *out << "</widget>" << endl;
	*out << "</UI>" << endl;

	do {
	    line = in->readLine();
	} while ( line.isEmpty() );

	if ( !writeToFile )
	    target.append( buffer.copy() );

	if (out) {
	    delete out;
	    out = 0;
	}
	fileOut.close();

    } while ( line != blockStart1 );

    return TRUE;
}
// -------------------------------------------------------------------------
bool SpiceDialog::loadSpiceNetList(const QString& s)
{
  Comp->withSim = false;
  if(s.isEmpty()) return false;
  QFileInfo FileInfo(QucsWorkDir, s);

  NodesList->clear();
  PortsList->clear();
  textStatus = 0;
  Line = Error = "";

  QString preprocessor = PrepCombo->currentText();
  if (preprocessor != "none") {
    bool piping = true;
    QString script;
#ifdef __MINGW32__
    QString interpreter = "tinyperl.exe";
#else
    QString interpreter = "perl";
#endif
    if (preprocessor == "ps2sp") {
      script = "ps2sp";
    } else if (preprocessor == "spicepp") {
      script = "spicepp.pl";
    } else if (preprocessor == "spiceprm") {
      script = "spiceprm";
      piping = false;
    }
    script = QucsSettings.BinDir + script;
    SpicePrep = new Q3Process(this);
    SpicePrep->addArgument(interpreter);
    SpicePrep->addArgument(script);
    SpicePrep->addArgument(FileInfo.filePath());

    QFile PrepFile;
    QFileInfo PrepInfo(QucsWorkDir, s + ".pre");
    QString PrepName = PrepInfo.filePath();

    if (!piping) {
      SpicePrep->addArgument(PrepName);
      connect(SpicePrep, SIGNAL(readyReadStdout()), SLOT(slotSkipOut()));
      connect(SpicePrep, SIGNAL(readyReadStderr()), SLOT(slotGetPrepErr()));
    } else {
      connect(SpicePrep, SIGNAL(readyReadStdout()), SLOT(slotGetPrepOut()));
      connect(SpicePrep, SIGNAL(readyReadStderr()), SLOT(slotGetPrepErr()));
    }

    QMessageBox *MBox = new QMessageBox(tr("Info"),
	       tr("Preprocessing SPICE file \"%1\".").arg(FileInfo.filePath()),
               QMessageBox::NoIcon, QMessageBox::Abort,
               QMessageBox::NoButton, QMessageBox::NoButton, this, 0, true,
	       Qt::WStyle_DialogBorder |  Qt::WDestructiveClose);
    connect(SpicePrep, SIGNAL(processExited()), MBox, SLOT(close()));

    if (piping) {
      PrepFile.setName(PrepName);
      if(!PrepFile.open(QIODevice::WriteOnly)) {
	QMessageBox::critical(this, tr("Error"),
          tr("Cannot save preprocessed SPICE file \"%1\".").
	  arg(PrepName));
	return false;
      }
      prestream = new Q3TextStream(&PrepFile);
    }

    if(!SpicePrep->start()) {
      QMessageBox::critical(this, tr("Error"),
        tr("Cannot execute \"%1\".").arg(interpreter + " " + script));
      if (piping) {
	PrepFile.close();
	delete prestream;
      }
      return false;
    }
    SpicePrep->closeStdin();

    MBox->exec();
    delete SpicePrep;
    if (piping) {
      PrepFile.close();
      delete prestream;
    }

    if(!Error.isEmpty()) {
      QMessageBox::critical(this, tr("SPICE Preprocessor Error"), Error);
      return false;
    }
    FileInfo = QFileInfo(QucsWorkDir, s + ".pre");
  }

  // first call Qucsconv ............
  QucsConv = new Q3Process(this);
  QucsConv->addArgument(QucsSettings.BinDir + "qucsconv");
  QucsConv->addArgument("-if");
  QucsConv->addArgument("spice");
  QucsConv->addArgument("-of");
  QucsConv->addArgument("qucs");
  QucsConv->addArgument("-i");
  QucsConv->addArgument(FileInfo.filePath());
  connect(QucsConv, SIGNAL(readyReadStdout()), SLOT(slotGetNetlist()));
  connect(QucsConv, SIGNAL(readyReadStderr()), SLOT(slotGetError()));

  QMessageBox *MBox = new QMessageBox(tr("Info"),
	       tr("Converting SPICE file \"%1\".").arg(FileInfo.filePath()),
               QMessageBox::NoIcon, QMessageBox::Abort,
               QMessageBox::NoButton, QMessageBox::NoButton, this, 0, true,
	       Qt::WStyle_DialogBorder |  Qt::WDestructiveClose);
  connect(QucsConv, SIGNAL(processExited()), MBox, SLOT(close()));

  if(!QucsConv->start()) {
    QMessageBox::critical(this, tr("Error"),
      tr("Cannot execute \"%1\".").arg(QucsSettings.BinDir + "qucsconv"));
    return false;
  }
  QucsConv->closeStdin();

  MBox->exec();
  delete QucsConv;

  if(!Error.isEmpty())
    QMessageBox::critical(this, tr("QucsConv Error"), Error);

  Property *pp = Comp->Props.at(1);
  if(!pp->Value.isEmpty()) {
    PortsList->clear();
    PortsList->insertStringList(QStringList::split(',', pp->Value));
  }

  QString tmp;
  Q3ListBoxItem *pi;
  for(unsigned int i=0; i<PortsList->count(); i++) {
    tmp = PortsList->text(i).remove(0, 4);
    PortsList->changeItem(tmp, i);

    pi = NodesList->findItem(tmp, Qt::CaseSensitive | QKeySequence::ExactMatch);
    if(pi) delete pi;
    else PortsList->removeItem(i--);
  }
  return true;
}
Beispiel #26
0
bool RC2UI::makeStringTable()
{
    if ( !writeToFile )
	return TRUE;

    QFile fileOut;
    line = in->readLine();
    do {
	char stringtable[256];
	char discard[12];
	sscanf( line, "%s %s", stringtable, discard );
	if ( QString(stringtable) != "STRINGTABLE" )
	    return TRUE;
	do {
	    line = in->readLine();
	} while ( line != "BEGIN" );

	QString outputFile = QString(stringtable).lower() + ".h";
	if (outputFile ) {
	    fileOut.setName( outputFile );
	    if (!fileOut.open( IO_WriteOnly ) )
		qFatal( "rc2ui: Could not open output file '%s'", outputFile.latin1() );
	    out = new QTextStream( &fileOut );
	}

	*out << "#ifndef STRINGTABLE_H" << endl;
	*out << "#define STRINGTABLE_H" << endl;
	*out << endl;
	*out << "#include <qstring.h>" << endl;
	*out << "#include <qobject.h>" << endl;
	*out << endl;

	QString ID;
	QString value;
	do {
	    line = in->readLine().stripWhiteSpace();
	    if ( line == "END" )
		continue;

	    ID = parseNext(line, ' ');
	    value = parseNext(line).stripWhiteSpace();

	    *out << "static const QString " << ID << "= QT_TR_NOOP(" << value << ");" << endl;

	} while ( line != "END" );

	*out << endl;
	*out << "#endif // STRINGTABLE_H" << endl;

	do {
	    line = in->readLine();
	} while ( line.isEmpty() );

	if ( out ) {
	    delete out;
	    out = 0;
	}
    } while ( line != blockStart1 );

    return TRUE;
}
Beispiel #27
0
void WBWebPage::handleUnsupportedContent(QNetworkReply *reply)
{
    if(reply->url().scheme() == "mailto")
    {
        bool result = QDesktopServices::openUrl(reply->url());
        if (result)
            return;
    }

    QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString();
    bool isPDF = (contentType == "application/pdf");

    // Delete this big "if (isPDF)" block to get the pdf directly inside the browser
    if (isPDF)
    {
        QMessageBox messageBox(mainWindow());
        messageBox.setText(tr("Download PDF Document: would you prefer to download the PDF file or add it to the current OpenBoard document?"));

        messageBox.addButton(tr("Download"), QMessageBox::AcceptRole);
        QAbstractButton *addButton = messageBox.addButton(tr("Add to Current Document"), QMessageBox::AcceptRole);

        messageBox.exec();
        if (messageBox.clickedButton() == addButton)
        {
            UBApplication::applicationController->showBoard();
            UBApplication::boardController->downloadURL(reply->request().url());
            return;
        }
        else
        {
            isPDF = false;
        }
    }

    if (!isPDF && reply->error() == QNetworkReply::NoError)
    {
        if(contentType == "application/widget")
            WBBrowserWindow::downloadManager()->handleUnsupportedContent(reply,false, UBSettings::settings()->userGipLibraryDirectory());
        else
            WBBrowserWindow::downloadManager()->handleUnsupportedContent(reply);
        return;
    }

    QFile file;
    file.setFileName(isPDF ? QLatin1String(":/webbrowser/object-wrapper.html") : QLatin1String(":/webbrowser/notfound.html"));

    bool isOpened = file.open(QIODevice::ReadOnly);
    Q_ASSERT(isOpened);
    QString html;
    if (isPDF)
    {
        html = QString(QLatin1String(file.readAll()))
                        .arg(tr("PDF"))
                        .arg("application/x-ub-pdf")
                        .arg(reply->url().toString());
    }
    else
    {
        QString title = tr("Error loading page: %1").arg(reply->url().toString());
        html = QString(QLatin1String(file.readAll()))
                        .arg(title)
                        .arg(reply->errorString())
                        .arg(reply->url().toString());
    }

    QList<QWebFrame*> frames;
    frames.append(mainFrame());
    while (!frames.isEmpty())
    {
        QWebFrame *frame = frames.takeFirst();
        if (frame->url() == reply->url())
        {
            frame->setHtml(html, reply->url());
            return;
        }
        QList<QWebFrame *> children = frame->childFrames();
        foreach(QWebFrame *frame, children)
            frames.append(frame);
    }

    if (mLoadingUrl == reply->url())
    {
        mainFrame()->setHtml(html, reply->url());
    }
}
Beispiel #28
0
void ShortLocater::on_Internal_clicked()
{

/*
            IPsoc->resetRelays();
            usleep(500);
            IPsoc->writeSerial(0x42);
            IPsoc->writeSerial(0x9);
            usleep(500);
            IPsoc->writeSerial(0x42);
            IPsoc->writeSerial(0x15);
            usleep(500);
            IPsoc->writeSerial(0x42);
            IPsoc->writeSerial(0x13);
*/			IPsoc->switchFly();

            ui.Internal->setVisible(false);
            ui.External->setVisible(true);
    		ui.ah1_inner->setVisible(false);
    		ui.ah1_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah1_outer->setGeometry(22,26,41,41);

    		ui.ah2_inner->setVisible(false);
    		ui.ah2_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah2_outer->setGeometry(96,26,41,41);

    		ui.ah3_inner->setVisible(false);
    		ui.ah3_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah3_outer->setGeometry(167,26,41,41);

    		ui.ah0_inner->setVisible(false);
    		ui.ah0_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah0_outer->setGeometry(237,26,41,41);

    		ui.fp_VI1_ICM_SL->setGeometry(24,20,41,41);
    		ui.fp_VI1_ICM_SL->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/new/prefix1/Button-Blank-Gray-icon.png);");

    		ui.fp_VI2_EXT->setGeometry(110,20,41,41);
    		ui.fp_VI2_EXT->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/new/prefix1/Button-Blank-Gray-icon.png);");

    		QStringList stringList;
    		bool ok=true;
    		QFile textFile;
    	    if(ui.External->isVisible())
    	    	textFile.setFileName("shortValuesE.txt");
    	    if(ui.Internal->isVisible())
    	    	textFile.setFileName("shortValuesI.txt");

    	    if (textFile.open(QIODevice::ReadOnly))
    	    {
    	        QTextStream textStream(&textFile);
    	        while (!textStream.atEnd())
    	        {
    	            stringList.append(textStream.readLine());
    	        }
    	        r200EShortValue=stringList.value(0).toDouble(&ok);
    	        qDebug()<<"200E Short Value:"<<r200EShortValue;
    	        r2EShortValue=stringList.value(1).toDouble(&ok);
    	        qDebug()<<"2E Short Value:"<<r2EShortValue;
    	       	r200mEShortValue=stringList.value(2).toDouble(&ok);
    	        qDebug()<<"200mE Short Value:"<<r200mEShortValue;
    	    }else{
    	        r200EShortValue=r200mEShortValue=r2EShortValue=0.0;
    	    }

}
Beispiel #29
0
void Player::playIndex(int index, int listIndex)
{
        qDebug() << "PlayIndex,index: " << index << "listIndex: " << listIndex;
    if(listIndex > -1) {
        if(currentListIndex != listIndex || !listSync) {
            setList(parser->sources[listIndex]);
            currentListIndex = listIndex;
        }
    }

    if(index > playList.size() - 1)
        index = 0;

    prevIndex = curIndex;
    curIndex = index;

    mediaObject->stop();
    setState(Player::STOPED);

    buffer->close();
    buffer->setData("");
    buffer = new QBuffer(mediaObject);


    QFile file;
    QDir::setCurrent(savePath);
    QString fileName = playList[curIndex]["artist"]+" - "+playList[curIndex]["title"]+"__"+playList[curIndex]["opt4"]+".mp3";
    fileName.replace(QRegExp("[?*/\"<>]"), "_");
    file.setFileName(fileName);
    if(file.open(QIODevice::ReadOnly)) {
        emit bufferProgress(1, 1);
        //buffer->setData(file.readAll());
        //buffer->open(QBuffer::ReadWrite);
        if(obCreated) {
            nReply->reset();
            if(nReply->isRunning())
                nReply->abort();
        }
        mediaObject->stop();
        mediaObject->setCurrentSource(Phonon::MediaSource(fileName));
        mediaObject->play();
        setState(Player::PLAY);
        ob2Created = true;
    } else {
        if(bufferOff)
        {
            emit bufferProgress(-1, -1);
            mediaObject->stop();
            mediaObject->setCurrentSource(Phonon::MediaSource(playList[curIndex]["link"]));
            mediaObject->play();
            setState(Player::PLAY);
        } else {
            blockNum = 0;

            QNetworkRequest req;
            req.setUrl(QUrl(playList[curIndex]["link"]));

            if(obCreated) {
                if(nReply->isRunning())
                    nReply->abort();
            }
            canPlay = false;
            nReply = nManager.get(req);
            connect(nReply, SIGNAL(readyRead()), this, SLOT(readData()));
            connect(nReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(dProgress(qint64,qint64)));
            connect(nReply, SIGNAL(finished()), this, SLOT(rFinished()));
            connect(nReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(nError(QNetworkReply::NetworkError)));
            obCreated = true;
        }

    }
    file.close();

    emit curSong(playList[curIndex], curIndex, autoNext);
    autoNext = false;

    QRegExp rx("(.*):(.*)"); // Сиськиии!)
    rx.indexIn(playList[curIndex]["duration"]);
    QString c1 = rx.capturedTexts()[1];
    QString c2 = rx.capturedTexts()[2];
    int dur1 = c1.toInt();
    int dur2 = c2.toInt();
    duration = dur1 * 60;
    duration += dur2;

}
int LoadController::exec()
{
    clean();
    QFile zeus (filename());
    if(!zeus.open(QIODevice::ReadOnly))
    {
        return -1;
    }

    QDomDocument hera;
    if(!hera.setContent(&zeus))
    {
        return -2;
    }

    QDomElement athena = hera.documentElement();
    QDomNodeList hermes = athena.elementsByTagName("user");

    for(int appolon = 0; appolon < hermes.size(); appolon++)
    {
        QDomElement gaia = hermes.at(appolon).toElement();
        UserSPointer ares = UserController::user(cypher(gaia.elementsByTagName("username").at(0).toElement().text(), 57));
        if(ares)
            ares->setType((User::UserType)cypher(gaia.elementsByTagName("type").at(0).toElement().text(), 95).toInt());
    }


    hermes = athena.elementsByTagName("category");

    for(int apollon = 0; apollon < hermes.size(); apollon++)
    {
        if(hermes.at(apollon).parentNode().toElement().tagName() != "subCategory")
        {
            CategorySPointer ares(new Category);
            QDomElement aphrodite = hermes.at(apollon).toElement();
            ares->load(aphrodite);
            if(!categories().contains(ares->name()))
                addCategory(ares);
        }
    }
    hermes = athena.elementsByTagName("entry");

    for(int apollon = 0; apollon < hermes.size(); apollon++)
    {
        if(hermes.at(apollon).parentNode().toElement().tagName() != "subMedia")
        {
            MediaSPointer ares(new Media);
            QDomElement aphrodite = hermes.at(apollon).toElement();
            ares->load(aphrodite, AbstractController::categories());
            if(!medias().contains(qMakePair(ares->category()->name(),ares->name())))
            {
                ares->category()->addAssociations(ares);
                addMedia(ares);
            }
        }
    }

    zeus.close();

    return 0;
}