string ImageFileCaptureInterface::getImageFileName(uint imageNumber, uint channelNumber)
{
    // TODO: How to replace this with C++ construct? I.e. MFC's CString has a method Format() for this, but std::string doesn't. :(
    char pathName[256];

    if (mPathFmt.find("%0.0s") != string::npos)             // format comes from GUI with constant pair for debugging
    {
        snprintf2buf(pathName, mPathFmt.c_str(), "", channelNumber);// str + int (the way to disable pair switching over series)
    }
    else if (mPathFmt.find("%") != string::npos)            // format comes from GUI with series processing
    {
        // TODO: it would be good here to check that format expects exactly 2 integers
        snprintf2buf(pathName, mPathFmt.c_str(), imageNumber, channelNumber); // expects 2 ints
    }
    else if (!mPathFmt.empty())                             // format comes as a ready path, only from some tests
    {
        // one exclusion is possible here: when ctor got a direct path to the file!
        QFileInfo fi(mPathFmt.c_str());
        if (fi.isFile() && fi.exists()) {
            return mPathFmt;                                // return immediately the initial path as it's not a format
        }

        // mPathFmt has a real folder path
        if (mPathFmt[mPathFmt.length() - 1] != '/') {       // append slash at the end if absent
            mPathFmt += '/';
        }
        mPathFmt += sPgmImageFileFmt;                       // add default format to the pathFmt

        return getImageFileName(imageNumber, channelNumber);
    }

    if (imageNumber == 1 && mPathPrefix.empty() && !QFile::exists(pathName))
    {
        /**
         * We're to check correctness of the current directory, but we need a path to "data" folder with image files.
         *
         *       "../"  - Bin directory curDir
         *    "../../"  - OpenCL project curDir
         * "../../../"  - MSVC sets curDir to the project dir (= "hostSoft")
         *
         * \note  But from another side it's dangerously to scan up to 3 levels by trying to find a requested file.\n
         *        especially if there's a special folder structure with different series...
         *        Therefore for Unix it's applied only for one parent as we run from the bin directory, \n
         *        but usually use images by path like this: "data/pair".
         */
        string path(pathName);
        string prefix;

#ifdef WIN32
        cuint numRecursiveFoldersToCheck = 3;
#else
        cuint numRecursiveFoldersToCheck = 1;               // one check for parent dir is ok or also dangerously?
#endif
        for (unsigned k = 0; k < numRecursiveFoldersToCheck; k++)
        {
            path  .insert(0, "../");
            prefix.insert(0, "../");                        // try at folder one step up

            if (QFile::exists(path.c_str()))
            {
                mPathPrefix.assign(prefix);
                break;
            }
        }
    }

    return mPathPrefix + pathName;
}
Beispiel #2
0
bool ZInstrument::loadSfz(const QString& s)
      {
      _program = 0;
      QFileInfo fi(s);
      QString path = fi.absolutePath();

      QStringList fileContents = readFile(s);

      if (fileContents.empty()) {
            return false;
            }

      SfzControl c;
      c.init();
      c.defines.clear();
      for (int i = 0;i < 128; i++)
            c.set_cc[i] = -1;

      int idx = 0;
      bool inBlockComment = false;
      // preprocessor
      while(idx < fileContents.size()) {
            QRegularExpression findWithSpaces("\"(.+)\"");
            QRegularExpression comment("//.*$");
            QRegularExpression trailingSpacesOrTab("^[\\s\\t]*");
            QRegularExpressionMatch foundWithSpaces;
            QString curLine = fileContents[idx];
            QString curLineCopy = curLine;
            bool nextIsImportant = false;
            int idxBlockComment = 0;
            int from = 0;

            for (QChar chr : curLineCopy) {
                  bool terminated = false;

                  if (nextIsImportant) {
                        nextIsImportant = false;
                        if (inBlockComment && chr == '/') { // found block end
                              inBlockComment = false;
                              terminated = true;
                              curLine.remove(from, idxBlockComment - from + 1);
                              idxBlockComment = from - 1;
                              }
                        else if (!inBlockComment && chr == '*') { // found block start
                              inBlockComment = true;
                              terminated = true;
                              from = idxBlockComment - 1;
                              }
                        }

                  if (!terminated && inBlockComment && chr == '*')
                        nextIsImportant = true;
                  else if (!terminated && !inBlockComment && chr == '/')
                        nextIsImportant = true;

                  idxBlockComment++;
                  }

            if (inBlockComment)
                  curLine.remove(from, curLine.size() - from);

            curLine = curLine.remove(comment);
            curLine.remove(trailingSpacesOrTab);
            fileContents[idx] = curLine;

            if (curLine.startsWith("#define")) {
                  QStringList define = curLine.split(" ");
                  foundWithSpaces = findWithSpaces.match(curLine);
                  if (define.size() == 3)
                        c.defines.insert(std::pair<QString, QString>(define[1], define[2]));
                  else if(foundWithSpaces.hasMatch())
                        c.defines.insert(std::pair<QString, QString>(define[1], foundWithSpaces.captured(1)));
                  fileContents.removeAt(idx);
                  }
            else if (curLine.startsWith("#include")) {
                  foundWithSpaces = findWithSpaces.match(curLine);
                  if (foundWithSpaces.hasMatch()) {
                        QString newFilename = foundWithSpaces.captured(1);

                        for(auto define : c.defines) {
                              newFilename.replace(define.first, define.second);
                              }

                        QStringList newFileContents = readFile(path + "/" + newFilename);
                        if (newFileContents.empty())
                              return false;

                        int offset = 1;
                        for (QString newFileLine : newFileContents) {
                              fileContents.insert(idx+offset, newFileLine);
                              offset++;
                              }

                        fileContents.removeAt(idx);
                        }
                  }
            else if (curLine.isEmpty())
                  fileContents.removeAt(idx);
            else
                  idx++;
            }

      int total = fileContents.size();
      SfzRegion r;
      SfzRegion g;      // group
      SfzRegion glob;
      r.init(path);
      g.init(path);
      glob.init(path);

      bool groupMode = false;
      bool globMode = false;
      zerberus->setLoadProgress(0);

      for (int idx = 0; idx < fileContents.size(); idx++) {
            QString curLine = fileContents[idx];
            zerberus->setLoadProgress(((qreal) idx * 100) /  (qreal) total);

            if (zerberus->loadWasCanceled())
                  return false;
            if (curLine.startsWith("<global>")) {
                  if (!globMode && !groupMode && !r.isEmpty())
                        addRegion(r);
                  glob.init(path);
                  g.init(path); // global also resets group
                  r.init(path);
                  globMode = true;
                  }
            if (curLine.startsWith("<group>")) {
                  if (!groupMode && !globMode && !r.isEmpty())
                        addRegion(r);
                  g.init(path);
                  if (globMode) {
                        glob = r;
                        globMode = false;
                        }
                  else {
                        r = glob; // initialize group with global values
                        }
                  groupMode = true;
                  curLine = curLine.mid(7);
                  }
            else if (curLine.startsWith("<region>")) {
                  if (groupMode) {
                        g = r;
                        groupMode = false;
                        }
                  else if (globMode) {
                        glob = r;
                        g = glob;
                        globMode = false;
                        }
                  else {
                        if (!r.isEmpty())
                              addRegion(r);
                        r = g;  // initialize next region with group values
                        }
                  curLine = curLine.mid(8);
                  }
            else if (curLine.startsWith("<control>"))
                  c.init();

            QRegularExpression re("\\s?([\\w\\$]+)="); // defines often use the $-sign
            QRegularExpressionMatchIterator i = re.globalMatch(curLine);

            while (i.hasNext()) {
                  QRegularExpressionMatch match = i.next();
                  int si = match.capturedEnd();
                  int ei;
                  if (i.hasNext()) {
                        QRegularExpressionMatch nextMatch = i.peekNext();
                        ei = nextMatch.capturedStart();
                        }
                  else
                        ei = curLine.size();
                  QString s = curLine.mid(si, ei-si);
                  r.readOp(match.captured(1), s, c);
                  }
            }

      for (int i = 0; i < 128; i++)
            _setcc[i] = c.set_cc[i];

      zerberus->setLoadProgress(100);
      if (!groupMode && !globMode && !r.isEmpty())
            addRegion(r);
      return true;
      }
