void PSerialPort::stringToByteArray(QString &src, QByteArray &dst)
{
    for (int i = 0; i < src.size(); i++)
        dst[i] = src[i].cell();
}
void MultisigDialog::on_signTransactionButton_clicked()
{
    ui->signedTransaction->clear();

    if(!model)
        return;

    CWallet *wallet = model->getWallet();

    // Decode the raw transaction
    std::vector<unsigned char> txData(ParseHex(ui->transaction->text().toStdString()));
    CDataStream ss(txData, SER_NETWORK, PROTOCOL_VERSION);
    CTransaction tx;
    try
    {
        ss >> tx;
    }
    catch(std::exception &e)
    {
        (void)e;
        return;
    }
    CTransaction mergedTx(tx);

    // Fetch previous transactions (inputs)
    std::map<COutPoint, CScript> mapPrevOut;
    for(unsigned int i = 0; i < mergedTx.vin.size(); i++)
    {
        CTransaction tempTx;
        MapPrevTx mapPrevTx;
        CTxDB txdb("r");
        std::map<uint256, CTxIndex> unused;
        bool fInvalid;

        tempTx.vin.push_back(mergedTx.vin[i]);
        tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);

        BOOST_FOREACH(const CTxIn& txin, tempTx.vin)
        {
            const uint256& prevHash = txin.prevout.hash;
            if(mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size() > txin.prevout.n)
                mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
        }
    }

    // Add the redeem scripts to the wallet keystore
    for(int i = 0; i < ui->inputs->count(); i++)
    {
        MultisigInputEntry *entry = qobject_cast<MultisigInputEntry *>(ui->inputs->itemAt(i)->widget());
        if(entry)
        {
            QString redeemScriptStr = entry->getRedeemScript();
            if(redeemScriptStr.size() > 0)
            {
                std::vector<unsigned char> scriptData(ParseHex(redeemScriptStr.toStdString()));
                CScript redeemScript(scriptData.begin(), scriptData.end());
                wallet->AddCScript(redeemScript);
            }
        }
    }

    WalletModel::UnlockContext ctx(model->requestUnlock());
    if(!ctx.isValid())
        return;

    // Sign what we can
    bool fComplete = true;
    for(unsigned int i = 0; i < mergedTx.vin.size(); i++)
    {
        CTxIn& txin = mergedTx.vin[i];
        if(mapPrevOut.count(txin.prevout) == 0)
        {
            fComplete = false;
            continue;
        }
        const CScript& prevPubKey = mapPrevOut[txin.prevout];

        txin.scriptSig.clear();
        SignSignature(*wallet, prevPubKey, mergedTx, i, SIGHASH_ALL);
        txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, tx.vin[i].scriptSig);
        if(!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, true, 0))
        {
            fComplete = false;
        }
    }

    CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
    ssTx << mergedTx;
    ui->signedTransaction->setText(HexStr(ssTx.begin(), ssTx.end()).c_str());

    if(fComplete)
    {
        ui->statusLabel->setText(tr("Transaction signature is complete"));
        ui->sendTransactionButton->setEnabled(true);
    }
    else
    {
        ui->statusLabel->setText(tr("Transaction is NOT completely signed"));
        ui->sendTransactionButton->setEnabled(false);
    }
}
Example #3
0
bool PreprocessContext::process(const QString &in, QString *out, QString *errorMessage)
{
    out->clear();
    if (in.isEmpty())
        return true;

    out->reserve(in.size());
    reset();

    const QChar newLine = QLatin1Char('\n');
    const QStringList lines = in.split(newLine, QString::KeepEmptyParts);
    const int lineCount = lines.size();
    bool first = true;
    for (int l = 0; l < lineCount; l++) {
        // Check for element of the stack (be it dummy, else something is wrong).
        if (m_sectionStack.isEmpty()) {
            if (errorMessage)
                *errorMessage = msgEmptyStack(l);
            return false;
        }
        QString expression;
        bool expressionValue = false;
        PreprocessStackEntry &top = m_sectionStack.back();

        switch (preprocessorLine(lines.at(l), &expression)) {
        case IfSection:
            // '@If': Push new section
            if (top.condition) {
                if (!TemplateEngine::evaluateBooleanJavaScriptExpression(m_scriptEngine, expression,
                                                                         &expressionValue, errorMessage)) {
                    if (errorMessage)
                        *errorMessage = QString::fromLatin1("Error in @if at %1: %2")
                            .arg(l + 1).arg(*errorMessage);
                    return false;
                }
            }
            m_sectionStack.push(PreprocessStackEntry(IfSection,
                                                     top.condition, expressionValue, expressionValue));
            break;
        case ElsifSection: // '@elsif': Check condition.
            if (top.section != IfSection && top.section != ElsifSection) {
                if (errorMessage)
                    *errorMessage = QString::fromLatin1("No preceding @if found for @elsif at %1")
                        .arg(l + 1);
                return false;
            }
            if (top.parentEnabled) {
                if (!TemplateEngine::evaluateBooleanJavaScriptExpression(m_scriptEngine, expression,
                                                                         &expressionValue, errorMessage)) {
                    if (errorMessage)
                        *errorMessage = QString::fromLatin1("Error in @elsif at %1: %2")
                            .arg(l + 1).arg(*errorMessage);
                    return false;
                }
            }
            top.section = ElsifSection;
            // ignore consecutive '@elsifs' once something matched
            if (top.anyIfClauseMatched) {
                top.condition = false;
            } else {
                if ( (top.condition = expressionValue) )
                    top.anyIfClauseMatched = true;
            }
            break;
        case ElseSection: // '@else': Check condition.
            if (top.section != IfSection && top.section != ElsifSection) {
                if (errorMessage)
                    *errorMessage = QString::fromLatin1("No preceding @if/@elsif found for @else at %1")
                        .arg(l + 1);
                return false;
            }
            expressionValue = top.parentEnabled && !top.anyIfClauseMatched;
            top.section = ElseSection;
            top.condition = expressionValue;
            break;
        case EndifSection: // '@endif': Discard section.
            m_sectionStack.pop();
            break;
        case OtherSection: // Rest: Append according to current condition.
            if (top.condition) {
                if (first)
                    first = false;
                else
                    out->append(newLine);
                out->append(lines.at(l));
            }
            break;
        } // switch section

    } // for lines
    return true;
}
Example #4
0
Model::Model()
{
    this->background = new QList<Background *>;
    this->floors = new QList<Floor *>;
    this->safes = new QList<Safe*>;
    this->mushroom = new QList<Mushroom *>;
    this->golds = new QList<Gold *>;
    this->flames = new QList<Flame *>;
    this->splashScreen = new SplashScreen(330, 170, ":images/go2.png");
    this->darkEater=new QList<DarkEater *>;
    this->background = new QList<Background *>;
    this->header = new Header();
    this->compteur = new QList<Brick*> ;
    this->mysticTrees = new QList<MysticTree *>;
    this->mario = new Mario(200, 340);
    this->blood = new Blood(0,0);
    this->shock = new Shock(0,0);
    this->encart = new Encart(0,0, "");
    getEncart()->setType(EncartType::NONE);

    QFile fichier(":ModelMap.txt");

    if(fichier.open(QIODevice::ReadOnly))
    {
        QTextStream in (&fichier);
        while(!in.atEnd())
        {
            QString stock = in.readLine();
            if (stock.left(6)=="LIGNEa")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne1.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEb")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne2.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEc")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne3.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEd")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne4.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEe")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne5.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEf")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne6.append(stock.at(i));
                    }
                }
            }
        }
        fichier.close();
    }

    for (int i=0; i<NbrBrickVisible; i++) {
        Floor *k= new Floor(i*brickSize, Hauteur-brickSize, QString(":images/floor_bottom.jpg"));
        floors->append(k);
        Floor *k2= new Floor(i*brickSize, Hauteur-2*brickSize, QString(":images/floor_grass.png"));
        floors->append(k2);
    }
    for (int i=0; i<NbrBrickVisible; i++) {
        Brick *b=new Brick(i*brickSize,Hauteur+brickSize);
        compteur->append(b);
    }
    for (int i=0; i<2; i++) {
        Background* b = new Background(i*Model::Longueur, 0);
        background->append(b);
    }
}
Example #5
0
ApplicationUI::ApplicationUI() : QObject()
{
    backupVolume = 1;
    //OrientationSupport::instance()->setSupportedDisplayOrientation(SupportedDisplayOrientation::DisplayLandscape);
    rotationLocked = screenLocked = FALSE;

    bb::device::DisplayInfo displayInfo;
    screenSize = displayInfo.pixelSize();

    connect(Application::instance(), SIGNAL(asleep()), this, SLOT(onAppAsleep()));
    QStringList foundFilesList;

    QDir sharedPath = QDir::current();
    sharedPath.cd("shared");

    QStringList sharedFoldersContent = sharedPath.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    for(int i=0; i<sharedFoldersContent.size(); i++)
    {
        if(sharedFoldersContent.at(i)!="misc")
        {
            QDir temp = sharedPath;
            temp.cd(sharedFoldersContent.at(i));
            foundFilesList.append(searchForDirs(temp));
        }
    }

    QList<QVariantMap> foundFilesDetails;
    QVariantMap tempMap;
    //tempMap["drive"] = "_device";
    //qDebug()<<"Found List("<<foundFilesList.size()<<")--->>>>";
    QString tempS;
    unsigned short int deviceFilesSize = foundFilesList.size();
    for(int i=0; i<deviceFilesSize; ++i)
    {
        tempS = foundFilesList.at(i);
        tempS = tempS.right(tempS.size() - tempS.indexOf("shared") - 7);
        tempMap["filePath"] = tempS.left(tempS.lastIndexOf('/'));
        tempMap["rootFolder"] = "_DEVICE_" + tempS.left(tempS.indexOf('/'));
        tempMap["fileName"] = tempS.right(tempS.length() - tempS.lastIndexOf('/') - 1);
        foundFilesDetails.append(tempMap);
    }

    /*for(int i=0; i<foundFilesDetails.size(); ++i)
        qDebug()<<foundFilesDetails.at(i);*/
    //qDebug()<<"Search Over";

    //Invoked "/accounts/1000/removable/sdcard/downloads/IMG_03641_edit.jpg"
    QStringList memoryCardFiles;
    QDir rPath = QDir::current();
    //rPath.cdUp();
    //rPath.cdUp();
    rPath.cd("../../removable");
    if(rPath.entryList(QDir::Dirs | QDir::NoDotAndDotDot).contains("sdcard"))
    {
        rPath.cd("sdcard");
        memoryCardFiles.append(searchForDirs(rPath));

        //tempMap["drive"] = "_card";
        unsigned short int cardFilesSize = memoryCardFiles.size();
        for(int i=0; i<cardFilesSize; ++i)
        {
            tempS = memoryCardFiles.at(i);
            tempS = tempS.right(tempS.size() - tempS.indexOf("sdcard") - 7);
            tempMap["filePath"] = tempS.left(tempS.lastIndexOf('/'));
            tempMap["rootFolder"] = "_SDCARD_";// + tempS.left(tempS.indexOf('/'));
            //qDebug()<<tempMap["rootFolder"]
            tempMap["fileName"] = tempS.right(tempS.length() - tempS.lastIndexOf('/') - 1);
            foundFilesDetails.append(tempMap);
        }
    }
    else
    {
        qDebug()<<"No media card";
    }

    /*for(int i=0; i<foundFilesDetails.size();)
    {
        qDebug()<<foundFilesDetails.at(i++);
    }*/

    navPane = NavigationPane::create().
            backButtons(FALSE).
            peek(FALSE);
    Application::instance()->setScene(navPane);
    connect(navPane, SIGNAL(popTransitionEnded(bb::cascades::Page*)), this, SLOT(onClosed()));

    //screen_create_window();

    //screen_window_t controlHandle = new _screen_window;

    /*Window *mainWindow = Application::instance()->mainWindow();

    QString wName = "player_window";

    QByteArray windowName;
    windowName = wName.toLocal8Bit();

    screen_context_t screenContext;
    screen_window_t screenWindow;
    // We must create a context before you create a window.
    if (screen_create_context(&screenContext, SCREEN_APPLICATION_CONTEXT) != 0) {
        qDebug()<<"Unable to take context";
    }
    // Create a child window of the current window group, join the window group and set
    // a window ID.
    else if (screen_create_window_type(&screenWindow, screenContext, SCREEN_CHILD_WINDOW) != 0) {
        qDebug()<<"Unable to create window";
    }
    else if(screen_join_window_group(screenWindow, qPrintable(mainWindow->groupId())) != 0) {
        qDebug()<<"Unable to  join group";
    }
    else if(screen_set_window_property_cv(screenWindow, SCREEN_PROPERTY_ID_STRING, windowName.length(),
            windowName.constData()) != 0) {
        qDebug()<<"Unable to set property";
    }
    else if (screen_set_pixmap_property_iv(screen_pix, SCREEN_PROPERTY_BUFFER_SIZE, mSize) != 0) {
        qDebug()<<"Unable to set pixel map";
    }*/

    control = ForeignWindowControl::create().
            //parent(this).
            //windowHandle(mainWindow->handle()).
            //windowHandle(controlHandle).
            //preferredSize(1280, 768).
            horizontal(HorizontalAlignment::Center).
            vertical(VerticalAlignment::Center).
            windowId("MyWindow").
            updatedProperties(WindowProperty::Size | WindowProperty::Position | WindowProperty::Visible);
    //control->bindToWindow(screenWindow, mainWindow->groupId(), windowName);
    //control->setVisible(TRUE);
    //control->setWindowId("");
    //qDebug()<<"Debug string"<<mainWindow->toDebugString();
    //connect(Application::instance()->mainWindow()->, SIGNAL())

    /*int brightnessValue = 0;
    qDebug()<<"Has error getting?"<<screen_get_window_property_iv(mainWindow->handle(), SCREEN_PROPERTY_BRIGHTNESS, &brightnessValue);
    qDebug()<<"Brightness value:"<<brightnessValue;
    brightnessValue = -255;
    qDebug()<<"Has error setting?"<<screen_set_window_property_iv(mainWindow->handle(), SCREEN_PROPERTY_BRIGHTNESS, &brightnessValue);
    brightnessValue = -128;
    qDebug()<<"Has error setting contrast?"<<screen_set_window_property_iv(mainWindow->handle(), SCREEN_PROPERTY_CONTRAST, &brightnessValue);
    qDebug()<<"Has error getting contrast?"<<screen_get_window_property_iv(mainWindow->handle(), SCREEN_PROPERTY_CONTRAST, &brightnessValue);
    qDebug()<<"Contrast value:"<<brightnessValue;
    qDebug()<<"Has error getting?"<<screen_get_window_property_iv(mainWindow->handle(), SCREEN_PROPERTY_BRIGHTNESS, &brightnessValue);
    qDebug()<<"Brightness value:"<<brightnessValue;*/
    //qDebug()<<errno;

    //TODO
    videoSize = screenSize;
    //control->setPreferredSize(videoSize.width(), videoSize.height());

    /*videoSlider = Slider::create().
            horizontal(HorizontalAlignment::Fill).
            vertical(VerticalAlignment::Bottom).
            from(0).
            to(1);*/
    //connect(videoSlider, SIGNAL(immediateValueChanged(float)), this, SLOT(onSliderValueChanged(float)));

    myVideoScroll = new CustomScrollView(control);
    myVideoScroll->setHorizontalAlignment(HorizontalAlignment::Center);
    myVideoScroll->setVerticalAlignment(VerticalAlignment::Center);
    connect(myVideoScroll, SIGNAL(seekForward(int)), this, SLOT(onScrollSeekForward(int)));
    /*videoPlayerScroll = ScrollView::create(control).
            //ScrollView *videoPlayerScroll = ScrollView::create().
            horizontal(HorizontalAlignment::Center).
            vertical(VerticalAlignment::Center).
            minContentScale(0.25f).
            scrollMode(ScrollMode::Both).
            initialScalingMethod(ScalingMethod::None).
            overScrollEffectMode(OverScrollEffectMode::None).
            pinchToZoomEnabled(TRUE);*/
    //connect(videoPlayerScroll, SIGNAL(contentScaleChanged(float)), this, SLOT(onVideoOptionsZoomReset()));
    /*connect(videoPlayerScroll, SIGNAL(viewableAreaChanged(QRectF,float)),
            this, SLOT(onScrollViewAreaChanged(QRectF, float)));*/

    mySlider = new CustomSlider(screenSize.width()-80);
    mySlider->setHorizontalAlignment(HorizontalAlignment::Fill);
    mySlider->setVerticalAlignment(VerticalAlignment::Bottom);
    connect(mySlider, SIGNAL(valueChanged(float)), this, SLOT(onSliderValueChanged(float)));
    if(OrientationSupport::instance()->orientation()==UIOrientation::Landscape)
        mySlider->setScreenWidth(screenSize.height()-80);

    videoOptionsBar = new VideoOptionsBar;
    videoOptionsBar->setHorizontalAlignment(HorizontalAlignment::Fill);
    videoOptionsBar->setVerticalAlignment(VerticalAlignment::Top);
    connect(videoOptionsBar, SIGNAL(backPressed()), this, SLOT(onVideoOptionsBackPressed()));
    connect(videoOptionsBar, SIGNAL(rotationLock(bool)), this, SLOT(onVideoOptionsRotationLock(bool)));
    connect(videoOptionsBar, SIGNAL(screenLock(bool)), this, SLOT(onVideoOptionsScreenLock(bool)));
    connect(videoOptionsBar, SIGNAL(zoomLevelChanged(ZoomLevel::Level)),
            this, SLOT(onVideoOptionsZoomLevelChanged(ZoomLevel::Level)));
    connect(videoOptionsBar, SIGNAL(zoomReset()), this, SLOT(onVideoOptionsZoomReset()));

    VolumeBar *volumeBar = new VolumeBar;
    volumeBar->setVerticalAlignment(VerticalAlignment::Center);
    connect(myVideoScroll, SIGNAL(volumeChanged(float)), volumeBar, SLOT(onVolumeChanged(float)));

    Container *rootC = Container::create().
            layout(DockLayout::create()).
            background(Color::Black).
            add(myVideoScroll).
            //add(videoPlayerScroll).
            add(mySlider).
            add(videoOptionsBar).
            add(volumeBar);

    prevAction = ActionItem::create().
            image("asset:///images/icons/ic_previous.png").
            title("Previous").
            onTriggered(this, SLOT(onPlayPrev()));

    playPauseAction = ActionItem::create().
            image("asset:///images/icons/ic_pause.png").
            title("Pause").
            onTriggered(this, SLOT(onPlayPause()));

    nextAction = ActionItem::create().
            image("asset:///images/icons/ic_next.png").
            title("Next").
            onTriggered(this, SLOT(onPlayNext()));

    mediaPage = Page::create().
            actionBarVisibility(ChromeVisibility::Visible).
            content(rootC).
            parent(navPane).
            addAction(prevAction, ActionBarPlacement::OnBar).
            addAction(playPauseAction, ActionBarPlacement::OnBar).
            addAction(nextAction, ActionBarPlacement::OnBar);

    videoDuration = 0.0f;

    player = new MediaPlayer(this);
    //player->moveToThread(new QThread);
    connect(player, SIGNAL(durationChanged(unsigned int)), this, SLOT(onPlayerDurationChanged(unsigned int)));
    connect(player, SIGNAL(positionChanged(unsigned int)), this, SLOT(onPlayerPositionChanged(unsigned int)));
    connect(player, SIGNAL(metaDataChanged(QVariantMap)), this, SLOT(onPlayerMetaDataChanged(QVariantMap)));
    connect(player, SIGNAL(mediaStateChanged(bb::multimedia::MediaState::Type)),
            this, SLOT(onPlayerMediaStateChanged(bb::multimedia::MediaState::Type)));
    connect(volumeBar, SIGNAL(volumeChanged(double)), player, SLOT(setVolume(double)));

    //player->setRepeatMode(RepeatMode::Track);
    player->setAutoPause(TRUE);
    player->setVideoOutput(VideoOutput::PrimaryDisplay);
    player->setWindowGroupId(control->windowGroup());
    player->setWindowId(control->windowId());

    connect(OrientationSupport::instance(), SIGNAL(orientationAboutToChange(bb::cascades::UIOrientation::Type)),
            this, SLOT(onOrientationChange(bb::cascades::UIOrientation::Type)));

    //player->play();
    /*QmlDocument *doc;

    if(OrientationSupport::instance()->orientation()==UIOrientation::Portrait)
        doc = QmlDocument::create("asset:///portrait.qml").parent(this);
    else
        doc = QmlDocument::create("asset:///landscape.qml").parent(this);

    Application::instance()->setScene(doc->createRootObject<Page>());*/
    if(OrientationSupport::instance()->orientation()==UIOrientation::Portrait)
    {
        //control->setPreferredSize(768, 1280);
        portGrid = new PortraitImageGrid;
        listPage = Page::create().content(portGrid);
        navPane->push(listPage);
        portGrid->addContent(foundFilesDetails);
        connect(portGrid, SIGNAL(tapped(QString, QVariantList)), this, SLOT(onTapped(QString, QVariantList)));
        connect(portGrid, SIGNAL(nextChanged(QString)), this, SLOT(onListNextChanged(QString)));
        connect(portGrid, SIGNAL(prevChanged(QString)), this, SLOT(onListPrevChanged(QString)));

        landGrid = new LandscapeImageGrid;
        landGrid->setParent(listPage);
        landGrid->addContent();
        //connect(landGrid, SIGNAL(tapped(QString)), this, SLOT(onTapped(QString)));
    }
    else
    {
        //control->setPreferredSize(1280, 768);

        landGrid = new LandscapeImageGrid;
        listPage = Page::create().content(landGrid);
        navPane->push(listPage);
        landGrid->addContent();
        //qDebug()<<"Is landscape";
        //connect(landGrid, SIGNAL(tapped(QString)), this, SLOT(onTapped(QString)));

        portGrid = new PortraitImageGrid;
        portGrid->setParent(listPage);
        portGrid->addContent(foundFilesDetails);
        connect(portGrid, SIGNAL(tapped(QString, QVariantList)), this, SLOT(onTapped(QString, QVariantList)));
        connect(portGrid, SIGNAL(nextChanged(QString)), this, SLOT(onListNextChanged(QString)));
        connect(portGrid, SIGNAL(prevChanged(QString)), this, SLOT(onListPrevChanged(QString)));
        //connect(portGrid, SIGNAL(tapped(QString)), this, SLOT(onTapped(QString)));
    }
    //onOrientationChange(OrientationSupport::instance()->orientation());
}
QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
{
    static const QString usbVendorIdentifierPrefix(QLatin1String("VID_"));
    static const QString usbProductIdentifierPrefix(QLatin1String("PID_"));
    static const QString pciVendorIdentifierPrefix(QLatin1String("VEN_"));
    static const QString pciDeviceIdentifierPrefix(QLatin1String("DEV_"));

    static const int vendorIdentifierSize = 4;
    static const int productIdentifierSize = 4;

    QList<QSerialPortInfo> serialPortInfoList;
    static const int guidCount = sizeof(guidsArray)/sizeof(guidsArray[0]);

    for (int i = 0; i < guidCount; ++i) {
        const HDEVINFO deviceInfoSet = ::SetupDiGetClassDevs(&guidsArray[i], NULL, 0, DIGCF_PRESENT);
        if (deviceInfoSet == INVALID_HANDLE_VALUE)
            return serialPortInfoList;

        SP_DEVINFO_DATA deviceInfoData;
        ::memset(&deviceInfoData, 0, sizeof(deviceInfoData));
        deviceInfoData.cbSize = sizeof(deviceInfoData);

        DWORD index = 0;
        while (::SetupDiEnumDeviceInfo(deviceInfoSet, index++, &deviceInfoData)) {
            QSerialPortInfo serialPortInfo;

            QString s = devicePortName(deviceInfoSet, &deviceInfoData);
            if (s.isEmpty() || s.contains(QLatin1String("LPT")))
                continue;

            serialPortInfo.d_ptr->portName = s;
            serialPortInfo.d_ptr->device = QSerialPortPrivate::portNameToSystemLocation(s);
            serialPortInfo.d_ptr->description =
                    deviceRegistryProperty(deviceInfoSet, &deviceInfoData, SPDRP_DEVICEDESC).toString();
            serialPortInfo.d_ptr->manufacturer =
                    deviceRegistryProperty(deviceInfoSet, &deviceInfoData, SPDRP_MFG).toString();

            s = deviceInstanceIdentifier(deviceInfoSet, &deviceInfoData).toUpper();

            int index = s.indexOf(usbVendorIdentifierPrefix);
            if (index != -1) {
                serialPortInfo.d_ptr->vendorIdentifier = s.mid(index + usbVendorIdentifierPrefix.size(), vendorIdentifierSize)
                        .toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16);
            } else {
                index = s.indexOf(pciVendorIdentifierPrefix);
                if (index != -1)
                    serialPortInfo.d_ptr->vendorIdentifier = s.mid(index + pciVendorIdentifierPrefix.size(), vendorIdentifierSize)
                            .toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16);
            }

            index = s.indexOf(usbProductIdentifierPrefix);
            if (index != -1) {
                serialPortInfo.d_ptr->productIdentifier = s.mid(index + usbProductIdentifierPrefix.size(), productIdentifierSize)
                        .toInt(&serialPortInfo.d_ptr->hasProductIdentifier, 16);
            } else {
                index = s.indexOf(pciDeviceIdentifierPrefix);
                if (index != -1)
                    serialPortInfo.d_ptr->productIdentifier = s.mid(index + pciDeviceIdentifierPrefix.size(), productIdentifierSize)
                            .toInt(&serialPortInfo.d_ptr->hasProductIdentifier, 16);
            }

            serialPortInfoList.append(serialPortInfo);
        }
        ::SetupDiDestroyDeviceInfoList(deviceInfoSet);
    }
    return serialPortInfoList;
}
Example #7
0
void QUrlInfo_QtDShell::setOwner(const QString&  s0)
{
    qtd_QUrlInfo_setOwner_string_dispatch(this->dId, s0.utf16(), s0.size());
}
void Histgram::draw(QPainter *painter)
{
    QPen thickPen(palette().foreground(), 4);
    QPen thinPen(palette().foreground(), 0.5);

    // 默认0点坐标在左上角...
    QPoint zeroPoint(width() / WidthSlices,
                     (HeightSlices - 2) * height() / HeightSlices);
    int xaxisLength = XaixsLengthRatio * width();
    int yaxisLength = YaxisLengthRatio * height();
    painter->setPen(thickPen);
    // 画出Y轴
    painter->drawLine(zeroPoint.x(), zeroPoint.y(),
                      zeroPoint.x(), zeroPoint.y() - yaxisLength);
                                                // 0_0 默认0点坐标在左上角...
    // 画出X轴
    painter->drawLine(zeroPoint.x(), zeroPoint.y(),
                      zeroPoint.x() + xaxisLength, zeroPoint.y());

    // 画出Y轴刻度
    if (voterNums <= 10)     // 检查投票总人数是否为0
    {
        if (!voterNums)
        {
            return;
        }
        YaxisSlices = 1;//投票人数少于等于10的时候改为1
    }
    int yaxisScaleNums = qRound((float)voterNums / (float)YaxisSlices);    // 刻度数目
    int yaxisScaleSpace = yaxisLength / yaxisScaleNums;     // 刻度间隔
    for (int i = 1; i <= yaxisScaleNums; i++)
    {
        painter->setPen(thickPen);
        painter->drawLine(zeroPoint.x() - ScaleSize, zeroPoint.y() - i * yaxisScaleSpace,
                          zeroPoint.x(), zeroPoint.y() - i * yaxisScaleSpace);
                                            // 是“-”...原坐标0点在左上角问题...
        QString num = QString("%1").arg(i * YaxisSlices);
        painter->drawText(zeroPoint.x() - yFrontSpace, zeroPoint.y() - i * yaxisScaleSpace, num);
        // 如果纵轴虚线被设置成显示状态
        if (yAxisDashLineFlag)
        {
            painter->setPen(QPen(Qt::black, 0.1, Qt::DashLine, Qt::SquareCap));
            painter->drawLine(zeroPoint.x(), zeroPoint.y() - i * yaxisScaleSpace,
                              zeroPoint.x() + xaxisLength, zeroPoint.y() - i * yaxisScaleSpace);
        }
    }

    // 画出柱状图和X轴
    int xaxisScaleNums = columnNums;    // 刻度数目等于列数
    int xaxisScaleSpace = xaxisLength / xaxisScaleNums;     // 刻度间隔
    int rectWidth = rectRatio * xaxisScaleSpace;        // 设置柱状条宽度
    FontSize = (width() + height()) / 70;              // 设置字体大小
    xFrontSpace = (width() + height()) / 45;            // 设置字离X轴的距离
    QFont font("Arial",FontSize,QFont::Bold,true);  // 设置字体
    for (int i = 1; i <= columnNums; i++)
    {
        // 画出X轴刻度
        painter->setPen(thickPen);
        painter->drawLine(zeroPoint.x() + i * xaxisScaleSpace, zeroPoint.y(),
                          zeroPoint.x() + i * xaxisScaleSpace, zeroPoint.y() + ScaleSize);
        // 画出选项
        painter->setFont(font);
        painter->drawText(zeroPoint.x() + i * xaxisScaleSpace -(xaxisScaleSpace + FontSize * drawData->at(i - 1).getOptionName().length()) /2, // 文字的位置在每两个刻度的中间
                          zeroPoint.y() + xFrontSpace,
                          drawData->at(i - 1).getOptionName());

        // 画柱状图
        painter->setRenderHint(QPainter::Antialiasing, true);
        thinPen.setColor("black");
        painter->setPen(thickPen);
        // style determined by rectangelMetirial
        switch (rectangleStyle)
        {
        case 1:
            {
                painter->setBrush(QBrush(colorSet->at(i), Qt::SolidPattern));
                break;
            }
        case 2:
            {
                painter->setBrush(QBrush(colorSet->at(i), Qt::Dense5Pattern));
                break;
            }
        case 3:
            {
                painter->setBrush(QBrush(colorSet->at(i), Qt::CrossPattern));
                break;
            }
        default:
            {
                // 默认为纯色
                painter->setBrush(QBrush(colorSet->at(i), Qt::SolidPattern));
            }
        }

        // 如果被设置成显示正确答案
        if (disCorrectAnswerFlag)
        {
            // 如果是正确答案,设置成绿色,否则为红色
            if (drawData->at(i - 1).getOptionName() == correctAnswer)
            {
                painter->setBrush(QBrush("green", Qt::SolidPattern));
            }
            else
            {
                painter->setBrush(QBrush("red", Qt::SolidPattern));
            }
        }


        // 长方形左上角坐标
        int rectHeight = qRound(yaxisLength * ((float)drawData->at(i - 1).getVoterNum() / (float)voterNums));
        int rectX = zeroPoint.x() + i * xaxisScaleSpace - (xaxisScaleSpace + rectWidth) / 2;
        int rectY = zeroPoint.y() - rectHeight;

        painter->drawRect(rectX, rectY, rectWidth, rectHeight);
        // 画出各项投票人数及其所占比例
        painter->setFont(font);
        QString nums = QString("%1").arg(drawData->at(i - 1).getVoterNum());    // 将投票人数转换成字符串
        QString ratio = QString("%1").arg((float)drawData->at(i - 1).getVoterNum() \
                                          / (float)voterNums * 100);   // 算出比例,专程字符串
        if (ratio.size() > precision + 1)
        {
            ratio.resize(precision + 1);        // 只显示precision位小数,算上小数点故+1
        }
        ratio += "%";
        QString text = nums + "(" + ratio + ")";
        painter->drawText(rectX + (rectWidth - FontSize * (text.length() - 3)) / 2, \
                          rectY - FontSize / 2, text);      // 3 是试出来的... - -!
    }

    // 画出题目名称
    QFont titleFont("Arial",FontSize,QFont::Bold,true);
    painter->setFont(titleFont);
    painter->drawText(zeroPoint.x(), FontSize, questionName);
}
Example #9
0
AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, QString &name, const QString &password, QString &reasonStr, int &secondsLeft)
{
    if (name.size() > 35)
        name = name.left(35);
    
    Server_DatabaseInterface *databaseInterface = getDatabaseInterface();
    
    QWriteLocker locker(&clientsLock);
    
    AuthenticationResult authState = databaseInterface->checkUserPassword(session, name, password, reasonStr, secondsLeft);
    if ((authState == NotLoggedIn) || (authState == UserIsBanned || authState == UsernameInvalid))
        return authState;
    
    ServerInfo_User data = databaseInterface->getUserData(name, true);
    data.set_address(session->getAddress().toStdString());
    name = QString::fromStdString(data.name()); // Compensate for case indifference
    
    databaseInterface->lockSessionTables();
    
    if (authState == PasswordRight) {
        if (users.contains(name) || databaseInterface->userSessionExists(name)) {
            qDebug("Login denied: would overwrite old session");
            databaseInterface->unlockSessionTables();
            return WouldOverwriteOldSession;
        }
    } else if (authState == UnknownUser) {
        // Change user name so that no two users have the same names,
        // don't interfere with registered user names though.
        QSettings settings("servatrice.ini", QSettings::IniFormat);
        bool requireReg = settings.value("authentication/regonly", 0).toBool();
        if (requireReg) {
            qDebug("Login denied: registration required");
            databaseInterface->unlockSessionTables();
            return RegistrationRequired;
        }

        QString tempName = name;
        int i = 0;
        while (users.contains(tempName) || databaseInterface->userExists(tempName) || databaseInterface->userSessionExists(tempName))
            tempName = name + "_" + QString::number(++i);
        name = tempName;
        data.set_name(name.toStdString());
    }
    
    users.insert(name, session);
    qDebug() << "Server::loginUser:"******"name=" << name;
    
    data.set_session_id(databaseInterface->startSession(name, session->getAddress()));  
    databaseInterface->unlockSessionTables();
    
    usersBySessionId.insert(data.session_id(), session);
    
    qDebug() << "session id:" << data.session_id();
    session->setUserInfo(data);
    
    Event_UserJoined event;
    event.mutable_user_info()->CopyFrom(session->copyUserInfo(false));
    SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
    for (int i = 0; i < clients.size(); ++i)
        if (clients[i]->getAcceptsUserListChanges())
            clients[i]->sendProtocolItem(*se);
    delete se;
    
    event.mutable_user_info()->CopyFrom(session->copyUserInfo(true, true, true));
    locker.unlock();
    
    se = Server_ProtocolHandler::prepareSessionEvent(event);
    sendIsl_SessionEvent(*se);
    delete se;
    
    return authState;
}
Example #10
0
void Block::replaceAtPos(int pos, const QString &text, const TextStyle &style)
{
    m_changed = true;

    if (pos >= m_text_line.size()) {
        if (pos > m_text_line.size()) {
            int old_size = m_text_line.size();
            QString filling(pos - m_text_line.size(), QChar(' '));
            m_text_line.append(filling);
            m_style_list.append(TextStyleLine(m_screen->defaultTextStyle(), old_size, old_size + filling.size() -1));
        }
        m_text_line.append(text);
        m_style_list.append(TextStyleLine(style, pos, pos + text.size()-1));
        return;
    } else if (pos + text.size() > m_text_line.size()) {
        m_style_list.append(TextStyleLine(m_screen->defaultTextStyle(), pos + text.size() - m_text_line.size(), pos + text.size() -1));
    }

    m_text_line.replace(pos,text.size(),text);
    bool found = false;
    for (int i = 0; i < m_style_list.size(); i++) {
        TextStyleLine &current_style = m_style_list[i];
        if (found) {
            if (current_style.end_index <= pos + text.size() - 1) {
                current_style.releaseTextSegment(m_screen);
                m_style_list.remove(i);
                i--;
            } else if (current_style.start_index <= pos + text.size()) {
                current_style.start_index = pos + text.size();
                current_style.style_dirty = true;
                current_style.text_dirty = true;
                current_style.index_dirty = true;
            } else {
                break;
            }
        } else if (pos >= current_style.start_index && pos <= current_style.end_index) {
            found = true;
            if (pos + text.size() -1 <= current_style.end_index) {
                if (current_style.isCompatible(style)) {
                    current_style.text_dirty = true;
                } else {
                    if (current_style.start_index == pos && current_style.end_index == pos + text.size() - 1) {
                        current_style.setStyle(style);
                        current_style.text_dirty = true;
                        current_style.style_dirty = true;
                    } else if (current_style.start_index == pos) {
                        current_style.start_index = pos + text.size();
                        current_style.text_dirty = true;
                        m_style_list.insert(i, TextStyleLine(style,pos, pos+text.size() -1));
                    } else if (current_style.end_index == pos + text.size() - 1) {
                        current_style.end_index = pos - 1;
                        current_style.text_dirty = true;
                        m_style_list.insert(i+1, TextStyleLine(style,pos, pos + text.size() - 1));
                    } else {
                        int old_end = current_style.end_index;
                        current_style.end_index = pos - 1;
                        current_style.text_dirty = true;
                        m_style_list.insert(i+1, TextStyleLine(style,pos, pos + text.size() - 1));
                        if (pos + text.size() < m_text_line.size()) {
                            m_style_list.insert(i+2, TextStyleLine(current_style,pos + text.size(), old_end));
                        }
                    }
                }
                break;
            } else {
                if (current_style.isCompatible(style)) {
                    current_style.end_index = pos + text.size() - 1;
                    current_style.text_dirty = true;
                } else {
                    if (current_style.start_index == pos) {
                        if (i > 0 && m_style_list.at(i-1).isCompatible(style)) {
                            TextStyleLine &previous_style = m_style_list[i -1];
                            previous_style.end_index+= text.size();
                            previous_style.text_dirty = true;
                            current_style.releaseTextSegment(m_screen);
                            m_style_list.remove(i);
                            i--;
                        } else {
                            current_style.end_index = pos + text.size() - 1;
                            current_style.style = style.style;
                            current_style.forground = style.forground;
                            current_style.background = style.background;
                            current_style.text_dirty = true;
                            current_style.style_dirty = true;
                            current_style.index_dirty = true;
                        }
                    } else {
                        current_style.end_index = pos - 1;
                        current_style.text_dirty = true;
                        m_style_list.insert(i+1, TextStyleLine(style, pos, pos + text.size() -1));
                        i++;
                    }
                }
            }
        }
    }
}
static
void populate_database(const QString& fam)
{
    QFontDatabasePrivate *d = privateDb();
    if (!d)
        return;

    QtFontFamily *family = 0;
    if(!fam.isEmpty()) {
        family = d->family(fam);
        if(family && family->loaded)
            return;
    } else if (d->count) {
        return;
    }

    HDC dummy = GetDC(0);

    LOGFONT lf;
    lf.lfCharSet = DEFAULT_CHARSET;
    if (fam.isNull()) {
        lf.lfFaceName[0] = 0;
    } else {
        memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32));  // 32 = Windows hard-coded
    }
    lf.lfPitchAndFamily = 0;

    EnumFontFamiliesEx(dummy, &lf,
        (FONTENUMPROC)storeFont, (LPARAM)privateDb(), 0);

    ReleaseDC(0, dummy);

    for (int i = 0; i < d->applicationFonts.count(); ++i) {
        QFontDatabasePrivate::ApplicationFont fnt = d->applicationFonts.at(i);
        if (!fnt.memoryFont)
            continue;
        for (int j = 0; j < fnt.families.count(); ++j) {
            const QString familyName = fnt.families.at(j);
            HDC hdc = GetDC(0);
            LOGFONT lf;
            memset(&lf, 0, sizeof(LOGFONT));
            memcpy(lf.lfFaceName, familyName.utf16(), sizeof(wchar_t) * qMin(LF_FACESIZE, familyName.size()));
            lf.lfCharSet = DEFAULT_CHARSET;
            HFONT hfont = CreateFontIndirect(&lf);
            HGDIOBJ oldobj = SelectObject(hdc, hfont);

            TEXTMETRIC textMetrics;
            GetTextMetrics(hdc, &textMetrics);

            addFontToDatabase(familyName, QString(),
                              &textMetrics,
                              &fnt.signatures.at(j),
                              TRUETYPE_FONTTYPE);

            SelectObject(hdc, oldobj);
            DeleteObject(hfont);
            ReleaseDC(0, hdc);
        }
    }

    if(!fam.isEmpty()) {
        family = d->family(fam);
        if(family) {
            if(!family->writingSystemCheck) {
            }
            family->loaded = true;
        }
    }
}
Example #12
0
//MTL PARSER INSPIRED FROM KIXOR.NET "objloader" (http://www.kixor.net/dev/objloader/)
bool ccMaterialSet::ParseMTL(QString path, const QString& filename, ccMaterialSet &materials, QStringList& errors)
{
	//open mtl file
	QString fullPathFilename = path + QString('/') + filename;
	QFile file(fullPathFilename);
	if (!file.open(QFile::ReadOnly))
	{
		errors << QString("Error reading file: %1").arg(filename);
		return false;
	}

	//update path (if the input filename has already a relative path)
	path = QFileInfo(fullPathFilename).absolutePath();
	
	QTextStream stream(&file);

	QString currentLine = stream.readLine();
	unsigned currentLineIndex = 0;
	ccMaterial::Shared currentMaterial(0);
	while( !currentLine.isNull() )
	{
		++currentLineIndex;

		QStringList tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts);

		//skip comments & empty lines
		if( tokens.empty() || tokens.front().startsWith('/',Qt::CaseInsensitive) || tokens.front().startsWith('#',Qt::CaseInsensitive) )
		{
			currentLine = stream.readLine();
			continue;
		}

		//start material
		if (tokens.front() == "newmtl")
		{
			//push the previous material (if any)
			if (currentMaterial)
			{
				materials.addMaterial(currentMaterial);
				currentMaterial = ccMaterial::Shared(0);
			}

			// get the name
			QString materialName = currentLine.mid(7).trimmed(); //we must take the whole line! (see OBJ filter)
			if (materialName.isEmpty())
				materialName = "undefined";
			currentMaterial = ccMaterial::Shared(new ccMaterial(materialName));

		}
		else if (currentMaterial) //we already have a "current" material
		{
			//ambient
			if (tokens.front() == "Ka")
			{
				if (tokens.size() > 3)
				{
					ccColor::Rgbaf ambient(	tokens[1].toFloat(),
											tokens[2].toFloat(),
											tokens[3].toFloat(),
											1.0f);
					currentMaterial->setAmbient(ambient);
				}
			}

			//diff
			else if (tokens.front() == "Kd")
			{
				if (tokens.size() > 3)
				{
					ccColor::Rgbaf diffuse(	tokens[1].toFloat(),
											tokens[2].toFloat(),
											tokens[3].toFloat(),
											1.0f);
					currentMaterial->setDiffuse(diffuse);
				}
			}

			//specular
			else if (tokens.front() == "Ks")
			{
				if (tokens.size() > 3)
				{
					ccColor::Rgbaf specular(tokens[1].toFloat(),
											tokens[2].toFloat(),
											tokens[3].toFloat(),
											1.0f);
					currentMaterial->setSpecular(specular);
				}
			}
			//shiny
			else if (tokens.front() == "Ns")
			{
				if (tokens.size() > 1)
					currentMaterial->setShininess(tokens[1].toFloat());
			}
			//transparent
			else if (tokens.front() == "d" || tokens.front() == "Tr")
			{
				if (tokens.size() > 1)
					currentMaterial->setTransparency(tokens[1].toFloat());
			}
			//reflection
			else if (tokens.front() == "r")
			{
				//ignored
				//if (tokens.size() > 1)
				//	currentMaterial->reflect = tokens[1].toFloat();
			}
			//glossy
			else if (tokens.front() == "sharpness")
			{
				//ignored
				//if (tokens.size() > 1)
				//	currentMaterial->glossy = tokens[1].toFloat();
			}
			//refract index
			else if (tokens.front() == "Ni")
			{
				//ignored
				//if (tokens.size() > 1)
				//	currentMaterial->refract_index = tokens[1].toFloat();
			}
			// illumination type
			else if (tokens.front() == "illum")
			{
				//ignored
			}
			// texture map
			else if (tokens.front() == "map_Ka"
					|| tokens.front() == "map_Kd"
					|| tokens.front() == "map_Ks")
			{
				//DGM: in case there's hidden or space characters at the beginning of the line...
				int shift = currentLine.indexOf("map_K",0);
				QString textureFilename = (shift + 7 < currentLine.size() ? currentLine.mid(shift+7).trimmed() : QString());
				QString fullTexName = path + QString('/') + textureFilename;
				if (!currentMaterial->loadAndSetTexture(fullTexName))
				{
					errors << QString("Failed to load texture file: %1").arg(fullTexName);
				}
			}
			else
			{
				errors << QString("Unknown command '%1' at line %2").arg(tokens.front()).arg(currentLineIndex);
			}
		}

		currentLine = stream.readLine();
	}

	file.close();

	//don't forget to push the last material!
	if (currentMaterial)
		materials.addMaterial(currentMaterial);

	return true;
}
Example #13
0
void AsciiOpenDlg::updateTable()
{
    m_ui->tableWidget->setEnabled(false);
    m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false);

    bool hadValidHeader = !m_headerLine.isEmpty();
    m_headerLine.clear();

    if (m_filename.isEmpty())
    {
        m_ui->tableWidget->clear();
        return;
    }
    //we open the file in ASCII mode
    QFile file(m_filename);
    if (!file.open(QFile::ReadOnly))
    {
        m_ui->tableWidget->clear();
        m_columnsValidty.clear();
        return;
    }
    QTextStream stream(&file);

    //we skip first lines (if needed)
    {
        for (unsigned i=0; i<m_skippedLines; ++i)
        {
            QString currentLine = stream.readLine();
            //we keep track of the first line
            if (i == 0)
                m_headerLine = currentLine;
        }
    }

    //if the old setup has less than 3 columns, we forget it
    if (m_columnsCount < 3)
    {
        m_ui->tableWidget->clear();
        m_columnsCount = 0;
    }
    m_ui->tableWidget->setRowCount(DISPLAYED_LINES+1);    //+1 for first line shifting

    unsigned lineCount = 0;			//number of lines read
    unsigned totalChars = 0;		//total read characters (for stats)
    unsigned columnsCount = 0;		//max columns count per line
    unsigned commentLines = 0;		//number of comments line skipped

    std::vector<bool> valueIsNumber;	//identifies columns with numbers only [mandatory]
    std::vector<bool> valueIsBelowOne;	//identifies columns with values between -1 and 1 only
    std::vector<bool> valueIsInteger;	//identifies columns with integer values only
    std::vector<bool> valueIsBelow255;	//identifies columns with integer values between 0 and 255 only

    QChar decimalPoint = QLocale().decimalPoint();
    QString currentLine = stream.readLine();
    while (lineCount < LINES_READ_FOR_STATS && !currentLine.isNull())
    {
        //we recognize "//" as the beginning of a comment
        if (!currentLine.startsWith("//"))
        {
            QStringList parts = currentLine.trimmed().split(m_separator,QString::SkipEmptyParts);
            if (lineCount < DISPLAYED_LINES)
            {
                unsigned partsCount = std::min( MAX_COLUMNS, static_cast<unsigned>(parts.size()) );

                //do we need to add one or several new columns?
                if (partsCount > columnsCount)
                {
                    //we also extend vectors
                    for (unsigned i = columnsCount; i < partsCount; ++i)
                    {
                        valueIsNumber.push_back(true);
                        valueIsBelowOne.push_back(true);
                        valueIsBelow255.push_back(true);
                        valueIsInteger.push_back(true);
                    }

                    m_ui->tableWidget->setColumnCount(partsCount);
                    columnsCount = partsCount;
                }

                //we fill the current row with extracted parts
                for (unsigned i = 0; i < partsCount; ++i)
                {
                    QTableWidgetItem *newItem = new QTableWidgetItem(parts[i]);

                    //test values
                    bool isANumber = false;
                    double value = parts[i].toDouble(&isANumber);
                    if (!isANumber)
                    {
                        valueIsNumber[i] = false;
                        valueIsBelowOne[i] = false;
                        valueIsInteger[i] = false;
                        valueIsBelow255[i] = false;
                        newItem->setBackground(QBrush(QColor(255, 160, 160)));
                    }
                    else
                    {
                        valueIsBelowOne[i] = valueIsBelowOne[i] && (fabs(value) <= 1.0);
                        valueIsInteger[i] = valueIsInteger[i] && !parts[i].contains(decimalPoint);
                        valueIsBelow255[i] = valueIsBelow255[i] && valueIsInteger[i] && (value >= 0.0 && value <= 255.0);
                    }

                    m_ui->tableWidget->setItem(lineCount + 1, i, newItem); //+1 for first line shifting
                }
            }

            totalChars += currentLine.size() + 1; //+1 for return char at eol
            ++lineCount;
        }
        else
        {
            if (m_skippedLines == 0 && commentLines == 0)
            {
                //if the very first line is a comment, then we force the user to skip it!
                //this way it will be considered as a header
                m_ui->spinBoxSkipLines->setMinimum(1);
                return;
            }
            ++commentLines;
        }

        //read next line
        currentLine = stream.readLine();
    }

    file.close();

    //process header line
    if (!m_headerLine.isEmpty())
    {
        m_headerLine = m_headerLine.trimmed();
        int n = 0;
        while (n < m_headerLine.size() && m_headerLine.at(n) == '/')
            ++n;
        if (n != 0)
            m_headerLine.remove(0,n);
        m_ui->headerLabel->setText(QString("Header: ")+m_headerLine);
        m_ui->headerLabel->setVisible(true);
    }
    else
    {
        m_ui->headerLabel->setVisible(false);
    }

    m_ui->commentLinesSkippedLabel->setVisible(commentLines != 0);
    if (commentLines)
        m_ui->commentLinesSkippedLabel->setText(QString("+ %1 comment line(s) skipped").arg(commentLines));

    if (lineCount == 0 || columnsCount == 0)
    {
        m_averageLineSize = -1.0;
        m_ui->tableWidget->clear();
        m_columnsValidty.clear();
        return;
    }

    //average line size
    m_averageLineSize = static_cast<double>(totalChars)/lineCount;

    //we add a type selector for each column
    QStringList propsText;
    {
        for (unsigned i=0; i<ASCII_OPEN_DLG_TYPES_NUMBER; i++)
            propsText << QString(ASCII_OPEN_DLG_TYPES_NAMES[i]);
    }

    //remove unnecessary columns
    {
        while (columnsCount < m_columnsCount)
            m_ui->tableWidget->removeColumn(--m_columnsCount);
        if (m_columnsValidty.size() > columnsCount)
            m_columnsValidty.resize(columnsCount);
        for (unsigned i=lineCount+1; i<=DISPLAYED_LINES; ++i)
            m_ui->tableWidget->removeRow(i);
    }

    //setup table and widgets
    {
        //Icons
        static const QIcon xIcon		(QString::fromUtf8(":/CC/images/typeXCoordinate.png"));
        static const QIcon yIcon		(QString::fromUtf8(":/CC/images/typeYCoordinate.png"));
        static const QIcon zIcon		(QString::fromUtf8(":/CC/images/typeZCoordinate.png"));
        static const QIcon NormIcon		(QString::fromUtf8(":/CC/images/typeNormal.png"));
        static const QIcon RGBIcon		(QString::fromUtf8(":/CC/images/typeRgbCcolor.png"));
        static const QIcon GreyIcon		(QString::fromUtf8(":/CC/images/typeGrayColor.png"));
        static const QIcon ScalarIcon	(QString::fromUtf8(":/CC/images/typeSF.png"));

        int columnWidth = (m_ui->tableWidget->width()*9) / (columnsCount*10);
        columnWidth = std::max(columnWidth,80);

        for (unsigned i=0; i<columnsCount; i++)
        {
            QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0,i));
            QComboBox* _columnHeader = columnHeaderWidget;
            if (!columnHeaderWidget)
            {
                columnHeaderWidget = new QComboBox();
                columnHeaderWidget->addItems(propsText);
                columnHeaderWidget->setMaxVisibleItems(ASCII_OPEN_DLG_TYPES_NUMBER);
                columnHeaderWidget->setCurrentIndex(0);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_X,xIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Y,yIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Z,zIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NX,NormIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NY,NormIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NZ,NormIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_R,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_G,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_B,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Rf,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Gf,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Bf,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Grey,GreyIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Scalar,ScalarIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32i,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32f,RGBIcon);

                connect(columnHeaderWidget, SIGNAL(currentIndexChanged(int)), this, SLOT(columnsTypeHasChanged(int)));
            }

            while (m_columnsValidty.size() <= static_cast<size_t>(i))
                m_columnsValidty.push_back(false);
            assert(m_columnsValidty.size() >= static_cast<size_t>(i));

            if (!_columnHeader)
                m_ui->tableWidget->setCellWidget(0,i,columnHeaderWidget);
            m_ui->tableWidget->setColumnWidth(i,columnWidth);

            //a non-numerical column can't be valid
            if (!valueIsNumber[i])
                m_columnsValidty[i] = false;
        }
    }
