コード例 #1
0
ファイル: history.cpp プロジェクト: maxxant/qt
void HistoryManager::save()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("history"));
    settings.setValue(QLatin1String("historyLimit"), m_historyLimit);

    bool saveAll = m_lastSavedUrl.isEmpty();
    int first = m_history.count() - 1;
    if (!saveAll) {
        // find the first one to save
        for (int i = 0; i < m_history.count(); ++i) {
            if (m_history.at(i).url == m_lastSavedUrl) {
                first = i - 1;
                break;
            }
        }
    }
    if (first == m_history.count() - 1)
        saveAll = true;

    QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
    if (directory.isEmpty())
        directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
    if (!QFile::exists(directory)) {
        QDir dir;
        dir.mkpath(directory);
    }

    QFile historyFile(directory + QLatin1String("/history"));
    // When saving everything use a temporary file to prevent possible data loss.
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    bool open = false;
    if (saveAll) {
        open = tempFile.open();
    } else {
        open = historyFile.open(QFile::Append);
    }

    if (!open) {
        qWarning() << "Unable to open history file for saving"
                   << (saveAll ? tempFile.fileName() : historyFile.fileName());
        return;
    }

    QDataStream out(saveAll ? &tempFile : &historyFile);
    for (int i = first; i >= 0; --i) {
        QByteArray data;
        QDataStream stream(&data, QIODevice::WriteOnly);
        HistoryItem item = m_history.at(i);
        stream << HISTORY_VERSION << item.url << item.dateTime << item.title;
        out << data;
    }
    tempFile.close();

    if (saveAll) {
        if (historyFile.exists() && !historyFile.remove())
            qWarning() << "History: error removing old history." << historyFile.errorString();
        if (!tempFile.rename(historyFile.fileName()))
            qWarning() << "History: error moving new history over old." << tempFile.errorString() << historyFile.fileName();
    }
    m_lastSavedUrl = m_history.value(0).url;
}
コード例 #2
0
ファイル: WriteThread.cpp プロジェクト: NotDead/Ultracopier
bool WriteThread::internalOpen()
{
    //do a bug
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] internalOpen destination: ")+file.fileName());
    if(stopIt)
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
        emit closed();
        return false;
    }
    if(file.isOpen())
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] already open! destination: ")+file.fileName());
        return false;
    }
    if(file.fileName().isEmpty())
    {
        errorString_internal=tr("Path resolution error (Empty path)");
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Unable to open: %1, error: %2").arg(file.fileName()).arg(errorString_internal));
        emit error();
        return false;
    }
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] before the mutex"));
    //set to LISTBLOCKSIZE
    if(sequential)
    {
        while(writeFull.available()<1)
            writeFull.release();
        if(writeFull.available()>1)
            writeFull.acquire(writeFull.available()-1);
    }
    else
    {
        while(writeFull.available()<numberOfBlock)
            writeFull.release();
        if(writeFull.available()>numberOfBlock)
            writeFull.acquire(writeFull.available()-numberOfBlock);
    }
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] after the mutex"));
    stopIt=false;
    endDetected=false;
    #ifdef ULTRACOPIER_PLUGIN_DEBUG
    stat=InodeOperation;
    #endif
    //mkpath check if exists and return true if already exists
    QFileInfo destinationInfo(file);
    QDir destinationFolder;
    {
        mkpathTransfer->acquire();
        if(!destinationFolder.exists(destinationInfo.absolutePath()))
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Try create the path: %1")
                         .arg(destinationInfo.absolutePath()));
            if(!destinationFolder.mkpath(destinationInfo.absolutePath()))
            {
                if(!destinationFolder.exists(destinationInfo.absolutePath()))
                {
                    /// \todo do real folder error here
                    errorString_internal="mkpath error on destination";
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Unable create the folder: %1, error: %2")
                                 .arg(destinationInfo.absolutePath())
                                 .arg(errorString_internal));
                    emit error();
                    #ifdef ULTRACOPIER_PLUGIN_DEBUG
                    stat=Idle;
                    #endif
                    mkpathTransfer->release();
                    return false;
                }
            }
        }
        mkpathTransfer->release();
    }
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] after the mkpath"));
    if(stopIt)
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
        emit closed();
        return false;
    }
    //try open it
    QIODevice::OpenMode flags=QIODevice::ReadWrite;
    if(!buffer)
        flags|=QIODevice::Unbuffered;
    {
        QMutexLocker lock_mutex(&writeFileListMutex);
        if(writeFileList.count(file.fileName(),this)==0)
        {
            writeFileList.insert(file.fileName(),this);
            if(writeFileList.count(file.fileName())>1)
            {
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] in waiting because same file is found"));
                return false;
            }
        }
    }
    bool fileWasExists=file.exists();
    if(file.open(flags))
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] after the open"));
        {
            QMutexLocker lock_mutex(&accessList);
            if(!theBlockList.isEmpty())
            {
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("General file corruption detected"));
                stopIt=true;
                file.close();
                resumeNotStarted();
                file.setFileName(QStringLiteral(""));
                return false;
            }
        }
        pauseMutex.tryAcquire(pauseMutex.available());
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] after the pause mutex"));
        if(stopIt)
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
            file.close();
            resumeNotStarted();
            file.setFileName(QStringLiteral(""));
            emit closed();
            return false;
        }
        if(!file.seek(0))
        {
            file.close();
            resumeNotStarted();
            file.setFileName(QStringLiteral(""));
            errorString_internal=file.errorString();
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Unable to seek after open: %1, error: %2").arg(file.fileName()).arg(errorString_internal));
            emit error();
            #ifdef ULTRACOPIER_PLUGIN_DEBUG
            stat=Idle;
            #endif
            return false;
        }
        if(stopIt)
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
            file.close();
            resumeNotStarted();
            file.setFileName(QStringLiteral(""));
            emit closed();
            return false;
        }
        if(!file.resize(startSize))
        {
            file.close();
            resumeNotStarted();
            file.setFileName(QStringLiteral(""));
            errorString_internal=file.errorString();
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Unable to resize to %1 after open: %2, error: %3").arg(startSize).arg(file.fileName()).arg(errorString_internal));
            emit error();
            #ifdef ULTRACOPIER_PLUGIN_DEBUG
            stat=Idle;
            #endif
            return false;
        }
        if(stopIt)
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
            file.close();
            resumeNotStarted();
            file.setFileName(QStringLiteral(""));
            emit closed();
            return false;
        }
        isOpen.acquire();
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] emit opened()"));
        emit opened();
        #ifdef ULTRACOPIER_PLUGIN_DEBUG
        stat=Idle;
        #endif
        needRemoveTheFile=false;
        postOperationRequested=false;
        return true;
    }
    else
    {
        if(!fileWasExists && file.exists())
            if(!file.remove())
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] file created but can't be removed"));
        if(stopIt)
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
            resumeNotStarted();
            file.setFileName(QStringLiteral(""));
            emit closed();
            return false;
        }
        errorString_internal=file.errorString();
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Unable to open: %1, error: %2").arg(file.fileName()).arg(errorString_internal));
        emit error();
        #ifdef ULTRACOPIER_PLUGIN_DEBUG
        stat=Idle;
        #endif
        return false;
    }
}
コード例 #3
0
ファイル: qfileinfo.cpp プロジェクト: RSATom/Qt
/*!
    \overload

    Sets the file that the QFileInfo provides information about to \a
    file in directory \a dir.

    If \a file includes a relative path, the QFileInfo will also
    have a relative path.

    \sa isRelative()
*/
void QFileInfo::setFile(const QDir &dir, const QString &file)
{
    setFile(dir.filePath(file));
}
コード例 #4
0
ファイル: settingsdialog.cpp プロジェクト: singit/moonplayer
//Init settings
void initSettings()
{
    //open file
#ifdef Q_OS_WIN
    QSettings settings("HKEY_CURRENT_USER\\Software\\moonplayer", QSettings::NativeFormat);
#else
    QDir dir = QDir::home();
    if (!dir.cd(".moonplayer"))
    {
        dir.mkdir(".moonplayer");
        dir.cd(".moonplayer");
    }
    if (!dir.exists("plugins"))
        dir.mkdir("plugins");
    if (!dir.exists("skins"))
        dir.mkdir("skins");

    QSettings settings(QDir::homePath() + "/.config/moonplayer.ini", QSettings::IniFormat);
#endif

    //read settings
#ifdef Q_OS_WIN
    if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)
        vout = settings.value("Video/out", "direct3d").toString();
    else
        vout = settings.value("Video/out", "directx").toString();
#else
    vout = settings.value("Video/out", "xv").toString();
    path = "/usr/share/moonplayer";
#endif
    framedrop = settings.value("Video/framedrop", true).toBool();
    doubleBuffer = settings.value("Video/double", true).toBool();
    fixLastFrame = settings.value("Video/fixlastframe", false).toBool();
    ffodivxvdpau = settings.value("Video/ffodivxvdpau", true).toBool();
    aout = settings.value("Audio/out", "auto").toString();
    softvol = settings.value("Audio/softvol", false).toBool();
    volume = settings.value("Audio/volume", 10).toInt();
    currentSkin = settings.value("Player/current_skin", 0).toInt();
    autoResize = settings.value("Player/auto_resize", true).toBool();
    enableScreenshot = settings.value("Player/screenshot", true).toBool();
    rememberUnfinished = settings.value("Player/remember_unfinished", true).toBool();
    proxy = settings.value("Net/proxy").toString();
    port = settings.value("Net/port").toInt();
    cacheSize = settings.value("Net/cache_size", 4096).toInt();
    cacheMin = settings.value("Net/cache_min", 50).toInt();
    maxTasks = settings.value("Net/max_tasks", 3).toInt();
    downloadDir = settings.value("Net/download_dir", QDir::homePath()).toString();
    quality = (Quality) settings.value("Plugins/quality", (int) SUPER).toInt();
    autoCombine = settings.value("Plugins/auto_combine", false).toBool();
    autoCloseWindow = settings.value("Plugins/auto_close_window", true).toBool();
    danmakuAlpha = settings.value("Danmaku/alpha", 0.9).toDouble();
    danmakuFont = settings.value("Danmaku/font", "").toString();
    danmakuSize = settings.value("Danmaku/size", 0).toInt();
    durationScrolling = settings.value("Danmaku/dm", 0).toInt();
    durationStill = settings.value("Danmaku/ds", 6).toInt();

    //init proxy
    if (proxy.isEmpty())
        access_manager->setProxy(QNetworkProxy(QNetworkProxy::NoProxy));
    else
        access_manager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, port));

    //init skins
    QDir skinDir(path);
    skinDir.cd("skins");
    skinList = skinDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
#ifdef Q_OS_LINUX
    dir.cd("skins");
    skinList.append(dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name));