EngineError KadmosDialog::findClassifiers()
{
    findClassifierPath();

    KLocale *locale = KGlobal::locale();
    QStringList allCountries = locale->allLanguagesTwoAlpha ();
    for ( QStringList::Iterator it = allCountries.begin();
          it != allCountries.end(); ++it )
    {
        m_longCountry2short[locale->twoAlphaToCountryName(*it)] = *it;
    }
    m_longCountry2short[i18n("European Countries")] = "eu";
    m_longCountry2short[ CNTRY_CZ ] = "cz";
    m_longCountry2short[ CNTRY_GB ] = "us";

    QStringList lst;

    /* custom Path */
    if( ! m_customClassifierPath.isEmpty() )
    {
        QDir dir( m_customClassifierPath );

        QStringList lst1 = dir.entryList( "ttf*.rec" );

        for ( QStringList::Iterator it = lst1.begin(); it != lst1.end(); ++it )
        {
            lst << m_customClassifierPath + *it;
        }

        lst1 = dir.entryList( "hand*.rec" );

        for ( QStringList::Iterator it = lst1.begin(); it != lst1.end(); ++it )
        {
            lst << m_customClassifierPath + *it;
        }

        lst1 = dir.entryList( "norm*.rec" );

        for ( QStringList::Iterator it = lst1.begin(); it != lst1.end(); ++it )
        {
            lst << m_customClassifierPath + *it;
        }
    }
    else
    {
        /* standard location */
        KStandardDirs stdDir;
        kdDebug(28000) << "Starting to read resource" << endl;

        lst = stdDir.findAllResources( "data",
                                       "kooka/classifiers/*.rec",
                                       true,   /* recursive */
                                       true ); /* uniqu */
    }


    /* no go through lst and sort out hand-, ttf- and norm classifier */
    for ( QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
    {
        QFileInfo fi( *it);
        QString name = fi.fileName().lower();

        kdDebug(28000) << "Checking file " << *it << endl;

        if( name.startsWith( "ttf" ) )
        {
            QString lang = name.mid(3,2);
            if( allCountries.contains(lang) )
            {
                QString lngCountry = locale->twoAlphaToCountryName(lang);
                if( lngCountry.isEmpty() )
                    lngCountry = name;
                m_ttfClassifier << lngCountry;
                kdDebug(28000) << "ttf: Insert country " << lngCountry << endl;
            }
            else if( lang == "cz" )
            {
                m_ttfClassifier << CNTRY_CZ;
            }
            else if( lang == "us" )
            {
                m_ttfClassifier << CNTRY_GB;
            }
            else
            {
                m_ttfClassifier << name;
                kdDebug(28000) << "ttf: Unknown country" << endl;
            }
        }
        else if( name.startsWith( "hand" ) )
        {
            QString lang = name.mid(4,2);
            if( allCountries.contains(lang) )
            {
                QString lngCountry = locale->twoAlphaToCountryName(lang);
                if( lngCountry.isEmpty() )
                    lngCountry = name;
                m_handClassifier << lngCountry;
            }
            else if( lang == "cz" )
            {
                m_handClassifier << i18n( "Czech Republic, Slovakia");
            }
            else if( lang == "us" )
            {
                m_handClassifier << i18n( "Great Britain, USA" );
            }
            else
            {
                kdDebug(28000) << "Hand: Unknown country " << lang << endl;
                m_handClassifier << name;
            }
        }
        else if( name.startsWith( "norm" ))
        {
            m_haveNorm = true;
        }

        kdDebug(28000) << "Found classifier: " << *it << endl;
        m_classifierPath << *it;
    }

    if( m_handClassifier.count()+m_ttfClassifier.count()>0 )
    {
        /* There are classifiers */
        return ENG_OK;
    }
    else
    {
        /* Classifier are missing */
        return ENG_DATA_MISSING;
    }
}
Beispiel #4
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void FeatureInfoReader::dataCheck()
{
  setErrorCondition(0);
  DataArrayPath tempPath;

  DataContainer::Pointer m = getDataContainerArray()->getPrereqDataContainer<AbstractFilter>(this, m_FeatureIdsArrayPath.getDataContainerName());
  if(getErrorCondition() < 0) { return; }

  QVector<size_t> tDims(1, 0);
  m->createNonPrereqAttributeMatrix<AbstractFilter>(this, getCellFeatureAttributeMatrixName(), tDims, DREAM3D::AttributeMatrixType::CellFeature);

  QFileInfo fi(getInputFile());
  if (getInputFile().isEmpty() == true)
  {
    QString ss = QObject::tr("The input file must be set").arg(ClassName());
    setErrorCondition(-387);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }
  else if (fi.exists() == false)
  {
    QString ss = QObject::tr("The input file does not exist");
    setErrorCondition(-388);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }

  if (m_CellFeatureAttributeMatrixName.isEmpty() == true)
  {
    QString ss = QObject::tr("Feature Attribute Matrix name must be set");
    setErrorCondition(-1);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
  }

  QVector<size_t> cDims(1, 1);
  m_FeatureIdsPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter>(this, getFeatureIdsArrayPath(), cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_FeatureIdsPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_FeatureIds = m_FeatureIdsPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */

  if (m_CreateCellLevelArrays)
  {
    tempPath.update(m_FeatureIdsArrayPath.getDataContainerName(), m_FeatureIdsArrayPath.getAttributeMatrixName(), getCellPhasesArrayName() );
    m_CellPhasesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter, int32_t>(this,  tempPath, 0, cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
    if( NULL != m_CellPhasesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
    { m_CellPhases = m_CellPhasesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */

    cDims[0] = 3;
    tempPath.update(m_FeatureIdsArrayPath.getDataContainerName(), m_FeatureIdsArrayPath.getAttributeMatrixName(), getCellEulerAnglesArrayName() );
    m_CellEulerAnglesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<float>, AbstractFilter, float>(this,  tempPath, 0, cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
    if( NULL != m_CellEulerAnglesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
    { m_CellEulerAngles = m_CellEulerAnglesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
  }

  cDims[0] = 1;
  tempPath.update(m_FeatureIdsArrayPath.getDataContainerName(), getCellFeatureAttributeMatrixName(), getFeaturePhasesArrayName() );
  m_FeaturePhasesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<int32_t>, AbstractFilter, int32_t>(this,  tempPath, 0, cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_FeaturePhasesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_FeaturePhases = m_FeaturePhasesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */

  cDims[0] = 3;
  tempPath.update(m_FeatureIdsArrayPath.getDataContainerName(), getCellFeatureAttributeMatrixName(), getFeatureEulerAnglesArrayName() );
  m_FeatureEulerAnglesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<float>, AbstractFilter, float>(this,  tempPath, 0, cDims); /* Assigns the shared_ptr<> to an instance variable that is a weak_ptr<> */
  if( NULL != m_FeatureEulerAnglesPtr.lock().get() ) /* Validate the Weak Pointer wraps a non-NULL pointer to a DataArray<T> object */
  { m_FeatureEulerAngles = m_FeatureEulerAnglesPtr.lock()->getPointer(0); } /* Now assign the raw pointer to data from the DataArray<T> object */
}
Beispiel #5
0
QString InfoFile::getInfo(MediaData md)
{
    QString s;

    // General
    QFileInfo fi(md.filename);

    QString icon;

    switch (md.type) {
    case TYPE_FILE	:

        if (md.novideo)
            icon = "type_audio.png";
        else
            icon = "type_video.png";

        break;
    case TYPE_DVD	:
        icon = "type_dvd.png";
        break;
    case TYPE_VCD	:
        icon = "type_vcd.png";
        break;
    case TYPE_AUDIO_CD	:
        icon = "type_vcd.png";
        break;
    case TYPE_TV	:
        icon = "type_tv.png";
        break;
    case TYPE_STREAM :
        icon = "type_url.png";
        break;
    default 		:
        icon = "type_unknown.png";
    }

    icon = "<img src=\"" + Images::file(icon) + "\"> ";

    if (md.type == TYPE_DVD) {
        DiscData disc_data = DiscName::split(md.filename);
        s += title(icon + disc_data.protocol + "://" + QString::number(disc_data.title));
    } else {
        s += title(icon + md.displayName());
    }

    s += openPar(tr("General"));

    if (fi.exists()) {
        //s += addItem( tr("Path"), fi.dirPath() );
        s += addItem(tr("File"), fi.absoluteFilePath());
        s += addItem(tr("Size"), tr("%1 KB (%2 MB)").arg(fi.size() / 1024)
                     .arg(fi.size() / 1048576));
    } else {
        QString url = md.filename;
        s += addItem(tr("URL"), url);
    }

    s += addItem(tr("Length"), Helper::formatTime((int)md.duration));
    s += addItem(tr("Demuxer"), md.demuxer);
    s += closePar();

    // Clip info
    QString c;

    if (!md.clip_name.isEmpty()) c += addItem(tr("Name"), md.clip_name);

    if (!md.clip_artist.isEmpty()) c += addItem(tr("Artist"), md.clip_artist);

    if (!md.clip_author.isEmpty()) c += addItem(tr("Author"), md.clip_author);

    if (!md.clip_album.isEmpty()) c += addItem(tr("Album"), md.clip_album);

    if (!md.clip_genre.isEmpty()) c += addItem(tr("Genre"), md.clip_genre);

    if (!md.clip_date.isEmpty()) c += addItem(tr("Date"), md.clip_date);

    if (!md.clip_track.isEmpty()) c += addItem(tr("Track"), md.clip_track);

    if (!md.clip_copyright.isEmpty()) c += addItem(tr("Copyright"), md.clip_copyright);

    if (!md.clip_comment.isEmpty()) c += addItem(tr("Comment"), md.clip_comment);

    if (!md.clip_software.isEmpty()) c += addItem(tr("Software"), md.clip_software);

    if (!md.stream_title.isEmpty()) c += addItem(tr("Stream title"), md.stream_title);

    if (!md.stream_url.isEmpty()) c += addItem(tr("Stream URL"), md.stream_url);

    if (!c.isEmpty()) {
        s += openPar(tr("Clip info"));
        s += c;
        s += closePar();
    }

    // Video info
    if (!md.novideo) {
        s += openPar(tr("Video"));
        s += addItem(tr("Resolution"), QString("%1 x %2").arg(md.video_width).arg(md.video_height));
        s += addItem(tr("Aspect ratio"), QString::number(md.video_aspect));
        s += addItem(tr("Format"), md.video_format);
        s += addItem(tr("Bitrate"), tr("%1 kbps").arg(md.video_bitrate / 1000));
        s += addItem(tr("Frames per second"), md.video_fps);
        s += addItem(tr("Selected codec"), md.video_codec);
        s += closePar();
    }

    // Audio info
    s += openPar(tr("Initial Audio Stream"));
    s += addItem(tr("Format"), md.audio_format);
    s += addItem(tr("Bitrate"), tr("%1 kbps").arg(md.audio_bitrate / 1000));
    s += addItem(tr("Rate"), tr("%1 Hz").arg(md.audio_rate));
    s += addItem(tr("Channels"), QString::number(md.audio_nch));
    s += addItem(tr("Selected codec"), md.audio_codec);
    s += closePar();

    // Audio Tracks
    if (md.audios.numItems() > 0) {
        s += openPar(tr("Audio Streams"));
        row++;
        s += openItem();
        s += "<td>" + tr("#", "Info for translators: this is a abbreviation for number") + "</td><td>" +
             tr("Language") + "</td><td>" + tr("Name") + "</td><td>" +
             tr("ID", "Info for translators: this is a identification code") + "</td>";
        s += closeItem();

        for (int n = 0; n < md.audios.numItems(); n++) {
            row++;
            s += openItem();
            QString lang = md.audios.itemAt(n).lang();

            if (lang.isEmpty()) lang = "<i>&lt;" + tr("empty") + "&gt;</i>";

            QString name = md.audios.itemAt(n).name();

            if (name.isEmpty()) name = "<i>&lt;" + tr("empty") + "&gt;</i>";

            s += QString("<td>%1</td><td>%2</td><td>%3</td><td>%4</td>")
                 .arg(n).arg(lang).arg(name)
                 .arg(md.audios.itemAt(n).ID());
            s += closeItem();
        }

        s += closePar();
    }

    // Subtitles
    if (md.subs.numItems() > 0) {
        s += openPar(tr("Subtitles"));
        row++;
        s += openItem();
        s += "<td>" + tr("#", "Info for translators: this is a abbreviation for number") + "</td><td>" +
             tr("Type") + "</td><td>" +
             tr("Language") + "</td><td>" + tr("Name") + "</td><td>" +
             tr("ID", "Info for translators: this is a identification code") + "</td>";
        s += closeItem();

        for (int n = 0; n < md.subs.numItems(); n++) {
            row++;
            s += openItem();
            QString t;

            switch (md.subs.itemAt(n).type()) {
            case SubData::File:
                t = "FILE_SUB";
                break;
            case SubData::Vob:
                t = "VOB";
                break;
            default:
                t = "SUB";
            }

            QString lang = md.subs.itemAt(n).lang();

            if (lang.isEmpty()) lang = "<i>&lt;" + tr("empty") + "&gt;</i>";

            QString name = md.subs.itemAt(n).name();

            if (name.isEmpty()) name = "<i>&lt;" + tr("empty") + "&gt;</i>";

            /*
            s += QString("<td>%1</td><td>%2</td><td>%3</td><td>%4</td><td>%5</td>")
                 .arg(n).arg(t).arg(lang).arg(name)
                 .arg(md.subs.itemAt(n).ID());
            */
            s += "<td>" + QString::number(n) + "</td><td>" + t +
                 "</td><td>" + lang + "</td><td>" + name +
                 "</td><td>" + QString::number(md.subs.itemAt(n).ID()) + "</td>";
            s += closeItem();
        }

        s += closePar();
    }

    return "<html><body bgcolor=\"white\"><font color=\"black\">" + s + "</font></body></html>";
}
Beispiel #6
0
void 
PrintHelper::orderedtask_print(OrderedTask& task, const AircraftState &state) 
{
  abstracttask_print(task, state);
  if (!task.stats.task_valid)
    return;

  std::ofstream fi("results/res-isolines.txt");
  for (unsigned i=0; i<task.task_points.size(); i++) {
    fi << "## point " << i << "\n";
    if (task.task_points[i]->type == TaskPoint::AAT) {
      aatpoint_print(fi, (AATPoint&)*task.task_points[i], state,
                     task.GetTaskProjection(), 1);
    } else {
      orderedtaskpoint_print(fi,*task.task_points[i],state,1);
    }
    fi << "\n";
  }

  std::ofstream f1("results/res-task.txt");

  f1 << "#### Task points\n";
  for (unsigned i=0; i<task.task_points.size(); i++) {
    f1 << "## point " << i << " ###################\n";
    if (task.task_points[i]->type == TaskPoint::AAT) {
      aatpoint_print(f1, (AATPoint&)*task.task_points[i], state,
                     task.GetTaskProjection(), 0);
    } else {
      orderedtaskpoint_print(f1,*task.task_points[i],state,0);
    }
    f1 << "\n";
  }

  std::ofstream f5("results/res-ssample.txt");
  f5 << "#### Task sampled points\n";
  for (unsigned i=0; i<task.task_points.size(); i++) {
    f5 << "## point " << i << "\n";
    sampledtaskpoint_print_samples(f5,*task.task_points[i],state);
    f5 << "\n";
  }

  std::ofstream f2("results/res-max.txt");
  f2 << "#### Max task\n";
  for (unsigned i=0; i<task.task_points.size(); i++) {
    OrderedTaskPoint *tp = task.task_points[i];
    f2 <<  tp->GetLocationMax().longitude << " "
       <<  tp->GetLocationMax().latitude << "\n";
  }

  std::ofstream f3("results/res-min.txt");
  f3 << "#### Min task\n";
  for (unsigned i=0; i<task.task_points.size(); i++) {
    OrderedTaskPoint *tp = task.task_points[i];
    f3 <<  tp->GetLocationMin().longitude << " "
       <<  tp->GetLocationMin().latitude << "\n";
  }

  std::ofstream f4("results/res-rem.txt");
  f4 << "#### Remaining task\n";
  for (unsigned i=0; i<task.task_points.size(); i++) {
    OrderedTaskPoint *tp = task.task_points[i];
    f4 <<  tp->GetLocationRemaining().longitude << " "
       <<  tp->GetLocationRemaining().latitude << "\n";
  }
}
Beispiel #7
0
void docAttach::sSave()
{  
  XSqlQuery newDocass;
  QString title;
  QUrl url;

  //set the purpose
  if (_docAttachPurpose->currentIndex() == 0)
    _purpose = "S";
  else if (_docAttachPurpose->currentIndex() == 1)
    _purpose = "A";
  else if (_docAttachPurpose->currentIndex() == 2)
    _purpose = "C";
  else if (_docAttachPurpose->currentIndex() == 3)
    _purpose = "D";

  //if then series, type derived from the stack index. e.g.
  if (_docType->currentIndex() == 1)
  {
    _targettype = "T";
    _targetid = _cntct->id();
  }
  else if (_docType->currentIndex() == 2)
  {
    _targettype = "CRMA";
    _targetid = _crmacct->id();
  }
  else if (_docType->currentIndex() == 3)
  {
    _targettype = "C";
    _targetid = _cust->id();
  }
  else if (_docType->currentIndex() == 4)
  {
    _targettype = "EMP";
    _targetid = _emp->id();
  }
  else if (_docType->currentIndex() == 5)
  {
    if(_file->text().trimmed().isEmpty())
    {
      QMessageBox::warning( this, tr("Must Specify file"),
                            tr("You must specify a file before you may save.") );
      return;
    }

     _targettype = "URL";
     title = _filetitle->text();
     url = QUrl(_file->text());
     if (url.scheme().isEmpty())
       url.setScheme("file");
  }
  else if (_docType->currentIndex() == 6)
  {
     _targettype = "IMG";
     _targetid = _img->id();
  }
  else if (_docType->currentIndex() == 7)
  {
    _targettype = "INCDT";
    _targetid = _incdt->id();
  }
  else if (_docType->currentIndex() == 8)
  {
    _targettype = "I";
    _targetid = _item->id();
  }
  else if (_docType->currentIndex() == 9)
  {
    _targettype = "OPP";
    _targetid = _opp->id();
  }
  else if (_docType->currentIndex() == 10)
  {
    _targettype = "J";
    _targetid = _proj->id();
  }
  else if (_docType->currentIndex() == 11)
  {
    _targettype = "P";
    _targetid = _po->id();
  }
  else if (_docType->currentIndex() == 12)
  {
    _targettype = "S";
    _targetid = _so->id();
  }
  else if (_docType->currentIndex() == 13)
  {
    _targettype = "V";
    _targetid = _vend->id();
  }
  else if (_docType->currentIndex() == 14)
  {
    if(_url->text().trimmed().isEmpty())
    {
      QMessageBox::warning( this, tr("Must Specify file"),
                            tr("You must specify a file before you may save.") );
      return;
    }

    _targettype = "URL";
    title = _urltitle->text();
    url = QUrl(_url->text());
    if (url.scheme().isEmpty())
      url.setScheme("http");
  }
  else if (_docType->currentIndex() == 15)
  {
    _targettype = "W";
    _targetid = _wo->id();
  }

  if (_targettype == "IMG")
  {
     // For now images are handled differently because of legacy structures...
    newDocass.prepare( "INSERT INTO imageass "
                       "( imageass_source, imageass_source_id, imageass_image_id, imageass_purpose ) "
                       "VALUES "
                       "( :docass_source_type, :docass_source_id, :docass_target_id, :docass_purpose );" );
  }
  else if (_targettype == "URL")
  {
    if(!url.isValid())
    {
      QMessageBox::warning( this, tr("Must Specify valid path"),
                            tr("You must specify a path before you may save.") );
      return;
    }

    QByteArray  bytarr;
    QFileInfo fi(url.toLocalFile());

    if(_saveDbCheck->isChecked() &&
       (url.scheme()=="file") &&
       (_mode == "new"))
    {
      if (!fi.exists())
      {
        QMessageBox::warning( this, tr("File Error"),
                             tr("File %1 was not found and will not be saved.").arg(url.toLocalFile()));
        return;
      }
      QFile sourceFile(url.toLocalFile());
      if (!sourceFile.open(QIODevice::ReadOnly))
      {
        QMessageBox::warning( this, tr("File Open Error"),
                             tr("Could not open source file %1 for read.")
                                .arg(url.toLocalFile()));
        return;
      }
      bytarr = sourceFile.readAll();
      url.setPath(fi.fileName().remove(" "));
      url.setScheme("");
    }

    // For now urls are handled differently because of legacy structures...
    if (_mode == "new")
      newDocass.prepare( "INSERT INTO url "
                         "( url_source, url_source_id, url_title, url_url, url_stream ) "
                         "VALUES "
                         "( :docass_source_type, :docass_source_id, :title, :url, :stream );" );
    else
      newDocass.prepare( "UPDATE url SET "
                         "  url_title = :title, "
                         "  url_url = :url "
                         "WHERE (url_id=:url_id);" );
    newDocass.bindValue(":url_id", _urlid);
    newDocass.bindValue(":title", title);
    newDocass.bindValue(":url", url.toString());
    newDocass.bindValue(":stream", bytarr);
  }
  else
  {
    newDocass.prepare( "INSERT INTO docass "
                       "( docass_source_type, docass_source_id, docass_target_type, docass_target_id, docass_purpose ) "
                       "VALUES "
                       "( :docass_source_type, :docass_source_id, :docass_target_type, :docass_target_id, :docass_purpose );" );
    newDocass.bindValue(":docass_target_type", _targettype);
  }

  if (_targettype == Documents::_documentMap[_source].ident &&
      _targetid == _sourceid)
  {
    QMessageBox::critical(this,tr("Invalid Selection"),
                          tr("You may not attach a document to itself."));
    return;
  }

  newDocass.bindValue(":docass_source_type", Documents::_documentMap[_source].ident);
  newDocass.bindValue(":docass_source_id", _sourceid);
  newDocass.bindValue(":docass_target_id", _targetid);
  newDocass.bindValue(":docass_purpose", _purpose);

  newDocass.exec();

  accept();
}
void Addoredit_PovyshKval::on_pushButton_ok_clicked()
{
    bool error=false;
    if (ui->comboBox_sotr->currentIndex()==-1)
    {
        error = true;
    }
    else
    {
        error = false;
    }
    if (error == true)
    {
        ui->label_error->setVisible(true);
        return;
    }
    else
    {
        if (! this->isEdit)
        {
            if (! dal_main->checkConnection())
            {
                QMessageBox::warning(this, tr("Ошибка соединения"), tr("Соединение не установлено"));
                return;
            }
            QFileInfo fi(this->UrlFail);
            QString names = fi.fileName();
            QFile::copy(this->UrlFail, "C:\\Dropbox\\" + names);
            this->UrlFail = "C:\\Dropbox\\" + names;
            if (dal_prepodcontrol->addPovyskKval(ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt(),
                                                 ui->dateEdit->date(),
                                                 ui->lineEdit_tema->text(),
                                                 ui->lineEdit_kurs->text(),
                                                 ui->lineEdit_mesto->text(),
                                                 ui->lineEdit_sert->text(),
                                                 this->NameFails,
                                                 ui->lineEdit_ocenka->text().toDouble(),
                                                 this->UrlFail))
            {

                QMessageBox::information(this, tr("Информация"), tr("Запись успешно добавлена"));
            }
            else
            {
                QMessageBox::warning(this, tr("Ошибка"), tr("Данные не были добавлены в базу данных"));
            }
        }

        else
        {
            if (! dal_main->checkConnection())
            {
                QMessageBox::warning(this, tr("Ошибка соединения"), tr("Соединение не установлено"));
                return;
            }
            QFileInfo fi(this->UrlFail);
            QString names = fi.fileName();
            QFile::copy(this->UrlFail, "C:\\Dropbox\\" + names);
            this->UrlFail = "C:\\Dropbox\\" + names;
            if (dal_prepodcontrol->editPovyskKval(this->id_povyshKval,
                                                  ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt(),
                                                  ui->dateEdit->date(),
                                                  ui->lineEdit_tema->text(),
                                                  ui->lineEdit_kurs->text(),
                                                  ui->lineEdit_mesto->text(),
                                                  ui->lineEdit_sert->text(),
                                                  this->NameFails,
                                                  ui->lineEdit_ocenka->text().toDouble(),
                                                  this->UrlFail))
            {
                QMessageBox::information(this, tr("Информация"), tr("Данные успешно отредактированы"));
            }
            else
            {
                QMessageBox::warning(this, tr("Ошибка"), tr("Данные не были изменены"));
            }
        }
        this->close();
    }
}
Beispiel #9
0
tristate SqliteVacuum::run()
{
    const QString dump_app = QString::fromLatin1(KDB_SQLITE_DUMP_TOOL);
    //sqliteDebug() << dump_app;
    if (dump_app.isEmpty()) {
        m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not find tool \"%1\".")
                             .arg(dump_app));
        sqliteWarning() << m_result;
        return false;
    }
    const QString sqlite_app(KDb::sqlite3ProgramPath());
    //sqliteDebug() << sqlite_app;
    if (sqlite_app.isEmpty()) {
        m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not find application \"%1\".")
                             .arg(sqlite_app));
        sqliteWarning() << m_result;
        return false;
    }

    QFileInfo fi(m_filePath);
    if (!fi.isReadable()) {
        m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not read file \"%1\".")
                             .arg(m_filePath));
        sqliteWarning() << m_result;
        return false;
    }

    //sqliteDebug() << fi.absoluteFilePath() << fi.absoluteDir().path();

    delete m_dumpProcess;
    m_dumpProcess = new QProcess(this);
    m_dumpProcess->setWorkingDirectory(fi.absoluteDir().path());
    m_dumpProcess->setReadChannel(QProcess::StandardError);
    connect(m_dumpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStdErr()));
    connect(m_dumpProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(dumpProcessFinished(int,QProcess::ExitStatus)));

    delete m_sqliteProcess;
    m_sqliteProcess = new QProcess(this);
    m_sqliteProcess->setWorkingDirectory(fi.absoluteDir().path());
    connect(m_sqliteProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(sqliteProcessFinished(int,QProcess::ExitStatus)));

    m_dumpProcess->setStandardOutputProcess(m_sqliteProcess);
    m_dumpProcess->start(dump_app, QStringList() << fi.absoluteFilePath());
    if (!m_dumpProcess->waitForStarted()) {
        delete m_dumpProcess;
        m_dumpProcess = 0;
        m_result.setCode(ERR_OTHER);
        return false;
    }

    QTemporaryFile *tempFile = new QTemporaryFile(fi.absoluteFilePath());
    tempFile->open();
    m_tmpFilePath = tempFile->fileName();
    delete tempFile;
    //sqliteDebug() << m_tmpFilePath;
    m_sqliteProcess->start(sqlite_app, QStringList() << m_tmpFilePath);
    if (!m_sqliteProcess->waitForStarted()) {
        delete m_dumpProcess;
        m_dumpProcess = 0;
        delete m_sqliteProcess;
        m_sqliteProcess = 0;
        m_result.setCode(ERR_OTHER);
        return false;
    }

    delete m_dlg;
    m_dlg = new QProgressDialog(0); // krazy:exclude=qclasses
    m_dlg->setWindowTitle(tr("Compacting database"));
    m_dlg->setLabelText(
        QLatin1String("<qt>") + tr("Compacting database \"%1\"...")
            .arg(QLatin1String("<nobr>")
                 + QDir::fromNativeSeparators(fi.fileName())
                 + QLatin1String("</nobr>"))
    );
    m_dlg->adjustSize();
    m_dlg->resize(300, m_dlg->height());
    m_dlg->setMinimumDuration(1000);
    m_dlg->setAutoClose(true);
    m_dlg->setRange(0, 100);
    m_dlg->exec();
    if (m_dlg->wasCanceled()) {
        cancelClicked();
    }
    delete m_dlg;
    m_dlg = 0;
    while (m_dumpProcess->state() == QProcess::Running
           && m_sqliteProcess->state()  == QProcess::Running)
    {
        readFromStdErr();
        qApp->processEvents(QEventLoop::AllEvents, 50000);
    }

    readFromStdErr();
    return true;
}
bool QgsGeometryCheckerResultTab::exportErrorsDo( const QString &file )
{
  QList< QPair<QString, QString> > attributes;
  attributes.append( qMakePair( QStringLiteral( "Layer" ), QStringLiteral( "String;30;" ) ) );
  attributes.append( qMakePair( QStringLiteral( "FeatureID" ), QStringLiteral( "String;10;" ) ) );
  attributes.append( qMakePair( QStringLiteral( "ErrorDesc" ), QStringLiteral( "String;80;" ) ) );

  QFileInfo fi( file );
  QString ext = fi.suffix();
  QString driver = QgsVectorFileWriter::driverForExtension( ext );

  QLibrary ogrLib( QgsProviderRegistry::instance()->library( QStringLiteral( "ogr" ) ) );
  if ( !ogrLib.load() )
  {
    return false;
  }
  typedef bool ( *createEmptyDataSourceProc )( const QString &, const QString &, const QString &, QgsWkbTypes::Type, const QList< QPair<QString, QString> > &, const QgsCoordinateReferenceSystem & );
  createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( ogrLib.resolve( "createEmptyDataSource" ) );
  if ( !createEmptyDataSource )
  {
    return false;
  }
  if ( !createEmptyDataSource( file, driver, "UTF-8", QgsWkbTypes::Point, attributes, QgsProject::instance()->crs() ) )
  {
    return false;
  }
  QgsVectorLayer *layer = new QgsVectorLayer( file, QFileInfo( file ).baseName(), QStringLiteral( "ogr" ) );
  if ( !layer->isValid() )
  {
    delete layer;
    return false;
  }

  int fieldLayer = layer->fields().lookupField( QStringLiteral( "Layer" ) );
  int fieldFeatureId = layer->fields().lookupField( QStringLiteral( "FeatureID" ) );
  int fieldErrDesc = layer->fields().lookupField( QStringLiteral( "ErrorDesc" ) );
  for ( int row = 0, nRows = ui.tableWidgetErrors->rowCount(); row < nRows; ++row )
  {
    QgsGeometryCheckError *error = ui.tableWidgetErrors->item( row, 0 )->data( Qt::UserRole ).value<QgsGeometryCheckError *>();
    QgsVectorLayer *srcLayer = mChecker->getContext()->featurePools[error->layerId()]->layer();
    QgsFeature f( layer->fields() );
    f.setAttribute( fieldLayer, srcLayer->name() );
    f.setAttribute( fieldFeatureId, error->featureId() );
    f.setAttribute( fieldErrDesc, error->description() );
    QgsGeometry geom( new QgsPoint( error->location() ) );
    f.setGeometry( geom );
    layer->dataProvider()->addFeatures( QgsFeatureList() << f );
  }

  // Remove existing layer with same uri
  QStringList toRemove;
  for ( QgsMapLayer *maplayer : QgsProject::instance()->mapLayers() )
  {
    if ( dynamic_cast<QgsVectorLayer *>( maplayer ) &&
         static_cast<QgsVectorLayer *>( maplayer )->dataProvider()->dataSourceUri() == layer->dataProvider()->dataSourceUri() )
    {
      toRemove.append( maplayer->id() );
    }
  }
  if ( !toRemove.isEmpty() )
  {
    QgsProject::instance()->removeMapLayers( toRemove );
  }

  QgsProject::instance()->addMapLayers( QList<QgsMapLayer *>() << layer );
  return true;
}
bool QgsNewSpatialiteLayerDialog::createDb()
{
  QString dbPath = mDatabaseComboBox->currentText();
  if ( dbPath.isEmpty() )
    return false;

  QFile newDb( dbPath );
  if ( !newDb.exists() )
  {
    QString errCause;
    bool res = false;

    QString spatialite_lib = QgsProviderRegistry::instance()->library( "spatialite" );
    QLibrary* myLib = new QLibrary( spatialite_lib );
    bool loaded = myLib->load();
    if ( loaded )
    {
      QgsDebugMsg( "spatialite provider loaded" );

      typedef bool ( *createDbProc )( const QString&, QString& );
      createDbProc createDbPtr = ( createDbProc ) cast_to_fptr( myLib->resolve( "createDb" ) );
      if ( createDbPtr )
      {
        res = createDbPtr( dbPath, errCause );
      }
      else
      {
        errCause = "Resolving createDb(...) failed";
      }
    }
    delete myLib;

    if ( !res )
    {
      QMessageBox::warning( nullptr, tr( "SpatiaLite Database" ), errCause );
      pbnFindSRID->setEnabled( false );
    }
  }

  QFileInfo fi( newDb );
  if ( !fi.exists() )
  {
    pbnFindSRID->setEnabled( false );
    return false;
  }

  QString key = "/SpatiaLite/connections/" + fi.fileName() + "/sqlitepath";

  QSettings settings;
  if ( !settings.contains( key ) )
  {
    settings.setValue( "/SpatiaLite/connections/selected", fi.fileName() + tr( "@" ) + fi.canonicalFilePath() );
    settings.setValue( key, fi.canonicalFilePath() );

    QMessageBox::information( nullptr, tr( "SpatiaLite Database" ), tr( "Registered new database!" ) );
  }

  pbnFindSRID->setEnabled( true );

  return true;
}
Beispiel #12
0
void QgsShapeFile::setDefaultTable()
{
  QFileInfo fi( fileName );
  table_name = fi.baseName();
}
Beispiel #13
0
bool UIWizardExportApp::exportAppliance()
{
    /* Get export appliance widget: */
    UIApplianceExportEditorWidget *pExportApplianceWidget = field("applianceWidget").value<ExportAppliancePointer>();
    /* Fetch all settings from the appliance editor. */
    pExportApplianceWidget->prepareExport();
    /* Get the appliance. */
    CAppliance *pAppliance = pExportApplianceWidget->appliance();
    /* We need to know every filename which will be created, so that we can
     * ask the user for confirmation of overwriting. For that we iterating
     * over all virtual systems & fetch all descriptions of the type
     * HardDiskImage. Also add the manifest file to the check. In the ova
     * case only the target file itself get checked. */
    QFileInfo fi(field("path").toString());
    QVector<QString> files;
    files << fi.fileName();
    if (fi.suffix().toLower() == "ovf")
    {
        if (field("manifestSelected").toBool())
            files << fi.baseName() + ".mf";
        CVirtualSystemDescriptionVector vsds = pAppliance->GetVirtualSystemDescriptions();
        for (int i = 0; i < vsds.size(); ++ i)
        {
            QVector<KVirtualSystemDescriptionType> types;
            QVector<QString> refs, origValues, configValues, extraConfigValues;
            vsds[i].GetDescriptionByType(KVirtualSystemDescriptionType_HardDiskImage, types,
                                         refs, origValues, configValues, extraConfigValues);
            foreach (const QString &s, origValues)
                files << QString("%2").arg(s);
        }
    }
    CVFSExplorer explorer = pAppliance->CreateVFSExplorer(uri(false /* fWithFile */));
    CProgress progress = explorer.Update();
    bool fResult = explorer.isOk();
    if (fResult)
    {
        /* Show some progress, so the user know whats going on: */
        msgCenter().showModalProgressDialog(progress, QApplication::translate("UIWizardExportApp", "Checking files ..."),
                                            ":/progress_refresh_90px.png", this);
        if (progress.GetCanceled())
            return false;
        if (!progress.isOk() || progress.GetResultCode() != 0)
        {
            msgCenter().cannotCheckFiles(progress, this);
            return false;
        }
    }
    QVector<QString> exists = explorer.Exists(files);
    /* Check if the file exists already, if yes get confirmation for overwriting from the user. */
    if (!msgCenter().confirmOverridingFiles(exists, this))
        return false;
    /* Ok all is confirmed so delete all the files which exists: */
    if (!exists.isEmpty())
    {
        CProgress progress1 = explorer.Remove(exists);
        fResult = explorer.isOk();
        if (fResult)
        {
            /* Show some progress, so the user know whats going on: */
            msgCenter().showModalProgressDialog(progress1, QApplication::translate("UIWizardExportApp", "Removing files ..."),
                                                ":/progress_delete_90px.png", this);
            if (progress1.GetCanceled())
                return false;
            if (!progress1.isOk() || progress1.GetResultCode() != 0)
            {
                msgCenter().cannotRemoveFiles(progress1, this);
                return false;
            }
        }
    }

    /* Export the VMs, on success we are finished: */
    return exportVMs(*pAppliance);
}
Beispiel #14
0
bool PreviewGenerator::Run(void)
{
    QString msg;
    QDateTime dtm = MythDate::current();
    QTime tm = QTime::currentTime();
    bool ok = false;
    QString command = GetAppBinDir() + "mythpreviewgen";
    bool local_ok = ((IsLocal() || !!(m_mode & kForceLocal)) &&
                     (!!(m_mode & kLocal)) &&
                     QFileInfo(command).isExecutable());
    if (!local_ok)
    {
        if (!!(m_mode & kRemote))
        {
            ok = RemotePreviewRun();
            if (ok)
            {
                msg =
                    QString("Generated remotely in %1 seconds, starting at %2")
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Run() cannot generate preview locally for: '%1'")
                    .arg(m_pathname));
            msg = "Failed, local preview requested for remote file.";
        }
    }
    else
    {
        // This is where we fork and run mythpreviewgen to actually make preview
        QStringList cmdargs;

        cmdargs << "--size"
                << QString("%1x%2").arg(m_outSize.width()).arg(m_outSize.height());
        if (m_captureTime >= 0)
        {
            if (m_timeInSeconds)
                cmdargs << "--seconds";
            else
                cmdargs << "--frame";
            cmdargs << QString::number(m_captureTime);
        }
        cmdargs << "--chanid"
                << QString::number(m_programInfo.GetChanID())
                << "--starttime"
                << m_programInfo.GetRecordingStartTime(MythDate::kFilename);

        if (!m_outFileName.isEmpty())
            cmdargs << "--outfile" << m_outFileName;

        // Timeout in 30s
        MythSystemLegacy *ms = new MythSystemLegacy(command, cmdargs,
                                        kMSDontBlockInputDevs |
                                        kMSDontDisableDrawing |
                                        kMSProcessEvents      |
                                        kMSAutoCleanup        |
                                        kMSPropagateLogs);
        ms->SetNice(10);
        ms->SetIOPrio(7);

        ms->Run(30);
        uint ret = ms->Wait();
        delete ms;

        if (ret != GENERIC_EXIT_OK)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Encountered problems running '%1 %2' - (%3)")
                    .arg(command).arg(cmdargs.join(" ")).arg(ret));
        }
        else
        {
            LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process returned 0.");
            QString outname = (!m_outFileName.isEmpty()) ?
                m_outFileName : (m_pathname + ".png");

            QString lpath = QFileInfo(outname).fileName();
            if (lpath == outname)
            {
                StorageGroup sgroup;
                QString tmpFile = sgroup.FindFile(lpath);
                outname = (tmpFile.isEmpty()) ? outname : tmpFile;
            }

            QFileInfo fi(outname);
            ok = (fi.exists() && fi.isReadable() && fi.size());
            if (ok)
            {
                LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process ran ok.");
                msg = QString("Generated on %1 in %2 seconds, starting at %3")
                    .arg(gCoreContext->GetHostName())
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Preview process not ok." +
                    QString("\n\t\t\tfileinfo(%1)").arg(outname) +
                    QString(" exists: %1").arg(fi.exists()) +
                    QString(" readable: %1").arg(fi.isReadable()) +
                    QString(" size: %1").arg(fi.size()));
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Despite command '%1' returning success")
                        .arg(command));
                msg = QString("Failed to read preview image despite "
                              "preview process returning success.");
            }
        }
    }

    QMutexLocker locker(&m_previewLock);

    // Backdate file to start of preview time in case a bookmark was made
    // while we were generating the preview.
    QString output_fn = m_outFileName.isEmpty() ?
        (m_programInfo.GetPathname()+".png") : m_outFileName;

    QDateTime dt;
    if (ok)
    {
        QFileInfo fi(output_fn);
        if (fi.exists())
            dt = fi.lastModified();
    }

    QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
    if (m_listener)
    {
        QStringList list;
        list.push_back(QString::number(m_programInfo.GetRecordingID()));
        list.push_back(output_fn);
        list.push_back(msg);
        list.push_back(dt.isValid()?dt.toUTC().toString(Qt::ISODate):"");
        list.push_back(m_token);
        QCoreApplication::postEvent(m_listener, new MythEvent(message, list));
    }

    return ok;
}
Beispiel #15
0
//----------------create book -----------KIrtasse-----------
void classepub::ebubOpenContent(QString fileName,bool write)
{
    QDomDocument m_doc;
    QFileInfo fi(fileName);
    QString   pathHtml= fi.path();
QString  tocName;
    //---------------
   m_listContent.clear();
    //---------------
    QFile    file(fileName);
    if (!file.open(QIODevice::ReadOnly)){
        //qDebug()<<"no open  : "+pathDir+"/"+fullPath;
        return ;
    }
    if (!m_doc.setContent(&file)){
        qDebug()<<"doc no Content";
        return ;
    }
    file.close();
    QDomElement racine2 = m_doc.documentElement(); //
    int count=racine2.childNodes().count();
//---------------------------------
    QFile fileX(QDir::homePath()+"/.kirtasse/download/book.xml");
    if (!fileX.open(QFile::WriteOnly | QFile::Text)) {
        return ;
    }
     QXmlStreamWriter stream;
     int page=0;
     if(write==true){
     stream.setDevice(&fileX);
     stream.setAutoFormatting(true);
     stream.writeStartDocument();
     stream.writeStartElement("dataroot");
     m_listId.clear();
     }



    //-------------------------------
     for(int i=0;i< count;i++){
         QDomNode metadata= racine2.childNodes().item(i);
         //-------جلب معلومات عن الكتاب والمؤبف
         if (metadata.nodeName()=="metadata"){
             QDomElement metadataElement=metadata.toElement();
             //QDomNode item= metadataElement.childNodes();
             int counts=metadataElement.childNodes().count();
             for(int r=0;r< counts;r++){
                 QDomNode item=metadataElement.childNodes().item(r);
                 if  (  item.nodeName()=="dc:title"){
                     QDomElement itemElement=item.toElement();

                     QString txt=itemElement.text();
                infoBookTitle=txt;

                 }
                 if  (  item.nodeName()=="dc:creator"){
                     QDomElement itemElement=item.toElement();

                     QString txt=itemElement.text();
                 infoBookAutor=txt;

                 }
                 if  (  item.nodeName()=="dc:description"){
                     QDomElement itemElement=item.toElement();

                     QString txt=itemElement.text();

                     infoBookBetaka=txt;

                 }
             }
         }


    //     saveBookInfo();
         //---------------جلب الصفحات-------------------------
         if (metadata.nodeName()=="manifest"){
             QDomElement metadataElement=metadata.toElement();
             //QDomNode item= metadataElement.childNodes();
             int counts=metadataElement.childNodes().count();
             for(int r=0;r< counts;r++){
                 QDomNode item=metadataElement.childNodes().item(r);
                 if  (  item.nodeName()=="item"){

                     QDomElement itemElement=item.toElement();
                       if(itemElement.attribute("media-type")=="application/x-dtbncx+xml"){
                           tocName=itemElement.attribute("href");
                       }
                       if(write==false){
                           if(itemElement.attribute("media-type")=="application/xhtml+xml"){
                          QString  href=itemElement.attribute("href");
                               m_listContent.append(pathHtml+"/"+href);
                    //           qDebug()<<pathHtml+"/"+itemElement.attribute("href");;
                           }
                       }
                       if(write==true){
                           if(itemElement.attribute("media-type")=="application/xhtml+xml"){
                               page++;
                               QString txt=itemElement.attribute("href");
                               //          qDebug()<<"item ="+txt;
                               //         qDebug()<<"path ="+pathHtml+"/"+txt;
                               m_listId.append(txt);
                               stream.writeStartElement("book");
                               stream.writeTextElement("id", txt);
                               stream.writeTextElement("part", "1");
                               stream.writeTextElement("page",QString::number( page));
                               stream.writeTextElement("nass",  ebubSetPage(pathHtml+"/"+txt));
                               stream.writeEndElement();
                           }
                       }

                 }

             }

         }

     }
   m_doc.clear();
     if(write==true){
    stream.writeEndElement(); // dataroot
     stream.writeEndDocument();


    epubOpenToc(pathHtml+"/"+tocName);
    return;
    }
    m_tocPath=pathHtml+"/"+tocName;
 pageCount=m_listContent.count()-1;

}
BasicWork::State
FetchRecentQsetsWork::doWork()
{
    // Phase 1: fetch remote history archive state
    if (!mGetHistoryArchiveStateWork)
    {
        mGetHistoryArchiveStateWork =
            addWork<GetHistoryArchiveStateWork>(mRemoteState, 0);
        return State::WORK_RUNNING;
    }
    else if (mGetHistoryArchiveStateWork->getState() != State::WORK_SUCCESS)
    {
        return mGetHistoryArchiveStateWork->getState();
    }

    // Phase 2: download some SCP messages; for now we just pull the past
    // 100 checkpoints = 9 hours of history. A more sophisticated view
    // would survey longer time periods at lower resolution.
    uint32_t numCheckpoints = 100;
    uint32_t step = mApp.getHistoryManager().getCheckpointFrequency();
    uint32_t window = numCheckpoints * step;
    uint32_t lastSeq = mRemoteState.currentLedger;
    uint32_t firstSeq = lastSeq < window ? (step - 1) : (lastSeq - window);

    if (!mDownloadSCPMessagesWork)
    {
        CLOG(INFO, "History") << "Downloading recent SCP messages: ["
                              << firstSeq << ", " << lastSeq << "]";
        auto range = CheckpointRange{firstSeq, lastSeq, step};
        mDownloadSCPMessagesWork = addWork<BatchDownloadWork>(
            range, HISTORY_FILE_TYPE_SCP, *mDownloadDir);
        return State::WORK_RUNNING;
    }
    else if (mDownloadSCPMessagesWork->getState() != State::WORK_SUCCESS)
    {
        return mDownloadSCPMessagesWork->getState();
    }

    // Phase 3: extract the qsets.
    for (uint32_t i = firstSeq; i <= lastSeq; i += step)
    {
        CLOG(INFO, "History") << "Scanning for QSets in checkpoint: " << i;
        XDRInputFileStream in;
        FileTransferInfo fi(*mDownloadDir, HISTORY_FILE_TYPE_SCP, i);
        try
        {
            in.open(fi.localPath_nogz());
        }
        catch (FileSystemException&)
        {
            CLOG(ERROR, "History") << POSSIBLY_CORRUPTED_LOCAL_FS;
            return State::WORK_FAILURE;
        }

        SCPHistoryEntry tmp;
        while (in && in.readOne(tmp))
        {
            mInferredQuorum.noteSCPHistory(tmp);
        }
    }

    return State::WORK_SUCCESS;
}
Beispiel #17
0
/*!
 * use latex to render LaTeX text (see tex2im, etc.)
 */
