Beispiel #1
0
void DataInput::start()
{
    QNetworkRequest nr;
    QString url;
    //qDebug() << "DataInput:start:"<<type<<":"<<input->arg1();

    if( type == "ifttt" ) {
        // url = "http://api.thingm.com/blink1/eventsall/" + iftttKey;
        url = "http://feed.thingm.com/blink1/eventsall/" + iftttKey;
        //url = "http://localhost:3232/blink1/eventsall/" + iftttKey;
        nr.setUrl(QUrl(url));
        reply = networkManager->get(nr);
        connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError()));
    }
    else if( type == "url" ) { 
        url = input->arg1();
        //qDebug() << "datainput:start url: "<<url; 
        if(!url.startsWith("http://") && !url.startsWith("https://"))
            url="http://"+url;
        QUrl correctUrl(url);
        if(correctUrl.isValid()) {
            nr.setUrl(QUrl(url));
            reply = networkManager->get(nr);
            connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));
            connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError()));
        }
        else {
            input->setArg2("Bad URL");
            input->setDate(-1);  // FIXME: don't like -1 here
            emit toDelete(this);
        }
    }
    else if( type == "file" ) { 
        QFileInfo fileInfo;
        fileInfo.setFile(input->arg1());
        if( !fileInfo.exists() ) {
            qDebug() << "datainput:start: no file";
            input->setArg2("Not Found");
            input->setDate(-1);
        }
        else { 
            int lastModTime = fileInfo.lastModified().toTime_t(); // why was cast to uint?
            if( lastModTime > input->date()) {
                qDebug() << "datainput:start: file newer";
                QFile f(input->arg1());
                if(!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
                    input->setArg2("Couldn't Open");
                    input->setDate(-1);  // FIXME: why -1? what does it mean?
                    emit toDelete(this);
                    return;
                }
                input->setDate( lastModTime); //fileInfo.lastModified().toTime_t());
                QString txt = "";
                QTextStream in(&f);
                txt.append(in.readAll());

                bool good = parsePatternOrColor( txt, type, lastModTime );
                if( !good ) { 
                    input->setArg2("Bad Parse");
                }
            } // last modified
            else { 
                //input->setArg2("Old File");  // FIXME: should do something to indicate older file
                //input->setDate(-1);
            }
        }
        emit toDelete(this);
    }
    else if( type == "script" ) { 
        //QString path = QStandardPaths::locate(QStandardPaths::DocumentsLocation, input->arg1());
        QFileInfo fileInfo;
        fileInfo.setFile( input->arg1() );
        if( !fileInfo.exists() ) {
            input->setArg2("Not Found");
            input->setDate(-1);
            emit toDelete(this);
        } 
        else if( !fileInfo.isExecutable() ) { 
            input->setArg2("Not Executable");
            input->setDate(-1);
            emit toDelete(this);
        }
        else { 
            // FIXME: should check new value compare to lastVal
            // (and FIXME: need to refactor to properly use lastVal for all monitor types)
            //if(fileInfo.lastModified().toTime_t() != (uint)input->date()){
            // no, don't do lastModTime check on exec file, jeez
            input->setDate(fileInfo.lastModified().toTime_t());
            process = new QProcess;
            connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(onProcessOutput()));
            connect(process, SIGNAL(readyReadStandardError()), this, SLOT(onError()));
            connect(process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError()));
            connect(process, SIGNAL(finished(int)), this, SLOT(onProcessFinished()));
            // start process running
            process->start( fileInfo.canonicalFilePath() );
        }
    }
Beispiel #2
0
void loadSession(DocEngine* docEngine, TopEditorContainer* editorContainer, QString sessionPath)
{
    QFile file(sessionPath);
    file.open(QIODevice::ReadOnly);

    if (!file.isOpen())
        return;

    SessionReader reader(file);

    bool success = false;
    const auto& views = reader.readData(&success);

    if (!success || views.empty()) {
        return;
    }

    int viewCounter = 0;
    for (const auto& view : views) {
        // Each new view must be created if it does not yet exist.
        EditorTabWidget* tabW = editorContainer->tabWidget(viewCounter);
        int activeIndex = 0;

        if (!tabW)
            tabW = editorContainer->addTabWidget();

        viewCounter++;

        for (const TabData& tab : view.tabs) {
            const QFileInfo fileInfo(tab.filePath);
            const bool fileExists = fileInfo.exists();
            const bool cacheFileExists = QFileInfo(tab.cacheFilePath).exists();

            const QUrl fileUrl = QUrl::fromLocalFile(tab.filePath);
            const QUrl cacheFileUrl = QUrl::fromLocalFile(tab.cacheFilePath);

            // This is the file to load the document from
            const QUrl& loadUrl = cacheFileExists ? cacheFileUrl : fileUrl;

            const bool success = docEngine->loadDocumentSilent(loadUrl, tabW);

            if (!success)
                continue;

            int idx = tabW->findOpenEditorByUrl(loadUrl);

            if (idx == -1)
                continue;

            // DocEngine sets the editor's fileName to loadUrl since this is where the file
            // was loaded from. Since loadUrl could point to a cached file we reset it here.
            Editor* editor = tabW->editor(idx);

            if (cacheFileExists) {
                editor->markDirty();
                editor->setLanguageFromFileName();
                // Since we loaded from cache we want to unmonitor the cache file.
                docEngine->unmonitorDocument(editor);
            }

            if (fileExists) {
                editor->setFileName(fileUrl);
                docEngine->monitorDocument(editor);
            } else {
                editor->setFileName(QUrl());
                tabW->setTabText(idx, docEngine->getNewDocumentName());
            }

            // If we're loading an existing file from cache we want to inform the user whether
            // the file has changed since Nqq was last closed. For this we can compare the
            // file's last modification date.
            if (fileExists && cacheFileExists && tab.lastModified != 0) {
                auto lastModified = fileInfo.lastModified().toMSecsSinceEpoch();

                if (lastModified > tab.lastModified) {
                    editor->setFileOnDiskChanged(true);
                }
            }

            // If the orig. file does not exist but *should* exist, we inform the user of its removal.
            if (!fileExists && !fileUrl.isEmpty()) {
                editor->setFileOnDiskChanged(true);
                emit docEngine->fileOnDiskChanged(tabW, idx, true);
            }


            if(tab.active) activeIndex = idx;

            if(!tab.language.isEmpty()) editor->setLanguage(tab.language);

            editor->setScrollPosition(tab.scrollX, tab.scrollY);
            editor->clearFocus();

        } // end for

        tabW->clearFocus();

        // In case a new tabwidget was created but no tabs were actually added to it,
        // we'll attempt to re-use the widget for the next view.
        if (tabW->count() == 0)
            viewCounter--;
        else // Otherwise we finish by making the right tab the currently open one.
            tabW->setCurrentIndex(activeIndex);

    } // end for

    // Stop if we haven't added any views at all, otherwise we have to clean up after ourselves.
    if (viewCounter <= 0)
        return;

    // If the last tabwidget still has no tabs in it at this point, we'll have to delete it.
    EditorTabWidget* lastTabW = editorContainer->tabWidget( editorContainer->count() -1);
    lastTabW->deleteIfEmpty();

    // Give focus to the last tab of the first tab widget.
    EditorTabWidget* firstTabW = editorContainer->tabWidget(0);
    Editor* lastEditor = firstTabW->editor(firstTabW->count()-1);
    lastEditor->setFocus();

    // This triggers `TopEditorContainer::on_currentTabChanged` and eventually
    // `MainWindow::on_currentEditorChanged` which calls refreshEditorUiInfo() to
    // get rid of the titlebar display bug when loading files from cache.
    firstTabW->currentChanged(firstTabW->count()-1);

    return;
}
Beispiel #3
0
void dibSHP::procesFile(Document_Interface *doc)
{
    int num_ent, st;
    double min_bound[4], max_bound[4];

    currDoc = doc;

    QFileInfo fi = QFileInfo(fileedit->text());
    if (fi.suffix() != "shp") {
        QMessageBox::critical ( this, "Shapefile", QString(tr("The file %1 not have extension .shp")).arg(fileedit->text()) );
        return;
    }

    if (!fi.exists() ) {
        QMessageBox::critical ( this, "Shapefile", QString(tr("The file %1 not exist")).arg(fileedit->text()) );
        return;
    }

    QString file = fi.canonicalFilePath ();

    SHPHandle sh = SHPOpen( file.toLocal8Bit(), "rb" );
    SHPGetInfo( sh, &num_ent, &st, min_bound, max_bound );
    DBFHandle dh = DBFOpen( file.toLocal8Bit(), "rb" );

    if (radiolay1->isChecked()) {
        layerF = -1;
        attdata.layer = currDoc->getCurrentLayer();
    } else {
        layerF = DBFGetFieldIndex( dh, (layerdata->currentText()).toLatin1().data() );
        layerT = DBFGetFieldInfo( dh, layerF, NULL, NULL, NULL );
    }
    if (radiocol1->isChecked())
        colorF = -1;
    else {
        colorF = DBFGetFieldIndex( dh, (colordata->currentText()).toLatin1().data() );
        colorT = DBFGetFieldInfo( dh, colorF, NULL, NULL, NULL );
    }
    if (radioltype1->isChecked())
        ltypeF = -1;
    else {
        ltypeF = DBFGetFieldIndex( dh, (ltypedata->currentText()).toLatin1().data() );
        ltypeT = DBFGetFieldInfo( dh, ltypeF, NULL, NULL, NULL );
    }
    if (radiolwidth1->isChecked())
        lwidthF = -1;
    else {
        lwidthF = DBFGetFieldIndex( dh, (lwidthdata->currentText()).toLatin1().data() );
        lwidthT = DBFGetFieldInfo( dh, lwidthF, NULL, NULL, NULL );
    }
    if (radiopoint1->isChecked())
        pointF = -1;
    else {
        pointF = DBFGetFieldIndex( dh, (pointdata->currentText()).toLatin1().data() );
        pointT = DBFGetFieldInfo( dh, pointF, NULL, NULL, NULL );
    }

    currlayer =currDoc->getCurrentLayer();
    for( int i = 0; i < num_ent; i++ ) {
        sobject= NULL;
        sobject = SHPReadObject( sh, i );
        if (sobject) {
            switch (sobject->nSHPType) {
            case SHPT_NULL:
                break;
            case SHPT_POINT:
            case SHPT_POINTM: //2d point with measure
            case SHPT_POINTZ: //3d point
                readPoint(dh, i);
                break;
            case SHPT_MULTIPOINT:
            case SHPT_MULTIPOINTM:
            case SHPT_MULTIPOINTZ:
                break;
            case SHPT_ARC:
            case SHPT_ARCM:
            case SHPT_ARCZ:
                readPolyline(dh, i);
                break;
            case SHPT_POLYGON:
            case SHPT_POLYGONM:
            case SHPT_POLYGONZ:
                readPolylineC(dh, i);
            case SHPT_MULTIPATCH:
                readMultiPolyline(dh, i);
            default:
                break;
            }
            SHPDestroyObject(sobject);
        }
    }

    SHPClose( sh );
    DBFClose( dh );
    currDoc->setLayer(currlayer);
}
Beispiel #4
0
bool QgsServer::init()
{
  if ( sInitialized )
  {
    return false;
  }

  QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
  QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
  QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME );

  QgsApplication::init();

#if defined(SERVER_SKIP_ECW)
  QgsMessageLog::logMessage( "Skipping GDAL ECW drivers in server.", "Server", Qgis::Info );
  QgsApplication::skipGdalDriver( "ECW" );
  QgsApplication::skipGdalDriver( "JP2ECW" );
#endif

  // reload settings to take into account QCoreApplication and QgsApplication
  // configuration
  sSettings.load();

  // init and configure logger
  QgsServerLogger::instance();
  QgsServerLogger::instance()->setLogLevel( sSettings.logLevel() );
  if ( ! sSettings.logFile().isEmpty() )
  {
    QgsServerLogger::instance()->setLogFile( sSettings.logFile() );
  }
  else if ( sSettings.logStderr() )
  {
    QgsServerLogger::instance()->setLogStderr();
  }

  // log settings currently used
  sSettings.logSummary();

  setupNetworkAccessManager();
  QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );

  // Instantiate the plugin directory so that providers are loaded
  QgsProviderRegistry::instance( QgsApplication::pluginPath() );
  QgsMessageLog::logMessage( "Prefix  PATH: " + QgsApplication::prefixPath(), QStringLiteral( "Server" ), Qgis::Info );
  QgsMessageLog::logMessage( "Plugin  PATH: " + QgsApplication::pluginPath(), QStringLiteral( "Server" ), Qgis::Info );
  QgsMessageLog::logMessage( "PkgData PATH: " + QgsApplication::pkgDataPath(), QStringLiteral( "Server" ), Qgis::Info );
  QgsMessageLog::logMessage( "User DB PATH: " + QgsApplication::qgisUserDatabaseFilePath(), QStringLiteral( "Server" ), Qgis::Info );
  QgsMessageLog::logMessage( "Auth DB PATH: " + QgsApplication::qgisAuthDatabaseFilePath(), QStringLiteral( "Server" ), Qgis::Info );
  QgsMessageLog::logMessage( "SVG PATHS: " + QgsApplication::svgPaths().join( QDir::separator() ), QStringLiteral( "Server" ), Qgis::Info );

  QgsApplication::createDatabase(); //init qgis.db (e.g. necessary for user crs)

  // Initialize the authentication system
  //   creates or uses qgis-auth.db in ~/.qgis3/ or directory defined by QGIS_AUTH_DB_DIR_PATH env variable
  //   set the master password as first line of file defined by QGIS_AUTH_PASSWORD_FILE env variable
  //   (QGIS_AUTH_PASSWORD_FILE variable removed from environment after accessing)
  QgsApplication::authManager()->init( QgsApplication::pluginPath(), QgsApplication::qgisAuthDatabaseFilePath() );

  QString defaultConfigFilePath;
  QFileInfo projectFileInfo = defaultProjectFile(); //try to find a .qgs/.qgz file in the server directory
  if ( projectFileInfo.exists() )
  {
    defaultConfigFilePath = projectFileInfo.absoluteFilePath();
    QgsMessageLog::logMessage( "Using default project file: " + defaultConfigFilePath, QStringLiteral( "Server" ), Qgis::Info );
  }
  else
  {
    QFileInfo adminSLDFileInfo = defaultAdminSLD();
    if ( adminSLDFileInfo.exists() )
    {
      defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
    }
  }
  // Store the config file path
  sConfigFilePath = new QString( defaultConfigFilePath );

  //create cache for capabilities XML
  sCapabilitiesCache = new QgsCapabilitiesCache();

#ifdef ENABLE_MS_TESTS
  QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Roman" ) << QStringLiteral( "Bold" ) );