#endif
    if (currentSkin >= skinList.size())
        currentSkin = 0;
}
コード例 #5
0
ファイル: main.cpp プロジェクト: qlands/GOBLET
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //Command line arguments
    TCLAP::CmdLine cmd("GOBLET (c) 2012, International Livestock Research Institute (ILRI) \n Developed by Carlos Quiros ([email protected])", ' ', "1.0 (Beta 1)");
    //Required arguments
    TCLAP::ValueArg<std::string> databaseArg("d","database","Database name",true,"","string");
    TCLAP::ValueArg<std::string> datasetArg("t","dataset","Dataset name",true,"","string");
    TCLAP::ValueArg<std::string> classArg("c","classdefinition","Class definition: 'ClassNumber:valueFrom ValueTo,ClassNumber:valueFrom ValueTo,...'",true,"","string");
    //Non required arguments
    TCLAP::ValueArg<std::string> pathArg("a","path","Path to database. Default .",false,".","string");
    TCLAP::ValueArg<std::string> hostArg("H","host","Connect to host. Default localhost",false,"localhost","string");
    TCLAP::ValueArg<std::string> portArg("P","port","Port number to use. Default 3306",false,"3306","string");
    TCLAP::ValueArg<std::string> userArg("u","user","User. Default empty",false,"","string");
    TCLAP::ValueArg<std::string> passArg("p","password","Passwork. Default no password",false,"","string");
    TCLAP::ValueArg<std::string> extentArg("e","extent","Extent: '(upperLeft degrees lat,log) (lowerRight degrees lat,log)'",false,"","string");
    TCLAP::ValueArg<std::string> shpConstraintArg("S","constraintbyshapes","Constraint classification using shapes: ShapeDataSet:shapeID,ShapeID,....",false,"","string");

    TCLAP::ValueArg<std::string> defValArg("v","defaultvalue","Default value 0",false,"0","string");

    //Switches
    TCLAP::SwitchArg remoteSwitch("r","remote","Connect to remote host", cmd, false);
    cmd.add(databaseArg);
    cmd.add(datasetArg);
    cmd.add(classArg);
    cmd.add(extentArg);
    cmd.add(shpConstraintArg);
    cmd.add(pathArg);
    cmd.add(hostArg);
    cmd.add(portArg);
    cmd.add(userArg);
    cmd.add(passArg);
    cmd.add(defValArg);

    //Parsing the command lines
    cmd.parse( argc, argv );

    //Getting the variables from the command
    bool remote = remoteSwitch.getValue();
    QString path = QString::fromUtf8(pathArg.getValue().c_str());
    QString dbName = QString::fromUtf8(databaseArg.getValue().c_str());
    QString host = QString::fromUtf8(hostArg.getValue().c_str());
    QString port = QString::fromUtf8(portArg.getValue().c_str());
    QString userName = QString::fromUtf8(userArg.getValue().c_str());
    QString password = QString::fromUtf8(passArg.getValue().c_str());
    QString tableName = QString::fromUtf8(datasetArg.getValue().c_str());    
    QString classDef = QString::fromUtf8(classArg.getValue().c_str());
    QString extent = QString::fromUtf8(extentArg.getValue().c_str());
    QString shapes = QString::fromUtf8(shpConstraintArg.getValue().c_str());
    QString defvalue = QString::fromUtf8(defValArg.getValue().c_str());

    myDBConn con;
    QSqlDatabase mydb;
    if (!remote)
    {
        QDir dir;
        dir.setPath(path);
        if (con.connectToDB(dir.absolutePath()) == 1)
        {
            if (!dir.cd(dbName))
            {
                gbtLog(QObject::tr("The database does not exists"));
                con.closeConnection();
                return 1;
            }
            mydb = QSqlDatabase::addDatabase(con.getDriver(),"connection1");
        }
    }
    else
    {
        mydb = QSqlDatabase::addDatabase("QMYSQL","connection1");
        mydb.setHostName(host);
        mydb.setPort(port.toInt());
        if (!userName.isEmpty())
            mydb.setUserName(userName);
        if (!password.isEmpty())
            mydb.setPassword(password);
    }

    mydb.setDatabaseName(dbName);

    if (!mydb.open())
    {
        gbtLog(QObject::tr("Cannot open database"));
        con.closeConnection();
        return 1;
    }
    else
    {
        QTime procTime;
        procTime.start();

        //We need to check if dataset is a grid

        getClasses(classDef);
        if (classes.count() ==0 )
        {
            gbtLog(QObject::tr("There are no classes!"));
            mydb.close();
            con.closeConnection();
            return 1;
        }

        QString sql;
        QString headsql;

        headsql = "UPDATE " + tableName + " TA";
        QString WhereClause;
        sql = " SET TA.classCode = CASE";
        for (int t=0; t <= classes.count()-1;t++)
        {
            sql = sql + " WHEN (TA.cellvalue >= " + QString::number(classes[t].from,'f',5);
            sql = sql + " AND TA.cellvalue <= " + QString::number(classes[t].to,'f',5);
            sql = sql + ") THEN " + QString::number(classes[t].classNumber);            
        }
        sql = sql + " ELSE " + defvalue + " END";

        if (!extent.isEmpty())
        {

            WhereClause = getWhereClauseFromExtent(extent,mydb,tableName);
            if (!WhereClause.isEmpty())
                sql = sql + " WHERE " + WhereClause;            
        }

        QSqlQuery qry(mydb);

        if (!shapes.isEmpty())
        {
            QString shapeClause;

            shapeClause = getShapeClause(shapes,mydb);


            if (!shapeClause.isEmpty())
            {
                //
                QString sqlcreate;
                sqlcreate = "CREATE TEMPORARY TABLE tmpshapes (";
                sqlcreate = sqlcreate + "geokey VARCHAR(14) NOT NULL ,";
                sqlcreate = sqlcreate + "PRIMARY KEY (geokey))";
                sqlcreate = sqlcreate + " ENGINE = MyISAM";
                if (qry.exec(sqlcreate))
                {
                    QString extentClause;
                    extentClause = WhereClause;
                    extentClause.replace("TA.","");

                    if (!extentClause.isEmpty())
                        sqlcreate = "INSERT INTO tmpshapes " + shapeClause + " AND " + extentClause;
                    else
                        sqlcreate = "INSERT INTO tmpshapes " + shapeClause;

                    gbtLog(QObject::tr("Preselecting shapes"));
                    if (qry.exec(sqlcreate))
                    {
                        headsql = headsql + ", tmpshapes TB";

                        if (sql.contains("WHERE"))
                            sql = sql + " AND TA.geokey = TB.geokey";
                        else
                            sql = sql + " WHERE TA.geokey = TB.geokey";

                    }
                    else
                    {
                        gbtLog(QObject::tr("Cannot insert temporary shapes."));
                        gbtLog(qry.lastError().databaseText());
                    }
                }
                else
                {
                    gbtLog(QObject::tr("Cannot shapes temporary table."));
                    gbtLog(qry.lastError().databaseText());
                }
            }
        }

        gbtLog(QObject::tr("Classifying...Please wait"));
        sql = headsql + sql;

        if (!qry.exec(sql))
        {
            gbtLog(QObject::tr("Cannot classify dataset."));
            gbtLog(qry.lastError().databaseText());
            mydb.close();
            con.closeConnection();
            return 1;
        }

        int Hours;
        int Minutes;
        int Seconds;
        int Milliseconds;

        Milliseconds = procTime.elapsed();

        Hours = Milliseconds / (1000*60*60);
        Minutes = (Milliseconds % (1000*60*60)) / (1000*60);
        Seconds = ((Milliseconds % (1000*60*60)) % (1000*60)) / 1000;

        gbtLog("Finished in " + QString::number(Hours) + " Hours," + QString::number(Minutes) + " Minutes and " + QString::number(Seconds) + " Seconds.");

        mydb.close();
        con.closeConnection();

        return 0;
    }

    return 0;

}
コード例 #6
0
ファイル: filesystem.cpp プロジェクト: 02JanDal/soqute
void FS::remove(const QDir &dir)
{
	if (!QDir(dir).removeRecursively()) {
		throw FileSystemException("Unable to remove " + dir.dirName());
	}
}
コード例 #7
0
ファイル: qfiledialog_win.cpp プロジェクト: husninazer/qt
QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
                                       QString *initialDirectory,
                                       QString *selectedFilter)
{
    QFileInfo fi;
    QDir dir;

    if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
        initialDirectory->remove(0, 5);
    fi = QFileInfo(*initialDirectory);

    if (initialDirectory && !fi.isDir()) {
        *initialDirectory = fi.absolutePath();
    }

    if (!fi.exists())
        *initialDirectory = QDir::homePath();

    DWORD selFilIdx = 0;

    QStringList filterLst = qt_win_make_filters_list(args.filter);
    int idx = 0;
    if (selectedFilter) {
        idx = filterLst.indexOf(*selectedFilter);
    }
    // Windows Vista (& above) allows users to search from file dialogs. If user selects
    // multiple files belonging to different folders from these search results, the
    // GetOpenFileName() will return only one folder name for all the files. To retrieve
    // the correct path for all selected files, we have to use Common Item Dialog interfaces.
#ifndef Q_WS_WINCE
    if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)
        return qt_win_CID_get_open_file_names(args, initialDirectory, filterLst, selectedFilter, idx);