QImage TeXRenderer::renderImageLaTeX( const QString& teXString, const QColor& fontColor, const int fontSize, const int dpi){
	QTemporaryFile file("/dev/shm/labplot_XXXXXX.tex");
	//file.setAutoRemove(false);
	if(file.open()) {
		QDir::setCurrent("/dev/shm");
	}
	else {
		kWarning()<<"/dev/shm failed. using /tmp"<<endl;
		file.setFileTemplate("/tmp/labplot_XXXXXX.tex");
		if(file.open())
			QDir::setCurrent("/tmp");
		else
			return QImage();
	}

	// create latex code
	QTextStream out(&file);
	out << "\\documentclass{minimal}";
	out << "\\usepackage{color}\\usepackage[active,displaymath,textmath,tightpage]{preview}";
	out << "\\begin{document}";
	out << "\\definecolor{fontcolor}{rgb}{" << fontColor.redF() << ',' << fontColor.greenF() << ','<<fontColor.blueF() << "}";
	out << "\\begin{preview}";
	out << "{\\fontsize{" << QString::number(fontSize) << "}{" << QString::number(fontSize) << "}\\selectfont";
	out << "{\\color{fontcolor}\n";
	out << teXString;
	out << "\n}}\\end{preview}";
	out << "\\end{document}";
	out.flush();

	// pdflatex: TeX -> PDF
	QProcess latexProcess, convertProcess;
	latexProcess.start("pdflatex", QStringList() << "-interaction=batchmode" << file.fileName());

	QFileInfo fi(file.fileName());
	if (latexProcess.waitForFinished()) { 	// pdflatex finished
		QFile::remove(fi.completeBaseName()+".aux");
		QFile::remove(fi.completeBaseName()+".log");

		//TODO: pdflatex doesn't come back with EX_OK
// 		if(latexProcess.exitCode() != 0)	// skip if pdflatex failed
// 			return QImage();

		// convert: PDF -> PNG
		convertProcess.start("convert",  QStringList() << "-density"<< QString::number(dpi) + 'x' + QString::number(dpi)
														<< fi.completeBaseName() + ".pdf"
														<< fi.completeBaseName() + ".png");
		//gs doesn't work here. Why?
// 		convertProcess.start("gs", QStringList()<< "-sDEVICE=png16m"
// 												<< "-dTextAlphaBits=4"
// 												<< "-r" + QString::number(dpi)
// 												<< "-dGraphicsAlphaBits=4"
// 												<< "-sDEVICE=pngalpha"
// 												<< "-dSAFER"
// 												<< "-q"
// 												<< "-dNOPAUSE"
// 												<< "-sOutputFile=" + fi.completeBaseName() + ".png"
// 												<< fi.completeBaseName() + ".pdf");

		// clean up and read png file
		if (convertProcess.waitForFinished()) {
			QFile::remove(fi.completeBaseName()+".pdf");

			QImage image;
			image.load(fi.completeBaseName()+".png");
			QFile::remove(fi.completeBaseName()+".png");

			return image;
		}else{
			QFile::remove(fi.completeBaseName()+".pdf");
			return QImage();
		}
	}else{
		kWarning()<<"pdflatex failed."<<endl;
	}

	//////////// fallback if pdflatex fails ///////////////

	// latex: TeX -> DVI
	latexProcess.start("latex", QStringList() << "-interaction=batchmode" << file.fileName());
	// also possible: latexmf -C
	if (!latexProcess.waitForFinished()) {
		kWarning()<<"latex failed."<<endl;
		QFile::remove(fi.completeBaseName()+".aux");
		QFile::remove(fi.completeBaseName()+".log");
		return QImage();
	}
	if(latexProcess.exitCode() != 0)	// skip if latex failed
		return QImage();

	// dvips: DVI -> PS
	QProcess dvipsProcess;
	dvipsProcess.start("dvips", QStringList() << "-E" << fi.completeBaseName());
	if (!dvipsProcess.waitForFinished()) {
		kWarning()<<"dvips failed."<<endl;
		QFile::remove(fi.completeBaseName()+".dvi");
		return QImage();
	}

	// convert: PS -> PNG
	convertProcess.start("convert", QStringList() << "-density" << QString::number(dpi) + 'x' + QString::number(dpi)  << fi.completeBaseName()+".ps" << fi.completeBaseName()+".png");
	if (!convertProcess.waitForFinished()) {
		kWarning()<<"convert failed."<<endl;
		QFile::remove(fi.completeBaseName()+".ps");
		return QImage();
	}

	// read png file
	QImage image;
	image.load(fi.completeBaseName()+".png", "png");

	//clean up
	QFile::remove(fi.completeBaseName()+".png");
	QFile::remove(fi.completeBaseName()+".aux");
	QFile::remove(fi.completeBaseName()+".log");
	QFile::remove(fi.completeBaseName()+".dvi");
	QFile::remove(fi.completeBaseName()+".ps");

	return image;
}
Beispiel #18
0
void preferenceDialog::on_listWidget_currentRowChanged(int currentRow)
{
    switch(currentRow)
    {
    case 0://qDebug()<<_settings->value("General/Priority","abovenormal").toString();
        ui->comboBox->setCurrentIndex(ui->comboBox->findText(_settings->value("General/Priority","abovenormal").toString()));
        ui->comboBoxStyle->setCurrentIndex(ui->comboBoxStyle->findText(_settings->value("Skin/style","aqua").toString()));
        if ( _settings->value("General/recentFilesClear",0).toInt()==2)
            ui->checkBoxRemrm->setCheckState(Qt::Checked);
        else
            ui->checkBoxRemrm->setCheckState(Qt::Unchecked);

        break;
    case  1 :
        if (_settings->value("Audio/EnableEQ","2").toInt()==2)
            ui->cbEnableAEq->setCheckState(Qt::Checked);
        else
            ui->cbEnableAEq->setCheckState(Qt::Unchecked);

        ui->cmbAO->setCurrentIndex(ui->cmbAO->findText(_settings->value("Audio/Driver","Auto").toString()));

        ui->hSliderVolumeBoost->setValue(_settings->value("Audio/VolumeBoost","500").toInt());
        break;
    case  2 :{QDesktopServices mycomputer;
        QString picfolder=mycomputer.storageLocation(QDesktopServices::PicturesLocation);
        ui->lineEditSc->setText(_settings->value("Video/CaptureDir",picfolder).toString());
        break;
    }
    case 3 :{AssStyles ass;
        ass.load(_settings);
        ColorUtils::setBackgroundColor(ui->texcol,QColor(ass.primarycolor));
        ColorUtils::setBackgroundColor(ui->shcol,QColor(ass.backcolor));
        ColorUtils::setBackgroundColor(ui->borcol,QColor(ass.outlinecolor));
        ui->fontComboBox->setCurrentFont(QFont(ass.fontname));
        ui->spinBoxFs->setValue(ass.fontsize);
        ui->checkBoxBold->setChecked(ass.bold);
        ui->checkBoxItalic->setChecked(ass.italic);
        ui->comboBoxHa->clear();
        ui->comboBoxHa->addItem(tr("Left", "horizontal alignment"), 1);
        ui->comboBoxHa->addItem(tr("Centered", "horizontal alignment"), 2);
        ui->comboBoxHa->addItem(tr("Right", "horizontal alignment"), 3);

        ui->comboBoxHa->setCurrentIndex(ui->comboBoxHa->itemData(ui->comboBoxHa->currentIndex()).toInt());
        ui->comboBoxVa->setCurrentIndex(ass.valignment);

        if (_settings->value("Subtitles/UseCodePage","0").toInt()==0)

            ui->checkBoxUseCodePage->setCheckState(Qt::Unchecked);
        else
            ui->checkBoxUseCodePage->setCheckState(Qt::Checked);

        ui->comboBoxSubEncoding->setCurrentIndex(ui->comboBoxSubEncoding->findText(_settings->value("Subtitles/CodePage","Western European Languages").toString()));

        break;
    }

    case 4:ui->groupBox_7->setVisible(false);
        ui->groupBox_8->setVisible(false);
        ui->groupBox_9->setVisible(false);
        ui->sbNetCache->setValue(_settings->value("Network/cache","320").toInt());
        break;
    case 6: int mousewheelrole ;
        mousewheelrole =_settings->value("Mouse/Wheel","0").toInt();

        if  (mousewheelrole==0)
            ui->rbVol->setChecked(true);
        else
            ui->rbSk->setChecked(true);
        break;
    case 8:{ QFileInfo fi(qApp->applicationFilePath());
        QDateTime dt=fi.created();
        ui->labelDate->setText(QString("Build on "+dt.toString()));
        break;
    }
    case  5 :
    {QList<QAction *> acts = _w->findChildren<QAction*>();

        for (int i=0;i<acts.count();i++)
        {
            if(acts.at(i)->objectName()!="")
            {QTableWidgetItem *newItem = new QTableWidgetItem(acts.at(i)->objectName());
                ui->twsc->setRowCount(i+1);
                newItem->setIcon(acts.at(i)->icon());
                ui->twsc->setItem(i,0,newItem);
                QTableWidgetItem *newItem1 = new QTableWidgetItem(acts.at(i)->text());
                ui->twsc->setItem(i,1,newItem1);
                QTableWidgetItem *newItem2 = new QTableWidgetItem(acts.at(i)->shortcut().toString());
                ui->twsc->setItem(i,2,newItem2);
            }
        }
        break;
    }
    case 7:{
        if (_settings->value("Updates/Automatic","1").toInt()==1)
            ui->checkUpdates->setCheckState(Qt::Checked);
        else
            ui->checkUpdates->setCheckState(Qt::Unchecked);

        //ui->checkUpdates->setChecked(_settings->value("","1").toInt());
        break;
    }

    }
}
Beispiel #19
0
bool MTest::saveScore(Score* score, const QString& name) const
{
    QFileInfo fi(name);
//      MScore::testMode = true;
    return score->Score::saveFile(fi);
}
Beispiel #20
0
CC_FILE_ERROR AsciiFilter::saveToFile(ccHObject* entity, QString filename, SaveParameters& parameters)
{
	assert(entity && !filename.isEmpty());

	AsciiSaveDlg* saveDialog = GetSaveDialog(parameters.parentWidget);
	assert(saveDialog);

	//if the dialog shouldn't be shown, we'll simply take the default values!
	if (parameters.alwaysDisplaySaveDialog && saveDialog->autoShow() && !saveDialog->exec())
	{
		return CC_FERR_CANCELED_BY_USER;
	}

	if (!entity->isKindOf(CC_TYPES::POINT_CLOUD))
	{
		if (entity->isA(CC_TYPES::HIERARCHY_OBJECT)) //multiple clouds?
		{
			QFileInfo fi(filename);
			QString extension = fi.suffix();
			QString baseName = fi.completeBaseName();
			QString path = fi.path();

			unsigned count = entity->getChildrenNumber();
			//we count the number of clouds first
			unsigned cloudCount = 0;
			{
				for (unsigned i=0; i<count; ++i)
				{
					ccHObject* child = entity->getChild(i);
					if (child->isKindOf(CC_TYPES::POINT_CLOUD))
						++cloudCount;
				}
			}
			
			//we can now create the corresponding file(s)
			if (cloudCount > 1)
			{
				unsigned counter = 0;
				//disable the save dialog so that it doesn't appear again!
				AsciiSaveDlg* saveDialog = GetSaveDialog();
				assert(saveDialog);

				bool autoShow = saveDialog->autoShow();
				saveDialog->setAutoShow(false);

				for (unsigned i=0; i<count; ++i)
				{
					ccHObject* child = entity->getChild(i);
					if (child->isKindOf(CC_TYPES::POINT_CLOUD))
					{
						QString subFilename = path+QString("/");
						subFilename += QString(baseName).replace("cloudname",child->getName(),Qt::CaseInsensitive);
						counter++;
						assert(counter <= cloudCount);
						subFilename += QString("_%1").arg(cloudCount-counter,6,10,QChar('0'));
						if (!extension.isEmpty())
							subFilename += QString(".") + extension;
						
						CC_FILE_ERROR result = saveToFile(entity->getChild(i),subFilename,parameters);
						if (result != CC_FERR_NO_ERROR)
						{
							return result;
						}
						else
						{
							ccLog::Print(QString("[ASCII] Cloud '%1' has been saved in: %2").arg(child->getName()).arg(subFilename));
						}
					}
					else
					{
						ccLog::Warning(QString("[ASCII] Entity '%1' can't be saved this way!").arg(child->getName()));
					}
				}

				//restore previous state
				saveDialog->setAutoShow(autoShow);

				return CC_FERR_NO_ERROR;
			}
		}
		else
		{
			return CC_FERR_BAD_ARGUMENT;
		}
	}

	QFile file(filename);
	if (!file.open(QFile::WriteOnly | QFile::Truncate))
		return CC_FERR_WRITING;
	QTextStream stream(&file);

	ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity);

	unsigned numberOfPoints = cloud->size();
	bool writeColors = cloud->hasColors();
	bool writeNorms = cloud->hasNormals();
	std::vector<ccScalarField*> theScalarFields;
	if (cloud->isKindOf(CC_TYPES::POINT_CLOUD))
	{
		ccPointCloud* ccCloud = static_cast<ccPointCloud*>(cloud);
		for (unsigned i=0; i<ccCloud->getNumberOfScalarFields(); ++i)
			theScalarFields.push_back(static_cast<ccScalarField*>(ccCloud->getScalarField(i)));
	}
	bool writeSF = (theScalarFields.size() != 0);

	//progress dialog
	ccProgressDialog pdlg(true, parameters.parentWidget);
	CCLib::NormalizedProgress nprogress(&pdlg, numberOfPoints);
	if (parameters.parentWidget)
	{
		pdlg.setMethodTitle(QObject::tr("Saving cloud [%1]").arg(cloud->getName()));
		pdlg.setInfo(QObject::tr("Number of points: %1").arg(numberOfPoints));
		pdlg.start();
	}

	//output precision
	const int s_coordPrecision = saveDialog->coordsPrecision();
	const int s_sfPrecision = saveDialog->sfPrecision(); 
	const int s_nPrecision = 2+sizeof(PointCoordinateType);

	//other parameters
	bool saveColumnsHeader = saveDialog->saveColumnsNamesHeader();
	bool savePointCountHeader = saveDialog->savePointCountHeader();
	bool swapColorAndSFs = saveDialog->swapColorAndSF();
	QChar separator(saveDialog->getSeparator());
	bool saveFloatColors = saveDialog->saveFloatColors();

	if (saveColumnsHeader)
	{
		QString header("//");
		header.append(AsciiHeaderColumns::X());
		header.append(separator);
		header.append(AsciiHeaderColumns::Y());
		header.append(separator);
		header.append(AsciiHeaderColumns::Z());

		if (writeColors && !swapColorAndSFs)
		{
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Rf() : AsciiHeaderColumns::R());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Gf() : AsciiHeaderColumns::G());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Bf() : AsciiHeaderColumns::B());
		}

		if (writeSF)
		{
			//add each associated SF name
			for (std::vector<ccScalarField*>::const_iterator it = theScalarFields.begin(); it != theScalarFields.end(); ++it)
			{
				QString sfName((*it)->getName());
				sfName.replace(separator,'_');
				header.append(separator);
				header.append(sfName);
			}
		}

		if (writeColors && swapColorAndSFs)
		{
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Rf() : AsciiHeaderColumns::R());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Gf() : AsciiHeaderColumns::G());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Bf() : AsciiHeaderColumns::B());
		}

		if (writeNorms)
		{
			header.append(separator);
			header.append(AsciiHeaderColumns::Nx());
			header.append(separator);
			header.append(AsciiHeaderColumns::Ny());
			header.append(separator);
			header.append(AsciiHeaderColumns::Nz());
		}
		
		stream << header << "\n";
	}

	if (savePointCountHeader)
	{
		stream << QString::number(numberOfPoints) << "\n";
	}

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;
	for (unsigned i=0; i<numberOfPoints; ++i)
	{
		//line for the current point
		QString line;

		//write current point coordinates
		const CCVector3* P = cloud->getPoint(i);
		CCVector3d Pglobal = cloud->toGlobal3d<PointCoordinateType>(*P);
		line.append(QString::number(Pglobal.x,'f',s_coordPrecision));
		line.append(separator);
		line.append(QString::number(Pglobal.y,'f',s_coordPrecision));
		line.append(separator);
		line.append(QString::number(Pglobal.z,'f',s_coordPrecision));

		QString colorLine;
		if (writeColors)
		{
			//add rgb color
			const ColorCompType* col = cloud->getPointColor(i);
			if (saveFloatColors)
			{
				colorLine.append(separator);
				colorLine.append(QString::number(static_cast<double>(col[0])/ccColor::MAX));
				colorLine.append(separator);
				colorLine.append(QString::number(static_cast<double>(col[1])/ccColor::MAX));
				colorLine.append(separator);
				colorLine.append(QString::number(static_cast<double>(col[2])/ccColor::MAX));
			}
			else
			{
				colorLine.append(separator);
				colorLine.append(QString::number(col[0]));
				colorLine.append(separator);
				colorLine.append(QString::number(col[1]));
				colorLine.append(separator);
				colorLine.append(QString::number(col[2]));
			}

			if (!swapColorAndSFs)
				line.append(colorLine);
		}

		if (writeSF)
		{
			//add each associated SF values
			for (std::vector<ccScalarField*>::const_iterator it = theScalarFields.begin(); it != theScalarFields.end(); ++it)
			{
				line.append(separator);
				double sfVal = (*it)->getGlobalShift() + (*it)->getValue(i);
				line.append(QString::number(sfVal,'f',s_sfPrecision));
			}
		}

		if (writeColors && swapColorAndSFs)
			line.append(colorLine);

		if (writeNorms)
		{
			//add normal vector
			const CCVector3& N = cloud->getPointNormal(i);
			line.append(separator);
			line.append(QString::number(N.x,'f',s_nPrecision));
			line.append(separator);
			line.append(QString::number(N.y,'f',s_nPrecision));
			line.append(separator);
			line.append(QString::number(N.z,'f',s_nPrecision));
		}

		stream << line << "\n";

		if (parameters.parentWidget && !nprogress.oneStep())
		{
			result = CC_FERR_CANCELED_BY_USER;
			break;
		}
	}

	return result;
}
void PropertyEditorView::changeValue(const QString &name)
{
    PropertyName propertyName = name.toUtf8();

    if (propertyName.isNull())
        return;

    if (locked())
        return;

    if (propertyName == "className")
        return;

    if (!m_selectedNode.isValid())
        return;

    if (propertyName == "id") {
        PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(QString::fromUtf8(propertyName));
        const QString newId = value->value().toString();

        if (newId == m_selectedNode.id())
            return;

        if (m_selectedNode.isValidId(newId)  && !hasId(newId)) {
            m_selectedNode.setIdWithRefactoring(newId);
        } else {
            m_locked = true;
            value->setValue(m_selectedNode.id());
            m_locked = false;
            if (!m_selectedNode.isValidId(newId))
                Core::AsynchronousMessageBox::warning(tr("Invalid Id"),  tr("%1 is an invalid id.").arg(newId));
            else
                Core::AsynchronousMessageBox::warning(tr("Invalid Id"),  tr("%1 already exists.").arg(newId));
        }
        return;
    }

    PropertyName underscoreName(propertyName);
    underscoreName.replace('.', '_');
    PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(QString::fromLatin1(underscoreName));

    if (value ==0)
        return;

    QmlObjectNode qmlObjectNode(m_selectedNode);

    QVariant castedValue;

    if (qmlObjectNode.modelNode().metaInfo().isValid() && qmlObjectNode.modelNode().metaInfo().hasProperty(propertyName)) {
        castedValue = qmlObjectNode.modelNode().metaInfo().propertyCastedValue(propertyName, value->value());
    } else if (propertyIsAttachedLayoutProperty(propertyName)) {
        castedValue = value->value();
    } else {
        qWarning() << "PropertyEditor:" <<propertyName << "cannot be casted (metainfo)";
        return ;
    }

    if (value->value().isValid() && !castedValue.isValid()) {
        qWarning() << "PropertyEditor:" << propertyName << "not properly casted (metainfo)";
        return ;
    }

    if (qmlObjectNode.modelNode().metaInfo().isValid() && qmlObjectNode.modelNode().metaInfo().hasProperty(propertyName)) {
        if (qmlObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "QUrl"
                || qmlObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "url") { //turn absolute local file paths into relative paths
                QString filePath = castedValue.toUrl().toString();
            QFileInfo fi(filePath);
            if (fi.exists() && fi.isAbsolute()) {
                QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
                castedValue = QUrl(fileDir.relativeFilePath(filePath));
            }
        }
    }

    if (castedValue.type() == QVariant::Color) {
        QColor color = castedValue.value<QColor>();
        QColor newColor = QColor(color.name());
        newColor.setAlpha(color.alpha());
        castedValue = QVariant(newColor);
    }

    try {
        if (!value->value().isValid()) { //reset
            qmlObjectNode.removeProperty(propertyName);
        } else {
            if (castedValue.isValid() && !castedValue.isNull()) {
                m_locked = true;
                qmlObjectNode.setVariantProperty(propertyName, castedValue);
                m_locked = false;
            }
        }
    }
    catch (const RewritingException &e) {
        e.showException();
    }
}
Beispiel #22
0
/** \fn PreviewGenerator::RunReal(void)
 *  \brief This call creates a preview without starting a new thread.
 */