Example #14
0
bool PGuiVirtualMachine::validateChar(QString value)
{
    return value.size() == 1;
}
void CalloutNote::record(QString pathName, bool ifDeleted)
{
	//get current date and time
	QDateTime dateTime = QDateTime::currentDateTime();
	QString dateTimeString = dateTime.toString("dd/mm/yy hh:mm");
	QStringList sNames = dateTimeString.split(" ");
    //QString timeNumbers = sNames[1];
	int dis=pathName.lastIndexOf("/");
	QString pathpart=pathName.mid(0,dis), namepart=pathName.mid(dis,pathName.size()-dis);
	pathName = pathpart + "noteFile/" + namepart;

	QString text;
	storeText(_pid,_type,_id);
	bool flag=true;
	bool write=false;
	int size=nodeText.size();
	//for(int i=0; i<nodeText.size(); i++)
	{
	    //text = nodeText[i]->getPlainText();	   
		text = m_note->toPlainText();
		if((text.size()>0 && !compare(_preText,text)) || ifDeleted) 
		{
			if(!pathName.contains(".note"))
				pathName +=".note";
	
			QFile infile(pathName);
			vector<QString> out1;
			if(infile.open(QIODevice::ReadOnly))
			{
			    QTextStream in(&infile);
                 
				 while(!in.atEnd())
			     {
				    QString  line = in.readLine();
				    out1.push_back(line);					
				 }
			}
			infile.close();

			QFile outfile( pathName );
			if(!outfile.open(QIODevice::WriteOnly | QIODevice::Truncate))
			return;

			//return;
			QTextStream out(&outfile); 
			
			
			for(int j=0; j<out1.size(); j++)
			{  
				QStringList sname=out1[j].split(' ');
				vector<int> item;
				for(int i=0; i<5 && i<sname.size(); i++)
				{
					QString s=sname[i];				 						
					int id=s.toInt();						
					item.push_back(id);
				}	
				if(item.size()>4 && item[2]==_type && item[3]==_id)
				{
					flag=false;	
					if(!ifDeleted)
					{
						if(!write) //if not written in this time, write the text back
						{
							 //out << "<-:#:-> " << _pid << " " <<  _type << " " << _id << " " << _cid << " " << _scene->userName << " " << dateTimeString << " " << text << "\n"; 
							 out <<  "<-:#:-> " << _pid << " " <<  _type << " " << _id << " " << _cid << "\n";  
							 out << m_note->toHtml();
							 out << "\n"; 
							 write =true;
							 
						}
						//out << out1[j];// << "\n";  
					    //if(out1[j][0]!='\n')
						//out << "\n";  										    			
					}
					int J=j;
					for(int k=j+1; k<out1.size(); k++)
					{
						if(out1[k][0]!='<' || out1[k][1]!= '-' || out1[k][2]!= ':'  || out1[k][3]!= '#'  || out1[k][4]!=  ':'  || out1[k][5]!= '-'  || out1[k][6]!= '>')
						{
						   J=k;     
						}
						else
						   break;
					}
					j=J;
				}
				else 
				{
					out << out1[j];// << "\n";  
					if(out1[j][0]!='\n')
						out << "\n";  
				}
			}
			if(flag)
			{
				//out <<  "<-:#:-> " << _pid << " " <<  _type << " " << _id << " " << _cid << " " << _scene->userName << " " << dateTimeString << " " << text << "\n";  			
				out <<  "<-:#:-> " << _pid << " " <<  _type << " " << _id << " " << _cid << "\n";  			
				out << m_note->toHtml();
				out << "\n"; 
				return;
			}
			
			outfile.close();
			
			//break;
			
		}		
	}
}
Example #16
0
void SearchFind::search()
{
	 
	int count=0,itemCount=0;
	QString str;
	str = this->_path->text();
	if(str.size()==0)
	{
		//_scene->searchInPathBubble();
		return;
	}
	
	int index;
	if(str.contains(" *"))
	while(str.indexOf(" ")==0)
	{	
		index = str.indexOf(" ");
		str = str.mid(index+1, str.size()-index);		
	}
	
	if(str.contains("* "))
	while(str.lastIndexOf(" ")==str.size()-1)
	{	
		index= str.lastIndexOf(" ");				
		str = str.mid(0, index);		
		if(str.size()==0)
			break;
	}	
	QList<ItemBase *> mlist=_scene->getGroupMembers(_webItem);	 
	for(int i=0; i<mlist.size(); i++) 
	{
		int type=mlist[i]->getType();
	    if ( mlist[i]->getType() == SUBPATHBUBBLE1 || mlist[i]->getType() == PATHBUBBLE1)
		{			
			itemCount += _scene->searchInPathBubble(str, SearchList, "",  mlist[i]);	
		}
		if ( mlist[i]->getType() == EXPRESSIONBUBBLE)
		{			
			itemCount +=_scene->searchInExpressionBubble(str, SearchList, "",  mlist[i]);	
		}
		if ( mlist[i]->getType() == TREERING)
		{			
			itemCount +=_scene->searchInTreeringBubble(str, SearchList, "",  mlist[i]);	
			itemCount +=_scene->searchPathwayInTreeRingforASymbol(str, SearchList, "",  mlist[i]);	
		}
		count++;
	}
	/*if(count==1) 
	{
		_scene->searchInPathBubble(str, SearchList, "all", NULL);
		_scene->searchInExpressionBubble(str, SearchList, "all",  NULL);	
	}*/
	if(itemCount==0)
	{
	       QMessageBox msgBox;
			msgBox.setWindowTitle("No item found");
			msgBox.setText("No item is found");
			msgBox.setStandardButtons(QMessageBox::Yes);
			if(msgBox.exec() == QMessageBox::Yes)
				return;
			/*msgBox.addButton (QMessageBox::No);
			if(msgBox.exec() == QMessageBox::No)
				return false;
			else 
				break;*/
	
	}
} 
bool CalloutNote::compare(QString &preText, QString &curText)
{
	int index=-1;
	while(preText.indexOf("\n")==0)
	{	
		index= preText.indexOf("\n");
		preText = preText.mid(index+1,preText.size()-index);		
	}

	if(preText.indexOf(" ")==0)
	{	
		index= preText.indexOf(" ");
		preText = preText.mid(index+1,preText.size()-index);		
	}
	
	while(preText.lastIndexOf("\n")==preText.size()-1)
	{	
		index= preText.lastIndexOf("\n");				
		preText = preText.mid(0, index);		
		if(preText.size()==0)
			break;
	}

	curText = curText.remove(lastInputTime);

	while(curText.indexOf("\n")==0)
	{	
		index= curText.indexOf("\n");
		curText = curText.mid(index+1,curText.size()-index);		
	}

	if(curText.indexOf(" ")==0)
	{	
		index= curText.indexOf(" ");
		curText = curText.mid(index+1,curText.size()-index);		
	}

	while(curText.lastIndexOf("\n")==curText.size()-1)
	{	
		index= curText.lastIndexOf("\n");
		curText = curText.mid(0, index);		
		if(curText.size()==0)
			break;
	}
	int size1=preText.size();
	int size2=curText.size();
	int index1= preText.lastIndexOf("\n");
	int index2= curText.lastIndexOf("\n");
	int index3= preText.indexOf("\n");
	int index4= curText.indexOf("\n");
	int index6= preText.lastIndexOf(" ");
	int index7= curText.lastIndexOf(" ");
	
	for(int i=0;i<preText.size()||i<curText.size();i++)
	{
	    QString p=preText[i];
		QString c=curText[i];		
	}
	
	if(preText!=curText)
	{
		int index = curText.indexOf(preText);
		if(index>=0)
		    curText=curText.mid(0, index) + curText.mid(index+preText.size(),curText.size()-index-preText.size());

		return false;
	}
	else 
		return true;
}
Example #18
0
bool TWScript::doParseHeader(const QString& beginComment, const QString& endComment,
							 const QString& Comment, bool skipEmpty /* = true */)
{
	QFile file(m_Filename);
	QStringList lines;
	QString line;
	bool codecChanged = true;
	bool success = false;
	QTextCodec* codec;

	if (!file.exists() || !file.open(QIODevice::ReadOnly))
		return false;
	
	m_Codec = QTextCodec::codecForName("UTF-8");
	if (!m_Codec)
		m_Codec = QTextCodec::codecForLocale();

	while (codecChanged) {
		codec = m_Codec;
		file.seek(0);
		lines = codec->toUnicode(file.readAll()).split(QRegExp("\r\n|[\n\r]"));
	
		// skip any empty lines
		if (skipEmpty) {
			while (!lines.isEmpty() && lines.first().isEmpty())
				lines.removeFirst();
		}
		if (lines.isEmpty())
			break;
	
		// is this a valid TW script?
		line = lines.takeFirst();
		if (!beginComment.isEmpty()) {
			if (!line.startsWith(beginComment))
				break;
			line = line.mid(beginComment.size()).trimmed();
		}
		else if (!Comment.isEmpty()) {
			if (!line.startsWith(Comment))
				break;
			line = line.mid(Comment.size()).trimmed();
		}
		if (!line.startsWith("TeXworksScript"))
			break;
	
		// scan to find the extent of the header lines
		QStringList::iterator i;
		for (i = lines.begin(); i != lines.end(); ++i) {
			// have we reached the end?
			if (skipEmpty && i->isEmpty()) {
				i = lines.erase(i);
				--i;
				continue;
			}
			if (!endComment.isEmpty()) {
				if (i->startsWith(endComment))
					break;
			}
			if (!i->startsWith(Comment))
				break;
			*i = i->mid(Comment.size()).trimmed();
		}
		lines.erase(i, lines.end());
		
		codecChanged = false;
		switch (doParseHeader(lines)) {
			case ParseHeader_OK:
				success = true;
				break;
			case ParseHeader_Failed:
				success = false;
				break;
			case ParseHeader_CodecChanged:
				codecChanged = true;
				break;
		}
	}
	
	file.close();
	return success;
}
Example #19
0
void QUrlInfo_QtDShell::setName(const QString&  name0)
{
    qtd_QUrlInfo_setName_string_dispatch(this->dId, name0.utf16(), name0.size());
}
Example #20
0
void Frame::writeString(const QString &string)
{
    writeInt(string.size());
    _data.append(string);
}
Example #21
0
int QResourceRoot::findNode(const QString &_path, const QLocale &locale) const
{
    QString path = _path;
    {
        QString root = mappingRoot();
        if(!root.isEmpty()) {
            if(root == path) {
                path = QLatin1Char('/');
            } else {
                if(!root.endsWith(QLatin1Char('/')))
                    root += QLatin1Char('/');
                if(path.size() >= root.size() && path.startsWith(root))
                    path = path.mid(root.length()-1);
                if(path.isEmpty())
                    path = QLatin1Char('/');
            }
        }
    }
#ifdef DEBUG_RESOURCE_MATCH
    qDebug() << "!!!!" << "START" << path << locale.country() << locale.language();
#endif

    if(path == QLatin1String("/"))
        return 0;

    //the root node is always first
    int child_count = (tree[6] << 24) + (tree[7] << 16) +
                      (tree[8] << 8) + (tree[9] << 0);
    int child       = (tree[10] << 24) + (tree[11] << 16) +
                      (tree[12] << 8) + (tree[13] << 0);

    //now iterate up the tree
    int node = -1;

    QStringSplitter splitter(path);
    while (child_count && splitter.hasNext()) {
        QStringRef segment = splitter.next();

#ifdef DEBUG_RESOURCE_MATCH
        qDebug() << "  CHILDREN" << segment;
        for(int j = 0; j < child_count; ++j) {
            qDebug() << "   " << child+j << " :: " << name(child+j);
        }
#endif
        const uint h = qt_hash(segment);

        //do the binary search for the hash
        int l = 0, r = child_count-1;
        int sub_node = (l+r+1)/2;
        while(r != l) {
            const uint sub_node_hash = hash(child+sub_node);
            if(h == sub_node_hash)
                break;
            else if(h < sub_node_hash)
                r = sub_node - 1;
            else
                l = sub_node;
            sub_node = (l + r + 1) / 2;
        }
        sub_node += child;

        //now do the "harder" compares
        bool found = false;
        if(hash(sub_node) == h) {
            while(sub_node > child && hash(sub_node-1) == h) //backup for collisions
                --sub_node;
            for(; sub_node < child+child_count && hash(sub_node) == h; ++sub_node) { //here we go...
                if(name(sub_node) == segment) {
                    found = true;
                    int offset = findOffset(sub_node);
#ifdef DEBUG_RESOURCE_MATCH
                    qDebug() << "  TRY" << sub_node << name(sub_node) << offset;
#endif
                    offset += 4;  //jump past name

                    const short flags = (tree[offset+0] << 8) +
                                        (tree[offset+1] << 0);
                    offset += 2;

                    if(!splitter.hasNext()) {
                        if(!(flags & Directory)) {
                            const short country = (tree[offset+0] << 8) +
                                                  (tree[offset+1] << 0);
                            offset += 2;

                            const short language = (tree[offset+0] << 8) +
                                                   (tree[offset+1] << 0);
                            offset += 2;
#ifdef DEBUG_RESOURCE_MATCH
                            qDebug() << "    " << "LOCALE" << country << language;
#endif
                            if(country == locale.country() && language == locale.language()) {
#ifdef DEBUG_RESOURCE_MATCH
                                qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node;
#endif
                                return sub_node;
                            } else if((country == QLocale::AnyCountry && language == locale.language()) ||
                                      (country == QLocale::AnyCountry && language == QLocale::C && node == -1)) {
                                node = sub_node;
                            }
                            continue;
                        } else {
#ifdef DEBUG_RESOURCE_MATCH
                            qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node;
#endif

                            return sub_node;
                        }
                    }

                    if(!(flags & Directory))
                        return -1;

                    child_count = (tree[offset+0] << 24) + (tree[offset+1] << 16) +
                                  (tree[offset+2] << 8) + (tree[offset+3] << 0);
                    offset += 4;
                    child = (tree[offset+0] << 24) + (tree[offset+1] << 16) +
                            (tree[offset+2] << 8) + (tree[offset+3] << 0);
                    break;
                }
            }
        }
        if(!found)
            break;
    }
#ifdef DEBUG_RESOURCE_MATCH
    qDebug() << "!!!!" << "FINISHED" << __LINE__ << node;
#endif
    return node;
}
Example #22
0
QString removePath(const QString& s){
    int length =  (s.size()-1) - s.lastIndexOf(QDir::separator()) ;
    return s.right(length);
}
void SupernovaeComponent::loadData()
{
    QString line;
    QString serialNo, hostGalaxy, date, type, offset, SNPosition, discoverers ;
    QStringList fields;
    dms ra, dec;
    float magnitude;
    KSFileReader fileReader;
    bool ok;
    kDebug()<<"Loading Supernovae data"<<endl;
    if( !fileReader.open("supernovae.dat")) return;
    //m_ObjectList.clear();
    latest.clear();
    objectNames(SkyObject::SUPERNOVA).clear();

    while (fileReader.hasMoreLines())
    {
        line=fileReader.readLine();
        Supernova *sup=0;
        //kDebug()<<line[0]<<" "<<line.size()<<endl;
        if(line[0]=='#' || line.size()<10) continue;
        fields=line.split(",");
        serialNo=fields.at(0);
        hostGalaxy=fields.at(1);
        date=fields.at(2);

        ra=dms(fields.at(3),false);
        dec=dms(fields.at(4));

        offset=fields.at(5);

        if(fields.at(6).isEmpty())
            magnitude=99;
        else
            magnitude=fields.at(6).toFloat(&ok);

        SNPosition=fields.at(8);
        type=fields.at(10);
        discoverers=fields.at(12);

        sup=new Supernova(ra, dec, date, magnitude, serialNo, type, hostGalaxy, offset, discoverers);

        if (!m_ObjectList.empty())
        {
            if ( findByName(sup->name() ) == 0 )
            {
                //kDebug()<<"List of supernovae not empty. Found new supernova";
                m_ObjectList.append(sup);
                latest.append(sup);
            }/*
            else
                m_ObjectList.append(sup);*/
        }
        else             //if the list is empty
        {
            m_ObjectList.append(sup);
            latest.append(sup);
            //notifyNewSupernovae();
        }

        objectNames(SkyObject::SUPERNOVA).append(sup->name());
    }
    //notifyNewSupernovae();
}
Example #24
0
/* //added by Rolando 04-11-08
 * initFlagListWidget: initializes QtFlagsListWidget with items according QtFlagsManager
 * parameters:  QtFlagsManager * qtFlagsManager, QString flagsNameLanguage
 * returns QString, the country name default stored in config
*/
QString QtFlagsListWidget::init(QtFlagsManager * qtFlagsManager, QComboBox * comboBox, QString flagsNameLanguage) {
    _qListWidget->clear();//VOXOX CHANGE by Rolando - 2009.06.12
    Config & config = ConfigManager::getInstance().getCurrentConfig();
    QString defaultFlagNameFile = QString::fromStdString(config.getCurrentFlag());//gets the default flagname file according config
    QString countryNameDefault = QString::null;

    QListWidgetItem *newItem = new QListWidgetItem();
    QFont font = _qListWidget->font();//VOXOX CHANGE by Rolando - 2009.06.12

    //gets the largest country name text and sets its name to the variable
    QString largestCountryNameText = qtFlagsManager->getLargestCountryNameText();

    //gets the largest country name size in pixels
    int largestCountryNamePixelSize = qtFlagsManager->getPixelSizeText(largestCountryNameText, font);


    int blankSpacePixelSize = qtFlagsManager->getPixelSizeText(QString(" "), font);
    int largestCountryCodePixelSize = 0;

    //gets the flaglist according flagsNameLanguage
    QtFlagsManager::QtFlagList flagList = qtFlagsManager->getQtFlagList(flagsNameLanguage);
    QtFlagsManager::QtFlagList::iterator it;
    QString countryName;
    QString areaCode;
    int numberTimes = 0;
    int tmpCountryCodePixelSize = 0;
    for (it = flagList.begin(); it != flagList.end(); it++) {
        countryName = it->getDefaultCountryName();//gets the country name
        areaCode = it->getDefaultCountryCode();
        //gets number times what FILL_CHAR is needed to justify the country name with code area number
        numberTimes = numberTimesToFillWithChar(FILL_CHAR, largestCountryNamePixelSize, countryName, font);
        if(numberTimes == -1) { // if it is not necessary to fill with FILL_CHAR
            numberTimes = 0;
        }

        newItem = new QListWidgetItem(QIcon(it->getPixmap()),it->getDefaultCountryName().leftJustified(countryName.size()+numberTimes, FILL_CHAR) + QString(" ") + it->getDefaultCountryCode(),_qListWidget);

        if(defaultFlagNameFile == it->getFlagNameFile()) { //if the country name is the default then sets their corresponding flag image to flagButton and selects it on _qtFlagsListWidget
            setDefaultFlag(newItem);
            countryNameDefault = countryName;

        }
    }

    //sortItems();

    //adds a item with text "None" because if we want to dial to another country not available on list or to dial a special phone number not must choose an area code, i.e the voice mail
    newItem = new QListWidgetItem(QIcon(QString::fromStdString(":/flags/none.png")),QString("None"));
    _qListWidget->insertItem ( 0, newItem );

    int totalPixelsSizeCountryName = getWidthNeededInItem(qtFlagsManager, flagsNameLanguage);
    setWidthSize(totalPixelsSizeCountryName);

    return countryNameDefault;

}
Example #25
0
/*

  dstPath = path specified by the user
*/
void FileLoader::createFlashCards(QString dstPath)
{
    if(!QDir(dstPath).exists()){
        emit fileLoaderError("Output directory does not exist!");
        return;
    }

    qDebug() << "FileLoader::createFlashCards() Destination = " << dstPath;

    QDir dirOutput;

    // Creating output folder
    // In case of name conflicts, it will append "(n)" to the folder name, n being an incremental number
    // The path to the created folder is stored to dirOutput
    {
        QString folderName = OUTPUT_FOLDER_NAME;

        for (int i = 1; ;i++){
            // coin the output folder path
            dirOutput.setPath(dstPath + "/" + folderName);
            // does it already exist?
            if (dirOutput.exists()){
                folderName = OUTPUT_FOLDER_NAME + "(" + QString::number(i) + ")";
                if (i > 1000){
                    // Folders "Output(1...1000)" are already in the same directory, which is not unlikely to happen
                    emit fileLoaderError("Output directory coudn't be created!");
                    return;
                }
            } else {
                // output folder path determined (stored to dirOutput)
                break;
            }
        }
    }

    // Create output folders
    qDebug() << "creating output folders...";
    dirOutput.mkpath(OUTPUT_WIDGET_FOLDER_NAME + "/" + OUTPUT_WIDGET_STYLE_FOLDER_NAME);
    dirOutput.mkpath(OUTPUT_WIDGET_FOLDER_NAME + "/" + OUTPUT_WIDGET_SCRIPT_FOLDER_NAME);
    dirOutput.mkpath(OUTPUT_WIDGET_FOLDER_NAME + "/" + OUTPUT_WIDGET_DATA_FOLDER_NAME);

    // Move to the widget directory
    dirOutput.cd(OUTPUT_WIDGET_FOLDER_NAME);

    // Copy files from the resource
    qDebug() << "copying files...";
    QFile::copy(":/SimpleFlashCard/info_plist", dirOutput.path() + "/info.plist");
    QFile::copy(":/SimpleFlashCard/icon_png", dirOutput.path() + "/icon.png");
    QFile::copy(":/SimpleFlashCard/index_html", dirOutput.path() + "/index.html");
    QFile::copy(":/SimpleFlashCard/style_css", dirOutput.path() + "/" + OUTPUT_WIDGET_STYLE_FOLDER_NAME + "/simpleflashcard.css");
    QFile::copy(":/SimpleFlashCard/flashcards_js", dirOutput.path() + "/" + OUTPUT_WIDGET_SCRIPT_FOLDER_NAME + "/flashcards.js");
    QFile::copy(":/SimpleFlashCard/ajax_js", dirOutput.path() + "/" + OUTPUT_WIDGET_SCRIPT_FOLDER_NAME + "/Ajax.js");
    QFile::copy(":/SimpleFlashCard/main_js", dirOutput.path() + "/" + OUTPUT_WIDGET_SCRIPT_FOLDER_NAME + "/main.js");

    // Write data.js
    QFile file(dirOutput.path() + "/" + OUTPUT_WIDGET_DATA_FOLDER_NAME + "/" + FILENAME_DATA_JS);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
        emit fileLoaderError("Couldn't open output file: " + file.fileName());
        return;
    }else{
        file.write(QString("var FlashCardCollection = new Array();\n").toUtf8());
        file.write(QString("var FlashCardCollectionNames = new Array();\n\n").toUtf8());

        for (int i = 0; i < m_lstFlashCards.size(); i++){   // collection loop
            QString strwrk;
            strwrk = "FlashCardCollectionNames[" + QString::number(i) + "] = '" + m_lstFlashCards[i]->collectionName() + " (" + QString::number(m_lstFlashCards[i]->entries().size()) + ")';\n";
            file.write(strwrk.toUtf8());
            strwrk = "FlashCardCollection[" + QString::number(i) + "] = [\n";
            file.write(strwrk.toUtf8());

            for (int j = 0; j < m_lstFlashCards[i]->entries().size(); j++){     // entry loop
                QString line = m_lstFlashCards[i]->entries()[j];
                line = line.trimmed();
                if (line.indexOf("\t") != -1){
                    line.replace("\"","\"\"");
                    QStringList wrk = line.split("\t");
                    QString writeline = ",\"" + wrk[0] + "\\t" + wrk[1] + "\"" + "\n";
                    if(j == 0){
                        writeline = writeline.mid(1);   // remove the preceeding comma
                    }
                    file.write(writeline.toUtf8());
                }
            }
            file.write(QString("];\n\n").toUtf8());
        }
        file.close();
    }

    // zip it up
    if (QFile("C:/Program Files/7-Zip/7z.exe").exists())
    {
        qDebug() << "zipping...";
        QString zip_program = "C:/Program Files/7-Zip/7z.exe";
        QStringList zip_arguments;
        zip_arguments << "a" << (dirOutput.path() + ".zip") << (dirOutput.path() + "\\");

        QProcess *zip_process = new QProcess(this);
        zip_process->start(zip_program, zip_arguments);
        zip_process->waitForFinished(5000);

        QFile zip_file(dirOutput.path() + ".zip");
        if(zip_file.exists())
        {
            qDebug() << "zip file already exists! renaming...";
            zip_file.rename(zip_file.fileName().left(zip_file.fileName().size()-4) + ".wgz");
        }
    }

    QString strExplorerPath1 = "C:/WINNT/explorer.exe";
    QString strExplorerPath2 = "C:/WINDOWS/explorer.exe";
    QString strExplorerPath;

    if (QFile(strExplorerPath1).exists()) {
        strExplorerPath = strExplorerPath1;
    } else if (QFile(strExplorerPath2).exists()) {
        strExplorerPath = strExplorerPath2;
    }

    // open the output folder
    if (strExplorerPath.size())
    {
        qDebug() << "opening output folder...";

        QString program = strExplorerPath;
        QStringList arguments;
        QDir dirwrk = dirOutput;
        dirwrk.cdUp();
        arguments << dirwrk.path().replace("/", "\\");

        QProcess *process = new QProcess(this);
        process->start(program, arguments);
    }
}
Example #26
0
		static QString FieldNameMorpher (const QString& str)
		{
			return str.left (str.size () - 1);
		}