#endif

  sServiceRegistry = new QgsServiceRegistry();

  sServerInterface = new QgsServerInterfaceImpl( sCapabilitiesCache, sServiceRegistry, &sSettings );

  // Load service module
  QString modulePath = QgsApplication::libexecPath() + "server";
  qDebug() << "Initializing server modules from " << modulePath << endl;
  sServiceRegistry->init( modulePath,  sServerInterface );

  sInitialized = true;
  QgsMessageLog::logMessage( QStringLiteral( "Server initialized" ), QStringLiteral( "Server" ), Qgis::Info );
  return true;
}
Beispiel #5
0
StrainPipeData::StrainPipeData(const QFileInfo &directory)
    : QTextDocument(), directory(directory), base_dir(directory.absoluteFilePath())
{
    if (directory.exists()) init();
}
bool QFileSystemIteratorPrivate::matchesFilters(const QAbstractFileEngineIterator *it) const
{
    const bool filterPermissions = ((filters & QDir::PermissionMask)
                                    && (filters & QDir::PermissionMask) != QDir::PermissionMask);
    const bool skipDirs     = !(filters & (QDir::Dirs | QDir::AllDirs));
    const bool skipFiles    = !(filters & QDir::Files);
    const bool skipSymlinks = (filters & QDir::NoSymLinks);
    const bool doReadable   = !filterPermissions || (filters & QDir::Readable);
    const bool doWritable   = !filterPermissions || (filters & QDir::Writable);
    const bool doExecutable = !filterPermissions || (filters & QDir::Executable);
    const bool includeHidden = (filters & QDir::Hidden);
    const bool includeSystem = (filters & QDir::System);

#ifndef QT_NO_REGEXP
    // Prepare name filters
    QList<QRegExp> regexps;
    bool hasNameFilters = !nameFilters.isEmpty() && !(nameFilters.contains(QLatin1String("*")));
    if (hasNameFilters) {
        for (int i = 0; i < nameFilters.size(); ++i) {
            regexps << QRegExp(nameFilters.at(i),
                               (filters & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive,
                               QRegExp::Wildcard);
        }
    }
#endif

    QString fileName = it->currentFileName();
    if (fileName.isEmpty()) {
        // invalid entry
        return false;
    }

    QFileInfo fi = it->currentFileInfo();
    QString filePath = it->currentFilePath();

#ifndef QT_NO_REGEXP
    // Pass all entries through name filters, except dirs if the AllDirs
    // filter is passed.
    if (hasNameFilters && !((filters & QDir::AllDirs) && fi.isDir())) {
        bool matched = false;
        for (int i = 0; i < regexps.size(); ++i) {
            if (regexps.at(i).exactMatch(fileName)) {
                matched = true;
                break;
            }
        }
        if (!matched)
            return false;
    }
#endif

    bool dotOrDotDot = (fileName == QLatin1String(".") || fileName == QLatin1String(".."));
    if ((filters & QDir::NoDotAndDotDot) && dotOrDotDot)
        return false;

    bool isHidden = !dotOrDotDot && fi.isHidden();
    if (!includeHidden && isHidden)
        return false;

    bool isSystem = (!fi.isFile() && !fi.isDir() && !fi.isSymLink())
                    || (!fi.exists() && fi.isSymLink());
    if (!includeSystem && isSystem)
        return false;

    bool alwaysShow = (filters & QDir::TypeMask) == 0
        && ((isHidden && includeHidden)
            || (includeSystem && isSystem));

    // Skip files and directories
    if ((filters & QDir::AllDirs) == 0 && skipDirs && fi.isDir()) {
        if (!alwaysShow)
            return false;
    }

    if ((skipFiles && (fi.isFile() || !fi.exists()))
        || (skipSymlinks && fi.isSymLink())) {
        if (!alwaysShow)
            return false;
    }

    if (filterPermissions
        && ((doReadable && !fi.isReadable())
            || (doWritable && !fi.isWritable())
            || (doExecutable && !fi.isExecutable()))) {
        return false;
    }

    if (!includeSystem && !dotOrDotDot && ((fi.exists() && !fi.isFile() && !fi.isDir() && !fi.isSymLink())
                                           || (!fi.exists() && fi.isSymLink()))) {
        return false;
    }

    return true;
}
/**
* Saves the given mitk::BaseData to a file. The user is prompted to
* enter a file name. Currently only mitk::Image, mitk::Surface, mitk::PointSet and
* mitk::VesselGraphData are supported. This function is deprecated
* until the save-problem is solved by means of a Save-Factory or any
* other "nice" mechanism
*/
void CommonFunctionality::SaveBaseData( mitk::BaseData* data, const char * aFileName )
{
  //save initial time
  QDateTime initialTime = QDateTime::currentDateTime();
  std::string fileNameUsed; //file name that was actually used by the writer (e.g. after file open dialog)
  bool writingSuccessful = false;

  try{
    if (data != NULL)
    {
      mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(data);
      QString classname(data->GetNameOfClass());
      if ( image.IsNotNull() && (classname.compare("Image")==0 || classname.compare("SeedsImage")==0  ) )
      {
        fileNameUsed = CommonFunctionality::SaveImage(image, aFileName, true);
        if(!(fileNameUsed.length()>0)){
          return;
        } else {
          writingSuccessful = true;
        }
      }

      if(!writingSuccessful)
      {
        mitk::PointSet::Pointer pointset = dynamic_cast<mitk::PointSet*>(data);
        if(pointset.IsNotNull())
        {
          std::string fileName;
          if(aFileName == NULL)
            fileName = "PointSet";
          else
            fileName = aFileName;

          
          
          fileName = itksys::SystemTools::GetFilenameWithoutExtension(fileName);
                    
          QString initialFileName = QString::fromStdString(fileName);

          QString selected_suffix("MITK Point-Sets (*.mps)");
          QString possible_suffixes("MITK Point-Sets (*.mps)");
          

          /*QString qfileName = QFileDialog::getSaveFileName( NULL, "Save image", initialFilename ,mitk::CoreObjectFactory::GetInstance()->GetSaveFileExtensions(),&selected_suffix);
          */
          QString qfileName = GetSaveFileNameStartingInLastDirectory("Save file", initialFileName, possible_suffixes, &selected_suffix);
          
          
          MITK_INFO<<qfileName.toLocal8Bit().constData();

          mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
          std::string extension = itksys::SystemTools::GetFilenameLastExtension( qfileName.toLocal8Bit().constData() );
          if (extension == "") // if no extension has been entered manually into the filename
          {
            // get from combobox selected file extension
            extension = itksys::SystemTools::GetFilenameLastExtension( selected_suffix.toLocal8Bit().constData());
            extension = extension.substr(0, extension.size()-1);
            qfileName += QString::fromStdString(extension);
          }

          MITK_INFO<<"extension: " << extension;
          // check if extension is valid
          if (!writer->IsExtensionValid(extension))
          {
            QString message;
            message.append("File extension not suitable for writing point set data. Choose one extension of this list: ");
            message.append(writer->GetPossibleFileExtensionsAsString().c_str());
            QMessageBox::critical(NULL,"ERROR",message);
            return;
          }

          if (qfileName.isEmpty() == false )
          {
            writer->SetInput( pointset );
            writer->SetFileName( qfileName.toLocal8Bit().constData() );
            writer->Update();
            fileNameUsed = writer->GetFileName();
            writingSuccessful = true;
          } else {
            return;
          }
        }

        if(!writingSuccessful)
        {
          mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(data);
          if(surface.IsNotNull())
          {
            fileNameUsed = CommonFunctionality::SaveSurface(surface, aFileName);
            if(!(fileNameUsed.length()>0)){
              return;
            } else {
              writingSuccessful = true;
            }
          }

          if(!writingSuccessful)
          {
            // now try the file writers provided by the CoreObjectFactory
            mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters();
            bool writerFound = false;

            for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) 
            {
              if ( (*it)->CanWriteBaseDataType(data) ) {
                writerFound = true;
                SaveToFileWriter(*it, data, NULL, aFileName); 
                fileNameUsed = (*it)->GetFileName();
                // correct writer has been found->break
                if(!(fileNameUsed.length()>0)){
                  return;
                } else {
                  writingSuccessful = true;
                  break;
                }
              } 
            }
            if(!writerFound)
            {
              // no appropriate writer has been found 
              QMessageBox::critical(NULL,"ERROR","Could not find file writer for this data type"); 
              return;
            }
          }
        }

      }
    } else {
      QMessageBox::critical(NULL,"ERROR","Cannot write data (invalid/empty)"); 
      return;
    }
  } catch(itk::ExceptionObject e)
  {
    QMessageBox::critical( NULL, "SaveDialog", e.GetDescription(),QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
  }

  //writing is assumed to have been successful

  //check if file exists, file size >0 and last modified after this function was called
  try{
    QFileInfo* fileInfo = new QFileInfo(QString(fileNameUsed.c_str()));
    if(!fileInfo->exists())
    {
      QMessageBox::warning(NULL,"WARNING","File was not created or was split into multiple files");
    } else if(fileInfo->size()==0) {
      QMessageBox::warning(NULL,"WARNING","File is empty");
    } else if(fileInfo->lastModified()<initialTime) {
      QMessageBox::warning(NULL,"WARNING","Save not successful. File was not updated (only old version available)");
    }
    delete fileInfo;
  } catch(...) {
    QMessageBox::critical(NULL,"ERROR","Save not successful. Possibly no writing permission.");
  }
}
FileErrorDialog::FileErrorDialog(QWidget *parent, QFileInfo fileInfo, std::string errorString, const ErrorType &errorType) :
    QDialog(parent),
    ui(new Ui::fileErrorDialog)
{
    Qt::WindowFlags flags = windowFlags();
    #ifdef Q_OS_LINUX
    flags=flags & ~Qt::X11BypassWindowManagerHint;
    #endif
    flags=flags | Qt::WindowStaysOnTopHint;
    setWindowFlags(flags);

    ui->setupUi(this);
    action=FileError_Cancel;
    ui->label_error->setText(QString::fromStdString(errorString));
    if(fileInfo.exists())
    {
        ui->label_content_file_name->setText(QString::fromStdString(TransferThread::resolvedName(fileInfo)));
        if(ui->label_content_file_name->text().isEmpty())
        {
            ui->label_content_file_name->setText(fileInfo.absoluteFilePath());
            ui->label_folder->setVisible(false);
            ui->label_content_folder->setVisible(false);
        }
        else
        {
            QString folder=fileInfo.absolutePath();
            if(folder.size()>80)
                folder=folder.mid(0,38)+"..."+folder.mid(folder.size()-38);
            ui->label_content_folder->setText(fileInfo.absolutePath());
        }
        ui->label_content_size->setText(QString::number(fileInfo.size()));
        QDateTime maxTime(QDate(ULTRACOPIER_PLUGIN_MINIMALYEAR,1,1));
        if(maxTime<fileInfo.lastModified())
        {
            ui->label_modified->setVisible(true);
            ui->label_content_modified->setVisible(true);
            ui->label_content_modified->setText(fileInfo.lastModified().toString());
        }
        else
        {
            ui->label_modified->setVisible(false);
            ui->label_content_modified->setVisible(false);
        }
        if(fileInfo.isDir())
        {
            this->setWindowTitle(tr("Error on folder"));
            ui->label_size->hide();
            ui->label_content_size->hide();
            ui->label_file_name->setText(tr("Folder name"));
        }
        ui->label_file_destination->setVisible(fileInfo.isSymLink());
        ui->label_content_file_destination->setVisible(fileInfo.isSymLink());
        if(fileInfo.isSymLink())
            ui->label_content_file_destination->setText(fileInfo.symLinkTarget());
    }
    else
    {
        ui->label_content_file_name->setText(QString::fromStdString(TransferThread::resolvedName(fileInfo)));
        if(ui->label_content_file_name->text().isEmpty())
        {
            ui->label_content_file_name->setText(fileInfo.absoluteFilePath());
            ui->label_folder->setVisible(false);
            ui->label_content_folder->setVisible(false);
        }
        else
            ui->label_content_folder->setText(fileInfo.absolutePath());

        ui->label_file_destination->hide();
        ui->label_content_file_destination->hide();
        ui->label_size->hide();
        ui->label_content_size->hide();
        ui->label_modified->hide();
        ui->label_content_modified->hide();
    }
    if(errorType==ErrorType_Folder || errorType==ErrorType_FolderWithRety)
        ui->PutToBottom->hide();
    if(errorType==ErrorType_Folder)
        ui->Retry->hide();

    ui->Rights->hide();
    #ifdef ULTRACOPIER_PLUGIN_RIGHTS
        if(isInAdmin)
            ui->Rights->hide();
        #ifdef Q_OS_WIN32
        if(errorType!=ErrorType_Rights)
            ui->Rights->hide();
        #else
        ui->Rights->hide();
        #endif
    #else
        ui->Rights->hide();
    #endif
}
Beispiel #9
0
void IanniXApp::launch(int &argc, char **argv) {
    //Display splash
    Application::splash = new UiSplashScreen(QPixmap(":/general/res_splash.png"));

    //Start
    setHelp();

    QDir pathApplicationDir = QDir(QCoreApplication::applicationDirPath()).absolutePath();
#ifdef Q_OS_MAC
    pathApplicationDir.cdUp();
    pathApplicationDir.cdUp();
    pathApplicationDir.cdUp();
#endif
#ifdef QT4
    Application::pathDocuments   = QFileInfo(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation) + "/IanniX");
#else
    Application::pathDocuments   = QFileInfo(QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first() + "/IanniX");
#endif
    Application::pathApplication = QFileInfo(pathApplicationDir.absolutePath());
    Application::pathCurrent     = QFileInfo(QDir::currentPath());
    if((Application::pathApplication.absoluteFilePath().endsWith("/IanniX-build-64")) || (Application::pathApplication.absoluteFilePath().endsWith("/IanniX-build-32")))
        Application::pathApplication = QFileInfo(Application::pathApplication.absoluteFilePath().remove("-build-64").remove("-build-32"));
    if(Application::pathApplication.absoluteFilePath().endsWith("/IanniX-build/release"))
        Application::pathApplication = QFileInfo(Application::pathApplication.absoluteFilePath().remove("-build/release"));
    if(Application::pathApplication.absoluteFilePath().endsWith("/IanniX-build"))
        Application::pathApplication = QFileInfo(Application::pathApplication.absoluteFilePath().remove("-build"));

    qDebug("Pathes");
    qDebug("\tDocuments  : %s", qPrintable(Application::pathDocuments  .absoluteFilePath()));
    qDebug("\tApplication: %s", qPrintable(Application::pathApplication.absoluteFilePath()));
    qDebug("\tCurrent    : %s", qPrintable(Application::pathCurrent    .absoluteFilePath()));
    qDebug("Arguments");
    for(quint16 i = 0 ; i < argc ; i++) {
        qDebug("\t%2d=\t%s", i, argv[i]);
    }
    /*
    if(Application::pathCurrent.absoluteFilePath().startsWith("/Users/Guillaume/Documents/buzzinglight/Projets/Coduys/IanniX/IanniX"))
        generateHelp();
    */

    QFileInfo file;
    for(quint16 i = 0 ; i < argc ; i++) {
        file = QFileInfo(argv[i]);
        if((file.exists()) && (file.suffix().toLower().contains("iannix"))) {
            project = file;
            break;
        }
        file = QFileInfo(Application::pathCurrent.absoluteFilePath() + "/" + argv[i]);
        if((file.exists()) && (file.suffix().toLower().contains("iannix"))) {
            project = file;
            break;
        }
        file = QFileInfo(Application::pathDocuments.absoluteFilePath() + "/" + argv[i]);
        if((file.exists()) && (file.suffix().toLower().contains("iannix"))) {
            project = file;
            break;
        }
    }

    //Add font
    if(QFontDatabase::addApplicationFont(Application::pathApplication.absoluteFilePath() + "/Tools/Museo.ttf"))
        qDebug("Loading IanniX font failed : %s", qPrintable(Application::pathApplication.absoluteFilePath() + "/Tools/Museo.ttf"));
    //List of fonts
    if(false) {
        qDebug("[FONTS]");
        QFontDatabase fontDb;
        QStringList fontList = fontDb.families();
        foreach(const QString &font, fontList) {
            qDebug("\tFamille : %s", qPrintable(font));
            if(true) {
                qDebug("\t\tFont : %s", qPrintable(font));
                QStringList styleList = fontDb.styles(font);
                foreach(const QString &style, styleList) {
                    int weight = fontDb.weight(font, style);
                    qDebug("\t\t\t > Style / Graisse %s %d", qPrintable(style), weight);
                }
Beispiel #10
0
void SpawnMonitor::loadSpawnPoints()
{
  QString fileName;
  
  fileName = m_zoneName + ".sp";

  QFileInfo fileInfo = 
    m_dataLocMgr->findExistingFile("spawnpoints", fileName, false);

  if (!fileInfo.exists())
  {
    seqWarn("Can't find spawn point file %s", 
	   (const char*)fileInfo.absFilePath());
    return;
  }
  
  fileName = fileInfo.absFilePath();

  QFile spFile(fileName);
  
  if (!spFile.open(IO_ReadOnly))
  {
    seqWarn( "Can't open spawn point file %s", (const char*)fileName );
    return;
  }
  
  QTextStream input( &spFile );
  
  int16_t x, y, z;
  unsigned long diffTime;
  uint32_t count;
  QString name;

  while (!input.atEnd())
  {
    input >> x;
    input >> y;
    input >> z;
    input >> diffTime;
    input >> count;
    name = input.readLine();
    name = name.stripWhiteSpace();
    
    EQPoint	loc(x, y, z);
    SpawnPoint*	p = new SpawnPoint( 0, loc, name, diffTime, count );
    if (p)
    {
      QString key = p->key();
      
      if (!m_points.find(key))
      {
	m_points.insert(key, p);
	emit newSpawnPoint(p);
      }
      else
      {
	seqWarn("Warning: spawn point key already in use!");
	delete p;
      }
    }
  }

  seqInfo("Loaded spawn points: %s", (const char*)fileName);
  m_modified = false;
}
Beispiel #11
0
/*!
 \fn int FileLoader::TestFile()
 \author Franz Schmid
 \date
 \brief Tests if the file "FileName" exists and determines the type of the file.
 \retval int -1 if the file doesn't exist or any other error has occurred, 0 for the old Format, 1 for the new Format, 2 for EPS and PS files, 3 for SVG files and 4 for PDF files
 */
int FileLoader::testFile()
{
	QFileInfo fi = QFileInfo(m_fileName);
	int ret = -1;
	if (!fi.exists())
		ret = -1;
	QString ext = fi.completeSuffix().toLower();

	bool found = false;
	QList<FileFormat> fileFormats(LoadSavePlugin::supportedFormats());
	QList<FileFormat>::const_iterator it(fileFormats.constBegin());
	QList<FileFormat>::const_iterator itEnd(fileFormats.constEnd());
	for ( ; it != itEnd ; ++it )
	{
		for (int a = 0; a < it->fileExtensions.count(); a++)
		{
			QString exts = it->fileExtensions[a].toLower();
			if (ext == exts)
			{
				if (it->plug != 0)
				{
					if (it->plug->fileSupported(0, m_fileName))
					{
						ret = it->formatId;
						found = true;
						break;
					}
				}
			}
		}
		if (found)
			break;
	}
	if (!found)
	{
	// now try for the last suffix
		ext = fi.suffix().toLower();
		it = fileFormats.constBegin();
		itEnd = fileFormats.constEnd();
		for ( ; it != itEnd ; ++it )
		{
			bool found = false;
			for (int a = 0; a < it->fileExtensions.count(); a++)
			{
				QString exts = it->fileExtensions[a].toLower();
				if (ext == exts)
				{
					if (it->plug != 0)
					{
						if (it->plug->fileSupported(0, m_fileName))
						{
							ret = it->formatId;
							found = true;
							break;
						}
					}
				}
			}
			if (found)
				break;
		}
	}
	m_fileType = ret;
	return ret;
}
Beispiel #12
0
/**
 * Server initialization
 */
bool QgsServer::init( int & argc, char ** argv )
{
  if ( mInitialised )
  {
    return FALSE;
  }

#ifndef _MSC_VER
  qInstallMsgHandler( dummyMessageHandler );
#endif

  QString optionsPath = getenv( "QGIS_OPTIONS_PATH" );
  if ( !optionsPath.isEmpty() )
  {
    QgsDebugMsg( "Options PATH: " + optionsPath );
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionsPath );
  }

  mQgsApplication = new QgsApplication( argc, argv, getenv( "DISPLAY" ) );

  QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
  QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
  QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME );

  //Default prefix path may be altered by environment variable
  QgsApplication::init();
#if !defined(Q_OS_WIN)
  // init QGIS's paths - true means that all path will be inited from prefix
  QgsApplication::setPrefixPath( CMAKE_INSTALL_PREFIX, TRUE );
#endif

#if defined(SERVER_SKIP_ECW)
  QgsDebugMsg( "Skipping GDAL ECW drivers in server." );
  QgsApplication::skipGdalDriver( "ECW" );
  QgsApplication::skipGdalDriver( "JP2ECW" );
#endif

  setupNetworkAccessManager();
  QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );

  // Instantiate the plugin directory so that providers are loaded
  QgsProviderRegistry::instance( QgsApplication::pluginPath() );
  QgsDebugMsg( "Prefix  PATH: " + QgsApplication::prefixPath() );
  QgsDebugMsg( "Plugin  PATH: " + QgsApplication::pluginPath() );
  QgsDebugMsg( "PkgData PATH: " + QgsApplication::pkgDataPath() );
  QgsDebugMsg( "User DB PATH: " + QgsApplication::qgisUserDbFilePath() );
  QgsDebugMsg( "SVG PATHS: " + QgsApplication::svgPaths().join( ":" ) );

  QgsApplication::createDB(); //init qgis.db (e.g. necessary for user crs)

  QString defaultConfigFilePath;
  QFileInfo projectFileInfo = defaultProjectFile(); //try to find a .qgs file in the server directory
  if ( projectFileInfo.exists() )
  {
    defaultConfigFilePath = projectFileInfo.absoluteFilePath();
    QgsDebugMsg( "Using default project file: " + defaultConfigFilePath );
  }
  else
  {
    QFileInfo adminSLDFileInfo = defaultAdminSLD();
    if ( adminSLDFileInfo.exists() )
    {
      defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
    }
  }
  //create cache for capabilities XML
  mCapabilitiesCache = new QgsCapabilitiesCache();
  mMapRenderer =  new QgsMapRenderer;
  mMapRenderer->setLabelingEngine( new QgsPalLabeling() );

#ifdef ENABLE_MS_TESTS
  QgsFontUtils::loadStandardTestFonts( QStringList() << "Roman" << "Bold" );
#endif

#ifdef HAVE_SERVER_PYTHON_PLUGINS
  mServerInterface = new QgsServerInterfaceImpl( mCapabilitiesCache );
  if ( mInitPython )
  {
    // Init plugins
    if ( ! QgsServerPlugins::initPlugins( mServerInterface ) )
    {
      QgsMessageLog::logMessage( "No server python plugins are available", "Server", QgsMessageLog::INFO );
    }
    else
    {
      QgsMessageLog::logMessage( "Server python plugins loaded", "Server", QgsMessageLog::INFO );
    }
  }
#endif

  QgsServerLogger::instance();

  QgsEditorWidgetRegistry::initEditors();
  mInitialised = TRUE;
  QgsMessageLog::logMessage( "Server intialised", "Server", QgsMessageLog::INFO );
  return TRUE;
}
bool DownloadRepoDialog::validateInputs()
{
    if (has_manual_merge_mode_ && manual_merge_mode_) {
        return validateInputsManualMergeMode();
    }

    setDirectoryText(mDirectory->text().trimmed());
    if (mDirectory->text().isEmpty()) {
        QMessageBox::warning(this, getBrand(),
                             tr("Please choose the folder to sync."),
                             QMessageBox::Ok);
        return false;
    }
    sync_with_existing_ = false;
    alternative_path_ = QString();
    QString path = QDir(mDirectory->text()).absoluteFilePath(repo_.name);
    QFileInfo fileinfo = QFileInfo(path);
    if (fileinfo.exists()) {
        sync_with_existing_ = true;
        // exist and but not a directory ?
        if (!fileinfo.isDir()) {
            QMessageBox::warning(this, getBrand(),
                                 tr("Conflicting with existing file \"%1\", please choose a different folder.").arg(path),
                                 QMessageBox::Ok);
            return false;
        }
        // exist and but conflicting?
        QString repo_name;
        if (isPathConflictWithExistingRepo(path, &repo_name)) {
            QMessageBox::warning(this, getBrand(),
                                 tr("Conflicting with existing library \"%1\", please choose a different folder.").arg(repo_name),
                                 QMessageBox::Ok);
            return false;
        }
        int ret = QMessageBox::question(
            this, getBrand(), tr("The folder \"%1\" already exists. Are you sure to sync with it (contents will be merged)?")
                                  .arg(path) + QString("<br/><br/><small>%1</small>").arg(tr("Click No to sync with a new folder instead")),
            QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes);
        if (ret & QMessageBox::Cancel)
            return false;
        if (ret & QMessageBox::No) {
            QString new_path = getAlternativePath(mDirectory->text(), repo_.name);
            if (new_path.isEmpty()) {
                QMessageBox::warning(this, getBrand(),
                                     tr("Unable to find an alternative folder name").arg(path),
                                     QMessageBox::Ok);
                return false;
            }
            alternative_path_ = new_path;
        }
    }
    if (repo_.encrypted) {
        mPassword->setText(mPassword->text().trimmed());
        if (mPassword->text().isEmpty()) {
            QMessageBox::warning(this, getBrand(),
                                 tr("Please enter the password"),
                                 QMessageBox::Ok);
            return false;
        }
    }
    return true;
}
bool ProjectFileParser::parseLogToFile(const QDomElement &element, LogSettings *pLogSettings)
{
    bool bRet = true;

    // Check attribute
    QString enabled = element.attribute(ProjectFileDefinitions::cEnabledAttribute, ProjectFileDefinitions::cTrueValue);

    if (!enabled.toLower().compare(ProjectFileDefinitions::cTrueValue))
    {
        pLogSettings->bLogToFile = true;
    }
    else
    {
        pLogSettings->bLogToFile = false;
    }

    // Check nodes
    QDomElement child = element.firstChildElement();
    while (!child.isNull())
    {
        if (child.tagName() == ProjectFileDefinitions::cFilenameTag)
        {
            QFileInfo fileInfo = QFileInfo(child.text());

            bool bValid = true;

            /* check file path points to existing file */
            if (!fileInfo.isFile())
            {
                /* Check if file path points to something else that already exists */
                if (fileInfo.exists())
                {
                    /* path exist, but it is not a file */
                    bValid = false;
                    _msgBox.setText(tr("Log file path (%1) already exists, but it is not a file. Log file is set to default.").arg(fileInfo.filePath()));
                    _msgBox.exec();
                }
                else
                {
                    /* file path does not exist yet */

                    /* Does parent directory exist? */
                    if (!fileInfo.dir().exists())
                    {
                        bValid = false;
                        _msgBox.setText(tr("Log file path (parent directory) does not exists (%1). Log file is set to default.").arg(fileInfo.filePath()));
                        _msgBox.exec();
                    }
                }
            }

            if (bValid)
            {
                pLogSettings->bLogToFileFile = true;
                pLogSettings->logFile = fileInfo.filePath();
            }
            else
            {
                pLogSettings->bLogToFileFile = false;
            }
        }
        else
        {
            // unkown tag: ignore
        }
        child = child.nextSiblingElement();
    }

    return bRet;
}
Beispiel #15
0
QStringList ScribusQApp::getLang(QString lang)
{
	QStringList langs;

	// read the locales
	if (!lang.isEmpty())
		langs.append(lang);

	//add in user preferences lang, only overridden by lang command line option
	QString Pff = QDir::toNativeSeparators(ScPaths::getApplicationDataDir());
	QFileInfo Pffi = QFileInfo(Pff);
	if (Pffi.exists())
	{
		QString PrefsPfad;
		if (Pffi.isDir())
			PrefsPfad = Pff;
		else
			PrefsPfad = QDir::homePath();
		QString prefsXMLFile=QDir::toNativeSeparators(PrefsPfad + "/prefs150.xml");
		QFileInfo infoPrefsFile(prefsXMLFile);
		if (infoPrefsFile.exists())
		{
			PrefsFile* prefsFile = new PrefsFile(prefsXMLFile);
			if (prefsFile)
			{
				PrefsContext* userprefsContext = prefsFile->getContext("user_preferences");
				if (userprefsContext)
				{
					QString prefslang = userprefsContext->get("gui_language","");
					if (!prefslang.isEmpty())
						langs.append(prefslang);
				}
			}
			delete prefsFile;
		}
	}

	if (!(lang = ::getenv("LANG")).isEmpty())
	{
		if (lang=="C")
			lang="en";
		langs.append(lang);
	}
	if (!(lang = ::getenv("LC_MESSAGES")).isEmpty())
	{
		if (lang=="C")
			lang="en";
		langs.append(lang);
	}
	if (!(lang = ::getenv("LC_ALL")).isEmpty())
	{
		if (lang=="C")
			lang="en";
		langs.append(lang);
	}

#if defined(_WIN32)
	wchar_t out[256];
	QString language, sublanguage;
	LCID lcIdo = GetUserDefaultLCID();
	WORD sortId = SORTIDFROMLCID(lcIdo);
	LANGID langId = GetUserDefaultUILanguage();
	LCID lcIdn = MAKELCID(langId, sortId);
	if ( GetLocaleInfoW(lcIdn, LOCALE_SISO639LANGNAME , out, 255) )
	{
		language = QString::fromUtf16( (ushort*)out );
		if ( GetLocaleInfoW(lcIdn, LOCALE_SISO3166CTRYNAME, out, 255) )
		{
			sublanguage = QString::fromUtf16( (ushort*)out ).toLower();
			lang = language;
			if ( sublanguage != language && !sublanguage.isEmpty() )
				lang += "_" + sublanguage.toUpper();
			langs.append(lang);
		}
	}
#endif

	langs.append(QString(QLocale::system().name()));

	// remove duplicate entries...
	QStringList::Iterator it = langs.end();
	while (it != langs.begin())
	{
		--it;
		if (langs.count(*it) > 1)
			it = langs.erase(it);
	}
	return langs;
}
bool OsmAnd::OnlineMapRasterTileProvider_P::obtainTile( const TileId& tileId, const ZoomLevel& zoom, std::shared_ptr<MapTile>& outTile )
{
    // Check if requested tile is already being processed, and wait until that's done
    // to mark that as being processed.
    lockTile(tileId, zoom);

    // Check if requested tile is already in local storage.
    const auto tileLocalRelativePath =
        QString::number(zoom) + QDir::separator() +
        QString::number(tileId.x) + QDir::separator() +
        QString::number(tileId.y) + QString::fromLatin1(".tile");
    QFileInfo localFile;
    {
        QMutexLocker scopedLocker(&_localCachePathMutex);
        localFile.setFile(_localCachePath.filePath(tileLocalRelativePath));
    }
    if(localFile.exists())
    {
        // Since tile is in local storage, it's safe to unmark it as being processed
        unlockTile(tileId, zoom);

        // If local file is empty, it means that requested tile does not exist (has no data)
        if(localFile.size() == 0)
        {
            outTile.reset();
            return true;
        }

        //NOTE: Here may be issue that SKIA can not handle opening files on different platforms correctly
        auto bitmap = new SkBitmap();
        SkFILEStream fileStream(qPrintable(localFile.absoluteFilePath()));
        if(!SkImageDecoder::DecodeStream(&fileStream, bitmap, SkBitmap::Config::kNo_Config, SkImageDecoder::kDecodePixels_Mode))
        {
            LogPrintf(LogSeverityLevel::Error, "Failed to decode tile file '%s'", qPrintable(localFile.absoluteFilePath()));

            delete bitmap;

            return false;
        }

        assert(bitmap->width() == bitmap->height());
        assert(bitmap->width() == owner->providerTileSize);

        // Return tile
        auto tile = new MapBitmapTile(bitmap, owner->alphaChannelData);
        outTile.reset(tile);
        return true;
    }

    // Since tile is not in local cache (or cache is disabled, which is the same),
    // the tile must be downloaded from network:

    // If network access is disallowed, return failure
    if(!_networkAccessAllowed)
    {
        // Before returning, unlock tile
        unlockTile(tileId, zoom);

        return false;
    }

    // Check if there is free download slot. If all download slots are used, wait for one to be freed
    if(owner->maxConcurrentDownloads > 0)
    {
        QMutexLocker scopedLocker(&_currentDownloadsCounterMutex);

        while(_currentDownloadsCounter >= owner->maxConcurrentDownloads)
            _currentDownloadsCounterChanged.wait(&_currentDownloadsCounterMutex);

        _currentDownloadsCounter++;
    }

    // Perform synchronous download
    auto tileUrl = owner->urlPattern;
    tileUrl
        .replace(QString::fromLatin1("${zoom}"), QString::number(zoom))
        .replace(QString::fromLatin1("${x}"), QString::number(tileId.x))
        .replace(QString::fromLatin1("${y}"), QString::number(tileId.y));
    const auto networkReply = Network::Downloader::download(tileUrl);

    // Free download slot
    {
        QMutexLocker scopedLocker(&_currentDownloadsCounterMutex);

        _currentDownloadsCounter--;
        _currentDownloadsCounterChanged.wakeAll();
    }

    // Ensure that all directories are created in path to local tile
    localFile.dir().mkpath(localFile.dir().absolutePath());

    // If there was error, check what the error was
    auto networkError = networkReply->error();
    if(networkError != QNetworkReply::NetworkError::NoError)
    {
        const auto httpStatus = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        LogPrintf(LogSeverityLevel::Warning, "Failed to download tile from %s (HTTP status %d)", qPrintable(tileUrl), httpStatus);

        // 404 means that this tile does not exist, so create a zero file
        if(httpStatus == 404)
        {
            // Save to a file
            QFile tileFile(localFile.absoluteFilePath());
            if(tileFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
            {
                tileFile.close();

                // Unlock the tile
                unlockTile(tileId, zoom);
                networkReply->deleteLater();
                return true;
            }
            else
            {
                LogPrintf(LogSeverityLevel::Error, "Failed to mark tile as non-existent with empty file '%s'", qPrintable(localFile.absoluteFilePath()));

                // Unlock the tile
                unlockTile(tileId, zoom);
                return false;
            }
        }

        // Unlock the tile
        unlockTile(tileId, zoom);
        return false;
    }

    // Save data to a file
#if defined(_DEBUG) || defined(DEBUG)
    LogPrintf(LogSeverityLevel::Info, "Downloaded tile from %s", qPrintable(tileUrl));
#endif
    const auto& data = networkReply->readAll();

    // Save to a file
    QFile tileFile(localFile.absoluteFilePath());
    if(tileFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        tileFile.write(data);
        tileFile.close();

#if defined(_DEBUG) || defined(DEBUG)
        LogPrintf(LogSeverityLevel::Info, "Saved tile from %s to %s", qPrintable(tileUrl), qPrintable(localFile.absoluteFilePath()));
#endif
    }
    else
        LogPrintf(LogSeverityLevel::Error, "Failed to save tile to '%s'", qPrintable(localFile.absoluteFilePath()));

    // Unlock tile, since local storage work is done
    unlockTile(tileId, zoom);

    // Decode in-memory
    auto bitmap = new SkBitmap();
    if(!SkImageDecoder::DecodeMemory(data.data(), data.size(), bitmap, SkBitmap::Config::kNo_Config, SkImageDecoder::kDecodePixels_Mode))
    {
        LogPrintf(LogSeverityLevel::Error, "Failed to decode tile file from '%s'", qPrintable(tileUrl));

        delete bitmap;

        return false;
    }

    assert(bitmap->width() == bitmap->height());
    assert(bitmap->width() == owner->providerTileSize);

    // Return tile
    auto tile = new MapBitmapTile(bitmap, owner->alphaChannelData);
    outTile.reset(tile);
    return true;
}
static PRL_RESULT GetEntryLists(
		const QString & aVmHomeDir,
		QList<QPair<QFileInfo, QString> > & dirList,
		QList<QPair<QFileInfo, QString> > & fileList)
{
	QString VmHomeDir = QFileInfo(aVmHomeDir).absoluteFilePath();
	QFileInfo dirInfo;
	QFileInfoList entryList;
	QDir dir;
	QDir startDir(VmHomeDir);
	int i, j;
	QFileInfo config, config_backup, log, statlog;

	config.setFile(VmHomeDir, VMDIR_DEFAULT_VM_CONFIG_FILE);
	config_backup.setFile(VmHomeDir, VMDIR_DEFAULT_VM_CONFIG_FILE VMDIR_DEFAULT_VM_BACKUP_SUFFIX);
	log.setFile(VmHomeDir, "parallels.log");
	statlog.setFile(VmHomeDir, PRL_VMTIMING_LOGFILENAME);

	dirInfo.setFile(VmHomeDir);
	if (!dirInfo.exists()) {
		WRITE_TRACE(DBG_FATAL, "Directory %s does not exist", QSTR2UTF8(VmHomeDir));
		return (PRL_ERR_VMDIR_INVALID_PATH);
	}
	dirList.append(qMakePair(dirInfo, QString(".")));
	for (i = 0; i < dirList.size(); ++i) {
		/* CDir::absoluteDir() is equal CDir::dir() : return parent directory */
		dir.setPath(dirList.at(i).first.absoluteFilePath());

		entryList = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs | QDir::Hidden);

		WRITE_TRACE(DBG_DEBUG, "Directory %s", QSTR2UTF8(dirList.at(i).first.absoluteFilePath()));

		for (j = 0; j < entryList.size(); ++j) {
			const QFileInfo& fileInfo = entryList.at(j);

			if (dirInfo == fileInfo) {
				WRITE_TRACE(DBG_FATAL, "Infinite recursion in : %s", QSTR2UTF8(dirInfo.absoluteFilePath()));
				return (PRL_ERR_FAILURE);
			}
			if (!fileInfo.absoluteFilePath().startsWith(VmHomeDir)) {
				WRITE_TRACE(DBG_FATAL, "Path %s does not starts from VM home dir (%s)",
					QSTR2UTF8(fileInfo.absoluteFilePath()),
					QSTR2UTF8(VmHomeDir));
				return PRL_ERR_FAILURE;
			}
			;
			if (fileInfo.isDir()) {
				dirList.append(qMakePair(
					fileInfo, startDir.relativeFilePath(fileInfo.absoluteFilePath())));
			} else {
				/* skip config & config backup */
				if (fileInfo.absoluteFilePath() == config.absoluteFilePath())
					continue;
				if (fileInfo.absoluteFilePath() == config_backup.absoluteFilePath())
					continue;
				/* skip parallels.log */
				if (fileInfo.absoluteFilePath() == log.absoluteFilePath())
					continue;
				if (fileInfo.absoluteFilePath() == statlog.absoluteFilePath())
					/* will save statistic.log to temporary file */
					fileList.append(qMakePair(statlog,
						QString(PRL_VMTIMING_LOGFILENAME VMDIR_DEFAULT_VM_MIGRATE_SUFFIX)));
				else
					fileList.append(qMakePair(
						fileInfo, startDir.relativeFilePath(fileInfo.absoluteFilePath())));
			}
			WRITE_TRACE(DBG_DEBUG, "%x\t%s.%s\t%s",
				int(fileInfo.permissions()),
				QSTR2UTF8(fileInfo.owner()),
				QSTR2UTF8(fileInfo.group()),
				QSTR2UTF8(fileInfo.absoluteFilePath()));
		}
		entryList.clear();
	}
	/* remove VM home directory */
	dirList.removeFirst();

	return (PRL_ERR_SUCCESS);
}
Beispiel #18
0
bool DkUtils::checkFile(const QFileInfo& file) {

	return file.exists();
}
Beispiel #19
0
/**
 * Copies selected files into sandbox. Existing files in sandbox are not overwriten.
 *
 * @c QDir::NoDotAndDotDot is always added into @a filters.
 */
bool Sandbox::addWorldFiles(const QString &directory, QDir::Filters filters,
    const QStringList &filterNames, bool recurse){
  Q_ASSERT(!isActive());
  Q_ASSERT(!directory.isEmpty());

  if (!prepare()){
    return false;
  }

  const QString sandboxedDirectory = m_workingSandboxDir.filePath(
      QDir::root().relativeFilePath(
        QFileInfo(directory).absoluteFilePath()));

  if (!QFileInfo(directory).exists()){
    // Accept missing world directory - allow to create directories inside sandbox
    qDebug("%s: Directory does not exist - an empty one will be created instead of copied: '%s'",
        Q_FUNC_INFO, qPrintable(directory));
  } else if (!QFileInfo(directory).isDir()){
    qWarning("%s: Is not a directory: '%s'", Q_FUNC_INFO, qPrintable(directory));
    return false;
  }

  if (!QFileInfo(sandboxedDirectory).exists()){
    if (!QDir().mkpath(sandboxedDirectory)){
      qWarning("%s: Failed to create sandbox directory '%s'", Q_FUNC_INFO,
          qPrintable(sandboxedDirectory));
      return false;
    }
  } else if (!QFileInfo(sandboxedDirectory).isDir()){
    qWarning("%s: Failed to create sandbox directory '%s': Is not a directory", Q_FUNC_INFO,
        qPrintable(sandboxedDirectory));
    return false;
  }

  if (filters == QDir::NoFilter){
    filters = QDir::AllEntries;
  }

  filters |= QDir::NoDotAndDotDot;

  foreach (const QFileInfo &worldEntryInfo, QDir(directory).entryInfoList(filterNames, filters)){

    const QFileInfo sandboxEntryInfo(QDir(sandboxedDirectory).filePath(worldEntryInfo.fileName()));

    if (worldEntryInfo.isDir()){
      if (!sandboxEntryInfo.exists()){
        if (!QDir(sandboxedDirectory).mkdir(worldEntryInfo.fileName())){
          qWarning("%s: Failed to create overlay directory '%s/%s'", Q_FUNC_INFO,
              qPrintable(sandboxedDirectory), qPrintable(worldEntryInfo.fileName()));
          return false;
        }
      } else if (!sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is not a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }

      if (recurse){
        if (!addWorldFiles(worldEntryInfo.absoluteFilePath(), filters, filterNames, true)){
          return false;
        }
      }
    } else{
      if (!sandboxEntryInfo.exists()){
        if (!QFile(worldEntryInfo.filePath()).copy(sandboxEntryInfo.filePath())){
          qWarning("%s: Failed to copy file into sandbox '%s'", Q_FUNC_INFO,
              qPrintable(worldEntryInfo.filePath()));
          return false;
        }
      } else if (sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }
    }
  }

  return true;
}
Beispiel #20
0
bool Config::isPortable() const {

    QFileInfo settingsFile = createSettingsFilePath();
    return settingsFile.isFile() && settingsFile.exists();
}
Beispiel #21
0
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;
}
Beispiel #22
0
    bool toLibrary::isValidLibrary(QFileInfo path)
    {
        if ( !path.exists())
            return false;

        QFile lib(path.absoluteFilePath());
        if ( !lib.open(QIODevice::ReadOnly))
            return false;

#ifdef Q_OS_LINUX
        static char Elf_ident[16];

        if ( lib.read(Elf_ident, sizeof(Elf_ident)) != sizeof(Elf_ident))
            return false;

        if ( Elf_ident[0] != 0x7f ||
                Elf_ident[1] != 'E'  ||
                Elf_ident[2] != 'L'  ||
                Elf_ident[3] != 'F'  ||
#ifdef __x86_64__
                Elf_ident[4] != 0x2
#else
                Elf_ident[4] != 0x1
#endif
           )
            return false;

        lib.close();
#endif

#ifdef Q_OS_WIN32
        static char COFF_header[68];
        quint32 offset;
        static char PE_header[6];
        quint16 machine;

        if ( lib.read(COFF_header, sizeof(COFF_header)) != sizeof(COFF_header))
            return false;

        if ( COFF_header[0] != 'M' ||
                COFF_header[1] != 'Z' )
            return false;

        memcpy(&offset, COFF_header + 60, sizeof(offset));
        if ( lib.seek(offset) == false)
            return false;

        if ( lib.read(PE_header, sizeof(PE_header)) != sizeof(PE_header))
            return false;

        memcpy(&machine, PE_header + 4, sizeof(machine));
        if ( PE_header[0] != 'P' ||
                PE_header[1] != 'E' ||
#ifdef Q_OS_WIN64
                machine != 0x8664
#else
                machine != 0x014c
#endif
           )
            return false;
#endif

#ifdef Q_OS_MAC
	TLOG(5, toDecorator, __HERE__) << "Validating:" << path.absoluteFilePath() << std::endl;
	bool retval = dlopen_preflight(path.absoluteFilePath().toStdString().c_str());
	if (retval)
	  TLOG(5, toNoDecorator, __HERE__) << "dlopen_preflight:" << path.absoluteFilePath() << " OK" << std::endl;
	else
	  TLOG(5, toNoDecorator, __HERE__) << "dlopen_preflight:" << path.absoluteFilePath() << std::endl
					   << '\t' << dlerror() << std::endl;
	// return OK regarless of dlopen_preflight return
	// it returns OK only if fix_oralib.rb was run, or DYLD_LIBRARY_PATH is set
	return true;
#endif
        return true;
    }
