Example #1
0
void Tags::setTagsFile( const QString & file )
{
	_tagsfile = file.toLocal8Bit();
}
Example #2
0
static void CompleteJob(int jobID, ProgramInfo *pginfo, bool useCutlist,
                        frm_dir_map_t *deleteMap, int &resultCode)
{
    int status = JobQueue::GetJobStatus(jobID);

    if (!pginfo)
    {
        JobQueue::ChangeJobStatus(jobID, JOB_ERRORED,
                                  "Job errored, unable to find Program Info for job");
        return;
    }

    WaitToDelete(pginfo);

    const QString filename = pginfo->GetPlaybackURL(false, true);
    const QByteArray fname = filename.toLocal8Bit();

    if (status == JOB_STOPPING)
    {
        // Transcoding may take several minutes.  Reload the bookmark
        // in case it changed, then save its translated value back.
        uint64_t previousBookmark =
            ComputeNewBookmark(ReloadBookmark(pginfo), deleteMap);
        pginfo->SaveBookmark(previousBookmark);

        const QString jobArgs = JobQueue::GetJobArgs(jobID);

        const QString tmpfile = filename + ".tmp";
        const QByteArray atmpfile = tmpfile.toLocal8Bit();

        // To save the original file...
        const QString oldfile = filename + ".old";
        const QByteArray aoldfile = oldfile.toLocal8Bit();

        QFileInfo st(tmpfile);
        qint64 newSize = 0;
        if (st.exists())
            newSize = st.size();

        QString cnf = filename;
        if ((jobArgs == "RENAME_TO_NUV") &&
                (filename.contains(QRegExp("mpg$"))))
        {
            QString newbase = pginfo->QueryBasename();

            cnf.replace(QRegExp("mpg$"), "nuv");
            newbase.replace(QRegExp("mpg$"), "nuv");
            pginfo->SaveBasename(newbase);
        }

        const QString newfile = cnf;
        const QByteArray anewfile = newfile.toLocal8Bit();

        if (rename(fname.constData(), aoldfile.constData()) == -1)
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("mythtranscode: Error Renaming '%1' to '%2'")
                .arg(filename).arg(oldfile) + ENO);
        }

        if (rename(atmpfile.constData(), anewfile.constData()) == -1)
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("mythtranscode: Error Renaming '%1' to '%2'")
                .arg(tmpfile).arg(newfile) + ENO);
        }

        if (!gCoreContext->GetNumSetting("SaveTranscoding", 0))
        {
            int err;
            bool followLinks =
                gCoreContext->GetNumSetting("DeletesFollowLinks", 0);

            LOG(VB_FILE, LOG_INFO,
                QString("mythtranscode: About to unlink/delete file: %1")
                .arg(oldfile));

            QFileInfo finfo(oldfile);
            if (followLinks && finfo.isSymLink())
            {
                QString link = getSymlinkTarget(oldfile);
                QByteArray alink = link.toLocal8Bit();
                err = transUnlink(alink.constData(), pginfo);

                if (err)
                {
                    LOG(VB_GENERAL, LOG_ERR,
                        QString("mythtranscode: Error deleting '%1' "
                                "pointed to by '%2'")
                        .arg(alink.constData())
                        .arg(aoldfile.constData()) + ENO);
                }

                err = unlink(aoldfile.constData());
                if (err)
                {
                    LOG(VB_GENERAL, LOG_ERR,
                        QString("mythtranscode: Error deleting '%1', "
                                "a link pointing to '%2'")
                        .arg(aoldfile.constData())
                        .arg(alink.constData()) + ENO);
                }
            }
            else
            {
                if ((err = transUnlink(aoldfile.constData(), pginfo)))
                    LOG(VB_GENERAL, LOG_ERR,
                        QString("mythtranscode: Error deleting '%1': ")
                        .arg(oldfile) + ENO);
            }
        }

        // Delete previews if cutlist was applied.  They will be re-created as
        // required.  This prevents the user from being stuck with a preview
        // from a cut area and ensures that the "dimensioned" previews
        // correspond to the new timeline
        if (useCutlist)
        {
            QFileInfo fInfo(filename);
            QString nameFilter = fInfo.fileName() + "*.png";
            // QDir's nameFilter uses spaces or semicolons to separate globs,
            // so replace them with the "match any character" wildcard
            // since mythrename.pl may have included them in filenames
            nameFilter.replace(QRegExp("( |;)"), "?");
            QDir dir (fInfo.path(), nameFilter);

            for (uint nIdx = 0; nIdx < dir.count(); nIdx++)
            {
                // If unlink fails, keeping the old preview is not a problem.
                // The RENAME_TO_NUV check below will attempt to rename the
                // file, if required.
                const QString oldfileop = QString("%1/%2")
                                          .arg(fInfo.path()).arg(dir[nIdx]);
                const QByteArray aoldfileop = oldfileop.toLocal8Bit();
                transUnlink(aoldfileop.constData(), pginfo);
            }
        }

        /* Rename all preview thumbnails. */
        if (jobArgs == "RENAME_TO_NUV")
        {
            QFileInfo fInfo(filename);
            QString nameFilter = fInfo.fileName() + "*.png";
            // QDir's nameFilter uses spaces or semicolons to separate globs,
            // so replace them with the "match any character" wildcard
            // since mythrename.pl may have included them in filenames
            nameFilter.replace(QRegExp("( |;)"), "?");

            QDir dir (fInfo.path(), nameFilter);

            for (uint nIdx = 0; nIdx < dir.count(); nIdx++)
            {
                const QString oldfileprev = QString("%1/%2")
                                            .arg(fInfo.path()).arg(dir[nIdx]);
                const QByteArray aoldfileprev = oldfileprev.toLocal8Bit();

                QString newfileprev = oldfileprev;
                QRegExp re("mpg(\\..*)?\\.png$");
                if (re.indexIn(newfileprev))
                {
                    newfileprev.replace(
                        re, QString("nuv%1.png").arg(re.cap(1)));
                }
                const QByteArray anewfileprev = newfileprev.toLocal8Bit();

                QFile checkFile(oldfileprev);

                if ((oldfileprev != newfileprev) && (checkFile.exists()))
                    rename(aoldfileprev.constData(), anewfileprev.constData());
            }
        }

        MSqlQuery query(MSqlQuery::InitCon());

        if (useCutlist)
        {
            query.prepare("DELETE FROM recordedmarkup "
                          "WHERE chanid = :CHANID "
                          "AND starttime = :STARTTIME "
                          "AND type != :BOOKMARK ");
            query.bindValue(":CHANID", pginfo->GetChanID());
            query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());
            query.bindValue(":BOOKMARK", MARK_BOOKMARK);

            if (!query.exec())
                MythDB::DBError("Error in mythtranscode", query);

            query.prepare("UPDATE recorded "
                          "SET cutlist = :CUTLIST "
                          "WHERE chanid = :CHANID "
                          "AND starttime = :STARTTIME ;");
            query.bindValue(":CUTLIST", "0");
            query.bindValue(":CHANID", pginfo->GetChanID());
            query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());

            if (!query.exec())
                MythDB::DBError("Error in mythtranscode", query);

            pginfo->SaveCommFlagged(COMM_FLAG_NOT_FLAGGED);
        }
        else
        {
            query.prepare("DELETE FROM recordedmarkup "
                          "WHERE chanid = :CHANID "
                          "AND starttime = :STARTTIME "
                          "AND type not in ( :COMM_START, "
                          "    :COMM_END, :BOOKMARK, "
                          "    :CUTLIST_START, :CUTLIST_END) ;");
            query.bindValue(":CHANID", pginfo->GetChanID());
            query.bindValue(":STARTTIME", pginfo->GetRecordingStartTime());
            query.bindValue(":COMM_START", MARK_COMM_START);
            query.bindValue(":COMM_END", MARK_COMM_END);
            query.bindValue(":BOOKMARK", MARK_BOOKMARK);
            query.bindValue(":CUTLIST_START", MARK_CUT_START);
            query.bindValue(":CUTLIST_END", MARK_CUT_END);

            if (!query.exec())
                MythDB::DBError("Error in mythtranscode", query);
        }

        if (newSize)
            pginfo->SaveFilesize(newSize);

        JobQueue::ChangeJobStatus(jobID, JOB_FINISHED);

    } else {
        // Not a successful run, so remove the files we created
        QString filename_tmp = filename + ".tmp";
        QByteArray fname_tmp = filename_tmp.toLocal8Bit();
        LOG(VB_GENERAL, LOG_NOTICE, QString("Deleting %1").arg(filename_tmp));
        transUnlink(fname_tmp.constData(), pginfo);

        QString filename_map = filename + ".tmp.map";
        QByteArray fname_map = filename_map.toLocal8Bit();
        unlink(fname_map.constData());

        if (status == JOB_ABORTING)                     // Stop command was sent
            JobQueue::ChangeJobStatus(jobID, JOB_ABORTED, "Job Aborted");
        else if (status != JOB_ERRORING)                // Recoverable error
            resultCode = GENERIC_EXIT_RESTART;
        else                                            // Unrecoverable error
            JobQueue::ChangeJobStatus(jobID, JOB_ERRORED,
                                      "Unrecoverable error");
    }
}
Example #3
0
void MainWindow::install()
{
    ui->statusLabel->setFont(getFont(ui->statusLabel, FONT_STATUSLABEL_RATIO));
    ui->statusProgressBar->setFont(getFont(ui->statusProgressBar, FONT_PROGRESSBAR_RATIO));

    qApp->processEvents();
    /* Find out what device we are running on */
    logger->addLine("Detecting device we are running on");
    device = targetList->getTarget(utils->getOSMCDev());
    if (device == NULL)
    {
        haltInstall("unsupported device"); /* No tr here as not got lang yet */
        return;
    }
    /* Mount the BOOT filesystem */
    logger->addLine("Mounting boot filesystem");
    bool hasMount = false;
    hasMount = utils->mountPartition(device, MNT_BOOT);
    if (! hasMount && utils->getOSMCDev() == "atv")
    {
        /* Super hacky for Apple TV 1st gen. Sometimes no internal disk */
        hasMount = utils->mountPartition(device, "/dev/sda1");
        device->setRoot("/dev/sda2");
        device->setBootNeedsFormat(false);
    }
    if (! hasMount)
    {
        haltInstall("could not mount bootfs");
        return;
    }
    /* Sanity check: need filesystem.tar.xz */
    QFile fileSystem(QString(MNT_BOOT) + "/filesystem.tar.xz");
    if (! fileSystem.exists())
    {
        haltInstall("no filesystem found");
        return;
    }
    /* Load in preseeded values */
    preseed = new PreseedParser();
    if (preseed->isLoaded())
    {
        logger->addLine("Preseed file found, will attempt to parse");
        /* Locales */
        locale = preseed->getStringValue("globe/locale");
        if (! locale.isEmpty())
        {
            logger->addLine("Found a definition for globalisation: " + locale);
            QTranslator translator;
            if (translator.load(qApp->applicationDirPath() + "/osmc_" + locale + ".qm"))
            {
                logger->addLine("Translation loaded successfully!");
                qApp->installTranslator(&translator);
                ui->retranslateUi(this);
            }
            else
                logger->addLine("Could not load translation");
        }
        /* Install target */
        installTarget = preseed->getStringValue("target/storage");
        if (! installTarget.isEmpty())
        {
            logger->addLine("Found a definition for storage: " + installTarget);
            if (installTarget == "nfs")
            {
                QString nfsPath = preseed->getStringValue("target/storagePath");
                if (! nfsPath.isEmpty())
                {
                    device->setRoot(nfsPath);
                    useNFS = true;
                }
            }
            if (installTarget == "usb")
            {
                /* Behaviour for handling USB installs */
                if (utils->getOSMCDev() == "rbp1") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "rbp2") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "vero1") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "atv") { device->setRoot("/dev/sda1"); } /* It's not USB, it's the internal disk.. but this is a hack */
                for (int i = 0; i <= 60; i++)
                {
                    ui->statusLabel->setText(tr("USB install:") + " " + QString::number(60 - i) + " " + ("seconds to remove device before data loss"));
                    qApp->processEvents();
                    system("/bin/sleep 1");
                }
            }
        }
        /* Bring up network if using NFS */
        if (useNFS)
        {
            logger->addLine("NFS installation chosen, must bring up network");
            nw = new Network();
            nw->setIP(preseed->getStringValue("network/ip"));
            nw->setMask(preseed->getStringValue("network/mask"));
            nw->setGW(preseed->getStringValue("network/gw"));
            nw->setDNS1(preseed->getStringValue("network/dns1"));
            nw->setDNS2(preseed->getStringValue("network/dns2"));
            if (! nw->isDefined())
            {
                logger->addLine("Either network preseed definition incomplete, or user wants DHCP");
                nw->setAuto();
            }
            logger->addLine("Attempting to bring up eth0");
            ui->statusLabel->setText(tr("Configuring Network"));
            nw->bringUp();
        }
    }
    else
    {
        logger->addLine("No preseed file was found");
    }
    /* If !nfs, create necessary partitions */
    if (! useNFS)
    {
        logger->addLine("Creating root partition");
        ui->statusLabel->setText(tr("Formatting device"));
        qApp->processEvents(); /* Force GUI update */
        QString rootBase = device->getRoot();
        if (rootBase.contains("mmcblk"))
            rootBase.chop(2);
        else
            rootBase.chop(1);
        logger->addLine("From a root partition of " + device->getRoot() + ", I have deduced a base device of " + rootBase);
        if (device->hasRootChanged() && utils->getOSMCDev() != "atv") // && utils.getOSMCDev() != "pc" eventually.. -- cause we want boot there too.
        {
            logger->addLine("Must mklabel as root fs is on another device");
            utils->mklabel(rootBase, false);
            utils->mkpart(rootBase, "ext4", "4096s", "100%");
            utils->fmtpart(device->getRoot(), "ext4");
        }
        else
        {
            if (! device->doesBootNeedsFormat())
            {
                int size = utils->getPartSize(rootBase, device->getBootFS());
                if (size == -1)
                {
                    logger->addLine("Issue getting size of device");
                    haltInstall(tr("cannot work out partition size"));
                    return;
                }
                if (device->deviceUsesGPT())
                {
                    /* GPT is too clever: has secondary header; so we need to trash it and recreate the partition layout */
                    /* NB: for some reason on 4.x this does not work all the time. So we have some parted patches to make sure it does */
                    logger->addLine("We are using GPT. I need to erase the first 512 bytes and reconstruct the partition table");
                    QString ddCmd = "/bin/dd if=/dev/zero of=" + rootBase + " bs=512 count=1 conv=fsync";
                    system(ddCmd.toLocal8Bit());
                    int fd;
                    QFile dev(rootBase);
                    dev.open(fd, QIODevice::ReadOnly);
                    ioctl(fd, BLKRRPART, NULL);
                    ioctl(fd, BLKFLSBUF, NULL);
                    dev.close();
                    utils->updateDevTable();
                    utils->updateDevTable();
                    if (utils->getOSMCDev() == "atv")
                    {
                        logger->addLine("Re-creating Apple TV partition structure");
                        utils->mklabel(rootBase, true);
                        utils->updateDevTable();
                        utils->mkpart(rootBase, "hfsplus", "40s", "256M");
                        /* We don't format /boot */
                        utils->setflag(rootBase, "1 atvrecv", true);
                        utils->updateDevTable();
                    }
                }
                logger->addLine("Determined " + QString::number(size) + " MB as end of first partition");
                utils->mkpart(rootBase, "ext4", QString::number(size + 2) + "M", "100%");
                utils->fmtpart(device->getRoot(), "ext4");
            }
            else
            {
                /* We have to create the partition structure for /boot too */
                logger->addLine("Must mklabel as rootfs is on another device");
                utils->mklabel(rootBase, true); /* GPT favoured on PC */
                logger->addLine("Making boot partition as this type of system needs one");
                if (utils->getOSMCDev() == "atv")
                {
                    utils->mkpart(rootBase, device->getBootFS(), "40s", "256M"); /* Hack to hard-code this for now */
                    utils->setflag(rootBase, "1 atvrecv", true);
                    utils->fmtpart(device->getBoot(), "hfsplus");
                }
                utils->updateDevTable();
                logger->addLine("Making root partition");
                int size = utils->getPartSize(rootBase, device->getBootFS());
                if (size == -1)
                {
                    logger->addLine("Issue getting size of device");
                    haltInstall(tr("cannot work out partition size"));
                    return;
                }
                logger->addLine("Determined " + QString::number(size) + " MB as end of first partition");
                utils->mkpart(rootBase, "ext4", QString::number(size + 2) + "M", "100%");
                utils->fmtpart(device->getRoot(), "ext4");
            }
        }
    }
    /* Mount root filesystem */
    if (useNFS)
        bc = new BootloaderConfig(device, nw, utils, logger, preseed);
    else
        bc = new BootloaderConfig(device, NULL, utils, logger, preseed);
    logger->addLine("Mounting root");
    if ( ! utils->mountPartition(device, MNT_ROOT))
    {
        logger->addLine("Error occured trying to mount root of " + device->getRoot());
        haltInstall(tr("can't mount root"));
        return;
    }
    if (useNFS)
        system("rm -rf /mnt/root/*"); /* BusyBox tar does not like overwrites. Clear nfsroot first */
   /* Extract root filesystem */
   ui->statusLabel->setText(tr("Installing files"));
   logger->addLine("Extracting files to root filesystem");
   ui->statusProgressBar->setMinimum(0);
   ui->statusProgressBar->setMaximum(100);

   QThread* thread = new QThread(this);
   ExtractWorker *worker = new ExtractWorker(fileSystem.fileName(), MNT_ROOT, logger);
   worker->moveToThread(thread);
   connect(thread, SIGNAL(started()), worker, SLOT(extract()));
   connect(worker, SIGNAL(progressUpdate(unsigned)), this, SLOT(setProgress(unsigned)));
   connect(worker, SIGNAL(error(QString)), this, SLOT(haltInstall(QString)));
   connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
   connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
   connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
   connect(thread, SIGNAL(finished()), this, SLOT(finished()));
   thread->start();
}
Example #4
0
int verboseArgParse(QString arg)
{
    QString option;

    if (!verboseInitialized)
        verboseInit();

    QMutexLocker locker(&verboseMapMutex);

    verboseMask = verboseDefaultInt;
    verboseString = QString(verboseDefaultStr);

    if (arg.startsWith('-'))
    {
        cerr << "Invalid or missing argument to -v/--verbose option\n";
        return GENERIC_EXIT_INVALID_CMDLINE;
    }

    QStringList verboseOpts = arg.split(QRegExp("\\W+"));
    for (QStringList::Iterator it = verboseOpts.begin();
         it != verboseOpts.end(); ++it )
    {
        option = (*it).toLower();
        bool reverseOption = false;

        if (option != "none" && option.left(2) == "no")
        {
            reverseOption = true;
            option = option.right(option.length() - 2);
        }

        if (option == "help")
        {
            verboseHelp();
            return GENERIC_EXIT_INVALID_CMDLINE;
        }
        else if (option == "important")
        {
            cerr << "The \"important\" log mask is no longer valid.\n";
        }
        else if (option == "extra")
        {
            cerr << "The \"extra\" log mask is no longer valid.  Please try --loglevel debug instead.\n";
        }
        else if (option == "default")
        {
            if (haveUserDefaultValues)
            {
                verboseMask = userDefaultValueInt;
                verboseString = userDefaultValueStr;
            }
            else
            {
                verboseMask = verboseDefaultInt;
                verboseString = QString(verboseDefaultStr);
            }
        }
        else 
        {
            VerboseDef *item = verboseMap.value(option);

            if (item)
            {
                if (reverseOption)
                {
                    verboseMask &= ~(item->mask);
                    verboseString = verboseString.remove(' ' + item->name);
                    verboseString += " no" + item->name;
                }
                else
                {
                    if (item->additive)
                    {
                        if (!(verboseMask & item->mask))
                        {
                            verboseMask |= item->mask;
                            verboseString += ' ' + item->name;
                        }
                    }
                    else
                    {
                        verboseMask = item->mask;
                        verboseString = item->name;
                    }
                }
            }
            else
            {
                cerr << "Unknown argument for -v/--verbose: " << 
                        option.toLocal8Bit().constData() << endl;;
                return GENERIC_EXIT_INVALID_CMDLINE;
            }
        }
    }

    if (!haveUserDefaultValues)
    {
        haveUserDefaultValues = true;
        userDefaultValueInt = verboseMask;
        userDefaultValueStr = verboseString;
    }

    return GENERIC_EXIT_OK;
}
PythonEditorWidget::PythonEditorWidget(InviwoMainWindow* ivwwin, InviwoApplication* app)
    : InviwoDockWidget(tr("Python Editor"), ivwwin)
    , settings_("Inviwo", "Inviwo")
    , infoTextColor_(153, 153, 153)
    , errorTextColor_(255, 107, 107)
    , runAction_(nullptr)
    , script_()
    , unsavedChanges_(false)
    , app_(app)
    , appendLog_(true)
{

    setObjectName("PythonEditor");
    settings_.beginGroup("PythonEditor");
    QString lastFile = settings_.value("lastScript", "").toString();
    appendLog_ = settings_.value("appendLog", appendLog_).toBool();
    settings_.endGroup();
    setVisible(false);
    setWindowIcon(QIcon(":/icons/python.png"));

    QMainWindow* mainWindow = new QMainWindow();
    mainWindow->setContextMenuPolicy(Qt::NoContextMenu);
    QToolBar* toolBar = new QToolBar();
    mainWindow->addToolBar(toolBar);
    toolBar->setFloatable(false);
    toolBar->setMovable(false);
    setWidget(mainWindow);

    {
        runAction_ = toolBar->addAction(QIcon(":/icons/python.png"), "Compile and Run");
        runAction_->setShortcut(QKeySequence(tr("F5")));
        runAction_->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        runAction_->setToolTip("Compile and Run Script");
        mainWindow->addAction(runAction_);
        connect(runAction_, &QAction::triggered, [this]() {run(); });
    }
    {
        auto action = toolBar->addAction(QIcon(":/icons/new.png"), tr("&New Script"));
        action->setShortcut(QKeySequence::New);
        action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        action->setToolTip("New Script");
        mainWindow->addAction(action);
        connect(action, &QAction::triggered, [this](){setDefaultText();});
    }
    {
        auto action = toolBar->addAction(QIcon(":/icons/open.png"), tr("&Open Script"));
        action->setShortcut(QKeySequence::Open);
        action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        action->setToolTip("Open Script");
        mainWindow->addAction(action);
        connect(action, &QAction::triggered, [this](){open();});
    }

    {
        auto action = toolBar->addAction(QIcon(":/icons/save.png"), tr("&Save Script"));
        action->setShortcut(QKeySequence::Save);
        action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        action->setToolTip("Save Script");
        mainWindow->addAction(action);
        connect(action, &QAction::triggered, [this](){save();});
    }
    {
        auto action = toolBar->addAction(QIcon(":/icons/saveas.png"), tr("&Save Script As..."));
        action->setShortcut(QKeySequence::SaveAs);
        action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        action->setToolTip("Save Script As...");
        mainWindow->addAction(action);
        connect(action, &QAction::triggered, [this](){saveAs();});
    }
    {
        QIcon icon;
        icon.addFile(":/icons/log-append.png", QSize(), QIcon::Normal, QIcon::On);
        icon.addFile(":/icons/log-clearonrun.png", QSize(), QIcon::Normal, QIcon::Off);

        QString str = (appendLog_ ? "Append Log" : "Clear Log on Run");
        auto action = toolBar->addAction(icon, str);
        action->setShortcut(Qt::ControlModifier + Qt::Key_E);
        action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        action->setCheckable(true);
        action->setChecked(appendLog_);
        action->setToolTip(appendLog_ ? "Append Log" : "Clear Log on Run");
        mainWindow->addAction(action);
        connect(action, &QAction::toggled, [this, action](bool toggle) { 
            appendLog_ = toggle; 
            // update tooltip and menu entry
            QString tglstr = (toggle ? "Append Log" : "Clear Log on Run");
            action->setText(tglstr);
            action->setToolTip(tglstr);
            // update settings
            settings_.beginGroup("PythonEditor");
            settings_.setValue("appendLog", appendLog_);
            settings_.endGroup();
        });
    }
    {
        auto action = toolBar->addAction(QIcon(":/icons/log-clear.png"), "Clear Log Output");
        action->setShortcut(Qt::ControlModifier + Qt::Key_E);
        action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
        action->setToolTip("Clear Log Output");
        mainWindow->addAction(action);
        connect(action, &QAction::triggered, [this](){clearOutput();});
    }

    // Done creating buttons
    QSplitter* splitter = new QSplitter(nullptr);
    splitter->setOrientation(Qt::Vertical);
    pythonCode_ = new PythonTextEditor(nullptr);
    pythonCode_->setObjectName("pythonEditor");
    pythonCode_->setUndoRedoEnabled(true);
    setDefaultText();
    pythonOutput_ = new QTextEdit(nullptr);
    pythonOutput_->setObjectName("pythonConsole");
    pythonOutput_->setReadOnly(true);
    pythonOutput_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    syntaxHighligther_ =
        SyntaxHighligther::createSyntaxHighligther<Python>(pythonCode_->document());

    splitter->addWidget(pythonCode_);
    splitter->addWidget(pythonOutput_);
    splitter->setStretchFactor(0, 1);
    splitter->setStretchFactor(1, 0);
    splitter->setHandleWidth(2);
    // enable QSplitter:hover stylesheet
    // QTBUG-13768 https://bugreports.qt.io/browse/QTBUG-13768
    splitter->handle(1)->setAttribute(Qt::WA_Hover);
    mainWindow->setCentralWidget(splitter);

    QObject::connect(pythonCode_, SIGNAL(textChanged()), this, SLOT(onTextChange()));
    // close this window before the main window is closed
    QObject::connect(ivwwin, &InviwoMainWindow::closingMainWindow, [this]() { delete this; });

    this->updateStyle();

    
    this->resize(500, 700);

    if (app_) {
        app_->getSettingsByType<SystemSettings>()->pythonSyntax_.onChange(
            this, &PythonEditorWidget::updateStyle);
        app_->getSettingsByType<SystemSettings>()->pyFontSize_.onChange(
            this, &PythonEditorWidget::updateStyle);
        app_->registerFileObserver(this);
    }
    unsavedChanges_ = false;

    if (lastFile.size() != 0) loadFile(lastFile.toLocal8Bit().constData(), false);

    setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    setFloating(true);
}
void receiveChatMessage(QByteArray msg, Player* player)
{
    QString txt = dataToString(msg.mid(7));
    QString author = player->pony.name;
    //win.logMessage("Chat "+author+":"+txt);

    if (txt.startsWith("/stuck") || txt.startsWith("unstuck me"))
    {
        sendLoadSceneRPC(player, player->pony.sceneName);
    }
    else if (txt == ":commands")
    {
        sendChatMessage(player, "<span color=\"yellow\">List of Commands:</span><br /><em>:roll</em><br /><span color=\"yellow\">Rolls a random number between 00 and 99</span><br /><em>:msg player message</em><br /><span color=\"yellow\">Sends a private message to a player</span><br /><em>:names</em><br /><span color=\"yellow\">Lists all players on the server</span><br /><em>:me action</em><br /><span color=\"yellow\">States your current action</span><br /><em>:tp location</em><br /><span color=\"yellow\">Teleports your pony to the specified region</span>", "[Server]", ChatLocal);
    }
    else if (txt.startsWith(":msg"))
    {
        if(txt.count(" ") < 2)
            sendChatMessage(player, ":msg<br /><span color=\"yellow\">Usage:</span><br /><em>:msg player message</em><br /><span color=\"yellow\">Player names are case-insensitive, ignore spaces and you do not need to type out their full name.</span>", author, ChatLocal);
        else
        {
            for (int i=0; i<win.udpPlayers.size(); i++)
            {
                if (win.udpPlayers[i]->inGame>=2 && win.udpPlayers[i]->pony.name.toLower().remove(" ").startsWith(txt.toLower().section(" ", 1, 1)))
                {
                    txt = txt.remove(0, txt.indexOf(" ", 5) + 1);
                    sendChatMessage(win.udpPlayers[i], "<span color=\"yellow\">[PM] </span>" + txt, author, ChatLocal);
                    sendChatMessage(player, "<span color=\"yellow\">[PM to " + win.udpPlayers[i]->pony.name + "] </span>" + txt, author, ChatLocal);
                }
            }
        }
    }
    else if (txt.startsWith(":names"))
    {
        QString namesmsg = "<span color=\"yellow\">Players currently in game:</span>";

        for (int i=0; i<win.udpPlayers.size(); i++)
            if (win.udpPlayers[i]->inGame>=2)
                namesmsg += "<br />#b" + win.udpPlayers[i]->pony.name + "#b<br /><span color=\"yellow\"> - in " + win.udpPlayers[i]->pony.sceneName + "</span>";

        sendChatMessage(player, namesmsg, "[Server]", ChatLocal);
    }
    else if (txt.startsWith(":tp"))
    {
        if (txt.count(" ") < 1)
        {
          QString msgtosend = ":tp<br /><span color=\"yellow\">Usage:</span><br /><em>:tp location</em><br /><span color=\"yellow\">Available locations:</span><em>";

            for (int i=0; i<win.scenes.size(); i++)
                msgtosend += "<br />" + win.scenes[i].name;

            sendChatMessage(player, msgtosend + "</em>", author, ChatLocal);
        }

        else
            sendLoadSceneRPC(player, txt.remove(0, 4));
    }
    else if (txt == ":me")
    {
        sendChatMessage(player, ":me<br /><span color=\"yellow\">Usage:</span><br /><em>:me action</em>", author, ChatLocal);
    }
    else // Broadcast the message
    {
        int rollnum = -1;
        QString rollstr;
        bool actmsg = false;

        if (txt == ":roll")
        {
            if (player->chatRollCooldownEnd < QDateTime::currentDateTime())
            {
                rollnum = qrand() % 100;
                rollstr.sprintf("<span color=\"yellow\">#b%s#b rolls %02d</span>", author.toLocal8Bit().data(), rollnum);
                player->chatRollCooldownEnd = QDateTime::currentDateTime().addSecs(10);
            }
        }
        if (txt.startsWith(":me "))
        {
            actmsg = true;
            txt.remove(0, 3);
            txt = "<em>#b* " + author + "#b" + txt + "</em>";
        }
        if ((quint8)msg[6] == 8) // Local chat only
        {
            Scene* scene = findScene(player->pony.sceneName);
            if (scene->name.isEmpty())
                win.logMessage("UDP: Can't find the scene for chat message, aborting");
            else
            {
                for (int i=0; i<scene->players.size(); i++)
                {
                    if (scene->players[i]->inGame>=2)
                    {
                        if (rollnum > -1)
                            sendChatMessage(scene->players[i], rollstr, "[Server]", ChatLocal);
                        else if (actmsg)
                            sendChatMessage(scene->players[i], txt, "", ChatLocal);
                        else if (txt.startsWith(">"))
                            sendChatMessage(scene->players[i], "<span color=\"green\">" + txt + "</span>", author, ChatLocal);
                        else
                            sendChatMessage(scene->players[i], txt, author, ChatLocal);
                    }
                }
            }
        }
        else // Send globally
        {
            for (int i=0; i<win.udpPlayers.size(); i++)
            {
                if (win.udpPlayers[i]->inGame>=2)
                {
                    if (rollnum > -1)
                        sendChatMessage(win.udpPlayers[i], rollstr, "[Server]", ChatGeneral);
                    else if (actmsg)
                        sendChatMessage(win.udpPlayers[i], txt, "", ChatGeneral);
                    else if (txt.startsWith(">"))
                        sendChatMessage(win.udpPlayers[i], "<span color=\"green\">" + txt + "</span>", author, ChatGeneral);
                    else
                        sendChatMessage(win.udpPlayers[i], txt, author, ChatGeneral);

                }
            }
        }
    }
}
Example #7
0
QString GalleryUtil::GetCaption(const QString &filePath)
{
    QString caption("");

    try
    {
#ifdef EXIF_SUPPORT
        char *exifvalue = new char[1024];
        ExifData *data = exif_data_new_from_file(
            filePath.toLocal8Bit().constData());
        if (data)
        {
            for (int i = 0; i < EXIF_IFD_COUNT; i++)
            {
                ExifEntry *entry = exif_content_get_entry (data->ifd[i],
                                                    EXIF_TAG_USER_COMMENT);
                if (entry)
                {
#if NEW_LIB_EXIF
                    exif_entry_get_value(entry, exifvalue, 1023);
                    caption = exifvalue;
#else
                    caption = exif_entry_get_value(entry);
#endif
                    // Found one, done
                    if(!caption.trimmed().isEmpty())
                       break;
                }

                entry = exif_content_get_entry (data->ifd[i],
                                                EXIF_TAG_IMAGE_DESCRIPTION);
                if (entry)
                {
#if NEW_LIB_EXIF
                    exif_entry_get_value(entry, exifvalue, 1023);
                    caption = exifvalue;
#else
                    caption = exif_entry_get_value(entry);
#endif
                    // Found one, done
                    if(!caption.trimmed().isEmpty())
                       break;
                }
            }
            exif_data_free(data);
        }
        else
        {
           VERBOSE(VB_FILE, LOC_ERR +
                   QString("Could not load exif data from '%1'")
                   .arg(filePath));
        }

        delete [] exifvalue;
#endif // EXIF_SUPPORT
    }
    catch (...)
    {
        VERBOSE(VB_IMPORTANT, LOC_ERR +
                QString("Failed to extract EXIF headers from '%1'")
                .arg(filePath));
    }

    return caption;
}
Example #8
0
string q2s(const QString &s){
	return string((const char *)s.toLocal8Bit());  
}  
void ConsolePrinter::print(float f, QString label = "")
{
	cout << label.toLocal8Bit().constData() << f << endl;
}
Example #10
0
void CRemoteControl::sendData(QString value)
{
    if (connected)
        client->write(value.toLocal8Bit());
}
void GdbRemoteServerEngine::setupInferior()
{
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
    const DebuggerStartParameters &sp = startParameters();
#ifdef Q_OS_WIN
    #define PATHSEP ";"
#else
    #define PATHSEP ":"
#endif
    QString executableFileName;
    if (!sp.executable.isEmpty()) {
        QFileInfo fi(sp.executable);
        executableFileName = fi.absoluteFilePath();
    }
    QString symbolFileName;
    if (!sp.symbolFileName.isEmpty()) {
        QFileInfo fi(sp.symbolFileName);
        symbolFileName = fi.absoluteFilePath();
    }

    //const QByteArray sysroot = sp.sysroot.toLocal8Bit();
    //const QByteArray remoteArch = sp.remoteArchitecture.toLatin1();
    const QString args = sp.processArgs;

//    if (!remoteArch.isEmpty())
//        postCommand("set architecture " + remoteArch);
    const QString solibSearchPath = sp.solibSearchPath.join(QLatin1String(PATHSEP));
    if (!solibSearchPath.isEmpty())
        postCommand("set solib-search-path " + solibSearchPath.toLocal8Bit());

    if (!args.isEmpty())
        postCommand("-exec-arguments " + args.toLocal8Bit());

    // This has to be issued before 'target remote'. On pre-7.0 the
    // command is not present and will result in ' No symbol table is
    // loaded.  Use the "file" command.' as gdb tries to set the
    // value of a variable with name 'target-async'.
    //
    // Testing with -list-target-features which was introduced at
    // the same time would not work either, as this need an existing
    // target.
    //
    // Using it even without a target and having it fail might still
    // be better as:
    // Some external comment: '[but] "set target-async on" with a native
    // windows gdb will work, but then fail when you actually do
    // "run"/"attach", I think..


    // gdb/mi/mi-main.c:1958: internal-error:
    // mi_execute_async_cli_command: Assertion `is_running (inferior_ptid)'
    // failed.\nA problem internal to GDB has been detected,[...]
    if (debuggerCore()->boolSetting(TargetAsync))
        postCommand("set target-async on", CB(handleSetTargetAsync));

    if (executableFileName.isEmpty() && symbolFileName.isEmpty()) {
        showMessage(tr("No symbol file given."), StatusBar);
        callTargetRemote();
        return;
    }

    if (!symbolFileName.isEmpty()) {
        postCommand("-file-symbol-file \""
                    + symbolFileName.toLocal8Bit() + '"',
                    CB(handleFileExecAndSymbols));
    }
    if (!executableFileName.isEmpty()) {
        postCommand("-file-exec-and-symbols \"" + executableFileName.toLocal8Bit() + '"',
            CB(handleFileExecAndSymbols));
    }
}
Example #12
0
bool WalletModel::backupWallet(const QString &filename)
{
    return BackupWallet(*wallet, filename.toLocal8Bit().data());
}
Example #13
0
QFileInfo Content::GetPreviewImage(        int        nRecordedId,
                                           int        nChanId,
                                     const QDateTime &recstarttsRaw,
                                           int        nWidth,
                                           int        nHeight,
                                           int        nSecsIn,
                                     const QString   &sFormat )
{
    if ((nRecordedId <= 0) &&
        (nChanId <= 0 || !recstarttsRaw.isValid()))
        throw QString("Recorded ID or Channel ID and StartTime appears invalid.");

    if (!sFormat.isEmpty()
        && !QImageWriter::supportedImageFormats().contains(sFormat.toLower().toLocal8Bit()))
    {
        throw "GetPreviewImage: Specified 'Format' is not supported.";
    }

    // ----------------------------------------------------------------------
    // Read Recording From Database
    // ----------------------------------------------------------------------

    // TODO Should use RecordingInfo
    ProgramInfo pginfo;
    if (nRecordedId > 0)
        pginfo = ProgramInfo(nRecordedId);
    else
        pginfo = ProgramInfo(nChanId, recstarttsRaw.toUTC());

    if (!pginfo.GetChanID())
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("GetPreviewImage: No recording for '%1'")
            .arg(nRecordedId));
        return QFileInfo();
    }

    if (pginfo.GetHostname().toLower() != gCoreContext->GetHostName().toLower())
    {
        QString sMsg =
            QString("GetPreviewImage: Wrong Host '%1' request from '%2'")
                          .arg( gCoreContext->GetHostName())
                          .arg( pginfo.GetHostname() );

        LOG(VB_UPNP, LOG_ERR, sMsg);

        throw HttpRedirectException( pginfo.GetHostname() );
    }

    QString sImageFormat = sFormat;
    if (sImageFormat.isEmpty())
        sImageFormat = "PNG";

    QString sFileName = GetPlaybackURL(&pginfo);

    // ----------------------------------------------------------------------
    // check to see if default preview image is already created.
    // ----------------------------------------------------------------------

    QString sPreviewFileName;

    if (nSecsIn <= 0)
    {
        nSecsIn = -1;
        sPreviewFileName = QString("%1.png").arg(sFileName);
    }
    else
    {
        sPreviewFileName = QString("%1.%2.png").arg(sFileName).arg(nSecsIn);
    }

    if (!QFile::exists( sPreviewFileName ))
    {
        // ------------------------------------------------------------------
        // Must generate Preview Image, Generate Image and save.
        // ------------------------------------------------------------------
        if (!pginfo.IsLocal() && sFileName.startsWith("/"))
            pginfo.SetPathname(sFileName);

        if (!pginfo.IsLocal())
            return QFileInfo();

        PreviewGenerator *previewgen = new PreviewGenerator( &pginfo, 
                                                             QString(), 
                                                             PreviewGenerator::kLocal);
        previewgen->SetPreviewTimeAsSeconds( nSecsIn          );
        previewgen->SetOutputFilename      ( sPreviewFileName );

        bool ok = previewgen->Run();

        previewgen->deleteLater();

        if (!ok)
            return QFileInfo();
    }

    bool bDefaultPixmap = (nWidth == 0) && (nHeight == 0);

    QString sNewFileName;

    if (bDefaultPixmap)
        sNewFileName = sPreviewFileName;
    else
    {
        sNewFileName = QString( "%1.%2.%3x%4.%5" )
                          .arg( sFileName )
                          .arg( nSecsIn   )
                          .arg( nWidth == 0 ? -1 : nWidth )
                          .arg( nHeight == 0 ? -1 : nHeight )
                          .arg( sImageFormat.toLower() );

        // ----------------------------------------------------------------------
        // check to see if scaled preview image is already created and isn't
        // out of date
        // ----------------------------------------------------------------------
        if (QFile::exists( sNewFileName ))
        {
            if (QFileInfo(sPreviewFileName).lastModified() <=
                QFileInfo(sNewFileName).lastModified())
                return QFileInfo( sNewFileName );
        }

        QImage image = QImage(sPreviewFileName);

        if (image.isNull())
            return QFileInfo();

        // We can just re-scale the default (full-size version) to avoid
        // a preview generator run
        if ( nWidth <= 0 )
            image = image.scaledToHeight(nHeight, Qt::SmoothTransformation);
        else if ( nHeight <= 0 )
            image = image.scaledToWidth(nWidth, Qt::SmoothTransformation);
        else
            image = image.scaled(nWidth, nHeight, Qt::IgnoreAspectRatio,
                                        Qt::SmoothTransformation);

        image.save(sNewFileName, sImageFormat.toUpper().toLocal8Bit());

        // Let anybody update it
        bool ret = makeFileAccessible(sNewFileName.toLocal8Bit().constData());
        if (!ret)
        {
            LOG(VB_GENERAL, LOG_ERR, "Unable to change permissions on "
                                     "preview image. Backends and frontends "
                                     "running under different users will be "
                                     "unable to access it");
        }
    }

    if (QFile::exists( sNewFileName ))
        return QFileInfo( sNewFileName );

    PreviewGenerator *previewgen = new PreviewGenerator( &pginfo,
                                                         QString(),
                                                         PreviewGenerator::kLocal);
    previewgen->SetPreviewTimeAsSeconds( nSecsIn             );
    previewgen->SetOutputFilename      ( sNewFileName        );
    previewgen->SetOutputSize          (QSize(nWidth,nHeight));

    bool ok = previewgen->Run();

    previewgen->deleteLater();

    if (!ok)
        return QFileInfo();

    return QFileInfo( sNewFileName );
}
Example #14
0
File: main.cpp Project: Suneal/qt
int runIdc(int argc, char **argv)
{
    QString error;
    QString tlbfile;
    QString idlfile;
    QString input;
    QString version = QLatin1String("1.0");
    
    int i = 1;
    while (i < argc) {
        QString p = QString::fromLocal8Bit(argv[i]).toLower();
        
        if (p == QLatin1String("/idl") || p == QLatin1String("-idl")) {
            ++i;
            if (i > argc) {
                error = QLatin1String("Missing name for interface definition file!");
                break;
            }
            idlfile = QLatin1String(argv[i]);
            idlfile = idlfile.trimmed().toLower();            
        } else if (p == QLatin1String("/version") || p == QLatin1String("-version")) {
            ++i;
            if (i > argc)
                version = QLatin1String("1.0");
            else
                version = QLatin1String(argv[i]);
        } else if (p == QLatin1String("/tlb") || p == QLatin1String("-tlb")) {
            ++i;
            if (i > argc) {
                error = QLatin1String("Missing name for type library file!");
                break;
            }
            tlbfile = QLatin1String(argv[i]);
            tlbfile = tlbfile.trimmed().toLower();            
        } else if (p == QLatin1String("/v") || p == QLatin1String("-v")) {
            fprintf(stdout, "Qt Interface Definition Compiler version 1.0\n");
            return 0;
        } else if (p == QLatin1String("/regserver") || p == QLatin1String("-regserver")) {
            if (!registerServer(input)) {
                fprintf(stderr, "Failed to register server!\n");
                return 1;
            }
            fprintf(stderr, "Server registered successfully!\n");
            return 0;
        } else if (p == QLatin1String("/unregserver") || p == QLatin1String("-unregserver")) {
            if (!unregisterServer(input)) {
                fprintf(stderr, "Failed to unregister server!\n");
                return 1;
            }
            fprintf(stderr, "Server unregistered successfully!\n");
            return 0;
        } else if (p[0] == QLatin1Char('/') || p[0] == QLatin1Char('-')) {
            error = QLatin1String("Unknown option \"") + p + QLatin1Char('\"');
            break;
        } else {
            input = QLatin1String(argv[i]);
            input = input.trimmed().toLower();            
        }
        i++;
    }
    if (!error.isEmpty()) {
        fprintf(stderr, "%s", error.toLatin1().data());
        fprintf(stderr, "\n");
        return 5;
    }
    if (input.isEmpty()) {
        fprintf(stderr, "No input file specified!\n");
        return 1;
    }
    if (input.endsWith(QLatin1String(".exe")) && tlbfile.isEmpty() && idlfile.isEmpty()) {
        fprintf(stderr, "No type output file specified!\n");
        return 2;
    }
    if (input.endsWith(QLatin1String(".dll")) && idlfile.isEmpty() && tlbfile.isEmpty()) {
        fprintf(stderr, "No interface definition file and no type library file specified!\n");
        return 3;
    }
    slashify(input);
    if (!tlbfile.isEmpty()) {
        slashify(tlbfile);
        QFile file(tlbfile);
        if (!file.open(QIODevice::ReadOnly)) {
            fprintf(stderr, "Couldn't open %s for read\n", (const char*)tlbfile.toLocal8Bit().data());
            return 4;
        }
        QByteArray data = file.readAll();
        QString error;
        bool ok = attachTypeLibrary(input, 1, data, &error);
        fprintf(stderr, "%s", error.toLatin1().data());
        fprintf(stderr, "\n");
        return ok ? 0 : 4;
    } else if (!idlfile.isEmpty()) {
        slashify(idlfile);
        idlfile = quotePath(idlfile);
        fprintf(stderr, "\n\n%s\n\n", (const char*)idlfile.toLocal8Bit().data());
        quotePath(input);
        HRESULT res = dumpIdl(input, idlfile, version);
        
        switch(res) {
        case S_OK:
            break;
        case E_FAIL:
            fprintf(stderr, "IDL generation failed trying to run program %s!\n", (const char*)input.toLocal8Bit().data());
            return res;
        case -1:
            fprintf(stderr, "Couldn't open %s for writing!\n", (const char*)idlfile.toLocal8Bit().data());
            return res;
        case 1:
            fprintf(stderr, "Malformed appID value in %s!\n", (const char*)input.toLocal8Bit().data());
            return res;
        case 2:
            fprintf(stderr, "Malformed typeLibID value in %s!\n", (const char*)input.toLocal8Bit().data());
            return res;
        case 3:
            fprintf(stderr, "Class has no metaobject information (error in %s)!\n", (const char*)input.toLocal8Bit().data());
            return res;
        case 4:
            fprintf(stderr, "Malformed classID value in %s!\n", (const char*)input.toLocal8Bit().data());
            return res;
        case 5:
            fprintf(stderr, "Malformed interfaceID value in %s!\n", (const char*)input.toLocal8Bit().data());
            return res;
        case 6:
            fprintf(stderr, "Malformed eventsID value in %s!\n", (const char*)input.toLocal8Bit().data());
            return res;
            
        default:
            fprintf(stderr, "Unknown error writing IDL from %s\n", (const char*)input.toLocal8Bit().data());
            return 7;
        }
    }
    return 0;
}
Example #15
0
int myDBConn::connectToDB(QString path)
{
    QDir dir;
    dir.setPath(path);
    if (!dir.exists())
    {
        gbtLog(tr("The target path does not exists"));
        return 0;
    }

    QString npath;
    npath = path;
#ifdef Q_OS_WIN
    npath = npath.replace("\\","/");
#endif

    if (!m_connected)
    {

        QString dbParam;
        dbParam = "--datadir="+npath;

        QString kbSize;
        kbSize = "--key_buffer_size="+QString::number(getBufferSize());


        QByteArray ba = dbParam.toLocal8Bit();
        char *c_str2 = ba.data();

        QByteArray ba2 = kbSize.toLocal8Bit();
        char *c_str3 = ba2.data();


        QString baseParam;
        baseParam = "--basedir="+npath;
        QByteArray ba3 = baseParam.toLocal8Bit();
        char *c_str4 = ba3.data();



        static char *server_options[] = \
        { (char *)"mysql_test",
          c_str2,

          c_str4,

          (char *)"--default-storage-engine=MyISAM",
          (char *)"--loose-innodb=0",
          (char *)"--skip-grant-tables=1",
          (char *)"--myisam-recover=FORCE",
          c_str3,
          (char *)"--character-set-server=utf8",
          (char *)"--collation-server=utf8_bin",
          NULL };

        int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;


        mysql_library_init(num_elements, server_options, NULL);
        m_mysql = mysql_init(NULL);

        int valopt;
        valopt = 1;
        if (mysql_options(m_mysql,MYSQL_OPT_LOCAL_INFILE,(void *)&valopt))
            gbtLog("Error setting option");

        mysql_real_connect(m_mysql, NULL,NULL,NULL, "database1", 0,NULL,0);

        m_drv = new GOBLETDriver(m_mysql);

        if (m_drv)
        {
            m_connected = true;
            return 1;
        }
    }
    return 0;
}
Example #16
0
void ConsolePrinter::print(vec3 v, QString label = "")
{
	cout << label.toLocal8Bit().constData() << "("<< v.x << "," << v.y << "," << v.z << ")" << endl;
}
Example #17
0
void ChannelData::handleChannels(int id, ChannelInfoList *chanlist)
{
    if (m_guideDataOnly)
    {
        LOG(VB_GENERAL, LOG_NOTICE, "Skipping Channel Updates");
        return;
    }

    ChannelList existingChannels = channelList(id);
    QString fileprefix = SetupIconCacheDirectory();

    QDir::setCurrent(fileprefix);

    fileprefix += "/";

    bool insertChan = insert_chan(id);  // unscannable source

    ChannelInfoList::iterator i = chanlist->begin();
    for (; i != chanlist->end(); ++i)
    {
        if ((*i).xmltvid.isEmpty())
            continue;

        QString localfile;

        if (!(*i).icon.isEmpty())
        {
            QDir remotefile = QDir((*i).icon);
            QString filename = remotefile.dirName();

            localfile = fileprefix + filename;
            QFile actualfile(localfile);
            if (!actualfile.exists() &&
                !GetMythDownloadManager()->download((*i).icon, localfile))
            {
                LOG(VB_GENERAL, LOG_ERR,
                    QString("Failed to fetch icon from '%1'")
                        .arg((*i).icon));
            }

            localfile = filename;
        }

        MSqlQuery query(MSqlQuery::InitCon());

        if (!(*i).old_xmltvid.isEmpty())
        {
            query.prepare(
                "SELECT xmltvid "
                "FROM channel "
                "WHERE xmltvid = :XMLTVID");
            query.bindValue(":XMLTVID", (*i).old_xmltvid);

            if (!query.exec())
            {
                MythDB::DBError("xmltvid conversion 1", query);
            }
            else if (query.next())
            {
                LOG(VB_GENERAL, LOG_INFO,
                    QString("Converting old xmltvid (%1) to new (%2)")
                        .arg((*i).old_xmltvid).arg((*i).xmltvid));

                query.prepare("UPDATE channel "
                              "SET xmltvid = :NEWXMLTVID"
                              "WHERE xmltvid = :OLDXMLTVID");
                query.bindValue(":NEWXMLTVID", (*i).xmltvid);
                query.bindValue(":OLDXMLTVID", (*i).old_xmltvid);

                if (!query.exec())
                {
                    MythDB::DBError("xmltvid conversion 2", query);
                }
            }
        }

        ChannelInfo dbChan = FindMatchingChannel(*i, existingChannels);
        if (dbChan.chanid > 0) // Channel exists, updating
        {
            LOG(VB_XMLTV, LOG_NOTICE,
                    QString("Match found for xmltvid %1 to channel %2 (%3)")
                        .arg((*i).xmltvid).arg(dbChan.name).arg(dbChan.chanid));
            if (m_interactive)
            {

                cout << "### " << endl;
                cout << "### Existing channel found" << endl;
                cout << "### " << endl;
                cout << "### xmltvid  = "
                     << (*i).xmltvid.toLocal8Bit().constData()        << endl;
                cout << "### chanid   = "
                     << dbChan.chanid                                 << endl;
                cout << "### name     = "
                     << dbChan.name.toLocal8Bit().constData()         << endl;
                cout << "### callsign = "
                     << dbChan.callsign.toLocal8Bit().constData()     << endl;
                cout << "### channum  = "
                     << dbChan.channum.toLocal8Bit().constData()      << endl;
                if (m_channelPreset)
                {
                    cout << "### freqid   = "
                         << dbChan.freqid.toLocal8Bit().constData()   << endl;
                }
                cout << "### finetune = "
                     << dbChan.finetune                               << endl;
                cout << "### tvformat = "
                     << dbChan.tvformat.toLocal8Bit().constData()     << endl;
                cout << "### icon     = "
                     << dbChan.icon.toLocal8Bit().constData()         << endl;
                cout << "### " << endl;

                // The only thing the xmltv data supplies here is the icon
                (*i).name = dbChan.name;
                (*i).callsign = dbChan.callsign;
                (*i).channum  = dbChan.channum;
                (*i).finetune = dbChan.finetune;
                (*i).freqid = dbChan.freqid;
                (*i).tvformat = dbChan.tvformat;

                promptForChannelUpdates(i, dbChan.chanid);

                if ((*i).callsign.isEmpty())
                    (*i).callsign = dbChan.name;

                if (dbChan.name     != (*i).name ||
                    dbChan.callsign != (*i).callsign ||
                    dbChan.channum  != (*i).channum ||
                    dbChan.finetune != (*i).finetune ||
                    dbChan.freqid   != (*i).freqid ||
                    dbChan.icon     != localfile ||
                    dbChan.tvformat != (*i).tvformat)
                {
                    MSqlQuery subquery(MSqlQuery::InitCon());
                    subquery.prepare("UPDATE channel SET chanid = :CHANID, "
                                     "name = :NAME, callsign = :CALLSIGN, "
                                     "channum = :CHANNUM, finetune = :FINE, "
                                     "icon = :ICON, freqid = :FREQID, "
                                     "tvformat = :TVFORMAT "
                                     " WHERE xmltvid = :XMLTVID "
                                     "AND sourceid = :SOURCEID;");
                    subquery.bindValue(":CHANID", dbChan.chanid);
                    subquery.bindValue(":NAME", (*i).name);
                    subquery.bindValue(":CALLSIGN", (*i).callsign);
                    subquery.bindValue(":CHANNUM", (*i).channum);
                    subquery.bindValue(":FINE", (*i).finetune);
                    subquery.bindValue(":ICON", localfile);
                    subquery.bindValue(":FREQID", (*i).freqid);
                    subquery.bindValue(":TVFORMAT", (*i).tvformat);
                    subquery.bindValue(":XMLTVID", (*i).xmltvid);
                    subquery.bindValue(":SOURCEID", id);

                    if (!subquery.exec())
                    {
                        MythDB::DBError("update failed", subquery);
                    }
                    else
                    {
                        cout << "### " << endl;
                        cout << "### Change performed" << endl;
                        cout << "### " << endl;
                    }
                }
                else
                {
                    cout << "### " << endl;
                    cout << "### Nothing changed" << endl;
                    cout << "### " << endl;
                }
            }
            else if ((dbChan.icon != localfile) ||
                     (dbChan.xmltvid != (*i).xmltvid))
            {
                LOG(VB_XMLTV, LOG_NOTICE, QString("Updating channel %1 (%2)")
                                        .arg(dbChan.name).arg(dbChan.chanid));

                if (localfile.isEmpty())
                    localfile = dbChan.icon;

                if (dbChan.xmltvid != (*i).xmltvid)
                {
                    MSqlQuery subquery(MSqlQuery::InitCon());

                    subquery.prepare("UPDATE channel SET icon = :ICON "
                            ", xmltvid:= :XMLTVID WHERE "
                                     "chanid = :CHANID;");
                    subquery.bindValue(":ICON", localfile);
                    subquery.bindValue(":XMLTVID", (*i).xmltvid);
                    subquery.bindValue(":CHANID", dbChan.chanid);

                    if (!subquery.exec())
                        MythDB::DBError("Channel icon change", subquery);
                }
                else
                {
                    MSqlQuery subquery(MSqlQuery::InitCon());
                    subquery.prepare("UPDATE channel SET icon = :ICON WHERE "
                                     "chanid = :CHANID;");
                    subquery.bindValue(":ICON", localfile);
                    subquery.bindValue(":CHANID", dbChan.chanid);

                    if (!subquery.exec())
                        MythDB::DBError("Channel icon change", subquery);
                }

            }
        }
        else if (insertChan) // Only insert channels for non-scannable sources
        {
            int major, minor = 0;
            long long freq = 0;
            get_atsc_stuff((*i).channum, id, (*i).freqid.toInt(), major, minor, freq);

            if (m_interactive && ((minor == 0) || (freq > 0)))
            {
                cout << "### " << endl;
                cout << "### New channel found" << endl;
                cout << "### " << endl;
                cout << "### name     = "
                     << (*i).name.toLocal8Bit().constData()     << endl;
                cout << "### callsign = "
                     << (*i).callsign.toLocal8Bit().constData() << endl;
                cout << "### channum  = "
                     << (*i).channum.toLocal8Bit().constData()  << endl;
                if (m_channelPreset)
                {
                    cout << "### freqid   = "
                         << (*i).freqid.toLocal8Bit().constData() << endl;
                }
                cout << "### finetune = "
                     << (*i).finetune                           << endl;
                cout << "### tvformat = "
                     << (*i).tvformat.toLocal8Bit().constData() << endl;
                cout << "### icon     = "
                     << localfile.toLocal8Bit().constData()     << endl;
                cout << "### " << endl;

                uint chanid = promptForChannelUpdates(i,0);

                if ((*i).callsign.isEmpty())
                    (*i).callsign = QString::number(chanid);

                int mplexid = 0;
                if ((chanid > 0) && (minor > 0))
                    mplexid = ChannelUtil::CreateMultiplex(id,   "atsc",
                                                           freq, "8vsb");

                if (((mplexid > 0) || ((minor == 0) && (chanid > 0))) &&
                    ChannelUtil::CreateChannel(
                        mplexid,          id,               chanid,
                        (*i).callsign,    (*i).name,        (*i).channum,
                        0 /*service id*/, major,            minor,
                        false /*use on air guide*/, false /*hidden*/,
                        false /*hidden in guide*/,
                        (*i).freqid,      localfile,        (*i).tvformat,
                        (*i).xmltvid))
                {
                    cout << "### " << endl;
                    cout << "### Channel inserted" << endl;
                    cout << "### " << endl;
                }
                else
                {
                    cout << "### " << endl;
                    cout << "### Channel skipped" << endl;
                    cout << "### " << endl;
                }
            }
            else if ((minor == 0) || (freq > 0))
            {
                // We only do this if we are not asked to skip it with the
                // --update-guide-only (formerly --update) flag.
                int mplexid = 0, chanid = 0;
                if (minor > 0)
                {
                    mplexid = ChannelUtil::CreateMultiplex(
                        id, "atsc", freq, "8vsb");
                }

                if ((mplexid > 0) || (minor == 0))
                    chanid = ChannelUtil::CreateChanID(id, (*i).channum);

                if ((*i).callsign.isEmpty())
                {
                    QStringList words = (*i).name.simplified().toUpper()
                        .split(" ");
                    QString callsign = "";
                    QString w1 = words.size() > 0 ? words[0] : QString();
                    QString w2 = words.size() > 1 ? words[1] : QString();
                    if (w1.isEmpty())
                        callsign = QString::number(chanid);
                    else if (w2.isEmpty())
                        callsign = words[0].left(5);
                    else
                    {
                        callsign = w1.left(w2.length() == 1 ? 4:3);
                        callsign += w2.left(5 - callsign.length());
                    }
                    (*i).callsign = callsign;
                }

                if (chanid > 0)
                {
                    QString cstr = QString((*i).channum);
                    if(m_channelPreset && cstr.isEmpty())
                        cstr = QString::number(chanid % 1000);

                    bool retval = ChannelUtil::CreateChannel(
                                                     mplexid, id,
                                                     chanid,
                                                     (*i).callsign,
                                                     (*i).name, cstr,
                                                     0 /*service id*/,
                                                     major, minor,
                                                     false /*use on air guide*/,
                                                     false /*hidden*/,
                                                     false /*hidden in guide*/,
                                                     (*i).freqid,
                                                     localfile,
                                                     (*i).tvformat,
                                                     (*i).xmltvid
                                                            );
                    if (!retval)
                        cout << "Channel " << chanid << " creation failed"
                             << endl;
                }
            }
        }
    }
}
Example #18
0
void ConsolePrinter::print(QString qstr, char* label = "")
{
	cout << label << qstr.toLocal8Bit().constData() << endl;
}
Example #19
0
long GalleryUtil::GetNaturalRotation(const QString &filePathString)
{
    long rotateAngle = 0;
#ifdef EXIF_SUPPORT
    QByteArray filePathBA = filePathString.toLocal8Bit();
    const char *filePath = filePathBA.constData();

    try
    {
        char *exifvalue = new char[1024];
        ExifData *data = exif_data_new_from_file (filePath);
        if (data)
        {
            for (int i = 0; i < EXIF_IFD_COUNT; i++)
            {
                ExifEntry *entry = exif_content_get_entry (data->ifd[i],
                                                        EXIF_TAG_ORIENTATION);
                ExifByteOrder byteorder = exif_data_get_byte_order (data);

                if (entry)
                {
                    ExifShort v_short = exif_get_short (entry->data, byteorder);
                    VERBOSE(VB_GENERAL|VB_EXTRA, QString("Exif entry=%1").arg(v_short));
                    /* See http://sylvana.net/jpegcrop/exif_orientation.html*/
                    if (v_short == 8)
                    {
                        rotateAngle = -90;
                    }
                    else if (v_short == 6)
                    {
                        rotateAngle = 90;
                    }
                    break;
                }
            }
            exif_data_free(data);
        }
        else
        {
            VERBOSE(VB_FILE, LOC_ERR +
                    QString("Could not load exif data from '%1'")
                    .arg(filePath));
        }
        
        delete [] exifvalue;
        
#if 0
        Exiv2::ExifData exifData;
        int rc = exifData.read(filePath);
        if (!rc)
        {
            Exiv2::ExifKey key = Exiv2::ExifKey("Exif.Image.Orientation");
            Exiv2::ExifData::iterator pos = exifData.findKey(key);
            if (pos != exifData.end())
            {
                long orientation = pos->toLong();
                switch (orientation)
                {
                    case 6:
                        rotateAngle = 90;
                        break;
                    case 8:
                        rotateAngle = -90;
                        break;
                    default:
                        rotateAngle = 0;
                        break;
                }
            }
        }
#endif
    }
    catch (...)
    {
        VERBOSE(VB_IMPORTANT, LOC_ERR +
                QString("Failed to extract EXIF headers from '%1'")
                .arg(filePathString));
    }

#else
    // Shut the compiler up about the unused argument
    (void)filePathString;
#endif // EXIF_SUPPORT
    return rotateAngle;
}
Example #20
0
void ConsolePrinter::print(QString qstr)
{
	cout << qstr.toLocal8Bit().constData() << endl;

}
Example #21
0
void logStart(QString logfile, int progress, int quiet, int facility,
              LogLevel_t level, bool dblog, bool propagate)
{
    LoggerBase *logger;

    {
        QMutexLocker qLock(&logQueueMutex);
        if (!logThread)
            logThread = new LoggerThread();
    }

    if (logThread->isRunning())
        return;

    logLevel = level;
    LOG(VB_GENERAL, LOG_NOTICE, QString("Setting Log Level to LOG_%1")
             .arg(logLevelGetName(logLevel).toUpper()));

    logPropagateOpts.propagate = propagate;
    logPropagateOpts.quiet = quiet;
    logPropagateOpts.facility = facility;
    logPropagateOpts.dblog = dblog;

    if (propagate)
    {
        QFileInfo finfo(logfile);
        QString path = finfo.path();
        logPropagateOpts.path = path;
    }

    logPropagateCalc();

    /* log to the console */
    logger = new FileLogger((char *)"-", progress, quiet);

    /* Debug logfile */
    if( !logfile.isEmpty() )
        logger = new FileLogger((char *)logfile.toLocal8Bit().constData(),
                                false, false);

#ifndef _WIN32
    /* Syslog */
    if( facility == -1 )
        LOG(VB_GENERAL, LOG_CRIT,
                 "Syslogging facility unknown, disabling syslog output");
    else if( facility >= 0 )
        logger = new SyslogLogger(facility);
#endif

    /* Database */
    if( dblog )
        logger = new DatabaseLogger((char *)"logging");

#ifndef _WIN32
    /* Setup SIGHUP */
    LOG(VB_GENERAL, LOG_NOTICE, "Setting up SIGHUP handler");
    struct sigaction sa;
    sa.sa_sigaction = logSighup;
    sigemptyset( &sa.sa_mask );
    sa.sa_flags = SA_RESTART | SA_SIGINFO;
    sigaction( SIGHUP, &sa, NULL );
#endif

    (void)logger;

    logThread->start();
}
Example #22
0
KUserGroup::KUserGroup(const QString& _name)
    : d(new Private(_name.toLocal8Bit().data()))
{
}
Example #23
0
void message(const QString msg)
{
	fprintf(stderr, "%s\n", msg.toLocal8Bit().constData());
}
Example #24
0
KUser::KUser(const QString& name)
    : d(new Private( name.toLocal8Bit().data() ))
{
}
void LocationListModel::setPattern(const QString& pattern)
{
  beginResetModel();

  for (QList<Location*>::iterator location=locations.begin();
       location!=locations.end();
       ++location) {
      delete *location;
  }

  locations.clear();

  osmscout::LocationSearchResult searchResult;

  std::string osmPattern=pattern.toUtf8().constData();

  osmscout::GeoCoord coord;

  if (osmscout::GeoCoord::Parse(osmPattern,
                                coord)) {
      QString name=QString::fromLocal8Bit(coord.GetDisplayText().c_str());
      QString label=name;

      Location *location=new Location(name,
                                      label,
                                      coord);
      locations.append(location);
  }

  std::cout << "Searching for '" << osmPattern << "'" << std::endl;

  DBThread::GetInstance()->SearchForLocations(osmPattern,
                                              50,
                                              searchResult);

  std::map<osmscout::FileOffset,osmscout::AdminRegionRef> adminRegionMap;

  for (std::list<osmscout::LocationSearchResult::Entry>::const_iterator entry=searchResult.results.begin();
      entry!=searchResult.results.end();
      ++entry) {
      Location *location=NULL;

    if (entry->adminRegion &&
        entry->location &&
        entry->address) {
      QString adminRegion=GetAdminRegionLabel(adminRegionMap,
                                              entry->adminRegion);
      QString loc=QString::fromUtf8(entry->location->name.c_str());
      QString address=QString::fromUtf8(entry->address->name.c_str());
      QString name;
      QString label;

      name+=loc;
      name+=" ";
      name+=address;
      name+=" ";
      name+=adminRegion;

      label+="<b>";
      label+=loc;
      label+=" ";
      label+=address;
      label+="</b>";
      label+=" ";
      label+=adminRegion;
      label+="<br/>";
      label+="<i>";
      label+=GetObjectTypLabel(entry->address->object);
      label+="</i>";

      std::cout << "- " << name.toLocal8Bit().data() << std::endl;

      location=new Location(Location::typeObject,
                            name,
                            label);
      location->addReference(entry->address->object);
    }
    else if (entry->adminRegion &&
             entry->location) {
      QString adminRegion=GetAdminRegionLabel(adminRegionMap,
                                              entry->adminRegion);
      QString loc=QString::fromUtf8(entry->location->name.c_str());
      QString name;
      QString label;

      name+=loc;
      name+=" ";
      name+=adminRegion;

      label+="<b>";
      label+=loc;
      label+="</b>";
      label+=" ";
      label+=adminRegion;

      label+="<br/>";
      label+="<i>";
      label+=GetObjectTypLabel(entry->location->objects.front());
      label+="</i>";

      std::cout << "- " << name.toLocal8Bit().data() << std::endl;

      location=new Location(Location::typeObject,
                            name,
                            label);

      for (std::vector<osmscout::ObjectFileRef>::const_iterator object=entry->location->objects.begin();
          object!=entry->location->objects.end();
          ++object) {
          location->addReference(*object);
      }
    }
    else if (entry->adminRegion &&
             entry->poi) {
      QString adminRegion=GetAdminRegionLabel(adminRegionMap,
                                              entry->adminRegion);
      QString poi=QString::fromUtf8(entry->poi->name.c_str());
      QString name;
      QString label;

      name+=poi;

      name+=" ";
      name+=adminRegion;

      label+="<b>";
      label+=poi;
      label+="</b>";

      label+=" ";
      label+=adminRegion;

      label+="<br/>";
      label+="<i>";
      label+=GetObjectTypLabel(entry->poi->object);
      label+="</i>";

      std::cout << "- " << name.toLocal8Bit().data() << std::endl;

      location=new Location(Location::typeObject,
                            name,
                            label);
      location->addReference(entry->poi->object);
    }
    else if (entry->adminRegion) {
        QString adminRegion=GetAdminRegionLabel(adminRegionMap,
                                                entry->adminRegion);
        QString name;
        QString label;

        name+=adminRegion;

        label+="<b>";
        label+=adminRegion;
        label+="</b>";
        label+="<br/>";
        label+="<i>";
        if (entry->adminRegion->aliasObject.Valid()) {
            label+=GetObjectTypLabel(entry->adminRegion->aliasObject);
        }
        else {
            label+=GetObjectTypLabel(entry->adminRegion->object);
        }
        label+="</i>";

        location=new Location(Location::typeObject,
                              name,
                              label);

        std::cout << "- " << name.toLocal8Bit().data() << std::endl;

        if (entry->adminRegion->aliasObject.Valid()) {
            location->addReference(entry->adminRegion->aliasObject);
        }
        else {
            location->addReference(entry->adminRegion->object);
        }
    }

    if (location!=NULL) {
        locations.append(location);
    }
  }

  endResetModel();
}
Example #26
0
void autofix(QString originalFileName, int numFiles, QSize size)
{
    std::cout << "Autofixing " << numFiles << size.width() << "x" << size.height()
              << " thumbnails of " << originalFileName.toLocal8Bit().constData() << "\n";

    QEventLoop loop;
    QTime time;

    Quill::setTemporaryFilePath(QDir::homePath() + Strings::testsTempDir);
    Quill::setPreviewSize(0, size);

    QString fileName[numFiles];
    QuillFile *quillFile[numFiles];

    for (int i=0; i<numFiles; i++) {
        {   // Needed for the life of the QTemporaryFile
            QTemporaryFile file;
            file.setFileTemplate(QDir::homePath() + Strings::testsTempFilePattern);
            file.open();
            fileName[i] = file.fileName();
            file.close();
        }
        QFile::remove(fileName[i]);
        QFile::copy(originalFileName, fileName[i]);
    }

    time.start();

    for (int i=0; i<numFiles; i++) {
        quillFile[i] = new QuillFile(fileName[i], Strings::jpegMimeType);
        QObject::connect(quillFile[i], SIGNAL(imageAvailable(const QuillImageList)),
                         &loop, SLOT(quit()));
    }

    int initTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        quillFile[i]->setDisplayLevel(0);

    int displayLevelTime = time.elapsed();

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int prepareTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are loaded!\n";
            return;
        }

    time.restart();

    for (int i=0; i<numFiles; i++) {
        QuillImageFilter *filter =
            QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_AutoLevels);
        quillFile[i]->runFilter(filter);
    }

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int finalTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are edited!\n";
            return;
        }

    std::cout << "Initialize " << numFiles << " QuillFiles: "
             << initTime << "ms" << "\n";

    std::cout << "Set display levels of " << numFiles << " QuillFiles: "
             << displayLevelTime - initTime << "ms" << "\n";

    std::cout << "Total prepare " << numFiles << " QuillFiles: "
             << prepareTime << "ms" << "\n";

    std::cout << "Use case edit response for " << numFiles << " QuillFiles: "
             << finalTime << "ms" << "\n";

    for (int i=0; i<numFiles; i++) {
        delete quillFile[i];
        QFile::remove(fileName[i]);
    }
}
Example #27
0
void QTorrentHandle::set_tracker_login(const QString& username, const QString& password) const {
  torrent_handle::set_tracker_login(std::string(username.toLocal8Bit().constData()), std::string(password.toLocal8Bit().constData()));
}
Example #28
0
void gbtLog(QString message)
{
    QString temp;
    temp = message + "\n";
    printf(temp.toLocal8Bit().data());
}
Example #29
0
QByteArray zipobject::getCharPtr(const QString& string){
    return string.toLocal8Bit();
}
Example #30
0
void QgsGrassNewMapset::loadRegions()
{

  QString path = QgsApplication::pkgDataPath() + "/grass/locations.gml";
  QgsDebugMsg( QString( "load:%1" ).arg( path.toLocal8Bit().constData() ) );

  QFile file( path );

  if ( !file.exists() )
  {
    QgsGrass::warning( tr( "Regions file (%1) not found." ).arg( path ) );
    return;
  }
  if ( ! file.open( QIODevice::ReadOnly ) )
  {
    QgsGrass::warning( tr( "Cannot open locations file (%1)" ).arg( path ) );
    return;
  }

  QDomDocument doc( QStringLiteral( "gml:FeatureCollection" ) );
  QString err;
  int line, column;

  if ( !doc.setContent( &file,  &err, &line, &column ) )
  {
    QString errmsg = tr( "Cannot read locations file (%1):" ).arg( path )
                     + tr( "\n%1\nat line %2 column %3" ).arg( err ).arg( line ).arg( column );
    QgsDebugMsg( errmsg );
    QgsGrass::warning( errmsg );
    file.close();
    return;
  }

  QDomElement docElem = doc.documentElement();
  QDomNodeList nodes = docElem.elementsByTagName( QStringLiteral( "gml:featureMember" ) );

  for ( int i = 0; i < nodes.count(); i++ )
  {
    QDomNode node = nodes.item( i );

    if ( node.isNull() )
    {
      continue;
    }

    QDomElement elem = node.toElement();
    QDomNodeList nameNodes = elem.elementsByTagName( QStringLiteral( "gml:name" ) );
    if ( nameNodes.count() == 0 )
      continue;
    if ( nameNodes.item( 0 ).isNull() )
      continue;

    QDomElement nameElem = nameNodes.item( 0 ).toElement();
    if ( nameElem.text().isNull() )
      continue;

    QDomNodeList envNodes = elem.elementsByTagName( QStringLiteral( "gml:Envelope" ) );
    if ( envNodes.count() == 0 )
      continue;
    if ( envNodes.item( 0 ).isNull() )
      continue;
    QDomElement envElem = envNodes.item( 0 ).toElement();

    QDomNodeList coorNodes = envElem.elementsByTagName( QStringLiteral( "gml:coordinates" ) );
    if ( coorNodes.count() == 0 )
      continue;
    if ( coorNodes.item( 0 ).isNull() )
      continue;
    QDomElement coorElem = coorNodes.item( 0 ).toElement();
    if ( coorElem.text().isNull() )
      continue;

    QStringList coor = coorElem.text().split( QStringLiteral( " " ), QString::SkipEmptyParts );
    if ( coor.size() != 2 )
    {
      QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
      continue;
    }

    QStringList ll = coor[0].split( QStringLiteral( "," ), QString::SkipEmptyParts );
    QStringList ur = coor[1].split( QStringLiteral( "," ), QString::SkipEmptyParts );
    if ( ll.size() != 2 || ur.size() != 2 )
    {
      QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
      continue;
    }

    // Add region
    mRegionsComboBox->addItem( nameElem.text() );

    QgsPointXY llp( ll[0].toDouble(), ll[1].toDouble() );
    mRegionsPoints.push_back( llp );
    QgsPointXY urp( ur[0].toDouble(), ur[1].toDouble() );
    mRegionsPoints.push_back( urp );
  }
  mRegionsComboBox->setCurrentIndex( -1 );

  file.close();
}