bool PreviewGenerator::RunReal(void)
{
    QString msg;
    QTime tm = QTime::currentTime();
    bool ok = false;
    bool is_local = IsLocal();

    if (!is_local && !!(mode & kRemote))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("Run() file not local: '%1'")
                .arg(pathname));
    }
    else if (!(mode & kLocal) && !(mode & kRemote))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("Run() Preview of '%1' failed "
                                               "because mode was invalid 0x%2")
                .arg(pathname).arg((int)mode,0,16));
    }
    else if (is_local && !!(mode & kLocal) && LocalPreviewRun())
    {
        ok = true;
        msg = QString("Generated on %1 in %2 seconds, starting at %3")
            .arg(gCoreContext->GetHostName())
            .arg(tm.elapsed()*0.001)
            .arg(tm.toString(Qt::ISODate));
    }
    else if (!!(mode & kRemote))
    {
        if (is_local && (mode & kLocal))
        {
            LOG(VB_GENERAL, LOG_WARNING, LOC + "Failed to save preview."
                    "\n\t\t\tYou may need to check user and group ownership on"
                    "\n\t\t\tyour frontend and backend for quicker previews.\n"
                    "\n\t\t\tAttempting to regenerate preview on backend.\n");
        }
        ok = RemotePreviewRun();
        if (ok)
        {
            msg = QString("Generated remotely in %1 seconds, starting at %2")
                .arg(tm.elapsed()*0.001)
                .arg(tm.toString(Qt::ISODate));
        }
        else
        {
            msg = "Remote preview failed";
        }
    }
    else
    {
        msg = "Could not access recording";
    }

    QMutexLocker locker(&previewLock);
    if (listener)
    {
        QString output_fn = outFileName.isEmpty() ?
            (programInfo.GetPathname()+".png") : outFileName;

        QDateTime dt;
        if (ok)
        {
            QFileInfo fi(output_fn);
            if (fi.exists())
                dt = fi.lastModified();
        }

        QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
        QStringList list;
        list.push_back(programInfo.MakeUniqueKey());
        list.push_back(output_fn);
        list.push_back(msg);
        list.push_back(dt.isValid()?dt.toString(Qt::ISODate):"");
        list.push_back(token);
        QCoreApplication::postEvent(listener, new MythEvent(message, list));
    }

    return ok;
}
Beispiel #23
0
void KviWindow::pasteLastLog()
{
	bool bChannel = type() == KviWindow::Channel || type() == KviWindow::DeadChannel;
	QDate date = QDate::currentDate();
	int iInterval = -(int)KVI_OPTION_UINT(bChannel ? KviOption_uintDaysIntervalToPasteOnChannelJoin : KviOption_uintDaysIntervalToPasteOnQueryJoin);
	QDate checkDate = date.addDays(iInterval);

	unsigned int uMaxLines = KVI_OPTION_UINT(bChannel ? KviOption_uintLinesToPasteOnChannelJoin : KviOption_uintLinesToPasteOnQueryJoin);
	if (!uMaxLines)
		return;

	std::vector<std::tuple<QString, QDate, int>> vLines;

	for (; date >= checkDate; date = date.addDays(-1))
		for (int iGzip = 0; iGzip <= 1; iGzip++)
			for (unsigned int uDatetimeFormat = 0; uDatetimeFormat < 3; uDatetimeFormat++)
			{
				bool bGzip = !!iGzip;

				QString szFileName;
				getDefaultLogFileName(szFileName, date, bGzip, uDatetimeFormat);

				QFileInfo fi(szFileName);
				if (!fi.exists() || !fi.isFile())
					continue;

				// Load the log
				QByteArray log = loadLogFile(szFileName, bGzip);

				if(log.size() == 0)
					continue;

				QList<QByteArray> list = log.split('\n');
				unsigned int uCount = list.size();

				while (uCount)
				{
					vLines.emplace_back(QString(list.at(--uCount)), date, uDatetimeFormat);

					if (vLines.size() == uMaxLines)
						goto enough;
				}
			}

	if (vLines.empty())
		return;

enough:
	QString szDummy = __tr2qs("Starting last log");
	output(KVI_OUT_LOG, szDummy);

	for (auto logIter = vLines.rbegin(); logIter != vLines.rend(); ++logIter)
	{
		QString & szLine      = std::get<0>(*logIter);
		const QDate & logDate = std::get<1>(*logIter);
		int uDatetimeFormat   = std::get<2>(*logIter);

		bool ok;
		int msgType = szLine.section(' ', 0, 0).toInt(&ok);
		if (ok)
			szLine = szLine.section(' ', 1);
		else
			msgType = KVI_OUT_LOG;

		QDateTime date;
		switch(uDatetimeFormat)
		{
			case 0:
			{
				QTime time = QTime::fromString(szLine.section(' ', 0, 0), "[hh:mm:ss]");
				if (time.isValid())
				{
					date = QDateTime(logDate, time);
					szLine = szLine.section(' ', 1);
				}
				break;
			}
			case 1:
				date = QDateTime::fromString(szLine.section(' ', 0, 0), Qt::ISODate);
				if (date.isValid())
					szLine = szLine.section(' ', 1);
				break;
			case 2:
			{
				// The system-locale format is hairy, because it has no clear delimiter.
				// Count how many spaces a typical time format has,
				// and assume that that number is not going to change.
				static int iSpaceCount = -1;
				if (iSpaceCount == -1)
				{
					QString szTypicalDate = QDateTime::currentDateTime().toString(Qt::SystemLocaleShortDate);
					iSpaceCount = szTypicalDate.count(' ');
				}
				date = QDateTime::fromString(szLine.section(' ', 0, iSpaceCount), Qt::SystemLocaleShortDate);
				if (date.isValid())
				{
					szLine = szLine.section(' ', iSpaceCount+1);

					// Work around Qt bug:
					// if the date string contains a two-digit year, it may be
					// parsed in the wrong century (i.e. 1916 instead of 2016).
					if (logDate.year() == date.date().year() + 100)
						date = date.addYears(100);
				}
				break;
			}
		}

		if (szLine.isEmpty())
			continue;

		// Print the line in the channel buffer
		output(msgType, date, "%Q", &szLine);
	}

	szDummy = __tr2qs("End of log");
	output(KVI_OUT_LOG, szDummy);
}
Beispiel #24
0
bool PreviewGenerator::Run(void)
{
    QString msg;
    QDateTime dtm = QDateTime::currentDateTime();
    QTime tm = QTime::currentTime();
    bool ok = false;
    QString command = GetInstallPrefix() + "/bin/mythpreviewgen";
    bool local_ok = ((IsLocal() || !!(mode & kForceLocal)) &&
                     (!!(mode & kLocal)) &&
                     QFileInfo(command).isExecutable());
    if (!local_ok)
    {
        if (!!(mode & kRemote))
        {
            ok = RemotePreviewRun();
            if (ok)
            {
                msg =
                    QString("Generated remotely in %1 seconds, starting at %2")
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Run() cannot generate preview locally for: '%1'")
                    .arg(pathname));
            msg = "Failed, local preview requested for remote file.";
        }
    }
    else
    {
        // This is where we fork and run mythpreviewgen to actually make preview
        command += QString(" --size %1x%2")
            .arg(outSize.width()).arg(outSize.height());
        if (captureTime >= 0)
        {
            if (timeInSeconds)
                command += QString(" --seconds %1").arg(captureTime);
            else
                command += QString(" --frame %1").arg(captureTime);
        }
        command += QString(" --chanid %1").arg(programInfo.GetChanID());
        command += QString(" --starttime %1")
            .arg(programInfo.GetRecordingStartTime(MythDate));

        if (!outFileName.isEmpty())
            command += QString(" --outfile \"%1\"").arg(outFileName);

        command += logPropagateArgs;
        if (!logPropagateQuiet())
            command += " --quiet";

        // Timeout in 30s
        uint ret = myth_system(command, kMSDontBlockInputDevs |
                                        kMSDontDisableDrawing |
                                        kMSProcessEvents, 30);
        if (ret != GENERIC_EXIT_OK)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + 
                QString("Encountered problems running '%1' (%2)")
                    .arg(command) .arg(ret));
        }
        else
        {
            LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process returned 0.");
            QString outname = (!outFileName.isEmpty()) ?
                outFileName : (pathname + ".png");

            QString lpath = QFileInfo(outname).fileName();
            if (lpath == outname)
            {
                StorageGroup sgroup;
                QString tmpFile = sgroup.FindFile(lpath);
                outname = (tmpFile.isEmpty()) ? outname : tmpFile;
            }

            QFileInfo fi(outname);
            ok = (fi.exists() && fi.isReadable() && fi.size());
            if (ok)
            {
                LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process ran ok.");
                msg = QString("Generated on %1 in %2 seconds, starting at %3")
                    .arg(gCoreContext->GetHostName())
                    .arg(tm.elapsed()*0.001)
                    .arg(tm.toString(Qt::ISODate));
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, LOC + "Preview process not ok." +
                    QString("\n\t\t\tfileinfo(%1)").arg(outname) +
                    QString(" exists: %1").arg(fi.exists()) +
                    QString(" readable: %1").arg(fi.isReadable()) +
                    QString(" size: %1").arg(fi.size()));
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Despite command '%1' returning success")
                        .arg(command));
                msg = QString("Failed to read preview image despite "
                              "preview process returning success.");
            }
        }
    }

    QMutexLocker locker(&previewLock);

    // Backdate file to start of preview time in case a bookmark was made
    // while we were generating the preview.
    QString output_fn = outFileName.isEmpty() ?
        (programInfo.GetPathname()+".png") : outFileName;

    QDateTime dt;
    if (ok)
    {
        QFileInfo fi(output_fn);
        if (fi.exists())
            dt = fi.lastModified();
    }

    QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED";
    if (listener)
    {
        QStringList list;
        list.push_back(programInfo.MakeUniqueKey());
        list.push_back(outFileName.isEmpty() ?
                       (programInfo.GetPathname()+".png") : outFileName);
        list.push_back(msg);
        list.push_back(dt.isValid()?dt.toString(Qt::ISODate):"");
        list.push_back(token);
        QCoreApplication::postEvent(listener, new MythEvent(message, list));
    }

    return ok;
}
QString
ITunesDevice::LibraryPath()
{
    if ( !m_iTunesLibraryPath.isEmpty() )
        return m_iTunesLibraryPath;

    QString path;
    QString confPath;

#ifdef Q_WS_MAC
    QSettings ist( "apple.com", "iTunes" );
    path = ist.value( "AppleNavServices:ChooseObject:0:Path" ).toString();
    path = path.remove( "file://localhost" );
    qDebug() << "Found iTunes Library in:" << path;

    QFileInfo fi( path + "iTunes Music Library.xml" );
    if ( fi.exists() )
        m_iTunesLibraryPath = fi.absoluteFilePath();
    else
        m_iTunesLibraryPath = QFileInfo( QDir::homePath() + "/Music/iTunes/iTunes Music Library.xml" ).absoluteFilePath();

    return m_iTunesLibraryPath;
#endif

#ifdef WIN32
    {
        // Get path to My Music
        char acPath[MAX_PATH];
        HRESULT h = SHGetFolderPathA( NULL, CSIDL_MYMUSIC,
                                      NULL, 0, acPath );

        if ( h == S_OK )
            path = QString::fromLocal8Bit( acPath );
//        else
//            LOG( 1, "Couldn't get My Music path\n" );

        qDebug() << "CSIDL_MYMUSIC path: " << path;
    }

    {
        // Get path to Local App Data
        char acPath[MAX_PATH];
        HRESULT h = SHGetFolderPathA( NULL, CSIDL_LOCAL_APPDATA,
                                      NULL, 0, acPath );

        if ( h == S_OK )
            confPath = QString::fromLocal8Bit( acPath );
//        else
//            LOG( 1, "Couldn't get Local Application Data path\n" );

        qDebug() << "CSIDL_LOCAL_APPDATA path: " << confPath;
    }

    // Try reading iTunesPrefs.xml for custom library path
    QFile f( confPath + "/Apple Computer/iTunes/iTunesPrefs.xml" );
    if ( f.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
        qDebug() << "Found iTunesPrefs.xml";

        QByteArray content = f.readAll();

        int tagStart = content.indexOf( "iTunes Library XML Location:1" );

        if ( tagStart != -1 )
        {
            // TODO: this could fail if the XML is broken
            int dataTagStart = content.indexOf( "<data>", tagStart );
            int dataTagEnd = dataTagStart + 6;
            int dataEndTagStart = content.indexOf( "</data>", dataTagStart );
            QByteArray lp = content.mid( dataTagEnd, dataEndTagStart - dataTagEnd );

            qDebug() << "lp before trim: " << lp;

            // The file contains whitespace and linebreaks in the middle of
            // the data so need to squeeze all that out
            lp = lp.simplified();
            lp = lp.replace( ' ', "" );

            qDebug() << "lp after simplified: " << lp;

            lp = QByteArray::fromBase64( lp );

            qDebug() << "lp after base64: " << lp;

            QString sp = QString::fromUtf16( (ushort*)lp.data() );

            qDebug() << "Found iTunes Library path (after conversion to QString):" << sp;

            QFileInfo fi( sp );
            if ( fi.exists() )
            {
                qDebug() << "file exists, returning: " << fi.absoluteFilePath();
                m_iTunesLibraryPath = fi.absoluteFilePath();
                return m_iTunesLibraryPath;
            }
        }
        else
        {
            qDebug() << "No custom library location found in iTunesPrefs.xml";
        }
    }

    // Fall back to default path otherwise
    m_iTunesLibraryPath = path + "/iTunes/iTunes Music Library.xml";

    qDebug() << "Will use default iTunes Library path: " << m_iTunesLibraryPath;

    return m_iTunesLibraryPath;

#endif

    // Fallback for testing
//    m_iTunesLibraryPath = "/tmp/iTunes Music Library.xml";
//    return m_iTunesLibraryPath;
}
Beispiel #26
0
bool QLibraryPrivate::load_sys()
{
    QFileInfo fi(fileName);
    QString path = fi.path();
    QString name = fi.fileName();
    if (path == QLatin1String(".") && !fileName.startsWith(path))
        path.clear();
    else
        path += QLatin1Char('/');

    QStringList suffixes, prefixes("");
    if (QLibrary::isLibrary(fileName))
        suffixes << "";
    if (pluginState != IsAPlugin) {
        prefixes << "lib";
#if defined(Q_OS_HPUX)
        suffixes << ".sl";
        suffixes << QString(".%1").arg(majorVerNum);
#elif defined(Q_OS_AIX)
        suffixes << ".a";
#else
        suffixes << ".so";       
        if (majorVerNum > -1)
            suffixes << QString(".so.%1").arg(majorVerNum);
#endif
# ifdef Q_OS_MAC
        suffixes << ".bundle" << ".dylib";
        if (majorVerNum > -1) {
            suffixes << QString(".%1.bundle").arg(majorVerNum);
            suffixes << QString(".%1.dylib").arg(majorVerNum);
        }

#endif            
    }
        
    QString attempt;
    for(int prefix = 0; !pHnd && prefix < prefixes.size(); prefix++) {
        for(int suffix = 0; !pHnd && suffix < suffixes.size(); suffix++) {
            if (!prefixes.at(prefix).isEmpty() && name.startsWith(prefixes.at(prefix)))
                continue;
            if (!suffixes.at(suffix).isEmpty() && name.endsWith(suffixes.at(suffix)))
                continue;
            attempt = path + prefixes.at(prefix) + name + suffixes.at(suffix);                        
            pHnd = DL_PREFIX(dlopen)(QFile::encodeName(attempt), RTLD_LAZY);
        }
    }
#ifdef Q_OS_MAC
    if (!pHnd) {
        if(QCFType<CFBundleRef> bundle = CFBundleGetBundleWithIdentifier(QCFString(fileName))) {
            QCFType<CFURLRef> url = CFBundleCopyExecutableURL(bundle);
            QCFString str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
            pHnd = DL_PREFIX(dlopen)(QFile::encodeName(str), RTLD_LAZY);
            attempt = str;
        }
    }
# endif
#if defined(QT_DEBUG_COMPONENT)
    if (!pHnd) {
        qWarning("QLibrary: Cannot load '%s' :%s", QFile::encodeName(fileName).constData(),
                 qdlerror());
    }
#endif
    if (pHnd)
        qualifiedFileName = attempt;        
    return (pHnd != 0);
}
Beispiel #27
0
int main(int argc, char **argv)
{
    // parse command line
    int ret = Option::init(argc, argv);
    if(ret != Option::QMAKE_CMDLINE_SUCCESS) {
        if ((ret & Option::QMAKE_CMDLINE_ERROR) != 0)
            return 1;
        return 0;
    }

    QString oldpwd = qmake_getpwd();
#ifdef Q_WS_WIN
    if(!(oldpwd.length() == 3 && oldpwd[0].isLetter() && oldpwd.endsWith(":/")))
#endif
    {
        if(oldpwd.right(1) != QString(QChar(QDir::separator())))
            oldpwd += QDir::separator();
    }
    Option::output_dir = oldpwd; //for now this is the output dir

    if(Option::output.fileName() != "-") {
        QFileInfo fi(Option::output);
        QString dir;
        if(fi.isDir()) {
            dir = fi.filePath();
        } else {
            QString tmp_dir = fi.path();
            if(!tmp_dir.isEmpty() && QFile::exists(tmp_dir))
                dir = tmp_dir;
        }
        if(!dir.isNull() && dir != ".")
            Option::output_dir = dir;
        if(QDir::isRelativePath(Option::output_dir))
            Option::output_dir.prepend(oldpwd);
        Option::output_dir = QDir::cleanPath(Option::output_dir);
    }

    QMakeProperty prop;
    if(Option::qmake_mode == Option::QMAKE_QUERY_PROPERTY || Option::qmake_mode == Option::QMAKE_SET_PROPERTY)
        return prop.exec() ? 0 : 101;

    QMakeProject proj(&prop);
    int exit_val = 0;
    QStringList files;
    if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT)
        files << "(*hack*)"; //we don't even use files, but we do the for() body once
    else
        files = Option::mkfile::project_files;
    for(QStringList::Iterator pfile = files.begin(); pfile != files.end(); pfile++) {
        if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
           Option::qmake_mode == Option::QMAKE_GENERATE_PRL) {
            QString fn = Option::fixPathToLocalOS((*pfile));
            if(!QFile::exists(fn)) {
                fprintf(stderr, "Cannot find file: %s.\n", fn.toLatin1().constData());
                exit_val = 2;
                continue;
            }

            //setup pwd properly
            debug_msg(1, "Resetting dir to: %s", oldpwd.toLatin1().constData());
            qmake_setpwd(oldpwd); //reset the old pwd
            int di = fn.lastIndexOf(Option::dir_sep);
            if(di != -1) {
                debug_msg(1, "Changing dir to: %s", fn.left(di).toLatin1().constData());
                if(!qmake_setpwd(fn.left(di)))
                    fprintf(stderr, "Cannot find directory: %s\n", fn.left(di).toLatin1().constData());
                fn = fn.right(fn.length() - di - 1);
            }

            // read project..
            if(!proj.read(fn)) {
                fprintf(stderr, "Error processing project file: %s\n",
                        fn == "-" ? "(stdin)" : (*pfile).toLatin1().constData());
                exit_val = 3;
                continue;
            }
            if(Option::mkfile::do_preprocess) //no need to create makefile
                continue;
        }

        MetaMakefileGenerator *mkfile = MetaMakefileGenerator::createMetaGenerator(&proj);
        if(mkfile && !mkfile->write(oldpwd)) {
            if(Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT)
                fprintf(stderr, "Unable to generate project file.\n");
            else
                fprintf(stderr, "Unable to generate makefile for: %s\n", (*pfile).toLatin1().constData());
            exit_val = 5;
        }
        delete mkfile;
        mkfile = NULL;
    }
    return exit_val;
}
Beispiel #28
0
void classepub::chargeTreeIndex(QTreeWidget *view)
{
    QFile file(m_tocPath);

    QDomDocument m_doc;
    if (!file.open(QIODevice::ReadOnly)){
        qDebug()<<m_tocPath+"   no open";
        return ;
    }
    if (!m_doc.setContent(&file)){
        qDebug()<<m_tocPath+"   no Content";
        return ;
    }
view->clear();
    QDomElement racine2 = m_doc.documentElement(); //

    int count=racine2.childNodes().count();
    for(int i=0;i< count;i++){

        QDomNode metadata= racine2.childNodes().item(i);
        if (metadata.nodeName()=="navMap"){
            QDomElement metadataElement=metadata.toElement();
            int counts=metadataElement.childNodes().count();
            for(int r=0;r< counts;r++){
                QDomNode itemMeta=metadataElement.childNodes().item(r);
                if  (  itemMeta.nodeName()=="navPoint"){
                    QDomElement itemElement=itemMeta.toElement();
                    int i=itemElement.childNodes().count();
                    QString titleE;
                    QString idE;
                    QTreeWidgetItem *itemV=new QTreeWidgetItem(view);
                    for(int r=0;r< i;r++){

                        QDomNode item=itemElement.childNodes().item(r);

                        if( item.toElement().nodeName()=="navLabel"){

                            titleE=(item.toElement().text());

                        }
                        if( item.toElement().nodeName()=="content"){
                              idE=item.toElement().attribute("src").section("#",0,0);

                        }
                        if( item.toElement().nodeName()=="navPoint"){
                       QDomNode itemCild=item.toElement();
                       getChild(itemCild,itemV);
                        }


//----------------------
                    }
                    QFileInfo fi(m_tocPath);

itemV->setText(0,titleE);
itemV->setData(0,1,fi.path()+"/"+idE);

                }
            }
        }
    }

}
Beispiel #29
0
/*!
    Returns the path of the URL. If \a correct is true, the path is
    cleaned (deals with too many or too few slashes, cleans things
    like "/../..", etc). Otherwise path() returns exactly the path
    that was parsed or set.

    \sa setPath() hasPath()
*/
QString Q3Url::path( bool correct ) const
{
    if ( !correct )
	return d->path;

    if ( d->cleanPathDirty ) {
	bool check = true;
	if ( QDir::isRelativePath( d->path ) ) {
	    d->cleanPath = d->path;
	} else if ( isLocalFile() ) {
#if defined(Q_OS_WIN32)
	    // hack for stuff like \\machine\path and //machine/path on windows
	    if ( ( d->path.startsWith(QLatin1Char('/')) || d->path.startsWith(QLatin1Char('\\')) ) &&
		 d->path.length() > 1 ) {
		d->cleanPath = d->path;
		bool share = (d->cleanPath[0] == QLatin1Char('\\') && d->cleanPath[1] == QLatin1Char('\\')) ||
		             (d->cleanPath[0] == QLatin1Char('/') && d->cleanPath[1] == QLatin1Char('/'));
		slashify( d->cleanPath, false );
		d->cleanPath = QDir::cleanDirPath( d->cleanPath );
		if ( share ) {
		    check = false;
		    while (d->cleanPath.at(0) != QLatin1Char('/') || d->cleanPath.at(1) != QLatin1Char('/'))
			d->cleanPath.prepend(QLatin1Char('/'));
		}
	    }
#endif
	    if ( check ) {
		QFileInfo fi( d->path );
		if ( !fi.exists() )
		    d->cleanPath = d->path;
		else if ( fi.isDir() ) {
                    QString canPath = QDir( d->path ).canonicalPath();
                    QString dir;
                    if ( qt_resolve_symlinks && !canPath.isNull() )
                       dir = QDir::cleanDirPath( canPath );
                    else
                       dir = QDir::cleanDirPath( QDir( d->path ).absPath() );
                    dir += QLatin1Char('/');
		    if ( dir == QLatin1String("//") )
			d->cleanPath = QLatin1String("/");
		    else
			d->cleanPath = dir;
		} else {
		    QString p =
			QDir::cleanDirPath( (qt_resolve_symlinks ?
					    fi.dir().canonicalPath() :
					    fi.dir().absPath()) );
		    d->cleanPath = p + QLatin1Char('/') + fi.fileName();
		}
	    }
	} else {
		d->cleanPath = QDir::cleanDirPath( d->path );
	    if ( d->path.length() > 1 && d->path.endsWith(QLatin1Char('/')) )
    		d->cleanPath += QLatin1Char('/');
	}

	if ( check )
	    slashify( d->cleanPath, false );
	d->cleanPathDirty = false;
    }

    return d->cleanPath;
}
MythFontProperties *MythFontProperties::ParseFromXml(
    const QString &filename,
    const QDomElement &element,
    MythUIType *parent,
    bool addToGlobal,
    bool showWarnings)
{
    // Crappy, but cached.  Move to GlobalFontMap?

    bool fromBase = false;
    MythFontProperties *newFont = new MythFontProperties();
    newFont->Freeze();

    if (element.tagName() == "font")
        LOG(VB_GENERAL, LOG_WARNING, LOC +
            QString("File %1: Use of 'font' is deprecated in favour of "
                    "'fontdef'") .arg(filename));

    QString name = element.attribute("name", "");
    if (name.isEmpty())
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR,
                    filename, element, "Font requires a name");
        delete newFont;
        return NULL;
    }

    QString base = element.attribute("from", "");

    if (!base.isEmpty())
    {
        MythFontProperties *tmp = NULL;

        if (parent)
            tmp = parent->GetFont(base);

        if (!tmp)
            tmp = GetGlobalFontMap()->GetFont(base);

        if (!tmp)
        {
            VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                QString("Specified base font '%1' does not exist.").arg(base));

            delete newFont;
            return NULL;
        }

        *newFont = *tmp;
        fromBase = true;
    }

    int size, pixelsize;
    size = pixelsize = -1;

    QString face = element.attribute("face", "");
    if (face.isEmpty())
    {
        if (!fromBase)
        {
            VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                        "Font needs a face");
            delete newFont;
            return NULL;
        }
    }
    else
    {
        newFont->m_face.setFamily(face);
    }

    if (addToGlobal && GetGlobalFontMap()->Contains(name))
    {
        MythFontProperties *tmp = GetGlobalFontMap()->GetFont(name);
        if (showWarnings)
        {
            VERBOSE_XML(VB_GENERAL, LOG_WARNING, filename, element,
                QString("Attempting to define '%1'\n\t\t\t"
                        "with face '%2', but it already "
                        "exists with face '%3'")
                .arg(name).arg(QFontInfo(newFont->m_face).family())
                .arg((tmp) ? QFontInfo(tmp->m_face).family() : "ERROR"));
        }
        delete newFont;
        return NULL;
    }

    QString hint = element.attribute("stylehint", "");
    if (!hint.isEmpty())
    {
        newFont->m_face.setStyleHint((QFont::StyleHint)hint.toInt());
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
         child = child.nextSibling())
    {
        QDomElement info = child.toElement();
        if (!info.isNull())
        {
            if (info.tagName() == "size")
            {
                size = getFirstText(info).toInt();
            }
            else if (info.tagName() == "pixelsize")
            {
                pixelsize = getFirstText(info).toInt();
            }
            else if (info.tagName() == "color")
            {
                newFont->m_brush = QBrush(QColor(getFirstText(info)));
            }
            else if (info.tagName() == "gradient")
            {
                newFont->m_brush = parseGradient(info);
            }
            else if (info.tagName() == "shadowcolor")
            {
                newFont->m_shadowColor = QColor(getFirstText(info));
            }
            else if (info.tagName() == "shadowoffset")
            {
                newFont->m_hasShadow = true;
                newFont->m_shadowOffset = parsePoint(info);
            }
            else if (info.tagName() == "shadowalpha")
            {
                newFont->m_shadowAlpha = getFirstText(info).toInt();
            }
            else if (info.tagName() == "outlinecolor")
            {
                newFont->m_outlineColor = QColor(getFirstText(info));
            }
            else if (info.tagName() == "outlinesize")
            {
                newFont->m_hasOutline = true;
                newFont->m_outlineSize = getFirstText(info).toInt();
            }
            else if (info.tagName() == "outlinealpha")
            {
                newFont->m_outlineAlpha = getFirstText(info).toInt();
            }
            else if (info.tagName() == "italics")
            {
                newFont->m_face.setItalic(parseBool(info));
            }
            else if (info.tagName() == "letterspacing")
            {
                newFont->m_face.setLetterSpacing(QFont::AbsoluteSpacing,
                                              getFirstText(info).toInt());
            }
            else if (info.tagName() == "wordspacing")
            {
                newFont->m_face.setWordSpacing(getFirstText(info).toInt());
            }
            else if (info.tagName() == "decoration")
            {
                QString dec = getFirstText(info).toLower();
                QStringList values = dec.split(',');

                QStringList::Iterator it;
                for ( it = values.begin(); it != values.end(); ++it )
                {
                    if (*it == "underline")
                        newFont->m_face.setUnderline(true);
                    else if (*it == "overline")
                        newFont->m_face.setOverline(true);
                    else if (*it == "strikeout")
                        newFont->m_face.setStrikeOut(true);
                }
            }
            else if (info.tagName() == "weight")
            {
                QString weight = getFirstText(info).toLower();

                if (weight == "ultralight" ||
                    weight == "1")
                    newFont->m_face.setWeight(1);
                else if (weight == "light" ||
                         weight == "2")
                    newFont->m_face.setWeight(QFont::Light);
                else if (weight == "normal" ||
                         weight == "3")
                    newFont->m_face.setWeight(QFont::Normal);
                else if (weight == "demibold" ||
                         weight == "4")
                    newFont->m_face.setWeight(QFont::DemiBold);
                else if (weight == "bold" ||
                         weight == "5")
                    newFont->m_face.setWeight(QFont::Bold);
                else if (weight == "black" ||
                         weight == "6")
                    newFont->m_face.setWeight(QFont::Black);
                else if (weight == "ultrablack" ||
                         weight == "7")
                    newFont->m_face.setWeight(99);
                else
                    newFont->m_face.setWeight(QFont::Normal);
            }
            else if (info.tagName() == "stretch")
            {
                QString stretch = getFirstText(info).toLower();

                if (stretch == "ultracondensed" ||
                    stretch == "1")
                    newFont->m_stretch = QFont::UltraCondensed;
                else if (stretch == "extracondensed" ||
                         stretch == "2")
                    newFont->m_stretch = QFont::ExtraCondensed;
                else if (stretch == "condensed" ||
                         stretch == "3")
                    newFont->m_stretch = QFont::Condensed;
                else if (stretch == "semicondensed" ||
                         stretch == "4")
                    newFont->m_stretch = QFont::SemiCondensed;
                else if (stretch == "unstretched" ||
                         stretch == "5")
                    newFont->m_stretch = QFont::Unstretched;
                else if (stretch == "semiexpanded" ||
                         stretch == "6")
                    newFont->m_stretch = QFont::SemiExpanded;
                else if (stretch == "expanded" ||
                         stretch == "7")
                    newFont->m_stretch = QFont::Expanded;
                else if (stretch == "extraexpanded" ||
                         stretch == "8")
                    newFont->m_stretch = QFont::ExtraExpanded;
                else if (stretch == "ultraexpanded" ||
                         stretch == "9")
                    newFont->m_stretch = QFont::UltraExpanded;
                else
                    newFont->m_stretch = QFont::Unstretched;

                newFont->m_face.setStretch(newFont->m_stretch);
            }
            else
            {
                VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, info,
                            QString("Unknown tag in font '%1'").arg(name));
                delete newFont;
                return NULL;
            }
        }
    }

    if (size <= 0 && pixelsize <= 0 && !fromBase)
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                    "Font size must be greater than 0.");
        delete newFont;
        return NULL;
    }
    else if (pixelsize > 0)
    {
        newFont->SetPixelSize(pixelsize);
    }
    else if (size > 0)
    {
        newFont->SetPointSize(size);
    }

    newFont->Unfreeze();

    QFontInfo fi(newFont->m_face);
    if (newFont->m_face.family() != fi.family())
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                    QString("Failed to load '%1', got '%2' instead")
            .arg(newFont->m_face.family()).arg(fi.family()));
    }
    else
    {
        VERBOSE_XML(VB_GUI, LOG_DEBUG, filename, element,
                    QString("loaded '%1'").arg(fi.family()));
    }

    if (addToGlobal)
        GetGlobalFontMap()->AddFont(name, newFont);

    return newFont;
}