Beispiel #23
0
void p3d::checkFile(const QFileInfo &file) {
  if (!file.exists())
    throw ErrorD("cant locate file "+file.absoluteFilePath().toStdString()+" (media path = "+_mediaPath.absolutePath().toStdString()+")");
}
Beispiel #24
0
void set_defaults (MISC *misc, OPTIONS *options, NV_BOOL restore)
{
  if (!restore)
    {
      misc->draw_area_width = 1220;
      misc->draw_area_height = 950;
      misc->drawing_canceled = NVFalse;
      misc->feature = NULL;
      memset (&misc->bfd_header, 0, sizeof (BFDATA_HEADER));
      misc->feature_mod = NVFalse;
      misc->resized = NVTrue;
      misc->area_drawn = NVFalse;
      misc->poly_count = 0;
      misc->maxd = 10;
      misc->reference_flag = NVFalse;
      misc->slice = NVFalse;
      misc->hotkey = -1;
      misc->busy = NVFalse;
      misc->visible_feature_count = 0;
      misc->html_help_tag = "#edit_pfm";
      misc->marker_mode = 0;
      misc->frozen_point = -1;
      misc->need_sparse = NVFalse;
      misc->mask_active = NVFalse;
      misc->filter_mask = NVFalse;
      misc->filter_kill_list = NULL;
      misc->filter_kill_count = 0;
      misc->av_dist_list = NULL;
      misc->av_dist_count = 0;
      misc->filtered = NVFalse;
      misc->hydro_lidar_present = NVFalse;
      misc->lidar_present = NVFalse;
      misc->hof_present = NVFalse;
      misc->gsf_present = NVFalse;
      misc->highlight_count = 0;
      misc->highlight = NULL;
      misc->num_lines = 0;


      //  Set up the sine and cosine values for slicing.

      for (NV_INT32 i = 0 ; i < 3600 ; i++)
        {
          misc->sin_array[i] = sinf (((NV_FLOAT32) i / 10.0) * NV_DEG_TO_RAD);
          misc->cos_array[i] = cosf (((NV_FLOAT32) i / 10.0) * NV_DEG_TO_RAD);
        }


      //  Tooltip text for the buttons and actions that have editable accelerators

      misc->buttonText[SAVE_EXIT_KEY] = pfmEdit3D::tr ("Save changes and exit");
      misc->buttonText[SAVE_EXIT_MASK_KEY] = pfmEdit3D::tr ("Save changes, exit, and filter mask in pfmView");
      misc->buttonText[NO_SAVE_EXIT_KEY] = pfmEdit3D::tr ("Exit without saving changes");
      misc->buttonText[RESET_KEY] = pfmEdit3D::tr ("Reset to original view");
      misc->buttonText[DELETE_POINT_MODE_KEY] = pfmEdit3D::tr ("Select delete subrecord/record edit mode");
      misc->buttonText[DELETE_RECTANGLE_MODE_KEY] = pfmEdit3D::tr ("Select delete rectangle edit mode");
      misc->buttonText[DELETE_POLYGON_MODE_KEY] = pfmEdit3D::tr ("Select delete polygon edit mode");
      misc->buttonText[FILTER_KEY] = pfmEdit3D::tr ("Run the statistical filter");
      misc->buttonText[ATTR_FILTER_KEY] = pfmEdit3D::tr ("Run the attribute filter");
      misc->buttonText[RECTANGLE_FILTER_MASK_KEY] = pfmEdit3D::tr ("Select rectangle filter mask mode");
      misc->buttonText[POLYGON_FILTER_MASK_KEY] = pfmEdit3D::tr ("Select polygon filter mask mode");
      misc->buttonText[RUN_HOTKEY_POLYGON_MODE_KEY] = pfmEdit3D::tr ("Select run hotkey program in polygon mode");
      misc->buttonText[EDIT_FEATURE_MODE_KEY] = pfmEdit3D::tr ("Select edit feature mode");
      misc->buttonText[UNDO_KEY] = pfmEdit3D::tr ("Undo last edit operation");
      misc->buttonText[DISPLAY_MULTIPLE_KEY] = pfmEdit3D::tr ("Select display multiple lines mode");
      misc->buttonText[DISPLAY_ALL_KEY] = pfmEdit3D::tr ("Display all lines");
      misc->buttonText[CLEAR_HIGHLIGHT_KEY] = pfmEdit3D::tr ("Clear all highlighted/marked points");
      misc->buttonText[HIGHLIGHT_POLYGON_MODE_KEY] = pfmEdit3D::tr ("Select highlight/mark points in polygon mode");
      misc->buttonText[CLEAR_POLYGON_MODE_KEY] = pfmEdit3D::tr ("Select clear all highlighted/marked points in polygon mode");
      misc->buttonText[TOGGLE_CONTOUR_KEY] = pfmEdit3D::tr ("Toggle contour drawing");
      misc->buttonText[COLOR_BY_DEPTH_ACTION_KEY] = pfmEdit3D::tr ("Color by depth");
      misc->buttonText[COLOR_BY_LINE_ACTION_KEY] = pfmEdit3D::tr ("Color by line");
      misc->buttonText[AV_DISTANCE_THRESHOLD_KEY] = pfmEdit3D::tr ("CZMIL LIDAR attribute viewer distance threshold tool");


      //  Icons for the buttons and actions that have editable accelerators

      misc->buttonIcon[SAVE_EXIT_KEY] = QIcon (":/icons/exit_save.xpm");
      misc->buttonIcon[SAVE_EXIT_MASK_KEY] = QIcon (":/icons/exit_mask.xpm");
      misc->buttonIcon[NO_SAVE_EXIT_KEY] = QIcon (":/icons/exit_no_save.xpm");
      misc->buttonIcon[RESET_KEY] = QIcon (":/icons/reset_view.xpm");
      misc->buttonIcon[DELETE_POINT_MODE_KEY] = QIcon (":/icons/delete_point.xpm");
      misc->buttonIcon[DELETE_RECTANGLE_MODE_KEY] = QIcon (":/icons/delete_rect.xpm");
      misc->buttonIcon[DELETE_POLYGON_MODE_KEY] = QIcon (":/icons/delete_poly.xpm");
      misc->buttonIcon[FILTER_KEY] = QIcon (":/icons/filter.xpm");
      misc->buttonIcon[ATTR_FILTER_KEY] = QIcon (":/icons/attr_filter.xpm");
      misc->buttonIcon[RECTANGLE_FILTER_MASK_KEY] = QIcon (":/icons/filter_mask_rect.xpm");
      misc->buttonIcon[POLYGON_FILTER_MASK_KEY] = QIcon (":/icons/filter_mask_poly.xpm");
      misc->buttonIcon[RUN_HOTKEY_POLYGON_MODE_KEY] = QIcon (":/icons/hotkey_poly.xpm");
      misc->buttonIcon[EDIT_FEATURE_MODE_KEY] = QIcon (":/icons/editfeature.xpm");
      misc->buttonIcon[UNDO_KEY] = QIcon (":/icons/undo.png");
      misc->buttonIcon[DISPLAY_MULTIPLE_KEY] = QIcon (":/icons/displaylines.xpm");
      misc->buttonIcon[DISPLAY_ALL_KEY] = QIcon (":/icons/displayall.xpm");
      misc->buttonIcon[CLEAR_HIGHLIGHT_KEY] = QIcon (":/icons/clear_highlight.xpm");
      misc->buttonIcon[HIGHLIGHT_POLYGON_MODE_KEY] = QIcon (":/icons/highlight_polygon.xpm");
      misc->buttonIcon[CLEAR_POLYGON_MODE_KEY] = QIcon (":/icons/clear_polygon.xpm");
      misc->buttonIcon[TOGGLE_CONTOUR_KEY] = QIcon (":/icons/contour.xpm");
      misc->buttonIcon[COLOR_BY_DEPTH_ACTION_KEY] = QIcon (":/icons/color_by_depth.xpm");
      misc->buttonIcon[COLOR_BY_LINE_ACTION_KEY] = QIcon (":/icons/color_by_line.xpm");
      misc->buttonIcon[AV_DISTANCE_THRESHOLD_KEY] = QIcon(":/icons/distance_threshold.xpm");


      //  NULL out the buttons and actions so we can tell them apart.

      for (NV_INT32 i = 0 ; i < HOTKEYS ; i++)
        {
          misc->button[i] = NULL;
          misc->action[i] = NULL;
        }


      misc->abe_share->key = 0;
      misc->abe_share->modcode = 0;
      misc->displayed_area.min_y = -91.0;

      misc->qsettings_org = pfmEdit3D::tr ("navo.navy.mil");
      misc->qsettings_app = pfmEdit3D::tr ("pfmEdit3D");

      misc->add_feature_index = -1;
      misc->nearest_feature_point = -1;

      misc->bfd_open = NVFalse;

      misc->undo = NULL;
      misc->undo_count = 0;
      misc->time_attr = -1;
      misc->datum_attr = -1;
      misc->ellipsoid_attr = -1;
      misc->process_id = getpid ();


      //  This is a special case for an option.  We don't want to reset the undo levels if we called for a restore of defaults from the prefs dialog.

      options->undo_levels = 100;


#ifdef NVWIN3X

      misc->help_browser = "C:\\Program Files\\Mozilla Firefox\\firefox.exe";

      QFileInfo br (misc->help_browser);

      if (!br.exists () || !br.isExecutable ()) misc->help_browser = "C:\\Program Files\\Internet Explorer\\iexplore.exe";

#else

      misc->help_browser = "firefox";

#endif
    }


  /*

    Ancillary program command line substitutions:


    [MOSAIC_FILE] - associated mosaic file name
    [TARGET_FILE] - associated feature (target) file name
    [PFM_FILE] - PFM list or handle file name
    [BIN_FILE] - PFM bin directory name
    [INDEX_FILE] - PFM index directory name
    [INPUT_FILE] - input data file associated with the current point
    [SHARED_MEMORY_ID] - ABE shared memory ID (some programs like chartsPic require this)
    [LINE] - line name associated with the current point
    [Z_VALUE] - Z value of the current point
    [X_VALUE] - X value (usually longitude) associated with the current point
    [Y_VALUE] - Y value (usually latitude) associated with the current point
    [MIN_Y] - minimum Y value in the currently displayed area
    [MIN_X] - minimum X value in the currently displayed area
    [MAX_Y] - maximum Y value in the currently displayed area
    [MAX_X] - maximum X value in the currently displayed area
    [FILE_NUMBER] - PFM input file number associated with the current point
    [LINE_NUMBER] - PFM input line number associated with the current point
    [VALIDITY] - PFM validity word for the current point
    [RECORD] - input file record number associated with the current point
    [SUBRECORD] - input file subrecord (usually beam) number associated with the current point
    [DATA_TYPE] - PFM data type of the current point

    [CL] - run this program as a command line program (creates a dialog for output)
    [SHARED_MEMORY_KEY] - Add the shared memory ID so the outboard program can track it


    Note: the commands used to be options (i.e. user modifiable but it became too complicated).
    If you change these you must update the documentation in hotkeysHelp.cpp.

    Note: Polygon eligible commands cannot have an associated button.  Associated buttons are set in pfmEdit3D.cpp.

    If you want to add or subtract programs it needs to be done here, in pfmEdit3DDef.hpp, and add or subtract buttons
    in pfmEdit3D.cpp.

  */


  options->kill_and_respawn = NVFalse;

  for (NV_INT32 i = 0 ; i < NUMPROGS ; i++)
    {
      options->kill_switch[i] = KILL_SWITCH_OFFSET + i;

      for (NV_INT32 j = 0 ; j < PFM_DATA_TYPES ; j++) options->data_type[i][j] = NVFalse;

      switch (i)
        {
        case EXAMGSF:
          options->prog[i] = "examGSF --file [INPUT_FILE] --record [RECORD]";
          options->name[i] = "examGSF";
          options->description[i] = pfmEdit3D::tr ("GSF non-graphical data viewer.  Displays data for nearest point.");
          options->data_type[i][PFM_GSF_DATA] = NVTrue;
          options->hotkey[i] = "e";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;

        case GSFMONITOR:
          options->prog[i] = "gsfMonitor [SHARED_MEMORY_KEY]";
          options->name[i] = "gsfMonitor";
          options->description[i] = pfmEdit3D::tr ("GSF non-graphical data viewer.  Displays ping data for nearest point.");
          options->data_type[i][PFM_GSF_DATA] = NVTrue;
          options->hotkey[i] = "g";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;

        case WAVEFORMMONITOR:
          options->prog[i] = "waveformMonitor [SHARED_MEMORY_KEY]";
          options->name[i] = "waveformMonitor";
          options->description[i] = pfmEdit3D::tr ("HOF/WLF waveform monitor (PMT, APD, IR, Raman).  Displays waveform for nearest point.");
          options->data_type[i][PFM_SHOALS_1K_DATA] = NVTrue;
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->data_type[i][PFM_WLF_DATA] = NVTrue;
          options->data_type[i][PFM_CZMIL_DATA] = NVTrue;
          options->hotkey[i] = "w";
          options->action[i] = "1,2,3,4";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;

        case UNISIPS:
          options->prog[i] = "unisips [INPUT_FILE] -record [RECORD]";
          options->name[i] = "unisips";
          options->description[i] = 
            pfmEdit3D::tr ("UNISIPS image file graphical data viewer.  Displays image data in line containing the nearest point.");
          options->data_type[i][PFM_UNISIPS_DEPTH_DATA] = NVTrue;
          options->hotkey[i] = "u";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;


          //  For historical reasons we are using "x" to kick this off.  It used to be the "extended" information
          //  for the waveformMonitor program.

        case LIDARMONITOR:
          options->prog[i] = "lidarMonitor [SHARED_MEMORY_KEY]";
          options->name[i] = "lidarMonitor";
          options->description[i] = pfmEdit3D::tr ("HOF, TOF, WLF, HAWKEYE textual data viewer.  Displays entire record for nearest point.");
          options->data_type[i][PFM_SHOALS_1K_DATA] = NVTrue;
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->data_type[i][PFM_SHOALS_TOF_DATA] = NVTrue;
          options->data_type[i][PFM_HAWKEYE_HYDRO_DATA] = NVTrue;
          options->data_type[i][PFM_HAWKEYE_TOPO_DATA] = NVTrue;
          options->data_type[i][PFM_CZMIL_DATA] = NVTrue;
          options->hotkey[i] = "x";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;

        case HAWKEYEMONITOR:
          options->prog[i] = "hawkeyeMonitor [SHARED_MEMORY_KEY]";
          options->name[i] = "hawkeyeMonitor";
          options->description[i] = pfmEdit3D::tr ("HAWKEYE graphic waveform and text data viewer.  Displays data for nearest point.");
          options->data_type[i][PFM_HAWKEYE_HYDRO_DATA] = NVTrue;
          options->hotkey[i] = "h";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;

        case CHARTSPIC:
          options->prog[i] = "chartsPic [SHARED_MEMORY_KEY]";
          options->name[i] = "chartsPic";
          options->description[i] = pfmEdit3D::tr ("HOF and TOF down-looking image viewer.  Displays nearest down-looking photo.");
          options->data_type[i][PFM_SHOALS_1K_DATA] = NVTrue;
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->data_type[i][PFM_SHOALS_TOF_DATA] = NVTrue;
          options->data_type[i][PFM_WLF_DATA] = NVTrue;
          options->data_type[i][PFM_CZMIL_DATA] = NVTrue;
          options->hotkey[i] = "i";
          options->action[i] = "r,t";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;


          //  Don't move mosaicView from 8 unless you change the zoom check in the keypress event in pfmEdit3D.cpp
          //  to match the new number.

        case MOSAICVIEW:
          options->prog[i] = "mosaicView [SHARED_MEMORY_KEY] [MOSAIC_FILE]";
          options->name[i] = "mosaicView";
          options->description[i] = pfmEdit3D::tr ("GeoTIFF viewer for photo mosaics or other GeoTIFF files (scanned maps, etc.).");
          options->data_type[i][PFM_UNDEFINED_DATA] = NVTrue;
          options->hotkey[i] = "m";
          options->action[i] = "z,+,-";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;

        case WAVEWATERFALL_APD:
          options->prog[i] = "waveWaterfall [SHARED_MEMORY_KEY] -a";
          options->name[i] = "waveWaterfall (APD)";
          options->description[i] = 
            pfmEdit3D::tr ("HOF/WLF waveform waterfall display (APD waveform).  Displays APD waveforms for geographically nearest 9 records.");
          options->data_type[i][PFM_SHOALS_1K_DATA] = NVTrue;
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->data_type[i][PFM_WLF_DATA] = NVTrue;
          options->data_type[i][PFM_CZMIL_DATA] = NVTrue;
          options->hotkey[i] = "a";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;

        case WAVEWATERFALL_PMT:
          options->prog[i] = "waveWaterfall [SHARED_MEMORY_KEY] -p";
          options->name[i] = "waveWaterfall (PMT)";
          options->description[i] = 
            pfmEdit3D::tr ("HOF/WLF waveform waterfall display (PMT waveform).  Displays PMT waveforms for geographically nearest 9 records.");
          options->data_type[i][PFM_SHOALS_1K_DATA] = NVTrue;
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->data_type[i][PFM_WLF_DATA] = NVTrue;
          options->data_type[i][PFM_CZMIL_DATA] = NVTrue;
          options->hotkey[i] = "p";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;

        case CZMILWAVEMONITOR:
          options->prog[i] = "CZMILwaveMonitor [SHARED_MEMORY_KEY]";
          options->name[i] = "CZMILwaveMonitor";
          options->description[i] = pfmEdit3D::tr ("CZMIL waveform monitor.  Displays waveform(s) for nearest point(s).");
          options->data_type[i][PFM_CZMIL_DATA] = NVTrue;
          options->hotkey[i] = "Alt+w";
          options->action[i] = "n,1,2,3,4,5";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;

        case HOFRETURNKILL:
          options->prog[i] = "hofReturnKill [SHARED_MEMORY_KEY]";
          options->name[i] = "hofReturnKill (invalidate low slope returns)";
          options->description[i] = pfmEdit3D::tr ("Kill HOF returns based on fore/back slope and amplitude.");
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->hotkey[i] = "!";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVTrue;
          options->hk_poly_filter[i] = 1;
          options->state[i] = 0;
          break;

        case HOFRETURNKILL_SWA:
          options->prog[i] = "hofReturnKill -s [SHARED_MEMORY_KEY]";
          options->name[i] = "hofReturnKill (invalidate shallow water algorithm data)";
          options->description[i] = pfmEdit3D::tr ("Kill HOF Shallow Water Algorithm or Shoreline Depth Swap data.");
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->hotkey[i] = "$";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVTrue;
          options->hk_poly_filter[i] = 1;
          options->state[i] = 0;
          break;


        case ATTRIBUTEVIEWER:
          options->prog[i] = "attributeViewer [SHARED_MEMORY_KEY]";
          options->name[i] = "attributeViewer";
          options->description[i] = pfmEdit3D::tr ("CZMIL LIDAR attribute viewer.  Analyze/edit key parameters of CZMIL LIDAR shot(s).");
          options->data_type[i][PFM_CZMIL_DATA] = NVTrue;
          options->hotkey[i] = "Alt+a";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;


        case RMSMONITOR:
          options->prog[i] = "rmsMonitor [SHARED_MEMORY_KEY]";
          options->name[i] = "rmsMonitor";
          options->description[i] = pfmEdit3D::tr ("CHARTS HOF and TOF navigation RMS textual data viewer.  Displays entire record for nearest point.");
          options->data_type[i][PFM_SHOALS_1K_DATA] = NVTrue;
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->data_type[i][PFM_SHOALS_TOF_DATA] = NVTrue;
          options->hotkey[i] = "r";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 1;
          break;


        case HOFWAVEFILTER:
          options->prog[i] = "hofWaveFilter [SHARED_MEMORY_KEY]";
          options->name[i] = "hofWaveFilter";
          options->description[i] = pfmEdit3D::tr ("CHARTS HOF waveform filter.  Checks adjacent waveforms for isolated points.");
          options->data_type[i][PFM_CHARTS_HOF_DATA] = NVTrue;
          options->hotkey[i] = "Ctrl+w";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 2;
          options->state[i] = 0;
          break;


          //  IMPORTANT NOTE: The following six functions are not ancillary programs.  If you have to add new ancillary programs,
          //  add them above these just for esthetics.

        case INVALIDATE_FEATURES:
          options->prog[i] = "INVALIDATE_FEATURES";
          options->name[i] = "INVALIDATE FEATURES";
          options->description[i] = pfmEdit3D::tr ("Invalidate all features included in the hotkey polygon.  This is an internal function.");
          options->data_type[i][PFM_UNDEFINED_DATA] = NVTrue;
          options->hotkey[i] = "v";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVTrue;
          options->hk_poly_filter[i] = 1;
          options->state[i] = 0;
          break;


        case ACCEPT_FILTER_HIGHLIGHTED:
          options->prog[i] = "DELETE FILTER HIGHLIGHTED";
          options->name[i] = "DELETE FILTER HIGHLIGHTED";
          options->description[i] = pfmEdit3D::tr ("Delete points marked by the filter or highlighted.  This is an internal function.");
          options->data_type[i][PFM_UNDEFINED_DATA] = NVTrue;
          options->hotkey[i] = "Del";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;


        case REJECT_FILTER_HIGHLIGHTED:
          options->prog[i] = "CLEAR FILTER HIGHLIGHTED";
          options->name[i] = "CLEAR FILTER HIGHLIGHTED";
          options->description[i] = pfmEdit3D::tr ("Clear points marked by the filter/highlighted or restore highlighted invalid points.  This is an internal function.");
          options->data_type[i][PFM_UNDEFINED_DATA] = NVTrue;
          options->hotkey[i] = "Ins";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;


        case DELETE_SINGLE_POINT:
          options->prog[i] = "DELETE SINGLE POINT";
          options->name[i] = "DELETE SINGLE POINT";
          options->description[i] = pfmEdit3D::tr ("Delete single point nearest cursor in DELETE_POINT mode.  This is an internal function.");
          options->data_type[i][PFM_UNDEFINED_DATA] = NVTrue;
          options->hotkey[i] = "d";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;


          //  IMPORTANT NOTE: The following two functions affect external ancillary programs.  They are used for freezing the marker
          //  or freezing all of the multi-markers.

        case FREEZE:
          options->prog[i] = "FREEZE";
          options->name[i] = "FREEZE MAIN BOX CURSOR";
          options->description[i] = pfmEdit3D::tr ("Toggle freezing of the box cursor.  This is an internal function that affects ancillary programs.");
          options->data_type[i][PFM_UNDEFINED_DATA] = NVTrue;
          options->hotkey[i] = "f";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;

        case FREEZE_ALL:
          options->prog[i] = "FREEZE ALL";
          options->name[i] = "FREEZE ALL BOX CURSORS";
          options->description[i] = pfmEdit3D::tr ("Toggle freezing of all of the box cursors.  This is an internal function that affects ancillary programs.");
          options->data_type[i][PFM_UNDEFINED_DATA] = NVTrue;
          options->hotkey[i] = "Alt+f";
          options->action[i] = "";
          options->progButton[i] = NULL;
          options->hk_poly_eligible[i] = NVFalse;
          options->hk_poly_filter[i] = 0;
          options->state[i] = 0;
          break;
        }
    }


  options->min_window_size = 4.0;
  options->iho_min_window = 0;
  options->display_man_invalid = NVFalse;
  options->display_flt_invalid = NVFalse;
  options->display_contours = NVFalse;
  options->display_null = NVFalse;
  options->display_feature = 0;
  options->display_children = NVFalse;
  options->display_reference = NVFalse;
  options->display_feature_info = NVFalse;
  options->function = DELETE_POLYGON;
  options->slice_percent = 5;
  options->slice_alpha = 24;
  options->contour_width = 2;
  options->smoothing_factor = 0;
  options->point_size = 3;
  options->contour_color = QColor (255, 255, 255);
  options->edit_color = QColor (255, 255, 255, 255);
  options->marker_color = QColor (255, 255, 255, 255);
  options->ref_color[0] = QColor (255, 255, 255, 255);
  options->tracker_color = QColor (255, 255, 0, 255);
  options->background_color = QColor (0, 0, 0, 255);
  options->scale_color = QColor (255, 255, 255, 255);
  options->feature_color = QColor (255, 255, 255, 128);
  options->feature_info_color = QColor (255, 255, 255, 255);
  options->feature_highlight_color = QColor (255, 0, 0, 255);
  options->verified_feature_color = QColor (0, 255, 0, 128);
  options->feature_size = 0.01;
  options->unload_prog = "pfm_unload";
  options->auto_unload = NVFalse;
  options->last_rock_feature_desc = 4;
  options->last_offshore_feature_desc = 17;
  options->last_light_feature_desc = 9;
  options->last_lidar_feature_desc = 0;
  options->last_feature_description = "";
  options->last_feature_remarks = "";
  options->overlap_percent = 5;
  options->feature_dir = ".";
  options->main_button_icon_size = 24;
  options->rotation_increment = 5.0;
  options->color_index = 0;
  options->flag_index = PRE_USER - 10;
  options->sparse_limit = 250000;
  options->exaggeration = 3.0;
  options->zoom_percent = 10;
  options->screenshot_delay = 2;
  options->draw_scale = NVTrue;
  options->zx_rotation = 0.0;
  options->y_rotation = 0.0;
  options->filterSTD = 2.4;
  options->deep_filter_only = NVFalse;
  options->feature_radius = 20.0;
  options->drawingMode = NVMAPGL_RENDER_POINT_MODE;
  options->objectWidth = 0.002;
  options->objectDivisionals = 8;
  options->distThresh = 4.0;
  options->auto_scale = NVTrue;
  options->hofWaveFilter_search_radius = 2.0;
  options->hofWaveFilter_search_width = 8;
  options->hofWaveFilter_rise_threshold = 5;
  options->hofWaveFilter_pmt_ac_zero_offset_required = 10;
  options->hofWaveFilter_apd_ac_zero_offset_required = 5;


  //  Default to red-blue, unlocked, 0.0 for all color bands.

  for (NV_INT32 i = 0 ; i < NUM_HSV ; i++)
    {
      options->min_hsv_color[i] = 0;
      options->max_hsv_color[i] = 240;
      options->min_hsv_locked[i] = NVFalse;
      options->max_hsv_locked[i] = NVFalse;
      options->min_hsv_value[i] = 0.0;
      options->max_hsv_value[i] = 0.0;
    }


  //  Now change the color by depth default to red-magenta.

  options->max_hsv_color[0] = 315;


  // 
  //  Set the multi-waveform cursor colors.  MAX_STACK_POINTS is 9 so we manually define 9 colors.
  //  If MAX_STACK_POINTS gets changed you should add/subtract.
  //

  // white

  misc->abe_share->mwShare.multiColors[0].r = 255;
  misc->abe_share->mwShare.multiColors[0].g = 255;
  misc->abe_share->mwShare.multiColors[0].b = 255;
  misc->abe_share->mwShare.multiColors[0].a = 255;


  // red 

  misc->abe_share->mwShare.multiColors[1].r = 255;
  misc->abe_share->mwShare.multiColors[1].g = 0;
  misc->abe_share->mwShare.multiColors[1].b = 0;
  misc->abe_share->mwShare.multiColors[1].a = 255;


  // yellow 

  misc->abe_share->mwShare.multiColors[2].r = 255;
  misc->abe_share->mwShare.multiColors[2].g = 255;
  misc->abe_share->mwShare.multiColors[2].b = 0;
  misc->abe_share->mwShare.multiColors[2].a = 255;


  // green

  misc->abe_share->mwShare.multiColors[3].r = 0;
  misc->abe_share->mwShare.multiColors[3].g = 255;
  misc->abe_share->mwShare.multiColors[3].b = 0;
  misc->abe_share->mwShare.multiColors[3].a = 255;


  // cyan

  misc->abe_share->mwShare.multiColors[4].r = 0;
  misc->abe_share->mwShare.multiColors[4].g = 255;
  misc->abe_share->mwShare.multiColors[4].b = 255;
  misc->abe_share->mwShare.multiColors[4].a = 255;


  // blue

  misc->abe_share->mwShare.multiColors[5].r = 0;
  misc->abe_share->mwShare.multiColors[5].g = 0;
  misc->abe_share->mwShare.multiColors[5].b = 255;
  misc->abe_share->mwShare.multiColors[5].a = 255;


  // orange

  misc->abe_share->mwShare.multiColors[6].r = 153;
  misc->abe_share->mwShare.multiColors[6].g = 128;
  misc->abe_share->mwShare.multiColors[6].b = 0;
  misc->abe_share->mwShare.multiColors[6].a = 255;


  // magenta

  misc->abe_share->mwShare.multiColors[7].r = 128;
  misc->abe_share->mwShare.multiColors[7].g = 0;
  misc->abe_share->mwShare.multiColors[7].b = 255;
  misc->abe_share->mwShare.multiColors[7].a = 255;


  // dark green

  misc->abe_share->mwShare.multiColors[8].r = 0;
  misc->abe_share->mwShare.multiColors[8].g = 153;
  misc->abe_share->mwShare.multiColors[8].b = 0;
  misc->abe_share->mwShare.multiColors[8].a = 255;


  for (NV_INT32 i = 0 ; i < MAX_STACK_POINTS ; i++)
    {
      options->waveColor[i].setRgb (misc->abe_share->mwShare.multiColors[i].r, misc->abe_share->mwShare.multiColors[i].g,
                                    misc->abe_share->mwShare.multiColors[i].b);
      options->waveColor[i].setAlpha (misc->abe_share->mwShare.multiColors[i].a);
    }


  options->buttonAccel[SAVE_EXIT_KEY] = "Ctrl+s";
  options->buttonAccel[SAVE_EXIT_MASK_KEY] = "Ctrl+f";
  options->buttonAccel[NO_SAVE_EXIT_KEY] = "Ctrl+q";
  options->buttonAccel[RESET_KEY] = "Ctrl+r";
  options->buttonAccel[DELETE_POINT_MODE_KEY] = "F3";
  options->buttonAccel[DELETE_RECTANGLE_MODE_KEY] = "F4";
  options->buttonAccel[DELETE_POLYGON_MODE_KEY] = "F5";
  options->buttonAccel[FILTER_KEY] = "F6";
  options->buttonAccel[ATTR_FILTER_KEY] = "Ctrl+a";
  options->buttonAccel[RECTANGLE_FILTER_MASK_KEY] = "F7";
  options->buttonAccel[POLYGON_FILTER_MASK_KEY] = "F8";
  options->buttonAccel[RUN_HOTKEY_POLYGON_MODE_KEY] = "F9";
  options->buttonAccel[EDIT_FEATURE_MODE_KEY] = "F10";
  options->buttonAccel[UNDO_KEY] = "Ctrl+z";
  options->buttonAccel[DISPLAY_MULTIPLE_KEY] = "F11";
  options->buttonAccel[DISPLAY_ALL_KEY] = "F12";
  options->buttonAccel[CLEAR_HIGHLIGHT_KEY] = "Ctrl+h";
  options->buttonAccel[HIGHLIGHT_POLYGON_MODE_KEY] = "Ctrl+p";
  options->buttonAccel[CLEAR_POLYGON_MODE_KEY] = "Ctrl+c";
  options->buttonAccel[TOGGLE_CONTOUR_KEY] = "Alt+c";
  options->buttonAccel[COLOR_BY_DEPTH_ACTION_KEY] = "Ctrl+d";
  options->buttonAccel[COLOR_BY_LINE_ACTION_KEY] = "Ctrl+l";
  options->buttonAccel[AV_DISTANCE_THRESHOLD_KEY] = "Alt+d";
}
Beispiel #25
0
int readDir(QFileInfo *fi,
            FileNameList *fnList,
            FileNameDict *fnDict,
            StringDict  *exclDict,
            QStrList *patList,
            QStrList *exclPatList,
            StringList *resultList,
            StringDict *resultDict,
            bool errorIfNotExist,
            bool recursive,
            QDict<void> *killDict,
            QDict<void> *paths
           )
{
  QCString dirName = fi->absFilePath().utf8();
  if (paths && paths->find(dirName)==0)
  {
    paths->insert(dirName,(void*)0x8);
  }
  if (fi->isSymLink())
  {
  }
  QDir dir(dirName);
  dir.setFilter( QDir::Files | QDir::Dirs | QDir::Hidden );
  int totalSize=0;
  //printf("killDict=%p count=%d\n",killDict,killDict->count());
  
  const QFileInfoList *list = dir.entryInfoList();
  if (list)
  {
    QFileInfoListIterator it( *list );
    QFileInfo *cfi;

    while ((cfi=it.current()))
    {
      if (exclDict==0 || exclDict->find(cfi->absFilePath().utf8())==0) 
      { // file should not be excluded
        //printf("killDict->find(%s)\n",cfi->absFilePath().data());
        if (!cfi->exists() || !cfi->isReadable())
        {
          if (errorIfNotExist)
          {
          }
        }
        else if (cfi->isFile() && 
            (patList==0 || patternMatch(*cfi,patList)) && 
            !patternMatch(*cfi,exclPatList) &&
            (killDict==0 || killDict->find(cfi->absFilePath().utf8())==0)
            )
        {
          totalSize+=cfi->size()+cfi->absFilePath().length()+4;
          QCString name=cfi->fileName().utf8();
          //printf("New file %s\n",name.data());
          if (fnDict)
          {
            FileDef  *fd=new FileDef(cfi->dirPath().utf8()+"/",name);
            FileName *fn=0;
            if (!name.isEmpty() && (fn=(*fnDict)[name]))
            {
              fn->append(fd);
            }
            else
            {
              fn = new FileName(cfi->absFilePath().utf8(),name);
              fn->append(fd);
              if (fnList) fnList->inSort(fn);
              fnDict->insert(name,fn);
            }
          }
          QCString *rs=0;
          if (resultList || resultDict)
          {
            rs=new QCString(cfi->absFilePath().utf8());
          }
          if (resultList) resultList->append(rs);
          if (resultDict) resultDict->insert(cfi->absFilePath().utf8(),rs);
          if (killDict) killDict->insert(cfi->absFilePath().utf8(),(void *)0x8);
        }
        else if (recursive &&
            cfi->isDir() && 
            !patternMatch(*cfi,exclPatList) &&
            cfi->fileName().at(0)!='.') // skip "." ".." and ".dir"
        {
          cfi->setFile(cfi->absFilePath());
          totalSize+=readDir(cfi,fnList,fnDict,exclDict,
              patList,exclPatList,resultList,resultDict,errorIfNotExist,
              recursive,killDict,paths);
        }
      }
      ++it;
    }
  }
  return totalSize;
}
Beispiel #26
0
	QPair<QString, QString> GetOSNameSplit ()
	{
#if defined(Q_OS_MAC)
		QSysInfo::MacVersion v = QSysInfo::MacintoshVersion;
		if (v == QSysInfo::MV_10_3)
			return SplitInfo_t ("Mac OS X", "10.3");
		else if(v == QSysInfo::MV_10_4)
			return SplitInfo_t ("Mac OS X", "10.4");
		else if(v == QSysInfo::MV_10_5)
			return SplitInfo_t ("Mac OS X", "10.5");
		else if(v == QSysInfo::MV_10_6)
			return SplitInfo_t ("Mac OS X", "10.6");
		else
			return SplitInfo_t ("Mac OS X", "Unknown version");
#elif defined(Q_OS_WIN32)
		QSysInfo::WinVersion v = QSysInfo::WindowsVersion;
		if (v == QSysInfo::WV_95)
			return SplitInfo_t ("Windows", "95");
		else if (v == QSysInfo::WV_98)
			return SplitInfo_t ("Windows", "98");
		else if (v == QSysInfo::WV_Me)
			return SplitInfo_t ("Windows", "Me");
		else if (v == QSysInfo::WV_DOS_based)
			return SplitInfo_t ("Windows", "9x/Me");
		else if (v == QSysInfo::WV_NT)
			return SplitInfo_t ("Windows", "NT 4.x");
		else if (v == QSysInfo::WV_2000)
			return SplitInfo_t ("Windows", "2000");
		else if (v == QSysInfo::WV_XP)
			return SplitInfo_t ("Windows", "XP");
		else if (v == QSysInfo::WV_2003)
			return SplitInfo_t ("Windows", "2003");
		else if (v == QSysInfo::WV_VISTA)
			return SplitInfo_t ("Windows", "Vista");
		else if (v == QSysInfo::WV_WINDOWS7)
			return SplitInfo_t ("Windows", "7");
		else if (v == QSysInfo::WV_NT_based)
			return SplitInfo_t ("Windows", "NT-based");
#else
		QString osName;

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

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

		utsname u;
		uname (&u);

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

		return qMakePair (QString ("Unknown OS"), QString ("Unknown version"));
	}