bool PreprocessorCompletionModel::shouldAbortCompletion(
    KTextEditor::View* const view
  , const KTextEditor::Range& inserted_range
  , const QString& inserted_text
  )
{
    auto* const doc = view->document();                     // get current document
    kDebug(DEBUG_AREA) << "completion text=" << inserted_text;

    if (!m_should_complete)
        return true;

    /// Make sure the current line starts w/ a hash.
    auto text_before = doc->text(
        {KTextEditor::Cursor(inserted_range.end().line(), 0), inserted_range.end()}
      );
    kDebug(DEBUG_AREA) << "text_before=" << text_before;

    /// Check if current line starts w/ \c '#' which is a sign of a preprocessor directive.
    if (text_before[0] != '#')
        return false;
    /// If we are start completion, and user entered text still empty,
    /// when no reason to abort completion.
    if (inserted_text.isEmpty())
        return false;

    /// Otherwise, try to collect indices of matched completion items.
    auto matches = std::vector<int>{};
    matches.reserve(COMPLETIONS.size());
    for (auto i = 0u; i < COMPLETIONS.size(); ++i)
    {
        auto text = COMPLETIONS[i].text;
        const auto end_of_first_word = text.indexOf(' ');
        if (end_of_first_word != -1)
            text = text.left(end_of_first_word);
        const auto is_match = inserted_text.size() < text.size()
          && text.startsWith(inserted_text)
          ;
        if (is_match)
            matches.emplace_back(i);
    }

    /// Then, if matched items count equal to one, that means
    /// we can auto-insert that item (cuz there is no other alternatives).
    if (matches.size() == 1)
    {
        auto item_text = COMPLETIONS[matches[0]].text;
        const auto column = item_text.indexOf('|');
        if (column != -1)
            item_text.remove(column, 1);

        doc->replaceText(inserted_range, item_text);

        // Try to reposition a cursor inside a current view
        if (column != -1)
        {
            auto pos = inserted_range.start();
            pos.setColumn(pos.column() + column);
            doc->activeView()->setCursorPosition(pos);
        }
        kDebug(DEBUG_AREA) << "yEAH! wANt ABrT;";
        return true;
    }
    m_should_complete = !matches.empty();
    kDebug(DEBUG_AREA) << "m_should_complete=" << m_should_complete;
    return !m_should_complete;
}
Example #28
0
void Widget::fillTables()
{
    mainLayout->removeItem(mainLayout->itemAt(2));
    m_isTables=true;
    tablesScrollArea=new QScrollArea;
    tablesGroupBox=new QGroupBox;
    tablesLayout=new QVBoxLayout;
    QString _f("z = ");
    QString restr;
    for(int i=0;i<nArgs+2*nEq;i++)
    {
        QString t;
        if(f[i]==-DBL_MAX)
            t=tr(" - M");
        else
        {
            if(i!=0)
            {
                if(f[i]<0)
                    t=tr(" - ");
                else
                    t=tr(" + ");
            }
            t+=QString::number(abs(f[i]));
        }
        t+=tr("x%1").arg(QString::number(i+1));
        restr+=tr("x%1, ").arg(QString::number(i+1));
        _f+=t;
    }
    _f+=tr("  -> ")+direction;
    restr.resize(restr.size()-2);
    restr+=tr(" >= 0");
    tablesLayout->addWidget(new QLabel(_f));
    tablesLayout->addWidget(new QLabel(restr));
    for(int i=0;i<simplex.count();i++)
    {
        tables.enqueue(simplex[i]->getTable());
        if(i!=0)
        {
            QPoint* r=simplex[i-1]->findR();
            if(r!=NULL)
            {
                tablesLayout->addWidget(new QLabel(tr("Найменша сума у %1 стовпцю, найменше відношення у %2 рядку.").arg(QString::number(r->y()+1),QString::number(r->x()+1))));
                tablesLayout->addWidget(new QLabel(tr("Вибраний розв'язувальний елемент: A[%1,%2] = %3").arg(QString::number(r->x()+1),QString::number(r->y()+1),QString::number(simplex[i-1]->A[r->x()][r->y()]))));
                tablesLayout->addWidget(new QLabel(tr("Перераховуємо таблицю: ")));
            }
            delete r;
        }
        tablesLayout->addWidget(tables.last());
    }
    QString res;
    int* ires;
    switch(m_result)
    {
        case RESULT_SUCCESS:
            tablesLayout->addWidget(new QLabel(tr("Відповідь:")));
            ires=new int[nArgs+2*nEq];
            res=tr("x = (");
            for(int i=0;i<nArgs+2*nEq;i++)
            {
                ires[i]=0;
            }
            for(int i=0;i<nEq;i++)
            {
                ires[simplex.last()->basis[i]]=simplex.last()->B[i];
            }
            for(int i=0;i<nArgs+2*nEq;i++)
            {
                res+=tr("%1, ").arg(QString::number(ires[i]));
            }
            res.resize(res.size()-2);
            res+=tr(")");
            delete [] ires;
            tablesLayout->addWidget(new QLabel(res));
            tablesLayout->addWidget(new QLabel(tr("z = %1").arg(QString::number(simplex.last()->sumB1))));
            break;
        case RESULT_CYCLE:
            QMessageBox::critical(NULL,tr(""),tr("Зациклення."),QMessageBox::Ok);
            tablesLayout->addWidget(new QLabel(tr("Зациклення. Задача розв'язку не має.")));
            break;
        case RESULT_NO:
            QMessageBox::information(NULL,tr(""),tr("Розв'язок М-задачі знайдено, вихідна задача розв'язку немає."),QMessageBox::Ok);
            tablesLayout->addWidget(new QLabel(tr("Вихідна задача розв'язку немає.")));
            break;
        case RESULT_INF:
            QMessageBox::information(NULL,tr(""),tr("Цільова функція необмежена."),QMessageBox::Ok);
            tablesLayout->addWidget(new QLabel(tr("Цільова функція необмежена.")));
            break;
    }

    tablesGroupBox->setLayout(tablesLayout);
    tablesScrollArea->setWidget(tablesGroupBox);
    tablesScrollArea->setWidgetResizable(true);
    tablesScrollArea->setMinimumWidth(tables.last()->minimumWidth()+80);

    mainLayout->addWidget(tablesScrollArea,2);
    move(pos().x(),0);
    myResize(size().width(),QApplication::desktop()->height()-100);
    m_isTables=true;
}
Example #29
0
void ITunesFeature::guessMusicLibraryMountpoint(QXmlStreamReader &xml) {
    // Normally the Folder Layout it some thing like that
    // iTunes/
    // iTunes/Album Artwork
    // iTunes/iTunes Media <- this is the "Music Folder"
    // iTunes/iTunes Music Library.xml <- this location we already knew
    QByteArray strlocbytes = xml.readElementText().toUtf8();
    QString music_folder = QUrl::fromEncoded(strlocbytes).toLocalFile();

    QString music_folder_test = music_folder;
    music_folder_test.replace(localhost_token(), "");
    QDir music_folder_dir(music_folder_test);

    // The music folder exists, so a simple transformation
    // of replacing localhost token with nothing will work.
    if (music_folder_dir.exists()) {
        // Leave defaults intact.
        return;
    }

    // The iTunes Music Library doesn't exist! This means we are likely loading
    // the library from a system that is different from the one that wrote the
    // iTunes configuration. The configuration file path, m_dbfile is a readable
    // location that in most situation is "close" to the music library path so
    // since we can read that file we will try to infer the music library mount
    // point from it.

    // Examples:

    // Windows with non-itunes-managed music:
    // m_dbfile: c:/Users/LegacyII/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/C:/Users/LegacyII/Music/
    // Transformation:  "//localhost/" -> ""

    // Mac OS X with iTunes-managed music:
    // m_dbfile: /Users/rjryan/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/Users/rjryan/Music/iTunes/iTunes Media/
    // Transformation: "//localhost" -> ""

    // Linux reading an OS X partition mounted at /media/foo to an
    // iTunes-managed music folder:
    // m_dbfile: /media/foo/Users/rjryan/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/Users/rjryan/Music/iTunes/iTunes Media/
    // Transformation: "//localhost" -> "/media/foo"

    // Linux reading a Windows partition mounted at /media/foo to an
    // non-itunes-managed music folder:
    // m_dbfile: /media/foo/Users/LegacyII/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/C:/Users/LegacyII/Music/
    // Transformation:  "//localhost/C:" -> "/media/foo"

    // Algorithm:
    // 1. Find the largest common subsequence shared between m_dbfile and "Music
    //    Folder"
    // 2. For all tracks, replace the left-side of of the LCS in "Music Folder"
    //    with the left-side of the LCS in m_dbfile.

    QString lcs = LCS(m_dbfile, music_folder);

    if (lcs.size() <= 1) {
        qDebug() << "ERROR: Couldn't find a suitable transformation to load iTunes data files. Leaving defaults intact.";
    }

    int musicFolderLcsIndex = music_folder.indexOf(lcs);
    if (musicFolderLcsIndex < 0) {
        qDebug() << "ERROR: Detected LCS" << lcs
                 << "is not present in music_folder:" << music_folder;
        return;
    }

    int dbfileLcsIndex = m_dbfile.indexOf(lcs);
    if (dbfileLcsIndex < 0) {
        qDebug() << "ERROR: Detected LCS" << lcs
                 << "is not present in m_dbfile" << m_dbfile;
        return;
    }

    m_dbItunesRoot = music_folder.left(musicFolderLcsIndex);
    m_mixxxItunesRoot = m_dbfile.left(dbfileLcsIndex);
    qDebug() << "Detected translation rule for iTunes files:"
             << m_dbItunesRoot << "->" << m_mixxxItunesRoot;
}
void
ExportGroupTemplateDialog::onOkClicked()
{
    QString dirPath = _imp->fileEdit->text();

    if ( !dirPath.isEmpty() && ( dirPath[dirPath.size() - 1] == QLatin1Char('/') ) ) {
        dirPath.remove(dirPath.size() - 1, 1);
    }
    QDir d(dirPath);

    if ( !d.exists() ) {
        Dialogs::errorDialog( tr("Error").toStdString(), tr("You must specify a directory to save the script").toStdString() );

        return;
    }
    QString pluginLabel = _imp->labelEdit->text();
    if ( pluginLabel.isEmpty() ) {
        Dialogs::errorDialog( tr("Error").toStdString(), tr("You must specify a label to name the script").toStdString() );

        return;
    } else {
        pluginLabel = QString::fromUtf8( NATRON_PYTHON_NAMESPACE::makeNameScriptFriendly( pluginLabel.toStdString() ).c_str() );
    }

    QString pluginID = _imp->idEdit->text();
    if ( pluginID.isEmpty() ) {
        Dialogs::errorDialog( tr("Error").toStdString(), tr("You must specify a unique ID to identify the script").toStdString() );

        return;
    }

    QString iconPath = _imp->iconPath->text();
    QString grouping = _imp->groupingEdit->text();
    QString description = _imp->descriptionEdit->getText();
    QString filePath = d.absolutePath() + QLatin1Char('/') + pluginLabel + QString::fromUtf8(".py");
    QStringList filters;
    filters.push_back( QString( pluginLabel + QString::fromUtf8(".py") ) );
    if ( !d.entryList(filters, QDir::Files | QDir::NoDotAndDotDot).isEmpty() ) {
        StandardButtonEnum rep = Dialogs::questionDialog(tr("Existing plug-in").toStdString(),
                                                         tr("A group plug-in with the same name already exists "
                                                            "would you like to "
                                                            "override it?").toStdString(), false);
        if  (rep == eStandardButtonNo) {
            return;
        }
    }

    bool foundInPath = false;
    QStringList groupSearchPath = appPTR->getAllNonOFXPluginsPaths();
    for (QStringList::iterator it = groupSearchPath.begin(); it != groupSearchPath.end(); ++it) {
        if ( !it->isEmpty() && ( it->at(it->size() - 1) == QLatin1Char('/') ) ) {
            it->remove(it->size() - 1, 1);
        }
        if (*it == dirPath) {
            foundInPath = true;
        }
    }

    if (!foundInPath) {
        QString message = dirPath + tr(" does not exist in the group plug-in search path, would you like to add it?");
        StandardButtonEnum rep = Dialogs::questionDialog(tr("Plug-in path").toStdString(),
                                                         message.toStdString(), false);

        if  (rep == eStandardButtonYes) {
            appPTR->getCurrentSettings()->appendPythonGroupsPath( dirPath.toStdString() );
        }
    }

    QFile file(filePath);
    if ( !file.open(QIODevice::ReadWrite | QIODevice::Truncate) ) {
        Dialogs::errorDialog( tr("Error").toStdString(), QString(tr("Cannot open ") + filePath).toStdString() );

        return;
    }

    QTextStream ts(&file);
    QString content;
    _imp->group->exportGroupToPython(pluginID, pluginLabel, description, iconPath, grouping, content);
    ts << content;

    accept();
} // ExportGroupTemplateDialog::onOkClicked