#endif

    QStringList result;
    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(args.parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);

    bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
    OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection,
                                        args.directory, args.caption,
                                        qt_win_filter(args.filter, hideFiltersDetails),
                                        QFileDialog::ExistingFiles,
                                        args.options);
    if (idx)
        ofn->nFilterIndex = idx + 1;
    if (GetOpenFileName(ofn)) {
        QString fileOrDir = QString::fromWCharArray(ofn->lpstrFile);
        selFilIdx = ofn->nFilterIndex;
        int offset = fileOrDir.length() + 1;
        if (ofn->lpstrFile[offset] == 0) {
            // Only one file selected; has full path
            fi.setFile(fileOrDir);
            QString res = fi.absoluteFilePath();
            if (!res.isEmpty())
                result.append(res);
        }
        else {
            // Several files selected; first string is path
            dir.setPath(fileOrDir);
            QString f;
            while(!(f = QString::fromWCharArray(ofn->lpstrFile + offset)).isEmpty()) {
                fi.setFile(dir, f);
                QString res = fi.absoluteFilePath();
                if (!res.isEmpty())
                    result.append(res);
                offset += f.length() + 1;
            }
        }
    }
    qt_win_clean_up_OFN(&ofn);

    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (!result.isEmpty()) {
        *initialDirectory = fi.path();    // only save the path if there is a result
        if (selectedFilter)
            *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
    }
    return result;
}
コード例 #8
0
int main(int argc, char** argv)
{
  ctkLogger::configure();
  ctkLogger logger ( "org.commontk.dicom.DICOMRetieveApp" );
  logger.setDebug();

  if (argc < 9)
  {
    print_usage();
    return EXIT_FAILURE;
  }

  QCoreApplication app(argc, argv);
  QTextStream out(stdout);

  QString StudyUID ( argv[1] );
  QDir OutputDirectory ( argv[2] );
  QString CallingAETitle ( argv[3] ); 
  bool ok;
  int CallingPort = QString ( argv[4] ).toInt ( &ok );
  if ( !ok )
    {
    std::cerr << "Could not convert " << argv[4] << " to an integer for the callingPort" << std::endl;
    print_usage();
    return EXIT_FAILURE;
    }

  QString CalledAETitle ( argv[5] ); 
  QString Host ( argv[6] ); 
  int CalledPort = QString ( argv[7] ).toInt ( &ok );
  if ( !ok )
    {
    std::cerr << "Could not convert " << argv[7] << " to an integer for the calledPoint" << std::endl;
    print_usage();
    return EXIT_FAILURE;
    }
  QString MoveDestinationAETitle ( argv[8] ); 

  ctkDICOMRetrieve retrieve;
  retrieve.setCallingAETitle ( CallingAETitle );
  retrieve.setCallingPort ( CallingPort );
  retrieve.setCalledAETitle ( CalledAETitle );
  retrieve.setCalledPort ( CalledPort );
  retrieve.setHost ( Host );
  retrieve.setMoveDestinationAETitle ( MoveDestinationAETitle );

  logger.info ( "StudyUID: " + StudyUID + "\n" 
                + "OutputDirectory: " + OutputDirectory.absolutePath() + "\n"
                + "CallingAETitle: " + CallingAETitle + "\n"
                + "CallingPort: " + QString::number ( CallingPort ) + "\n"
                + "CalledAEtitle: " + CalledAETitle + "\n"
                + "Host: " + Host + "\n"
                + "CalledPort: " + QString::number ( CalledPort ) + "\n" );


  logger.info ( "Starting to retrieve" );
  try
    {
    retrieve.retrieveStudy ( StudyUID, OutputDirectory );
    }
  catch (std::exception e)
    {
    logger.error ( "Retrieve failed" );
    return EXIT_FAILURE;
    }
  logger.info ( "Retrieve success" );
  return EXIT_SUCCESS;
}
コード例 #9
0
ファイル: mainwindow.cpp プロジェクト: shuge/dukto
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Creazione finestra
    ui->setupUi(this);
    mDialogSendIp = NULL;
    mDialogText = NULL;
    mDialogAbout = NULL;
    mNetworkSession = NULL;

    // Creazione menu'
    mSendFileAction = new QAction("Send a file", this);
    menuBar()->addAction(mSendFileAction);
    connect(mSendFileAction, SIGNAL(triggered()), this, SLOT(selectFileToSend()));

    mSendTextAction = new QAction("Send text message", this);
    menuBar()->addAction(mSendTextAction);
    connect(mSendTextAction, SIGNAL(triggered()), this, SLOT(showSendTextDialog()));

    mSendToIPAction = new QAction("Send by IP", this);
    menuBar()->addAction(mSendToIPAction);
    connect(mSendToIPAction, SIGNAL(triggered()), this, SLOT(sendToIp()));

    mCurrentIPAction = new QAction("Current IP address", this);
    menuBar()->addAction(mCurrentIPAction);
    connect(mCurrentIPAction, SIGNAL(triggered()), this, SLOT(showCurrentIP()));

    mChangeFolderAction = new QAction("Change folder", this);
    menuBar()->addAction(mChangeFolderAction);
    connect(mChangeFolderAction, SIGNAL(triggered()), this, SLOT(changeFolder()));

    mChangeNameAction = new QAction("Change user name", this);
    menuBar()->addAction(mChangeNameAction);
    connect(mChangeNameAction, SIGNAL(triggered()), this, SLOT(changeName()));

    mAboutAction = new QAction("About Dukto", this);
    menuBar()->addAction(mAboutAction);
    connect(mAboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));

    // Progress dialog per operazioni
    mProgressDialog = new QProgressDialog("", "", 0, 100);
    mProgressDialog->setWindowModality(Qt::WindowModal);

    // Connecting dialog
    mConnectingDialog = new QProgressDialog("\nConnecting...", "", 0, 0);
    mConnectingDialog->setCancelButton(NULL);
    mConnectingDialog->setAutoClose(false);
    mConnectingDialog->setMinimumDuration(0);
    mConnectingDialog->setWindowModality(Qt::WindowModal);

    // Percorso salvato
    QSettings settings("msec.it", "Dukto");
    QString path = settings.value("dukto/currentpath", "C:/Dukto").toString();
    QDir d;
    if (d.mkpath(path))
    {
        QDir::setCurrent(path);
        ui->labelDest->setText("Folder: " + path.replace('/', "\\"));
    }

    // Percorso di default
    else
    {
        path = "C:/Dukto";
        d.mkpath(path);
        QDir::setCurrent(path);
        ui->labelDest->setText("Folder: " + path.replace('/', "\\"));
        settings.setValue("dukto/currentpath", path);
    }

    // Inizialmente nascondo la lista
    ui->listWidget->setVisible(false);

}
コード例 #10
0
ファイル: grabbersettings.cpp プロジェクト: chadparry/mythtv
void GrabberSettings::Load(void)
{
    QDir TVScriptPath = QString("%1metadata/Television/").arg(GetShareDir());
    QStringList TVScripts = TVScriptPath.entryList(QDir::Files);
    QDir MovieScriptPath = QString("%1metadata/Movie/").arg(GetShareDir());
    QStringList MovieScripts = MovieScriptPath.entryList(QDir::Files);
    QDir GameScriptPath = QString("%1metadata/Game/").arg(GetShareDir());
    QStringList GameScripts = GameScriptPath.entryList(QDir::Files);

    if (MovieScripts.count())
    {
        for (QStringList::const_iterator i = MovieScripts.begin();
             i != MovieScripts.end(); ++i)
        {
            QString commandline = QString("%1/%2")
                                      .arg(MovieScriptPath.path()).arg(*i);
            MythSystemLegacy grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut);
            grabber.Run();
            grabber.Wait();
            QByteArray result = grabber.ReadAll();

            if (!result.isEmpty())
            {
                QDomDocument doc;
                doc.setContent(result, true);
                QDomElement root = doc.documentElement();
                if (!root.isNull())
                {
                    MetaGrabberScript *script = ParseGrabberVersion(root);
                    if (!script->GetName().isEmpty())
                        m_movieGrabberList.append(script);
                }
            }
        }
    }

    if (TVScripts.count())
    {
        for (QStringList::const_iterator i = TVScripts.end() - 1;
                i != TVScripts.begin() - 1; --i)
        {
            QString commandline = QString("%1/%2")
                                      .arg(TVScriptPath.path()).arg(*i);
            MythSystemLegacy grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut);
            grabber.Run();
            grabber.Wait();
            QByteArray result = grabber.ReadAll();

            if (!result.isEmpty())
            {
                QDomDocument doc;
                doc.setContent(result, true);
                QDomElement root = doc.documentElement();
                if (!root.isNull())
                {
                    MetaGrabberScript *script = ParseGrabberVersion(root);
                    if (!script->GetName().isEmpty())
                        m_tvGrabberList.append(script);

                }
            }
        }
    }

    if (GameScripts.count())
    {
        for (QStringList::const_iterator i = GameScripts.end() - 1;
                i != GameScripts.begin() - 1; --i)
        {
            QString commandline = QString("%1/%2")
                                      .arg(GameScriptPath.path()).arg(*i);
            MythSystemLegacy grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut);
            grabber.Run();
            grabber.Wait();
            QByteArray result = grabber.ReadAll();

            if (!result.isEmpty())
            {
                QDomDocument doc;
                doc.setContent(result, true);
                QDomElement root = doc.documentElement();
                if (!root.isNull())
                {
                    MetaGrabberScript *script = ParseGrabberVersion(root);
                    if (!script->GetName().isEmpty())
                        m_gameGrabberList.append(script);
                }
            }
        }
    }
}
コード例 #11
0
ファイル: pfmPage.cpp プロジェクト: schwehr/pfmabe
void
pfmPage::slotPFMFileEdit (const QString &string)
{
    pfm_def->name = string;


    if (!pfm_def->name.endsWith (".pfm")) pfm_def->name += ".pfm";


    mBinSize->setEnabled (TRUE);
    gBinSize->setEnabled (TRUE);
    minDepth->setEnabled (TRUE);
    maxDepth->setEnabled (TRUE);
    precision->setEnabled (TRUE);
    area_browse->setEnabled (TRUE);
    area_map->setEnabled (TRUE);
    area_pfm->setEnabled (TRUE);
    area_nsew->setEnabled (TRUE);


    //  Watch out for directory names that might be typed in.

    if (QFileInfo (string).isDir ()) return;


    FILE *fp;
    NV_INT32 hnd;
    PFM_OPEN_ARGS open_args;


    strcpy (open_args.list_path, pfm_def->name.toAscii ());


    //  Try to open the file.  If it exists we will not allow the user to change the bin size,
    //  depth precision, etc.

    pfm_def->existing = NVFalse;
    if ((fp = fopen (open_args.list_path, "r")) != NULL)
    {
        fclose (fp);

        open_args.checkpoint = 0;

        if ((hnd = open_existing_pfm_file (&open_args)) >= 0)
        {
            NV_CHAR file[512];
            get_target_file (hnd, open_args.list_path, file);
            feature_edit->setText (QString (file));
            get_mosaic_file (hnd, open_args.list_path, file);
            mosaic_edit->setText (QString (file));

            close_pfm_file (hnd);


            area_edit->setText (tr ("Defined in PFM structure"));


            mBinSize->setEnabled (FALSE);
            gBinSize->setEnabled (FALSE);
            minDepth->setEnabled (FALSE);
            maxDepth->setEnabled (FALSE);
            precision->setEnabled (FALSE);
            area_browse->setEnabled (FALSE);
            area_map->setEnabled (FALSE);
            area_pfm->setEnabled (FALSE);
            area_nsew->setEnabled (FALSE);

            pfm_def->existing = NVTrue;
        }
        else
        {
            QMessageBox::warning (this, tr ("Open PFM Structure"),
                                  tr ("The file ") + QDir::toNativeSeparators (QString (open_args.list_path)) +
                                  tr (" is not a PFM structure or there was an error reading the file.") +
                                  tr ("  The error message returned was:\n\n") +
                                  QString (pfm_error_str (pfm_error)));

            if (pfm_error == CHECKPOINT_FILE_EXISTS_ERROR)
            {
                fprintf (stderr, "\n\n%s\n", pfm_error_str (pfm_error));
                exit (-1);
            }
            return;
        }
    }
    else
    {
        if (area_edit->text () == tr ("Defined in PFM structure")) area_edit->clear ();

        feature_edit->setText ("NONE");
        mosaic_edit->setText ("NONE");

        QFileInfo fi = QFileInfo (pfm_def->name);
        if (fi.isRelative ())
        {
            //  Get the absolute path name

            QDir dir;

            pfm_def->name.prepend ("/");
            pfm_def->name.prepend (dir.canonicalPath());
        }
    }

    if (!pfm_file_edit->text ().isEmpty () && !area_edit->text ().isEmpty ())
    {
        setButtonText (QWizard::NextButton, tr ("Next"));
    }
    else
    {
        if (l_page_num > 1) setButtonText (QWizard::NextButton, tr ("Finish"));
    }
}
コード例 #12
0
ファイル: formatimporter.cpp プロジェクト: smarter/basket
void FormatImporter::importBaskets()
{
	kDebug() << "Import Baskets: Preparing...";

	// Some preliminary preparations (create the destination folders and the basket tree file):
	QDir dirPrep;
	dirPrep.mkdir(Global::savesFolder());
	dirPrep.mkdir(Global::basketsFolder());
	QDomDocument document("basketTree");
	QDomElement root = document.createElement("basketTree");
	document.appendChild(root);

	// First up, establish a list of every baskets, ensure the old order (if any), and count them.
	QStringList baskets;

	// Read the 0.5.0 baskets order:
	QDomDocument *doc = XMLWork::openFile("container", Global::savesFolder() + "container.baskets");
	if (doc != 0) {
		QDomElement docElem = doc->documentElement();
		QDomElement basketsElem = XMLWork::getElement(docElem, "baskets");
		QDomNode n = basketsElem.firstChild();
		while (!n.isNull()) {
			QDomElement e = n.toElement();
			if ((!e.isNull()) && e.tagName() == "basket")
				baskets.append(e.text());
			n = n.nextSibling();
		}
	}

	// Then load the baskets that weren't loaded (import < 0.5.0 ones):
	QDir dir(Global::savesFolder(), QString::null, QDir::Name | QDir::IgnoreCase, QDir::Dirs | QDir::NoSymLinks);
	QStringList list = dir.entryList();
	if (list.count() > 2) // Pass "." and ".."
		for (QStringList::Iterator it = list.begin(); it != list.end(); ++it) // For each folder
			if (*it != "." && *it != ".." && dir.exists(Global::savesFolder() + *it + "/.basket")) // If it can be a basket folder
				if (! (baskets.contains((*it) + "/")) && baskets.contains(*it) ) // And if it is not already in the imported baskets list
					baskets.append(*it);

	kDebug() << "Import Baskets: Found " << baskets.count() << " baskets to import.";

	// Import every baskets:
	int i = 0;
	for (QStringList::iterator it = baskets.begin(); it != baskets.end(); ++it) {
		++i;
		kDebug() << "Import Baskets: Importing basket " << i << " of " << baskets.count() << "...";

		// Move the folder to the new repository (normal basket) or copy the folder (mirorred folder):
		QString folderName = *it;
		if (folderName.startsWith("/")) { // It was a folder mirror:
			KMessageBox::information(0, i18n("<p>Folder mirroring is not possible anymore (see <a href='http://basket.kde.org/'>basket.kde.org</a> for more information).</p>"
				"<p>The folder <b>%1</b> has been copied for the basket needs. You can either delete this folder or delete the basket, or use both. But remember that "
				"modifying one will not modify the other anymore as they are now separate entities.</p>", folderName), i18n("Folder Mirror Import"),
				"", KMessageBox::AllowLink);
			// Also modify folderName to be only the folder name and not the full path anymore:
			QString newFolderName = folderName;
			if (newFolderName.endsWith("/"))
				newFolderName = newFolderName.left(newFolderName.length() - 1);
			newFolderName = newFolderName.mid(newFolderName.lastIndexOf('/') + 1);
			newFolderName = Tools::fileNameForNewFile(newFolderName, Global::basketsFolder());
			FormatImporter f;
			f.copyFolder(folderName, Global::basketsFolder() + newFolderName);
			folderName = newFolderName;
		} else
			dir.rename(Global::savesFolder() + folderName, Global::basketsFolder() + folderName); // Move the folder

		// Import the basket structure file and get the properties (to add them in the tree basket-properties cache):
		QDomElement properties = importBasket(folderName);

		// Add it to the XML document:
		QDomElement basketElement = document.createElement("basket");
		root.appendChild(basketElement);
		basketElement.setAttribute("folderName", folderName);
		basketElement.appendChild(properties);
	}

	// Finalize (write to disk and delete now useless files):
	kDebug() << "Import Baskets: Finalizing...";

	QFile file(Global::basketsFolder() + "baskets.xml");
	if (file.open(QIODevice::WriteOnly)) {
		QTextStream stream(&file);
		stream.setCodec("UTF-8");
		QString xml = document.toString();
		stream << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
		stream << xml;
		file.close();
	}

	Tools::deleteRecursively(Global::savesFolder() + ".tmp");
	dir.remove(Global::savesFolder() + "container.baskets");

	kDebug() << "Import Baskets: Finished.";
}
コード例 #13
0
 void dirTest(){
     QDir dir = Backend::directoryOf(QStringLiteral("/translations"));
     QVERIFY(dir.exists());
     dir = Backend::directoryOf(QStringLiteral("/dirDoesNotExist"));
     QVERIFY(!dir.exists());
 }