Beispiel #27
0
void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed)
{
    currentFilenames.push(filename);
    preprocessed.reserve(preprocessed.size() + symbols.size());
    while (hasNext()) {
        Token token = next();

        switch (token) {
        case PP_INCLUDE:
        {
            int lineNum = symbol().lineNum;
            QByteArray include;
            bool local = false;
            if (test(PP_STRING_LITERAL)) {
                local = lexem().startsWith('\"');
                include = unquotedLexem();
            } else
                continue;
            until(PP_NEWLINE);

            // #### stringery
            QFileInfo fi;
            if (local)
                fi.setFile(QFileInfo(QString::fromLocal8Bit(filename)).dir(), QString::fromLocal8Bit(include));
            for (int j = 0; j < Preprocessor::includes.size() && !fi.exists(); ++j) {
                const IncludePath &p = Preprocessor::includes.at(j);
                if (p.isFrameworkPath) {
                    const int slashPos = include.indexOf('/');
                    if (slashPos == -1)
                        continue;
                    QByteArray frameworkCandidate = include.left(slashPos);
                    frameworkCandidate.append(".framework/Headers/");
                    fi.setFile(QString::fromLocal8Bit(p.path + '/' + frameworkCandidate), QString::fromLocal8Bit(include.mid(slashPos + 1)));
                } else {
                    fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include));
                }
                // try again, maybe there's a file later in the include paths with the same name
                // (186067)
                if (fi.isDir()) {
                    fi = QFileInfo();
                    continue;
                }
            }

            if (!fi.exists() || fi.isDir())
                continue;
            include = fi.canonicalFilePath().toLocal8Bit();

            if (Preprocessor::preprocessedIncludes.contains(include))
                continue;
            Preprocessor::preprocessedIncludes.insert(include);

            QFile file(QString::fromLocal8Bit(include));
            if (!file.open(QFile::ReadOnly))
                continue;

            QByteArray input = file.readAll();
            file.close();
            if (input.isEmpty())
                continue;

            Symbols saveSymbols = symbols;
            int saveIndex = index;

            // phase 1: get rid of backslash-newlines
            input = cleaned(input);

            // phase 2: tokenize for the preprocessor
            symbols = tokenize(input);
            input.clear();

            index = 0;

            // phase 3: preprocess conditions and substitute macros
            preprocessed += Symbol(0, MOC_INCLUDE_BEGIN, include);
            preprocess(include, preprocessed);
            preprocessed += Symbol(lineNum, MOC_INCLUDE_END, include);

            symbols = saveSymbols;
            index = saveIndex;
            continue;
        }
        case PP_DEFINE:
        {
            next(IDENTIFIER);
            QByteArray name = lexem();
            int start = index;
            until(PP_NEWLINE);
            Macro macro;
            macro.symbols.reserve(index - start - 1);
            for (int i = start; i < index - 1; ++i)
                macro.symbols += symbols.at(i);
            macros.insert(name, macro);
            continue;
        }
        case PP_UNDEF: {
            next(IDENTIFIER);
            QByteArray name = lexem();
            until(PP_NEWLINE);
            macros.remove(name);
            continue;
        }
        case PP_IDENTIFIER:
        {
//             if (macros.contains(symbol()))
//                 ;
        }
            // we _could_ easily substitute macros by the following
            // four lines, but we choose not to.
            /*
            if (macros.contains(sym.lexem())) {
                preprocessed += substitute(macros, symbols, i);
                continue;
            }
            */
            break;
        case PP_HASH:
            until(PP_NEWLINE);
            continue; // skip unknown preprocessor statement
        case PP_IFDEF:
        case PP_IFNDEF:
        case PP_IF:
            while (!evaluateCondition()) {
                if (!skipBranch())
                    break;
                if (test(PP_ELIF)) {
                } else {
                    until(PP_NEWLINE);
                    break;
                }
            }
            continue;
        case PP_ELIF:
        case PP_ELSE:
            skipUntilEndif();
            // fall through
        case PP_ENDIF:
            until(PP_NEWLINE);
            continue;
        case SIGNALS:
        case SLOTS: {
            Symbol sym = symbol();
            if (macros.contains("QT_NO_KEYWORDS"))
                sym.token = IDENTIFIER;
            else
                sym.token = (token == SIGNALS ? Q_SIGNALS_TOKEN : Q_SLOTS_TOKEN);
            preprocessed += sym;
        } continue;
        default:
            break;
        }
        preprocessed += symbol();
    }

    currentFilenames.pop();
}
int main( int argc, char * argv[] )
{
#ifndef _MSC_VER
  qInstallMsgHandler( dummyMessageHandler );
#endif

  QgsApplication qgsapp( argc, argv, getenv( "DISPLAY" ) );

  //Default prefix path may be altered by environment variable
  char* prefixPath = getenv( "QGIS_PREFIX_PATH" );
  if ( prefixPath )
  {
    QgsApplication::setPrefixPath( prefixPath, TRUE );
  }
#if !defined(Q_OS_WIN)
  else
  {
    // init QGIS's paths - true means that all path will be inited from prefix
    QgsApplication::setPrefixPath( CMAKE_INSTALL_PREFIX, TRUE );
  }
#endif

#if defined(MAPSERVER_SKIP_ECW)
  QgsDebugMsg( "Skipping GDAL ECW drivers in server." );
  QgsApplication::skipGdalDriver( "ECW" );
  QgsApplication::skipGdalDriver( "JP2ECW" );
#endif

  QSettings settings;

  QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance();
  QNetworkDiskCache *cache = new QNetworkDiskCache( 0 );

  QString cacheDirectory = settings.value( "cache/directory", QgsApplication::qgisSettingsDirPath() + "cache" ).toString();
  qint64 cacheSize = settings.value( "cache/size", 50 * 1024 * 1024 ).toULongLong();
  QgsDebugMsg( QString( "setCacheDirectory: %1" ).arg( cacheDirectory ) );
  QgsDebugMsg( QString( "setMaximumCacheSize: %1" ).arg( cacheSize ) );
  cache->setCacheDirectory( cacheDirectory );
  cache->setMaximumCacheSize( cacheSize );
  QgsDebugMsg( QString( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ) );
  QgsDebugMsg( QString( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ) );

  nam->setCache( cache );

  QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );

  // Instantiate the plugin directory so that providers are loaded
  QgsProviderRegistry::instance( QgsApplication::pluginPath() );
  QgsDebugMsg( "Prefix  PATH: " + QgsApplication::prefixPath() );
  QgsDebugMsg( "Plugin  PATH: " + QgsApplication::pluginPath() );
  QgsDebugMsg( "PkgData PATH: " + QgsApplication::pkgDataPath() );
  QgsDebugMsg( "User DB PATH: " + QgsApplication::qgisUserDbFilePath() );

  QgsDebugMsg( qgsapp.applicationDirPath() + "/qgis_wms_server.log" );
  QgsApplication::createDB(); //init qgis.db (e.g. necessary for user crs)

  //create config cache and search for config files in the current directory.
  //These configurations are used if no mapfile parameter is present in the request
  QString defaultConfigFilePath;
  QFileInfo projectFileInfo = defaultProjectFile(); //try to find a .qgs file in the server directory
  if ( projectFileInfo.exists() )
  {
    defaultConfigFilePath = projectFileInfo.absoluteFilePath();
  }
  else
  {
    QFileInfo adminSLDFileInfo = defaultAdminSLD();
    if ( adminSLDFileInfo.exists() )
    {
      defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
    }
  }

  //create cache for capabilities XML
  QgsCapabilitiesCache capabilitiesCache;

  //creating QgsMapRenderer is expensive (access to srs.db), so we do it here before the fcgi loop
  QgsMapRenderer* theMapRenderer = new QgsMapRenderer();
  theMapRenderer->setLabelingEngine( new QgsPalLabeling() );

  while ( fcgi_accept() >= 0 )
  {
    printRequestInfos(); //print request infos if in debug mode

    //use QgsGetRequestHandler in case of HTTP GET and QgsSOAPRequestHandler in case of HTTP POST
    QgsRequestHandler* theRequestHandler = 0;
    char* requestMethod = getenv( "REQUEST_METHOD" );
    if ( requestMethod != NULL )
    {
      if ( strcmp( requestMethod, "POST" ) == 0 )
      {
        //QgsDebugMsg( "Creating QgsSOAPRequestHandler" );
        //theRequestHandler = new QgsSOAPRequestHandler();
        theRequestHandler = new QgsPostRequestHandler();
      }
      else
      {
        QgsDebugMsg( "Creating QgsGetRequestHandler" );
        theRequestHandler = new QgsGetRequestHandler();
      }
    }
    else
    {
      QgsDebugMsg( "Creating QgsGetRequestHandler" );
      theRequestHandler = new QgsGetRequestHandler();
    }

    QMap<QString, QString> parameterMap;

    try
    {
      parameterMap = theRequestHandler->parseInput();
    }
    catch ( QgsMapServiceException& e )
    {
      QgsDebugMsg( "An exception was thrown during input parsing" );
      theRequestHandler->sendServiceException( e );
      continue;
    }

    QMap<QString, QString>::const_iterator paramIt;

    //set admin config file to wms server object
    QString configFilePath( defaultConfigFilePath );

    paramIt = parameterMap.find( "MAP" );
    if ( paramIt == parameterMap.constEnd() )
    {
      QgsDebugMsg( QString( "Using default configuration file path: %1" ).arg( defaultConfigFilePath ) );
    }
    else
    {
      configFilePath = paramIt.value();
    }

    QgsConfigParser* adminConfigParser = QgsConfigCache::instance()->searchConfiguration( configFilePath );
    if ( !adminConfigParser )
    {
      QgsDebugMsg( "parse error on config file " + configFilePath );
      theRequestHandler->sendServiceException( QgsMapServiceException( "", "Configuration file problem : perhaps you left off the .qgs extension?" ) );
      continue;
    }

    //sld parser might need information about request parameters
    adminConfigParser->setParameterMap( parameterMap );

    //request to WMS?
    QString serviceString;
    paramIt = parameterMap.find( "SERVICE" );
    if ( paramIt == parameterMap.constEnd() )
    {
#ifndef QGISDEBUG
      serviceString = parameterMap.value( "SERVICE", "WMS" );
#else
      QgsDebugMsg( "unable to find 'SERVICE' parameter, exiting..." );
      theRequestHandler->sendServiceException( QgsMapServiceException( "ServiceNotSpecified", "Service not specified. The SERVICE parameter is mandatory" ) );
      delete theRequestHandler;
      continue;
#endif
    }
    else
    {
      serviceString = paramIt.value();
    }

    QgsWMSServer* theServer = 0;
    if ( serviceString == "WFS" )
    {
      delete theServer;
      QgsWFSServer* theServer = 0;
      try
      {
        theServer = new QgsWFSServer( parameterMap );
      }
      catch ( QgsMapServiceException e ) //admin.sld may be invalid
      {
        theRequestHandler->sendServiceException( e );
        continue;
      }

      theServer->setAdminConfigParser( adminConfigParser );


      //request type
      QString request = parameterMap.value( "REQUEST" );
      if ( request.isEmpty() )
      {
        //do some error handling
        QgsDebugMsg( "unable to find 'REQUEST' parameter, exiting..." );
        theRequestHandler->sendServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      if ( request.compare( "GetCapabilities", Qt::CaseInsensitive ) == 0 )
      {
        QDomDocument capabilitiesDocument;
        try
        {
          capabilitiesDocument = theServer->getCapabilities();
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending GetCapabilities response" );
        theRequestHandler->sendGetCapabilitiesResponse( capabilitiesDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }
      else if ( request.compare( "DescribeFeatureType", Qt::CaseInsensitive ) == 0 )
      {
        QDomDocument describeDocument;
        try
        {
          describeDocument = theServer->describeFeatureType();
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending GetCapabilities response" );
        theRequestHandler->sendGetCapabilitiesResponse( describeDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }
      else if ( request.compare( "GetFeature", Qt::CaseInsensitive ) == 0 )
      {
        //output format for GetFeature
        QString outputFormat = parameterMap.value( "OUTPUTFORMAT" );
        try
        {
          if ( theServer->getFeature( *theRequestHandler, outputFormat ) != 0 )
          {
            delete theRequestHandler;
            delete theServer;
            continue;
          }
          else
          {
            delete theRequestHandler;
            delete theServer;
            continue;
          }
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
      }
      else if ( request.compare( "Transaction", Qt::CaseInsensitive ) == 0 )
      {
        QDomDocument transactionDocument;
        try
        {
          transactionDocument = theServer->transaction( parameterMap.value( "REQUEST_BODY" ) );
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending Transaction response" );
        theRequestHandler->sendGetCapabilitiesResponse( transactionDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      return 0;
    }

    try
    {
      theServer = new QgsWMSServer( parameterMap, theMapRenderer );
    }
    catch ( QgsMapServiceException e ) //admin.sld may be invalid
    {
      theRequestHandler->sendServiceException( e );
      continue;
    }

    theServer->setAdminConfigParser( adminConfigParser );


    //request type
    QString request = parameterMap.value( "REQUEST" );
    if ( request.isEmpty() )
    {
      //do some error handling
      QgsDebugMsg( "unable to find 'REQUEST' parameter, exiting..." );
      theRequestHandler->sendServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) );
      delete theRequestHandler;
      delete theServer;
      continue;
    }

    QString version = parameterMap.value( "VERSION", "1.3.0" );
    bool getProjectSettings = ( request.compare( "GetProjectSettings", Qt::CaseInsensitive ) == 0 );
    if ( getProjectSettings )
    {
      version = "1.3.0"; //getProjectSettings extends WMS 1.3.0 capabilities
    }

    if ( request.compare( "GetCapabilities", Qt::CaseInsensitive ) == 0 || getProjectSettings )
    {
      const QDomDocument* capabilitiesDocument = capabilitiesCache.searchCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version );
      if ( !capabilitiesDocument ) //capabilities xml not in cache. Create a new one
      {
        QgsDebugMsg( "Capabilities document not found in cache" );
        QDomDocument doc;
        try
        {
          doc = theServer->getCapabilities( version, getProjectSettings );
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        capabilitiesCache.insertCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version, &doc );
        capabilitiesDocument = capabilitiesCache.searchCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version );
      }
      else
      {
        QgsDebugMsg( "Found capabilities document in cache" );
      }

      if ( capabilitiesDocument )
      {
        theRequestHandler->sendGetCapabilitiesResponse( *capabilitiesDocument );
      }
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetMap", Qt::CaseInsensitive ) == 0 )
    {
      QImage* result = 0;
      try
      {
        result = theServer->getMap();
      }
      catch ( QgsMapServiceException& ex )
      {
        QgsDebugMsg( "Caught exception during GetMap request" );
        theRequestHandler->sendServiceException( ex );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      if ( result )
      {
        QgsDebugMsg( "Sending GetMap response" );
        theRequestHandler->sendGetMapResponse( serviceString, result );
        QgsDebugMsg( "Response sent" );
      }
      else
      {
        //do some error handling
        QgsDebugMsg( "result image is 0" );
      }
      delete result;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetFeatureInfo", Qt::CaseInsensitive ) == 0 )
    {
      QDomDocument featureInfoDoc;
      try
      {
        if ( theServer->getFeatureInfo( featureInfoDoc, version ) != 0 )
        {
          delete theRequestHandler;
          delete theServer;
          continue;
        }
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      QString infoFormat = parameterMap.value( "INFO_FORMAT" );
      theRequestHandler->sendGetFeatureInfoResponse( featureInfoDoc, infoFormat );
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetContext", Qt::CaseInsensitive ) == 0 )
    {
      try
      {
        QDomDocument doc = theServer->getContext();
        theRequestHandler->sendGetStyleResponse( doc );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetStyles", Qt::CaseInsensitive ) == 0 || request.compare( "GetStyle", Qt::CaseInsensitive ) == 0 ) // GetStyle for compatibility with earlier QGIS versions
    {
      try
      {
        QDomDocument doc = theServer->getStyle();
        theRequestHandler->sendGetStyleResponse( doc );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetLegendGraphic", Qt::CaseInsensitive ) == 0 ||
              request.compare( "GetLegendGraphics", Qt::CaseInsensitive ) == 0 )
      // GetLegendGraphics for compatibility with earlier QGIS versions
    {
      QImage* result = 0;
      try
      {
        result = theServer->getLegendGraphics();
      }
      catch ( QgsMapServiceException& ex )
      {
        QgsDebugMsg( "Caught exception during GetLegendGraphic request" );
        theRequestHandler->sendServiceException( ex );
      }

      if ( result )
      {
        QgsDebugMsg( "Sending GetLegendGraphic response" );
        //sending is the same for GetMap and GetLegendGraphic
        theRequestHandler->sendGetMapResponse( serviceString, result );
        QgsDebugMsg( "Response sent" );
      }
      else
      {
        //do some error handling
        QgsDebugMsg( "result image is 0" );
      }
      delete result;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetPrint", Qt::CaseInsensitive ) == 0 )
    {
      QByteArray* printOutput = 0;
      try
      {
        printOutput = theServer->getPrint( theRequestHandler->format() );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      if ( printOutput )
      {
        theRequestHandler->sendGetPrintResponse( printOutput );
      }
      delete printOutput;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else//unknown request
    {
      QgsMapServiceException e( "OperationNotSupported", "Operation " + request + " not supported" );
      theRequestHandler->sendServiceException( e );
      delete theRequestHandler;
      delete theServer;
    }
  }

  delete theMapRenderer;
  QgsDebugMsg( "************* all done ***************" );
  return 0;
}
Beispiel #29
0
QStringList Q3FileDialog::winGetOpenFileNames(const QString &filter,
                                              QString* initialDirectory,
                                              QWidget *parent,
                                              const char* /*name*/,
                                              const QString& caption,
                                              QString* selectedFilter)
{
    QStringList result;
    QFileInfo fi;
    QDir dir;
    QString isel;

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

    if (initialDirectory && !fi.isDir()) {
        *initialDirectory = fi.dirPath(true);
        isel = fi.fileName();
    }

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

    QString title = caption;
    if (title.isNull())
        title = tr("Open ");

    DWORD selFilIdx = 0;

    int idx = 0;
    if (selectedFilter && !selectedFilter->isEmpty()) {
        QStringList filterLst = makeFiltersList(filter);
        idx = filterLst.findIndex(*selectedFilter);
    }

    if (parent) {
        QEvent e(QEvent::WindowBlocked);
        QApplication::sendEvent(parent, &e);
        QApplicationPrivate::enterModal(parent);
    }

    OPENFILENAME* ofn = makeOFN(parent, isel,
                                 *initialDirectory, title,
                                 winFilter(filter), ExistingFiles);
    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.absFilePath();
            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.absFilePath();
                if (!res.isEmpty())
                    result.append(res);
                offset += f.length() + 1;
            }
        }
    }
    cleanUpOFN(&ofn);

    if (parent) {
        QApplicationPrivate::leaveModal(parent);
        QEvent e(QEvent::WindowUnblocked);
        QApplication::sendEvent(parent, &e);
    }

    if (!result.isEmpty()) {
        *initialDirectory = fi.dirPath();    // only save the path if there is a result
        if (selectedFilter)
            *selectedFilter = selFilter(filter, selFilIdx);
    }
    return result;
}
Beispiel #30
0
FILE *rpp::pp::find_include_file(std::string const &p_input_filename, std::string *p_filepath,
                                 INCLUDE_POLICY p_include_policy, bool p_skip_current_path)  {
    assert(p_filepath != 0);
    assert(!p_input_filename.empty());

    p_filepath->assign(p_input_filename);

    if(is_absolute(*p_filepath))
        return std::fopen(p_filepath->c_str(), "r");

    if(!env.current_file.empty())
        _PP_internal::extract_file_path(env.current_file, p_filepath);

    if(p_include_policy == INCLUDE_LOCAL && !p_skip_current_path) {
        std::string __tmp(*p_filepath);
        __tmp += p_input_filename;

        if(file_exists(__tmp) && !file_isdir(__tmp)) {
            p_filepath->append(p_input_filename);
            if((verbose & DEBUGLOG_INCLUDE_DIRECTIVE) != 0)
                std::cout << "** INCLUDE local  " << *p_filepath << ": found" << std::endl;
            return std::fopen(p_filepath->c_str(), "r");
        }
    }

    std::vector<std::string>::const_iterator it = include_paths.begin();

    if(p_skip_current_path) {
        it = std::find(include_paths.begin(), include_paths.end(), *p_filepath);

        if(it != include_paths.end()) {
            ++it;
        } else {
            it = include_paths.begin();
        }
    }

    for(; it != include_paths.end(); ++it) {
        if(p_skip_current_path && it == include_paths.begin())
            continue;

        p_filepath->assign(*it);
        p_filepath->append(p_input_filename);

#ifdef Q_OS_MAC
        /* On MacOSX for those not familiar with the platform, it can group a collection of things
         *  like libraries/header files as installable modules called a framework.  A framework has
         *  a well defined layout, so <OpenGL/gl.h> would be transformed into a path
         *  /.../OpenGL.framework/Headers/gl.h
         */
        QString string = QString::fromStdString(p_input_filename);
        //QStringList list = string.split("/"); //could be used for error checks
        QString module = string.split("/")[0];
        if(!module.contains('.')) {
            string.replace(module + "/", module + ".framework/Headers/");
            string = QString::fromStdString(*it) + string;
            QFileInfo file = QFileInfo(string);
            if(file.exists() && file.isFile()) {
                QString path = QString::fromStdString(*it) + module + ".framework/Headers";
                push_include_path(path.toStdString());
                if((verbose & DEBUGLOG_INCLUDE_DIRECTIVE) != 0)
                    std::cout << "** INCLUDE system " << string.toStdString() << ": found" << std::endl;
                return std::fopen(string.toLatin1().data(), "r");
            }
        }
#endif
        if(file_exists(*p_filepath) && !file_isdir(*p_filepath)) {
            if((verbose & DEBUGLOG_INCLUDE_DIRECTIVE) != 0)
                std::cout << "** INCLUDE system " << *p_filepath << ": found" << std::endl;
            return std::fopen(p_filepath->c_str(), "r");
        }

        // Log all search attempts
        if((verbose & DEBUGLOG_INCLUDE_FULL) != 0)
            std::cout << "** INCLUDE system " << *p_filepath << ": " << strerror(errno) << std::endl;
    }

    return 0;
}