コード例 #14
0
/*
  Create a new project.
  - a new directory for the project
  - an XML project file for the project, from template
  - a stubbed out source file, from template
  Make sure the path name doesn't have any spaces in it, so make can work happily.
  Return the new project's name, or an empty string on failure.
*/
QString ProjectManager::createNewProject(QString newProjectPath)
{
  confirmValidProjectName(&newProjectPath);
  if(newProjectPath.contains(" ")) // if there are still spaces in the path, we have problems
    return "";
  QDir newProjectDir;
  newProjectDir.mkpath(newProjectPath);
  newProjectDir.setPath(newProjectPath);
  QString newProjName = newProjectDir.dirName();
  
  // grab the templates for a new project
  QDir templatesDir = QDir::current().filePath("resources/templates");
    
  // create the project file from our template
  QFile templateFile(templatesDir.filePath("project_template.xml"));
  templateFile.copy(newProjectDir.filePath(newProjName + ".xml"));
  templateFile.close();
  
  templateFile.setFileName(templatesDir.filePath("source_template.txt"));
  if( templateFile.open(QIODevice::ReadOnly | QFile::Text) )
  {
    // and create the main file
    QFile mainFile(newProjectDir.filePath(newProjName + ".c"));
    if( mainFile.open(QIODevice::WriteOnly | QFile::Text) )
    {
      QTextStream out(&mainFile);
      out << QString("// %1.c").arg(newProjName) << endl;
      out << QString("// created %1").arg(QDate::currentDate().toString("MMM d, yyyy") ) << endl;
      out << templateFile.readAll();
      mainFile.close();
    }
    QFileInfo fi(mainFile);
    addToProjectFile(newProjectDir.path(), fi.filePath(), "thumb");
    templateFile.close();
  }
  return newProjectDir.path();
}
コード例 #15
0
bool HierarchyTreePlatformNode::Save(YamlNode* node, bool saveAll)
{
	YamlNode* platform = new YamlNode(YamlNode::TYPE_MAP);
	platform->Set(WIDTH_NODE, GetWidth());
	platform->Set(HEIGHT_NODE, GetHeight());

	MultiMap<String, YamlNode*> &platformsMap = node->AsMap();
	platformsMap.erase(GetName().toStdString());
	platformsMap.insert(std::pair<String, YamlNode*>(GetName().toStdString(), platform));
	ActivatePlatform();
	
	MultiMap<String, YamlNode*> &platformMap = platform->AsMap();
	YamlNode* screens = new YamlNode(YamlNode::TYPE_ARRAY);
	platformMap.erase(SCREENS_NODE);
	platformMap.insert(std::pair<String, YamlNode*>(SCREENS_NODE, screens));
	
	YamlNode* aggregators = new YamlNode(YamlNode::TYPE_MAP);
	platformMap.erase(AGGREGATORS_NODE);
	platformMap.insert(std::pair<String, YamlNode*>(AGGREGATORS_NODE, aggregators));

    // Add the Localization info - specific for each Platform.
    SaveLocalization(platform);

	QString platformFolder = GetPlatformFolder();

	QDir dir;
	dir.mkpath(platformFolder);
	
	bool result = true;
	
	//save aggregators node before save screens
	for (HIERARCHYTREENODESCONSTITER iter = GetChildNodes().begin();
		 iter != GetChildNodes().end();
		 ++iter)
	{
		HierarchyTreeAggregatorNode* node = dynamic_cast<HierarchyTreeAggregatorNode*>(*iter);
		if (!node)
			continue;

		QString path = QString(SCREEN_PATH).arg(platformFolder).arg(node->GetName());
		MultiMap<String, YamlNode*> &aggregatorsMap = aggregators->AsMap();
		
		YamlNode* aggregator = new YamlNode(YamlNode::TYPE_MAP);
		result &= node->Save(aggregator, path, saveAll);
		
		aggregatorsMap.erase(node->GetName().toStdString());
		aggregatorsMap.insert(std::pair<String, YamlNode*>(node->GetName().toStdString(), aggregator));
	}
		
	
	for (HIERARCHYTREENODESCONSTITER iter = GetChildNodes().begin();
		 iter != GetChildNodes().end();
		 ++iter)
	{
		HierarchyTreeAggregatorNode* node = dynamic_cast<HierarchyTreeAggregatorNode*>(*iter);
		if (node)
			continue;	//skip aggregators
		
		HierarchyTreeScreenNode* screenNode = dynamic_cast<HierarchyTreeScreenNode*>(*iter);
		if (!screenNode)
			continue;
		
		QString screenPath = QString(SCREEN_PATH).arg(platformFolder).arg(screenNode->GetName());
		result &= screenNode->Save(screenPath, saveAll);
		
		screens->AddValueToArray(screenNode->GetName().toStdString());
	}
	return result;
}
コード例 #16
0
bool
BasicInfoPage::isComplete() const {

    QRegExp *exp = new QRegExp("[\\\\/<>\\=\\{\\}]");
    bool v_author = false, v_name = false, v_mail = false;
    QDir *dir = new QDir(QDir::homePath()+"/"+tr("My Collections"));



    /* Checking title */
    if (ui->nameEdit->text().contains(*exp)) {
        ui->nameEdit->setStyleSheet("QLineEdit { color: red; }");
        ui->errorLabel->setVisible(false);
        v_name = false;

    }
    else {
        if (dir->entryList(QDir::Dirs).contains(ui->nameEdit->text())) {
            ui->nameEdit->setStyleSheet("QLineEdit { color: red; }");
            ui->errorLabel->setVisible(true);
            v_name = false;
        } else {
            ui->nameEdit->setStyleSheet("");
            ui->errorLabel->setVisible(false);
            v_name = true;
        }
    }



    /* Checking author */
    if (ui->authorEdit->text().contains(*exp)){
        ui->authorEdit->setStyleSheet("QLineEdit { color: red; }");
        v_author = false;
    }
    else {
        ui->authorEdit->setStyleSheet("");
        v_author = true;
    }

    delete exp;



    /* Checking email */
    exp = new QRegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");

    if (!ui->mailEdit->text().contains(*exp)) {
        ui->mailEdit->setStyleSheet("QLineEdit { color: red; }");
        v_mail = false;

        if (ui->mailEdit->text()=="") {
            ui->mailEdit->setStyleSheet("");
            v_mail = true;
        }
    }
    else {
        ui->mailEdit->setStyleSheet("");
        v_mail = true;
    }

    if (!v_author || ui->authorEdit->text()=="")
        return false;
    if (!v_name || ui->nameEdit->text()=="")
        return false;
    if (!v_mail)
        return false;

    return true;
}
コード例 #17
0
void MythCDROM::onDeviceMounted()
{
    if (!QDir(m_MountPath).exists())
    {
        VERBOSE(VB_IMPORTANT, QString("Mountpoint '%1' doesn't exist")
                              .arg(m_MountPath));
        m_MediaType = MEDIATYPE_UNKNOWN;
        m_Status    = MEDIASTAT_ERROR;
        return;
    }

    QFileInfo audio = QFileInfo(m_MountPath + PATHTO_AUDIO_DETECT);
    QDir        dvd = QDir(m_MountPath  + PATHTO_DVD_DETECT);
    QDir       svcd = QDir(m_MountPath  + PATHTO_SVCD_DETECT);
    QDir        vcd = QDir(m_MountPath  + PATHTO_VCD_DETECT);
    QDir    bad_dvd = QDir(m_MountPath  + PATHTO_BAD_DVD_MOUNT);

    // Default is data media
    m_MediaType = MEDIATYPE_DATA;

    // Default is mounted media
    m_Status = MEDIASTAT_MOUNTED;

    if (dvd.exists())
    {
        VERBOSE(VB_MEDIA, "Probable DVD detected.");
        m_MediaType = MEDIATYPE_DVD;
        m_Status = MEDIASTAT_USEABLE; 
    }
    else if (audio.exists())
    {
        VERBOSE(VB_MEDIA, "Probable Audio CD detected.");
        m_MediaType = MEDIATYPE_AUDIO;
        m_Status = MEDIASTAT_USEABLE; 
    }
    else if (vcd.exists() || svcd.exists())
    {
        VERBOSE(VB_MEDIA, "Probable VCD/SVCD detected.");
        m_MediaType = MEDIATYPE_VCD;
        m_Status = MEDIASTAT_USEABLE; 
    }
    else if (bad_dvd.exists())
        VERBOSE(VB_IMPORTANT,
                "DVD incorrectly mounted? (ISO9660 instead of UDF)");
    else
    {
        VERBOSE(VB_GENERAL,
                QString("CD/DVD '%1' contained none of\n").arg(m_MountPath) +
                QString("\t\t\t%1, %2, %3 or %4").arg(PATHTO_DVD_DETECT)
                .arg(PATHTO_AUDIO_DETECT).arg(PATHTO_VCD_DETECT)
                .arg(PATHTO_SVCD_DETECT));
        VERBOSE(VB_GENERAL, "Searching CD statistically - file by file!");
    }

    // If not DVD/AudioCD/VCD/SVCD, use parent's more generic version
    if (MEDIATYPE_DATA == m_MediaType)
        MythMediaDevice::onDeviceMounted();


    // Unlock the door, and if appropriate unmount the media,
    // so the user can press the manual eject button
    if (m_AllowEject)
    {
        unlock();
        if (m_MediaType == MEDIATYPE_DVD || m_MediaType == MEDIATYPE_VCD)
            unmount();
    }
}
コード例 #18
0
ファイル: rcc.cpp プロジェクト: Kelloggs/installer-framework
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QXmlStreamReader reader(inputDevice);
    QStack<RCCXmlTag> tokens;

    QString prefix;
    QLocale::Language language = QLocale::c().language();
    QLocale::Country country = QLocale::c().country();
    QString alias;
    int compressLevel = m_compressLevel;
    int compressThreshold = m_compressThreshold;

    while (!reader.atEnd()) {
        QXmlStreamReader::TokenType t = reader.readNext();
        switch (t) {
        case QXmlStreamReader::StartElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty())
                    reader.raiseError(QLatin1String("expected <RCC> tag"));
                else
                    tokens.push(RccTag);
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (tokens.isEmpty() || tokens.top() != RccTag) {
                    reader.raiseError(QLatin1String("unexpected <RESOURCE> tag"));
                } else {
                    tokens.push(ResourceTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    language = QLocale::c().language();
                    country = QLocale::c().country();

                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                        QString attribute = attributes.value(m_strings.ATTRIBUTE_LANG).toString();
                        QLocale lang = QLocale(attribute);
                        language = lang.language();
                        if (2 == attribute.length()) {
                            // Language only
                            country = QLocale::AnyCountry;
                        } else {
                            country = lang.country();
                        }
                    }

                    prefix.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                        prefix = attributes.value(m_strings.ATTRIBUTE_PREFIX).toString();
                    if (!prefix.startsWith(slash))
                        prefix.prepend(slash);
                    if (!prefix.endsWith(slash))
                        prefix += slash;
                }
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (tokens.isEmpty() || tokens.top() != ResourceTag) {
                    reader.raiseError(QLatin1String("unexpected <FILE> tag"));
                } else {
                    tokens.push(FileTag);

                    QXmlStreamAttributes attributes = reader.attributes();
                    alias.clear();
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                        alias = attributes.value(m_strings.ATTRIBUTE_ALIAS).toString();

                    compressLevel = m_compressLevel;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                        compressLevel = attributes.value(m_strings.ATTRIBUTE_COMPRESS).toString().toInt();

                    compressThreshold = m_compressThreshold;
                    if (attributes.hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                        compressThreshold = attributes.value(m_strings.ATTRIBUTE_THRESHOLD).toString().toInt();

                    // Special case for -no-compress. Overrides all other settings.
                    if (m_compressLevel == -2)
                        compressLevel = 0;
                }
            } else {
                reader.raiseError(QString(QLatin1String("unexpected tag: %1")).arg(reader.name().toString()));
            }
            break;

        case QXmlStreamReader::EndElement:
            if (reader.name() == m_strings.TAG_RCC) {
                if (!tokens.isEmpty() && tokens.top() == RccTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_RESOURCE) {
                if (!tokens.isEmpty() && tokens.top() == ResourceTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            } else if (reader.name() == m_strings.TAG_FILE) {
                if (!tokens.isEmpty() && tokens.top() == FileTag)
                    tokens.pop();
                else
                    reader.raiseError(QLatin1String("unexpected closing tag"));
            }
            break;

        case QXmlStreamReader::Characters:
            if (reader.isWhitespace())
                break;
            if (tokens.isEmpty() || tokens.top() != FileTag) {
                reader.raiseError(QLatin1String("unexpected text"));
            } else {
                QString fileName = reader.text().toString();
                if (fileName.isEmpty()) {
                    const QString msg = QString::fromLatin1("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                    m_errorDevice->write(msg.toUtf8());
                }

                if (alias.isNull())
                    alias = fileName;

                alias = QDir::cleanPath(alias);
                while (alias.startsWith(QLatin1String("../")))
                    alias.remove(0, 3);
                alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                QString absFileName = fileName;
                if (QDir::isRelativePath(absFileName))
                    absFileName.prepend(currentPath);
                QFileInfo file(absFileName);
                if (!file.exists()) {
                    m_failedResources.push_back(absFileName);
                    const QString msg = QString::fromLatin1("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                    m_errorDevice->write(msg.toUtf8());
                    if (ignoreErrors)
                        continue;
                    else
                        return false;
                } else if (file.isFile()) {
                    const bool arc =
                        addFile(alias,
                                RCCFileInfo(alias.section(slash, -1),
                                            file,
                                            language,
                                            country,
                                            RCCFileInfo::NoFlags,
                                            compressLevel,
                                            compressThreshold)
                                );
                    if (!arc)
                        m_failedResources.push_back(absFileName);
                } else {
                    QDir dir;
                    if (file.isDir()) {
                        dir.setPath(file.filePath());
                    } else {
                        dir.setPath(file.path());
                        dir.setNameFilters(QStringList(file.fileName()));
                        if (alias.endsWith(file.fileName()))
                            alias = alias.left(alias.length()-file.fileName().length());
                    }
                    if (!alias.endsWith(slash))
                        alias += slash;
                    QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                    while (it.hasNext()) {
                        it.next();
                        QFileInfo child(it.fileInfo());
                        if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                            const bool arc =
                                addFile(alias + child.fileName(),
                                        RCCFileInfo(child.fileName(),
                                                    child,
                                                    language,
                                                    country,
                                                    child.isDir() ? RCCFileInfo::Directory : RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(child.fileName());
                        }
                    }
                }
            }
            break;

        default:
            break;
        }
    }

    if (reader.hasError()) {
        if (ignoreErrors)
            return true;
        int errorLine = reader.lineNumber();
        int errorColumn = reader.columnNumber();
        QString errorMessage = reader.errorString();
        QString msg = QString::fromLatin1("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMessage);
        m_errorDevice->write(msg.toUtf8());
        return false;
    }

    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading with QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
コード例 #19
0
ファイル: filesystem.cpp プロジェクト: 02JanDal/soqute
bool FS::exists(const QDir &directory)
{
	return directory.exists();
}
コード例 #20
0
ファイル: mapinfo.cpp プロジェクト: Vazzi/Stalker-Editor
bool MapInfo::loadFile(QString filePath){

    //load file
    //file structure:
        // name;info;width;backround;item_1;item_2;...item_n;
    QFile loadMap(filePath);
    int i;
    QList <QString> itemsInStr, members, bgInStr,membersInItems;
    QString data;

    //control if can work with file
    if(!loadMap.open(QFile::ReadOnly | QFile::Text))
        return false;

    data = loadMap.readAll();
    members = data.split(";");

    //control basics
    if(members[0] == "")
        return false;
    m_mapName = members[0];
    m_info = members[1];

    //width
    bool ok;
    m_sceneWidth = members[2].toInt(&ok , 10);
    if(!ok)
        return false;

    //background
    bgInStr = members[3].split(",");
    m_bgPath = bgInStr[0];
    m_bgRepeat = bgInStr[1].toInt(&ok, 10);

    //get all items
    i = 4;
    while(members[i] != ""){
        itemsInStr.append(members[i++]);
    }
    m_itemsPath.clear();

    for(i = 0 ; i < itemsInStr.count() ; i++){
        membersInItems = itemsInStr[i].split(",");
        m_itemsPath.append(membersInItems[0]);

        m_itemsX.append(membersInItems[1].toInt(&ok, 10));
        m_itemsY.append(membersInItems[2].toInt(&ok, 10));
        m_itemsZ.append(membersInItems[3].toInt(&ok, 10));
    }

    QString imageFolderPath = filePath.remove(".map",Qt::CaseSensitive);
    imageFolderPath.append("_images/");
    QDir imageFolder;
    filePath.remove(filePath.split("/").last());
    filePath = filePath.left(filePath.count()-1);
    if(imageFolder.cd(imageFolderPath)){
        if(!m_bgPath.startsWith(":/images/",Qt::CaseSensitive)){
            m_bgPath = filePath + m_bgPath;
        }
        for(i = 0; i < m_itemsPath.count(); i++ ){
            if(!m_itemsPath[i].startsWith(":/images/",Qt::CaseSensitive)){
                m_itemsPath[i] = filePath + m_itemsPath[i];
            }
        }
    }

    return true;

}
コード例 #21
0
ファイル: rcc.cpp プロジェクト: njsfzj/pyqt5
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, QString fname, QString currentPath)
{
    if (!currentPath.isEmpty() && !currentPath.endsWith(QLatin1String("/")))
        currentPath += '/';

    QDomDocument document;
    {
        QString errorMsg;
        int errorLine, errorColumn;
        if(!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) {
            fprintf(stderr, "pyrcc5 Parse Error:%s:%d:%d [%s]\n", fname.toLatin1().constData(),
                    errorLine, errorColumn, errorMsg.toLatin1().constData());
            return false;
        }
    }
    for(QDomElement root = document.firstChild().toElement(); !root.isNull();
        root = root.nextSibling().toElement()) {
        if (root.tagName() != QLatin1String(TAG_RCC))
            continue;

        for (QDomElement child = root.firstChild().toElement(); !child.isNull();
             child = child.nextSibling().toElement()) {
            if (child.tagName() == QLatin1String(TAG_RESOURCE)) {
                QLocale lang = QLocale::c();
                if (child.hasAttribute(ATTRIBUTE_LANG))
                    lang = QLocale(child.attribute(ATTRIBUTE_LANG));

                QString prefix;
                if (child.hasAttribute(ATTRIBUTE_PREFIX))
                    prefix = child.attribute(ATTRIBUTE_PREFIX);
                if (!prefix.startsWith(QLatin1String("/")))
                    prefix.prepend('/');
                if (!prefix.endsWith(QLatin1String("/")))
                    prefix += '/';


                for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) {
                    if (res.toElement().tagName() == QLatin1String(TAG_FILE)) {

                        QString fileName(res.firstChild().toText().data());
                        if (fileName.isEmpty())
                            fprintf(stderr, "Warning: Null node in XML\n");

                        QString alias;
                        if (res.toElement().hasAttribute(ATTRIBUTE_ALIAS))
                            alias = res.toElement().attribute(ATTRIBUTE_ALIAS);
                        else
                            alias = fileName;

                        int compressLevel = mCompressLevel;
                        if (res.toElement().hasAttribute(ATTRIBUTE_COMPRESS))
                            compressLevel = res.toElement().attribute(ATTRIBUTE_COMPRESS).toInt();
                        int compressThreshold = mCompressThreshold;
                        if (res.toElement().hasAttribute(ATTRIBUTE_THRESHOLD))
                            compressThreshold = res.toElement().attribute(ATTRIBUTE_THRESHOLD).toInt();

                        // Special case for -no-compress. Overrides all other settings.
                        if (mCompressLevel == -2)
                            compressLevel = 0;

                        alias = QDir::cleanPath(alias);
                        while (alias.startsWith("../"))
                            alias.remove(0, 3);
                        alias = prefix + alias;

                        QFileInfo file(currentPath + fileName);
                        if (!file.exists()) {
                            fprintf(stderr, "Cannot find file: %s\n", fileName.toLatin1().constData());
                            continue ;
                        } else if (file.isFile()) {
                            addFile(alias, RCCFileInfo(alias.section('/', -1), file, lang,
                                                       RCCFileInfo::NoFlags, compressLevel, compressThreshold));
                        } else {
                            QDir dir;
                            if(file.isDir()) {
                                dir.setPath(file.filePath());
                            } else {
                                dir.setPath(file.path());
                                dir.setNameFilters(QStringList(file.fileName()));
                                if(alias.endsWith(file.fileName()))
                                    alias = alias.left(alias.length()-file.fileName().length());
                            }
                            if (!alias.endsWith(QLatin1String("/")))
                                alias += '/';
                            QFileInfoList children = dir.entryInfoList();
                            for(int i = 0; i < children.size(); ++i) {
                                if(children[i].fileName() != QLatin1String(".") &&
                                   children[i].fileName() != QLatin1String(".."))
                                    addFile(alias + children[i].fileName(),
                                            RCCFileInfo(children[i].fileName(), children[i], lang,
                                                        RCCFileInfo::NoFlags, compressLevel, compressThreshold));
                            }
                        }
                    }
                }
            }
        }
    }
    if(this->root == 0) {
        fprintf(stderr, "No resources in resource description.\n");
        return false;
    }
    return true;
}
コード例 #22
0
ファイル: main.cpp プロジェクト: juniperdiego/usbW
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

	qInstallMsgHandler(customMessageHandler);	

#ifdef ARM
    //font
    QFont font;
    font.setPointSize(16);
    a.setFont(font);
#endif

    QTextCodec *codec = QTextCodec::codecForName("UTF-8");  

    QTextCodec::setCodecForLocale(codec);  
    QTextCodec::setCodecForCStrings(codec);  
    QTextCodec::setCodecForTr(codec);

    //create dir for update
    QDir appDir;
    appDir.mkpath(TMP_PATH);
    appDir.mkpath(APK_PATH);
    appDir.mkpath(LOG_PATH);
    appDir.mkpath(ENCYPT_LOG_PATH);

#if 1
    //init usb device
    if (!initUsbDevices())
    {
        QMessageBox::critical(NULL, APP_NAME, "USB端口初始化失败,系统无法正常工作!");
    }
#endif

    //test network
    int time = 2;
    while(time)
    {
        QNetworkInterface netInterface = QNetworkInterface::interfaceFromName(NET_NAME);
        if (netInterface.isValid())
        {
            if (netInterface.flags().testFlag(QNetworkInterface::IsUp))
            {
                QHostInfo host = QHostInfo::fromName(WEB_SITE);
                if (!host.addresses().isEmpty()) 
                {
                    Global::s_netState = true;
                    break;
                }
            }
        }
        sleep(5);
        --time;
    }

    //msgBox.hide();

    if (!Global::s_netState)
    {
        QMessageBox::information(NULL, APP_NAME, "没有发现网络连接,无法更新软件数据,系统将离线运行!");
    }

    MainWindow w;
    w.setWindowTitle("Welcome");
    w.show();

    if (Global::s_netState)
    {
        Gengxin gengXin(true);
        gengXin.show();
        gengXin.StartUpSoft();
#if 0
        if (Global::s_needRestart)
        {
            QString exePath = qApp->applicationFilePath();
            QString cmd = "unzip ";
            cmd += UPDATE_FILE_NAME;
            QFile::remove(exePath);
            QProcess::execute(cmd);
#ifdef ARM
            Global::reboot();
#else
            QProcess::startDetached(exePath, QStringList());
#endif
            return 0;
        }
#endif
        gengXin.hide();
        if (gengXin.getUpdateDevState())
            w.OnGengxin(false);
        else
            w.startUsbScan();
    }

    return a.exec();
}
コード例 #23
0
ファイル: Scanner.cpp プロジェクト: botvs/FinancialAnalytics
void Scanner::scan ()
{
  if (! fileList.count() && ! allSymbols->isChecked())
  {
    QMessageBox::information(this,
                             tr("Qtstalker: Error"),
			     tr("No symbols selected."));
    return;
  }

  // open the CUS plugin
  QString iplugin("CUS");
  IndicatorPlugin *plug = config.getIndicatorPlugin(iplugin);
  if (! plug)
  {
    config.closePlugin(iplugin);
    return;
  }

  QString s;
  list->getText(s);
  QStringList l = QStringList::split("\n", s, FALSE);
  plug->setCustomFunction(l);
  
  this->setEnabled(FALSE);
  
  // clear dir for scan symbols
  QDir dir;
  config.getData(Config::GroupPath, s);
  s.append("/Scanner");
  if (! dir.exists(s, TRUE))
    dir.mkdir(s, TRUE);
  s.append("/" + scannerName);
  if (! dir.exists(s, TRUE))
    dir.mkdir(s, TRUE);
  else
  {
    int loop;
    dir.setPath(s);
    for (loop = 2; loop < (int) dir.count(); loop++)
    {
      QString s2 = dir.absPath() + "/" + dir[loop];
      if (! dir.remove(s2, TRUE))
        qDebug("%s not removed", s2.latin1());
    }
  }
  
  if (allSymbols->isChecked())
  {
    QString ts;
    if (! basePath->currentText().compare(tr("Chart")))
      config.getData(Config::DataPath, ts);
    else
      config.getData(Config::GroupPath, ts);
    Traverse trav(Traverse::File);
    trav.traverse(ts);
    trav.getList(fileList);
  }
  
  QProgressDialog prog(tr("Scanning..."),
                       tr("Cancel"),
		       fileList.count(),
		       this,
		       "progress",
		       TRUE);
  prog.show();
  
  int minBars = bars->value();
  
  emit message(QString("Scanning..."));
  
  int loop;
  for (loop = 0; loop < (int) fileList.count(); loop++)
  {
    prog.setProgress(loop);
    emit message(QString());
    if (prog.wasCancelled())
    {
      emit message(QString("Scan cancelled"));
      break;
    }

    QFileInfo fi(fileList[loop]);
    if (fi.isDir())
      continue;

    DbPlugin db;
    QDir dir;
    if (! dir.exists(fileList[loop]))
      continue;
    db.open(fileList[loop], chartIndex);

    db.setBarRange(minBars);
    db.setBarLength((BarData::BarLength) barLengthList.findIndex(period->currentText()));

    BarData *recordList = new BarData(fileList[loop]);
    QDateTime dt = QDateTime::currentDateTime();
    db.getHistory(recordList, dt);
    db.close();
    
    // load the CUS plugin and calculate
    plug->setIndicatorInput(recordList);
    Indicator *i = plug->calculate();
    if (! i->getLines())
    {
      delete recordList;
      delete i;
      continue;
    }
    
    PlotLine *line = i->getLine(0);
    if (line && line->getSize() > 0)
    {
      if (line->getData(line->getSize() - 1) > 0)
      {
        QString ts;
        config.getData(Config::GroupPath, ts);
        QString s = "ln -s \"" + fileList[loop] + "\" " + ts + "/Scanner/" + scannerName;
        system(s);
      }
    }
    
    delete recordList;
    delete i;
    
    emit message(QString());
  }
  
  if (! prog.wasCancelled())
    emit message(QString("Scan complete"));
  
  config.closePlugin(iplugin);
  
  this->setEnabled(TRUE);

  emit scanComplete();
}
コード例 #24
0
bool QMakeSourceFileInfo::findDeps(SourceFile *file)
{
    if(file->dep_checked || file->type == TYPE_UNKNOWN)
        return true;
    files_changed = true;
    file->dep_checked = true;

    const QMakeLocalFileName sourceFile = fixPathForFile(file->file, true);

    struct stat fst;
    char *buffer = 0;
    int buffer_len = 0;
    {
        int fd;
#if defined(_MSC_VER) && _MSC_VER >= 1400
        if (_sopen_s(&fd, sourceFile.local().toLatin1().constData(),
            _O_RDONLY, _SH_DENYNO, _S_IREAD) != 0)
            fd = -1;
#else
        fd = open(sourceFile.local().toLatin1().constData(), O_RDONLY);
#endif
        if(fd == -1 || fstat(fd, &fst) || S_ISDIR(fst.st_mode))
            return false;
        buffer = getBuffer(fst.st_size);
        for(int have_read = 0;
            (have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len));
            buffer_len += have_read);
        QT_CLOSE(fd);
    }
    if(!buffer)
        return false;
    if(!file->deps)
        file->deps = new SourceDependChildren;

    int line_count = 1;

    for(int x = 0; x < buffer_len; ++x) {
        bool try_local = true;
        char *inc = 0;
        if(file->type == QMakeSourceFileInfo::TYPE_UI) {
            // skip whitespaces
            while(x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t'))
                ++x;
            if(*(buffer + x) == '<') {
                ++x;
                if(buffer_len >= x + 12 && !strncmp(buffer + x, "includehint", 11) &&
                   (*(buffer + x + 11) == ' ' || *(buffer + x + 11) == '>')) {
                    for(x += 11; *(buffer + x) != '>'; ++x);
                    int inc_len = 0;
                    for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                    *(buffer + x + inc_len) = '\0';
                    inc = buffer + x;
                } else if(buffer_len >= x + 13 && !strncmp(buffer + x, "customwidget", 12) &&
                          (*(buffer + x + 12) == ' ' || *(buffer + x + 12) == '>')) {
                    for(x += 13; *(buffer + x) != '>'; ++x); //skip up to >
                    while(x < buffer_len) {
                        for(x++; *(buffer + x) != '<'; ++x); //skip up to <
                        x++;
                        if(buffer_len >= x + 7 && !strncmp(buffer+x, "header", 6) &&
                           (*(buffer + x + 6) == ' ' || *(buffer + x + 6) == '>')) {
                            for(x += 7; *(buffer + x) != '>'; ++x); //skip up to >
                            int inc_len = 0;
                            for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                            *(buffer + x + inc_len) = '\0';
                            inc = buffer + x;
                            break;
                        } else if(buffer_len >= x + 14 && !strncmp(buffer+x, "/customwidget", 13) &&
                                  (*(buffer + x + 13) == ' ' || *(buffer + x + 13) == '>')) {
                            x += 14;
                            break;
                        }
                    }
                } else if(buffer_len >= x + 8 && !strncmp(buffer + x, "include", 7) &&
                          (*(buffer + x + 7) == ' ' || *(buffer + x + 7) == '>')) {
                    for(x += 8; *(buffer + x) != '>'; ++x) {
                        if(buffer_len >= x + 9 && *(buffer + x) == 'i' &&
                           !strncmp(buffer + x, "impldecl", 8)) {
                            for(x += 8; *(buffer + x) != '='; ++x);
                            if(*(buffer + x) != '=')
                                continue;
                            for(++x; *(buffer+x) == '\t' || *(buffer+x) == ' '; ++x);
                            char quote = 0;
                            if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                                quote = *(buffer + x);
                                ++x;
                            }
                            int val_len;
                            for(val_len = 0; true; ++val_len) {
                                if(quote) {
                                    if(*(buffer+x+val_len) == quote)
                                        break;
                                } else if(*(buffer + x + val_len) == '>' ||
                                          *(buffer + x + val_len) == ' ') {
                                    break;
                                }
                            }
//?                            char saved = *(buffer + x + val_len);
                            *(buffer + x + val_len) = '\0';
                            if(!strcmp(buffer+x, "in implementation")) {
                                //### do this
                            }
                        }
                    }
                    int inc_len = 0;
                    for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len);
                    *(buffer + x + inc_len) = '\0';
                    inc = buffer + x;
                }
            }
            //read past new line now..
            for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x);
            ++line_count;
        } else if(file->type == QMakeSourceFileInfo::TYPE_QRC) {
        } else if(file->type == QMakeSourceFileInfo::TYPE_C) {
            for(int beginning=1; x < buffer_len; ++x) {
                // whitespace comments and line-endings
                for(; x < buffer_len; ++x) {
                    if(*(buffer+x) == ' ' || *(buffer+x) == '\t') {
                        // keep going
                    } else if(*(buffer+x) == '/') {
                        ++x;
                        if(buffer_len >= x) {
                            if(*(buffer+x) == '/') { //c++ style comment
                                for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x);
                                beginning = 1;
                            } else if(*(buffer+x) == '*') { //c style comment
                                for(++x; x < buffer_len; ++x) {
                                    if(*(buffer+x) == '*') {
                                        if(x < buffer_len-1 && *(buffer + (x+1)) == '/') {
                                            ++x;
                                            break;
                                        }
                                    } else if(qmake_endOfLine(*(buffer+x))) {
                                        ++line_count;
                                    }
                                }
                            }
                        }
                    } else if(qmake_endOfLine(*(buffer+x))) {
                        ++line_count;
                        beginning = 1;
                    } else {
                        break;
                    }
                }

                if(x >= buffer_len)
                    break;

                // preprocessor directive
                if(beginning && *(buffer+x) == '#')
                    break;

                // quoted strings
                if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                    const char term = *(buffer+(x++));
                    for(; x < buffer_len; ++x) {
                        if(*(buffer+x) == term) {
                            ++x;
                            break;
                        } else if(*(buffer+x) == '\\') {
                            ++x;
                        } else if(qmake_endOfLine(*(buffer+x))) {
                            ++line_count;
                        }
                    }
                }
                beginning = 0;
            }
            if(x >= buffer_len)
                break;

            //got a preprocessor symbol
            ++x;
            while(x < buffer_len) {
                if(*(buffer+x) != ' ' && *(buffer+x) != '\t')
                    break;
                ++x;
            }

            int keyword_len = 0;
            const char *keyword = buffer+x;
            while(x+keyword_len < buffer_len) {
                if(((*(buffer+x+keyword_len) < 'a' || *(buffer+x+keyword_len) > 'z')) &&
                   *(buffer+x+keyword_len) != '_') {
                    for(x+=keyword_len; //skip spaces after keyword
                        x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t');
                        x++);
                    break;
                } else if(qmake_endOfLine(*(buffer+x+keyword_len))) {
                    x += keyword_len-1;
                    keyword_len = 0;
                    break;
                }
                keyword_len++;
            }

            if(keyword_len == 7 && !strncmp(keyword, "include", keyword_len)) {
                char term = *(buffer + x);
                if(term == '<') {
                    try_local = false;
                    term = '>';
                } else if(term != '"') { //wtf?
                    continue;
                }
                x++;

                int inc_len;
                for(inc_len = 0; *(buffer + x + inc_len) != term && !qmake_endOfLine(*(buffer + x + inc_len)); ++inc_len);
                *(buffer + x + inc_len) = '\0';
                inc = buffer + x;
                x += inc_len;
            } else if(keyword_len == 13 && !strncmp(keyword, "qmake_warning", keyword_len)) {
                char term = 0;
                if(*(buffer + x) == '"')
                    term = '"';
                if(*(buffer + x) == '\'')
                    term = '\'';
                if(term)
                    x++;

                int msg_len;
                for(msg_len = 0; (term && *(buffer + x + msg_len) != term) &&
                              !qmake_endOfLine(*(buffer + x + msg_len)); ++msg_len);
                *(buffer + x + msg_len) = '\0';
                debug_msg(0, "%s:%d %s -- %s", file->file.local().toLatin1().constData(), line_count, keyword, buffer+x);
                x += msg_len;
            } else if(*(buffer+x) == '\'' || *(buffer+x) == '"') {
                const char term = *(buffer+(x++));
                while(x < buffer_len) {
                    if(*(buffer+x) == term)
                        break;
                    if(*(buffer+x) == '\\') {
                        x+=2;
                    } else {
                        if(qmake_endOfLine(*(buffer+x)))
                            ++line_count;
                        ++x;
                    }
                }
            } else {
                --x;
            }
        }

        if(inc) {
            if(!includes)
                includes = new SourceFiles;
            SourceFile *dep = includes->lookupFile(inc);
            if(!dep) {
                bool exists = false;
                QMakeLocalFileName lfn(inc);
                if(QDir::isRelativePath(lfn.real())) {
                    if(try_local) {
                        QDir sourceDir = findFileInfo(sourceFile).dir();
                        QMakeLocalFileName f(sourceDir.absoluteFilePath(lfn.local()));
                        if(findFileInfo(f).exists()) {
                            lfn = fixPathForFile(f);
                            exists = true;
                        }
                    }
                    if(!exists) { //path lookup
                        for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin(); it != depdirs.end(); ++it) {
                            QMakeLocalFileName f((*it).real() + Option::dir_sep + lfn.real());
                            QFileInfo fi(findFileInfo(f));
                            if(fi.exists() && !fi.isDir()) {
                                lfn = fixPathForFile(f);
                                exists = true;
                                break;
                            }
                        }
                    }
                    if(!exists) { //heuristic lookup
                        lfn = findFileForDep(QMakeLocalFileName(inc), file->file);
                        if((exists = !lfn.isNull()))
                            lfn = fixPathForFile(lfn);
                    }
                } else {
                    exists = QFile::exists(lfn.real());
                }
                if(!lfn.isNull()) {
                    dep = files->lookupFile(lfn);
                    if(!dep) {
                        dep = new SourceFile;
                        dep->file = lfn;
                        dep->type = QMakeSourceFileInfo::TYPE_C;
                        files->addFile(dep);
                        includes->addFile(dep, inc, false);
                    }
                    dep->exists = exists;
                }
            }
            if(dep && dep->file != file->file) {
                dep->included_count++;
                if(dep->exists) {
                    debug_msg(5, "%s:%d Found dependency to %s", file->file.real().toLatin1().constData(),
                              line_count, dep->file.local().toLatin1().constData());
                    file->deps->addChild(dep);
                }
            }
        }
    }
    if(dependencyMode() == Recursive) { //done last because buffer is shared
        for(int i = 0; i < file->deps->used_nodes; i++) {
            if(!file->deps->children[i]->deps)
                findDeps(file->deps->children[i]);
        }
    }
    return true;
}
コード例 #25
0
QStringList KStandardDirs::resourceDirs(const char *type) const
{
    QStringList *candidates = dircache.find(type);

    if(!candidates)
    { // filling cache
        if(strcmp(type, "socket") == 0)
            const_cast< KStandardDirs * >(this)->createSpecialResource(type);
        else if(strcmp(type, "tmp") == 0)
            const_cast< KStandardDirs * >(this)->createSpecialResource(type);
        else if(strcmp(type, "cache") == 0)
            const_cast< KStandardDirs * >(this)->createSpecialResource(type);

        QDir testdir;

        candidates = new QStringList();
        QStringList *dirs;

        bool restrictionActive = false;
        if(d && d->restrictionsActive)
        {
            if(d->dataRestrictionActive)
                restrictionActive = true;
            else if(d->restrictions["all"])
                restrictionActive = true;
            else if(d->restrictions[type])
                restrictionActive = true;
            d->dataRestrictionActive = false; // Reset
        }

        dirs = relatives.find(type);
        if(dirs)
        {
            bool local = true;
            const QStringList *prefixList = 0;
            if(strncmp(type, "xdgdata-", 8) == 0)
                prefixList = &(d->xdgdata_prefixes);
            else if(strncmp(type, "xdgconf-", 8) == 0)
                prefixList = &(d->xdgconf_prefixes);
            else
                prefixList = &prefixes;

            for(QStringList::ConstIterator pit = prefixList->begin(); pit != prefixList->end(); ++pit)
            {
                for(QStringList::ConstIterator it = dirs->begin(); it != dirs->end(); ++it)
                {
                    QString path = realPath(*pit + *it);
                    testdir.setPath(path);
                    if(local && restrictionActive)
                        continue;
                    if((local || testdir.exists()) && !candidates->contains(path))
                        candidates->append(path);
                }
                local = false;
            }
        }
        dirs = absolutes.find(type);
        if(dirs)
            for(QStringList::ConstIterator it = dirs->begin(); it != dirs->end(); ++it)
            {
                testdir.setPath(*it);
                if(testdir.exists())
                {
                    QString filename = realPath(*it);
                    if(!candidates->contains(filename))
                        candidates->append(filename);
                }
            }
        dircache.insert(type, candidates);
    }

#if 0
    kdDebug() << "found dirs for resource " << type << ":" << endl;
    for (QStringList::ConstIterator pit = candidates->begin();
	 pit != candidates->end();
	 pit++)
    {
	fprintf(stderr, "%s\n", (*pit).latin1());
    }
#endif


    return *candidates;
}
コード例 #26
0
ファイル: FileEnum.cpp プロジェクト: frispete/mp3diags
string DirTreeEnumerator::DirTreeEnumeratorImpl::next() // returns an empty string if there's nothing next
{
    if (-1 == m_nCrtDirNdx)
    {
        m_nCrtDirNdx = 0;
        m_vstrCrtDirList.clear();

        set<string> sstrNewProc;
        m_sstrWaitingDirs.clear();
        m_sstrProcDirs = m_sstrIncludeDirs; // !!! needed for hasAncestorInProcDirs()

        for (set<string>::iterator it = m_sstrIncludeDirs.begin(), end = m_sstrIncludeDirs.end(); it != end; ++it)
        {
            if (!hasAncestorInProcDirs(*it))
            {
                sstrNewProc.insert(*it);
            }
            else
            {
                m_sstrWaitingDirs.insert(*it);
            }
        }

        m_sstrProcDirs.swap(sstrNewProc);
    }

    for (;;)
    {
        if (m_nCrtDirNdx < cSize(m_vstrCrtDirList))
        {
            return m_vstrCrtDirList[m_nCrtDirNdx++];
        }

        if (m_sstrProcDirs.empty())
        {
            if (m_sstrWaitingDirs.empty()) {
                return "";
            }
            set<string> sstrNewProc, sstrNewWt;
            m_sstrProcDirs = m_sstrWaitingDirs; // !!! needed for hasAncestorInProcDirs()

            for (set<string>::iterator it = m_sstrWaitingDirs.begin(), end = m_sstrWaitingDirs.end(); it != end; ++it)
            {
                if (!hasAncestorInProcDirs(*it))
                {
                    sstrNewProc.insert(*it);
                }
                else
                {
                    sstrNewWt.insert(*it);
                }
            }

            sstrNewWt.swap(m_sstrWaitingDirs);
            sstrNewProc.swap(m_sstrProcDirs);
        }

        m_vstrCrtDirList.clear();
        m_nCrtDirNdx = 0;
        m_strCrtDir = *m_sstrProcDirs.begin();
        m_sstrProcDirs.erase(m_sstrProcDirs.begin());

        for (set<string>::iterator it = m_sstrWaitingDirs.begin(), end = m_sstrWaitingDirs.end(); it != end; ++it)
        {
            if (!hasAncestorInProcDirs(*it))
            {
                m_sstrWaitingDirs.insert(*it);
            }
        }

        QDir dir (convStr(m_strCrtDir));

        QFileInfoList lst (dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot));
        for (QFileInfoList::iterator it = lst.begin(), end = lst.end(); it != end; ++it)
        {
            const QFileInfo& inf (*it);
            string s (convStr(inf.fileName()));

            s = m_strCrtDir + s;
            // !!! note that inf.isSymLink() may return true in addition to isFile() or isDir() returning true, so no "special case" processing is needed unless we want to exclude symlinks
            if (inf.isFile())
            {
                m_vstrCrtDirList.push_back(s);
            }
            else if (inf.isDir())
            {
                if (!endsWith(s, "/")) {
                    s += "/";
                }
                if (0 == m_sstrExcludeDirs.count(s))
                {
                    m_sstrProcDirs.insert(s);
                }
            }
        }
    }
}
コード例 #27
0
ファイル: qfileinfo.cpp プロジェクト: RSATom/Qt
/*!
    Constructs a new QFileInfo that gives information about the given
    \a file in the directory \a dir.

    If \a dir has a relative path, the QFileInfo will also have a
    relative path.

    If \a file is an absolute path, then the directory specified
    by \a dir will be disregarded.

    \sa isRelative()
*/
QFileInfo::QFileInfo(const QDir &dir, const QString &file)
    : d_ptr(new QFileInfoPrivate(dir.filePath(file)))
{
}
コード例 #28
0
ファイル: misc.cpp プロジェクト: cyclothunder/isoMultiCreator
hardDisk *Misc::get_HardDrivesInfo()
{

    QStringList deviceInfo;
    QDir dirs;
    QString item;

    foreach (const QFileInfo drivesList, dirs.drives()){
        qDebug() << "Drive List: " << drivesList.absolutePath();
    }

    int i=0;

    foreach (const QStorageInfo &deviceList, QStorageInfo::mountedVolumes()){
           if (deviceList.isValid() && deviceList.isReady()) {
               if (!deviceList.isReadOnly()) {
                   i++;
               }
           }
    }
     hddListCounter = i;
     hardDisk* hardDiskStruc = new hardDisk[i];

    i=0;
    foreach (const QStorageInfo &deviceList, QStorageInfo::mountedVolumes()){
           if (deviceList.isValid() && deviceList.isReady()) {
               if (!deviceList.isReadOnly()) {

                   QString itemDisplayNameFix;
                   // deviceName << deviceList.device();
                   itemDisplayNameFix = deviceList.displayName();
                   itemDisplayNameFix.replace("\\x20", " ");
                   item.append("Label: " + itemDisplayNameFix + "\n");
                   item.append("Device: " + deviceList.device() + "\n");

                   qint64 total_diskSize = deviceList.bytesTotal();
                   qint64 total_diskSize_temp = 0;

                   while (total_diskSize >= 1024) {
                       total_diskSize_temp = total_diskSize/1024;
                       total_diskSize = total_diskSize_temp;
                   }

                   item.append("Total: " + QString::number(total_diskSize) + " Gb" + "\n"); // Convert to Gb

                   qint64 free_diskSize = deviceList.bytesFree();
                   qint64 free_diskSize_temp = 0;

                   while (free_diskSize >= 1024) {
                       free_diskSize_temp = free_diskSize/1024;
                       free_diskSize = free_diskSize_temp;
                   }

                   item.append("Free: " + QString::number(free_diskSize) + " Gb" + "\n"); // Convert to Gb
                   item.append("State: Ready\n\n");
                   deviceInfo << item;

                   hardDiskStruc[i].label = itemDisplayNameFix;
                   hardDiskStruc[i].device = deviceList.device();
                   hardDiskStruc[i].totalBytes = QString::number(total_diskSize);
                   hardDiskStruc[i].freeBytes = QString::number(free_diskSize);
                   hardDiskStruc[i].state = "Ready";
                   ++i;
             }
          }
     }

    for (int var = 0; var < i; var++) {
        qDebug() << "Label -" << hardDiskStruc[var].label;
        qDebug() << "Device -" << hardDiskStruc[var].device;
        qDebug() << "Total -" << hardDiskStruc[var].totalBytes << "Gb";
        qDebug() << "Free -" << hardDiskStruc[var].freeBytes << "Gb";
        qDebug() << "State -" << hardDiskStruc[var].state;
        qDebug() << "------ empty line ------";

    }

    return hardDiskStruc;
}
コード例 #29
0
void GrabberSettings::Load(void)
{
    QString busymessage = tr("Searching for data sources...");
    MythScreenStack *popupStack = GetMythMainWindow()->GetStack("popup stack");
    MythUIBusyDialog *busyPopup = new MythUIBusyDialog(busymessage, popupStack,
                                                       "grabberbusydialog");

    if (busyPopup->Create())
    {
        popupStack->AddScreen(busyPopup, false);
    }
    else
    {
        delete busyPopup;
        busyPopup = NULL;
    }

    QDir TVScriptPath = QString("%1metadata/Television/").arg(GetShareDir());
    QStringList TVScripts = TVScriptPath.entryList(QDir::Files);
    QDir MovieScriptPath = QString("%1metadata/Movie/").arg(GetShareDir());
    QStringList MovieScripts = MovieScriptPath.entryList(QDir::Files);
    QDir GameScriptPath = QString("%1metadata/Game/").arg(GetShareDir());
    QStringList GameScripts = GameScriptPath.entryList(QDir::Files);

    if (MovieScripts.count())
    {
        for (QStringList::const_iterator i = MovieScripts.begin();
             i != MovieScripts.end(); ++i)
        {
            QString commandline = QString("%1/%2")
                                      .arg(MovieScriptPath.path()).arg(*i);
            MythSystem grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut | kMSBuffered);
            grabber.Run();
            grabber.Wait();
            QByteArray result = grabber.ReadAll();

            if (!result.isEmpty())
            {
                QDomDocument doc;
                doc.setContent(result, true);
                QDomElement root = doc.documentElement();
                if (!root.isNull())
                {
                    MetaGrabberScript *script = ParseGrabberVersion(root);
                    if (!script->GetName().isEmpty())
                        m_movieGrabberList.append(script);
                }
            }
        }
    }

    if (TVScripts.count())
    {
        for (QStringList::const_iterator i = TVScripts.end() - 1;
                i != TVScripts.begin() - 1; --i)
        {
            QString commandline = QString("%1/%2")
                                      .arg(TVScriptPath.path()).arg(*i);
            MythSystem grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut | kMSBuffered);
            grabber.Run();
            grabber.Wait();
            QByteArray result = grabber.ReadAll();

            if (!result.isEmpty())
            {
                QDomDocument doc;
                doc.setContent(result, true);
                QDomElement root = doc.documentElement();
                if (!root.isNull())
                {
                    MetaGrabberScript *script = ParseGrabberVersion(root);
                    if (!script->GetName().isEmpty())
                        m_tvGrabberList.append(script);

                }
            }
        }
    }

    if (GameScripts.count())
    {
        for (QStringList::const_iterator i = GameScripts.end() - 1;
                i != GameScripts.begin() - 1; --i)
        {
            QString commandline = QString("%1/%2")
                                      .arg(GameScriptPath.path()).arg(*i);
            MythSystem grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut | kMSBuffered);
            grabber.Run();
            grabber.Wait();
            QByteArray result = grabber.ReadAll();

            if (!result.isEmpty())
            {
                QDomDocument doc;
                doc.setContent(result, true);
                QDomElement root = doc.documentElement();
                if (!root.isNull())
                {
                    MetaGrabberScript *script = ParseGrabberVersion(root);
                    if (!script->GetName().isEmpty())
                        m_gameGrabberList.append(script);
                }
            }
        }
    }

    if (busyPopup)
    {
        busyPopup->Close();
        busyPopup = NULL;
    }
}
コード例 #30
0
ファイル: LPMain.cpp プロジェクト: cthunter01/pcbsd
LPMain::LPMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::LPMain){
  ui->setupUi(this); //load the Qt-designer UI file
  //Initialize the auto-refresh timer
  timer = new QTimer(this);
	timer->setSingleShot(true);
	timer->setInterval(60000); // 1 minute timer
	connect(timer, SIGNAL(timeout()), this, SLOT(updateTabs()) );
  //Initialize the system watcher
  watcher = new QFileSystemWatcher(this);
    //Make sure the lpreserver log directory exists and watch it
    if(!QFile::exists("/var/log/lpreserver")){
      qDebug() << "Creating the lpreserver log directory (/var/log/lpreserver)";
      QDir dir;
      dir.mkpath("/var/log/lpreserver");
    }
    watcher->addPath("/var/log/lpreserver/");
  WorkThread = new QThread();
  WORKER = new BackgroundWorker();
    WORKER->moveToThread(WorkThread);
    connect(this, SIGNAL(loadSnaps(LPDataset*)), WORKER, SLOT(loadSnapshotInfo(LPDataset*)) );
    WorkThread->start();
  //Initialize the waitbox pointer
  waitBox = 0;
  //Initialize the classic dialog pointer
  classicDLG = 0;
  //Create the basic/advanced view options
  viewBasic = new QRadioButton(tr("Basic"), ui->menuView);
	QWidgetAction *WABasic = new QWidgetAction(this); WABasic->setDefaultWidget(viewBasic);
	ui->menuView->addAction(WABasic);
  viewAdvanced = new QRadioButton(tr("Advanced"), ui->menuView);
	QWidgetAction *WAAdv = new QWidgetAction(this); WAAdv->setDefaultWidget(viewAdvanced);
	ui->menuView->addAction(WAAdv);
  connect(viewBasic, SIGNAL(toggled(bool)), this, SLOT(viewChanged()) );
  //Now set the default view type
  settings = new QSettings(QSettings::UserScope, "PC-BSD", "Life-Preserver-GUI", this);
  bool basicMode = settings->value("viewmode", true).toBool(); //basic by default
  if(basicMode){ viewBasic->setChecked(true); } //will automatically call the "viewChanged" function
  else{ viewAdvanced->setChecked(true); } //will automatically call the "viewChanged" function
  //Create the filesystem model and tie it to the treewidget
  fsModel = new QFileSystemModel(this);
	fsModel->setReadOnly(true);
	ui->treeView->setModel(fsModel);
  //Connect the UI to all the functions
  connect(ui->tool_refresh, SIGNAL(clicked()), this, SLOT(updatePoolList()) );
  connect(ui->combo_pools, SIGNAL(currentIndexChanged(int)), this, SLOT(updateTabs()) );
  connect(ui->combo_datasets, SIGNAL(currentIndexChanged(int)), this, SLOT(updateDataset()) );
  connect(ui->slider_snapshots, SIGNAL(valueChanged(int)), this, SLOT(updateSnapshot()) );
  connect(ui->push_prevsnap, SIGNAL(clicked()), this, SLOT(prevSnapshot()) );
  connect(ui->push_nextsnap, SIGNAL(clicked()), this, SLOT(nextSnapshot()) );
  connect(ui->check_hidden, SIGNAL(stateChanged(int)), this, SLOT(setFileVisibility()) );
  connect(ui->push_restore, SIGNAL(clicked()), this, SLOT(restoreFiles()) );
  connect(ui->push_configure, SIGNAL(clicked()), this, SLOT(openConfigGUI()) );
  //Connect the Menu buttons
  connect(ui->menuManage_Pool, SIGNAL(triggered(QAction*)), this, SLOT(menuAddPool(QAction*)) );
  connect(ui->menuUnmanage_Pool, SIGNAL(triggered(QAction*)), this, SLOT(menuRemovePool(QAction*)) );
  connect(ui->menuEnable_Offsite_Backups, SIGNAL(triggered(QAction*)), this, SLOT(menuSetupISCSI(QAction*)) );
  connect(ui->action_SaveKeyToUSB, SIGNAL(triggered()), this, SLOT(menuSaveSSHKey()) );
  connect(ui->actionClose_Window, SIGNAL(triggered()), this, SLOT(menuCloseWindow()) );
  connect(ui->menuCompress_Home_Dir, SIGNAL(triggered(QAction*)), this, SLOT(menuCompressHomeDir(QAction*)) );
  connect(ui->actionExtract_Home_Dir, SIGNAL(triggered()), this, SLOT(menuExtractHomeDir()) );
  connect(ui->actionAdd_Disk, SIGNAL(triggered()), this, SLOT(menuAddDisk()) );
  connect(ui->menuRemove_Disk, SIGNAL(triggered(QAction*)), this, SLOT(menuRemoveDisk(QAction*)) );
  connect(ui->menuSet_Disk_Offline, SIGNAL(triggered(QAction*)), this, SLOT(menuOfflineDisk(QAction*)) );
  connect(ui->menuSet_Disk_Online, SIGNAL(triggered(QAction*)), this, SLOT(menuOnlineDisk(QAction*)) );
  connect(ui->action_startScrub, SIGNAL(triggered()), this, SLOT(menuStartScrub()) );
  connect(ui->action_stopScrub, SIGNAL(triggered()), this, SLOT(menuStopScrub()) );
  connect(ui->action_newSnapshot, SIGNAL(triggered()), this, SLOT(menuNewSnapshot()) );
  connect(ui->menuDelete_Snapshot, SIGNAL(triggered(QAction*)), this, SLOT(menuRemoveSnapshot(QAction*)) );
  connect(ui->menuStart_Replication, SIGNAL(triggered(QAction*)), this, SLOT(menuStartReplication(QAction*)) );
  connect(ui->menuInit_Replications, SIGNAL(triggered(QAction*)), this, SLOT(menuInitReplication(QAction*)) );
  //Update the interface
  QTimer::singleShot(0,this,SLOT(updatePoolList()) );
  
  //Make sure the status tab is shown initially
  ui->tabWidget->setCurrentWidget(ui->tab_status);
  //Now connect the watcher to the update slot
  connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(autoRefresh()) );
  //Connect the worker process to the update routine
  connect(WORKER, SIGNAL(SnapshotsLoaded()), this, SLOT(updateSnapshots()) );
}