Example #1
0
//
// There have been problems with the finish-signal coming from the networkmanager.
// To avoid that, the reply-signals were connected and the data is taken from the
// sender() method.
//
void ownCloudInfo::slotReplyFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    QSslConfiguration sslConfig = reply->sslConfiguration();
    if (!sslConfig.isNull()) {
        QMutexLocker lock(&_certChainMutex);
        _certificateChain = sslConfig.peerCertificateChain();
    }

    if( ! reply ) {
        qDebug() << "ownCloudInfo: Reply empty!";
        return;
    }

    // Detect redirect url
    QUrl possibleRedirUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    /* We'll deduct if the redirection is valid in the redirectUrl function */


    if (!possibleRedirUrl.isEmpty() && _redirectCount++  > 10) {
        // Are we in a redirect loop
        qDebug() << "Redirect loop while redirecting to" << possibleRedirUrl;
        possibleRedirUrl.clear();
    }

    if(!possibleRedirUrl.isEmpty()) {
        QString configHandle;

        qDebug() << "Redirected to " << possibleRedirUrl;

        // We'll do another request to the redirection url.
        // an empty config handle is ok for the default config.
        if( _configHandleMap.contains(reply) ) {
            configHandle = _configHandleMap[reply];
            qDebug() << "Redirect: Have a custom config handle: " << configHandle;
        }

        QString path = _directories[reply];
        if (path.isEmpty()) {
            path = QLatin1String("status.php");
        } else {
            path.prepend( QLatin1String(WEBDAV_PATH) );
        }
        qDebug() << "This path was redirected: " << path;

        QString newUrl = possibleRedirUrl.toString();
        if( !path.isEmpty() && newUrl.endsWith( path )) {
            // cut off the trailing path
            newUrl.chop( path.length() );
            _urlRedirectedTo = newUrl;
            qDebug() << "Updated url to" << newUrl;
            getRequest( possibleRedirUrl );
        } else {
            qDebug() << "WRN: Path is not part of the redirect URL. NO redirect.";
        }
        reply->deleteLater();
        _directories.remove(reply);
        _configHandleMap.remove(reply);
        return;
    }

    // TODO: check if this is always the correct encoding
    const QString version = QString::fromUtf8( reply->readAll() );
    const QString url = reply->url().toString();
    QString plainUrl(url);
    plainUrl.remove( QLatin1String("/status.php"));

    QString info( version );

    if( url.endsWith( QLatin1String("status.php")) ) {
        // it was a call to status.php
        if( reply->error() == QNetworkReply::NoError && info.isEmpty() ) {
            // This seems to be a bit strange behaviour of QNetworkAccessManager.
            // It calls the finised slot multiple times but only the first read wins.
            // That happend when the code connected the finished signal of the manager.
            // It did not happen when the code connected to the reply finish signal.
            qDebug() << "WRN: NetworkReply with not content but also no error! " << reply;
            reply->deleteLater();
            return;
        }
        qDebug() << "status.php returns: " << info << " " << reply->error() << " Reply: " << reply;
        if( info.contains(QLatin1String("installed"))
                && info.contains(QLatin1String("version"))
                && info.contains(QLatin1String("versionstring")) ) {
            info.remove(0,1); // remove first char which is a "{"
            info.remove(-1,1); // remove the last char which is a "}"
            QStringList li = info.split( QLatin1Char(',') );

            QString versionStr;
            QString version;
            QString edition;

            foreach ( const QString& infoString, li ) {
                QStringList touple = infoString.split( QLatin1Char(':'));
                QString key = touple[0];
                key.remove(QLatin1Char('"'));
                QString val = touple[1];
                val.remove(QLatin1Char('"'));

                if( key == QLatin1String("versionstring") ) {
                    // get the versionstring out.
                    versionStr = val;
                } else if( key == QLatin1String( "version") ) {
                    // get version out
                    version = val;
                } else if( key == QLatin1String( "edition") ) {
                    // get version out
                    edition = val;
                } else if(key == QLatin1String("installed")) {
		    // Silently ignoring "installed = true" information
		} else {
                    qDebug() << "Unknown info from ownCloud status.php: "<< key << "=" << val;
                }
            }
            emit ownCloudInfoFound( plainUrl, versionStr, version, edition );
        } else {
Example #2
0
bool KDesktopFile::isDesktopFile(const QString& path)
{
  return (path.length() > 8
          && path.endsWith(QLatin1String(".desktop")));
}
Example #3
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('/');

    // The first filename we want to attempt to load is the filename as the callee specified.
    // Thus, the first attempt we do must be with an empty prefix and empty suffix.
    QStringList suffixes(QLatin1String("")), prefixes(QLatin1String(""));
    if (pluginState != IsAPlugin) {
        prefixes << QLatin1String("lib");
#if defined(Q_OS_HPUX)
        // according to
        // http://docs.hp.com/en/B2355-90968/linkerdifferencesiapa.htm

        // In PA-RISC (PA-32 and PA-64) shared libraries are suffixed
        // with .sl. In IPF (32-bit and 64-bit), the shared libraries
        // are suffixed with .so. For compatibility, the IPF linker
        // also supports the .sl suffix.

        // But since we don't know if we are built on HPUX or HPUXi,
        // we support both .sl (and .<version>) and .so suffixes but
        // .so is preferred.
# if defined(__ia64)
        if (!fullVersion.isEmpty()) {
            suffixes << QString::fromLatin1(".so.%1").arg(fullVersion);
        } else {
            suffixes << QLatin1String(".so");
        }
# endif
        if (!fullVersion.isEmpty()) {
            suffixes << QString::fromLatin1(".sl.%1").arg(fullVersion);
            suffixes << QString::fromLatin1(".%1").arg(fullVersion);
        } else {
            suffixes << QLatin1String(".sl");
        }
#elif defined(Q_OS_AIX)
        suffixes << ".a";
#else
        if (!fullVersion.isEmpty()) {
            suffixes << QString::fromLatin1(".so.%1").arg(fullVersion);
        } else {
            suffixes << QLatin1String(".so");
        }
#endif
# ifdef Q_OS_MAC
        if (!fullVersion.isEmpty()) {
            suffixes << QString::fromLatin1(".%1.bundle").arg(fullVersion);
            suffixes << QString::fromLatin1(".%1.dylib").arg(fullVersion);
        } else {
            suffixes << QLatin1String(".bundle") << QLatin1String(".dylib");
        }
#endif
    }
    int dlFlags = 0;
#if defined(QT_HPUX_LD)
    dlFlags = DYNAMIC_PATH | BIND_NONFATAL;
    if (loadHints & QLibrary::ResolveAllSymbolsHint) {
        dlFlags |= BIND_IMMEDIATE;
    } else {
        dlFlags |= BIND_DEFERRED;
    }
#else
    if (loadHints & QLibrary::ResolveAllSymbolsHint) {
        dlFlags |= RTLD_NOW;
    } else {
        dlFlags |= RTLD_LAZY;
    }
    if (loadHints & QLibrary::ExportExternalSymbolsHint) {
        dlFlags |= RTLD_GLOBAL;
    }
#if !defined(Q_OS_CYGWIN)
    else {
#if defined(Q_OS_MAC)
        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
#endif        
        dlFlags |= RTLD_LOCAL;
    }
#endif
#if defined(Q_OS_AIX)	// Not sure if any other platform actually support this thing.
    if (loadHints & QLibrary::LoadArchiveMemberHint) {
        dlFlags |= RTLD_MEMBER;
    }
#endif
#endif // QT_HPUX_LD
    QString attempt;
    bool retry = true;
    for(int prefix = 0; retry && !pHnd && prefix < prefixes.size(); prefix++) {
        for(int suffix = 0; retry && !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;
            if (loadHints & QLibrary::LoadArchiveMemberHint) {
                attempt = name;
                int lparen = attempt.indexOf(QLatin1Char('('));
                if (lparen == -1)
                    lparen = attempt.count();
                attempt = path + prefixes.at(prefix) + attempt.insert(lparen, suffixes.at(suffix));
            } else {
                attempt = path + prefixes.at(prefix) + name + suffixes.at(suffix);
            }
#if defined(QT_HPUX_LD)
            pHnd = (void*)shl_load(QFile::encodeName(attempt), dlFlags, 0);
#else
            pHnd = dlopen(QFile::encodeName(attempt), dlFlags);
#endif
            if (!pHnd && fileName.startsWith(QLatin1Char('/')) && QFile::exists(attempt)) {
                // We only want to continue if dlopen failed due to that the shared library did not exist.
                // However, we are only able to apply this check for absolute filenames (since they are
                // not influenced by the content of LD_LIBRARY_PATH, /etc/ld.so.cache, DT_RPATH etc...)
                // This is all because dlerror is flawed and cannot tell us the reason why it failed.
                retry = false;
            }
        }
    }

#ifdef Q_OS_MAC
    if (!pHnd) {
        if (CFBundleRef bundle = CFBundleGetBundleWithIdentifier(QCFString(fileName))) {
            QCFType<CFURLRef> url = CFBundleCopyExecutableURL(bundle);
            QCFString str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
            pHnd = dlopen(QFile::encodeName(str), dlFlags);
            attempt = str;
        }
    }
# endif
    if (!pHnd) {
        errorString = QLibrary::tr("Cannot load library %1: %2").arg(fileName).arg(qdlerror());
    }
    if (pHnd) {
        qualifiedFileName = attempt;
        errorString.clear();
    }
    return (pHnd != 0);
}
Example #4
0
bool NewWorld::execute()
{
    if(!this->processor->execute(new AskForSave()))
    {
        return false;
    }

    PIDGIRL::writeLog("Creating New World");

    QDir worldDir(QDir::current());
    worldDir.mkdir(PIDGIRL::WORLD_FOLDER_NAME);
    worldDir.cd(PIDGIRL::WORLD_FOLDER_NAME);

    QString fileName = QFileDialog::getSaveFileName
            (
                0,
                tr("Create New World..."),
                worldDir.absolutePath(),
                tr("PIDGIRL World Files (*").append(PIDGIRL::WORLD_SUFFIX).append(")")
            );

    if(fileName.isEmpty())
    {
        PIDGIRL::writeLogFail("No file was specified. The string, where the path should've been, was empty.");
        return false;
    }

    if(!fileName.endsWith(PIDGIRL::WORLD_SUFFIX))
    {
        fileName = fileName.append(PIDGIRL::WORLD_SUFFIX);
    }

    QFileInfo fileInfo = QFileInfo(fileName);
    QString worldDirName = fileName;
    worldDirName.remove(fileName.size() - PIDGIRL::WORLD_SUFFIX.size(),PIDGIRL::WORLD_SUFFIX.size());
    QDir dir = fileInfo.dir();

    if(!dir.mkdir(worldDirName))
    {
        PIDGIRL::writeLogFail("Creating the folder for the world failed.");
        return false;
    }

    if(!dir.cd(worldDirName))
    {
        PIDGIRL::writeLogFail("Changing the directory to the world folder failed.");
        return false;
    }

    this->worldModel->setWorldFileInfo(QFileInfo(dir, fileInfo.fileName()));

    if(!this->fileManager.serialize(this->worldModel, this->worldModel->refWorldFileInfo()->absoluteFilePath()))
    {
        QMessageBox::critical(0, tr("Failed to create a new world..."), tr("Creating a new world has failed."));
        PIDGIRL::writeLogFail(QString("The creating process of the map failed. Filepath was: ").append(this->worldModel->refWorldFileInfo()->absoluteFilePath()));
        return false;
    }

    if(this->mapModel)
    {
        this->mapModel->setNewStandardMap();
    }
    this->undoRedo->setOnlySavedWorldChanges(true);

    PIDGIRL::writeLogDone();
    return true;
}
Example #5
0
void TreeView::slotDropped (QDropEvent * e, Q3ListViewItem *parent, Q3ListViewItem*after)
{
   if(!e) return;

   // get destination folder
   TreeItem *parentItem = static_cast<TreeItem*>(parent);
   QString folder = parentItem ? parentItem->directory() : QString();
   MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;

   if (e->source() != this)
   {
     // External drop
     KUrl::List urls;
     if (!K3URLDrag::decode(e, urls) || (urls.count() != 1) || !urls[0].isLocalFile())
        return;
     QString path = urls[0].path();
     if (!path.endsWith(".desktop"))
        return;

     QString menuId;
     QString result = createDesktopFile(path, &menuId, &m_newMenuIds);
     KDesktopFile orig_df(path);
     KDesktopFile *df = orig_df.copyTo(result);
     df->desktopGroup().deleteEntry("Categories"); // Don't set any categories!

     KService::Ptr s(new KService(df));
     s->setMenuId(menuId);

     MenuEntryInfo *entryInfo = new MenuEntryInfo(s, df);

     QString oldCaption = entryInfo->caption;
     QString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
     entryInfo->setCaption(newCaption);

     // Add file to menu
     // m_menuFile->addEntry(folder, menuId);
     m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);

     // create the TreeItem
     if(parentItem)
        parentItem->setOpen(true);

     // update fileInfo data
     parentFolderInfo->add(entryInfo);

     TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);

     setSelected ( newItem, true);
     itemSelected( newItem);

     m_drag = 0;
     setLayoutDirty(parentItem);
     return;
   }

   // is there content in the clipboard?
   if (!m_drag) return;

   if (m_dragItem == after) return; // Nothing to do

   int command = m_drag;
   if (command == MOVE_FOLDER)
   {
      MenuFolderInfo *folderInfo = m_dragInfo;
      if (e->action() == QDropEvent::Copy)
      {
         // Ugh.. this is hard :)
         // * Create new .directory file
         // Add
      }
      else
      {
          TreeItem *tmpItem = static_cast<TreeItem*>(parentItem);
          while (  tmpItem )
          {
              if (  tmpItem == m_dragItem )
              {
                  m_drag = 0;
                  return;
              }
              tmpItem = static_cast<TreeItem*>(tmpItem->parent() );
          }

         // Remove MenuFolderInfo
         TreeItem *oldParentItem = static_cast<TreeItem*>(m_dragItem->parent());
         MenuFolderInfo *oldParentFolderInfo = oldParentItem ? oldParentItem->folderInfo() : m_rootFolder;
         oldParentFolderInfo->take(folderInfo);

         // Move menu
         QString oldFolder = folderInfo->fullId;
         QString folderName = folderInfo->id;
         QString newFolder = m_menuFile->uniqueMenuName(folder, folderName, parentFolderInfo->existingMenuIds());
         folderInfo->id = newFolder;

         // Add file to menu
         //m_menuFile->moveMenu(oldFolder, folder + newFolder);
         m_menuFile->pushAction(MenuFile::MOVE_MENU, oldFolder, folder + newFolder);

         // Make sure caption is unique
         QString newCaption = parentFolderInfo->uniqueMenuCaption(folderInfo->caption);
         if (newCaption != folderInfo->caption)
         {
            folderInfo->setCaption(newCaption);
         }

	 // create the TreeItem
	 if(parentItem)
	   parentItem->setOpen(true);

         // update fileInfo data
         folderInfo->updateFullId(parentFolderInfo->fullId);
         folderInfo->setInUse(true);
         parentFolderInfo->add(folderInfo);

         if ((parentItem != oldParentItem) || !after)
         {
            if (oldParentItem)
               oldParentItem->takeItem(m_dragItem);
            else
               takeItem(m_dragItem);
            if (parentItem)
               parentItem->insertItem(m_dragItem);
            else
               insertItem(m_dragItem);
         }
         m_dragItem->moveItem(after);
         m_dragItem->setName(folderInfo->caption);
         m_dragItem->setDirectoryPath(folderInfo->fullId);
         setSelected(m_dragItem, true);
         itemSelected(m_dragItem);
      }
   }
   else if (command == MOVE_FILE)
   {
      MenuEntryInfo *entryInfo = m_dragItem->entryInfo();
      QString menuId = entryInfo->menuId();

      if (e->action() == QDropEvent::Copy)
      {

         // Need to copy file and then add it
         KDesktopFile *df = copyDesktopFile(entryInfo, &menuId, &m_newMenuIds); // Duplicate
//UNDO-ACTION: NEW_MENU_ID (menuId)

         KService::Ptr s(new KService(df));
         s->setMenuId(menuId);

         entryInfo = new MenuEntryInfo(s, df);

         QString oldCaption = entryInfo->caption;
         QString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
         entryInfo->setCaption(newCaption);
      }
      else
      {
         del(m_dragItem, false);
         QString oldCaption = entryInfo->caption;
         QString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption);
         entryInfo->setCaption(newCaption);
         entryInfo->setInUse(true);
      }
      // Add file to menu
      // m_menuFile->addEntry(folder, menuId);
      m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);

      // create the TreeItem
      if(parentItem)
         parentItem->setOpen(true);

      // update fileInfo data
      parentFolderInfo->add(entryInfo);

      TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);

      setSelected ( newItem, true);
      itemSelected( newItem);
   }
   else if (command == COPY_SEPARATOR)
   {
      if (e->action() != QDropEvent::Copy)
         del(m_dragItem, false);

      TreeItem *newItem = createTreeItem(parentItem, after, m_separator, true);

      setSelected ( newItem, true);
      itemSelected( newItem);
   }
   else
   {
      // Error
   }
   m_drag = 0;
   setLayoutDirty(parentItem);
}
Example #6
0
/** Writes session to XML file in \a fileName path.
  * \sa restore()
  */
void Session::save(const QString &fileName) {
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly)) {
        QMessageBox::warning(convertDialog, tr("Session write error"),
                             tr("Session saving to %1 file failed.\n"
                                "Can't open the file.").arg(fileName) );
        return;
    }

    Version version;
    QString str; // working string

    XmlStreamWriter writer(&file);
    writer.setAutoFormatting(true);
    writer.setAutoFormattingIndent(2);
    writer.setCodec("UTF-8");
    writer.writeStartDocument();
    writer.writeStartElement("sir");
    writer.writeAttribute("version", version.version());
    writer.writeStartElement("session");

    writer.writeStartElement("files");
    for (int i=0; i<convertDialog->filesTreeWidget->topLevelItemCount(); i++) {
        QTreeWidgetItem *item = convertDialog->filesTreeWidget->topLevelItem(i);
        QString path = item->text(2);
        if (!path.endsWith(QDir::separator()))
            path += QDir::separator();
        path += item->text(0) + '.' + item->text(1);
        writer.writeStartElement("file");
        writer.writeCharacters(path);
        writer.writeEndElement(); // file
    }
    writer.writeEndElement(); // files

    writer.writeStartElement("target");
    writer.writeStartElement("dir");
    writer.writeCharacters(convertDialog->destFileEdit->text());
    writer.writeEndElement(); // dir
    writer.writeStartElement("prefix");
    writer.writeCharacters(convertDialog->destPrefixEdit->text());
    writer.writeEndElement(); // prefix
    writer.writeStartElement("suffix");
    writer.writeCharacters(convertDialog->destSuffixEdit->text());
    writer.writeEndElement(); // suffix
    writer.writeStartElement("format");
    writer.writeCharacters(convertDialog->targetFormatComboBox->currentText());
    writer.writeEndElement(); // format
    writer.writeEndElement(); // target

    writer.writeStartElement("size");
    writer.writeAttribute("keepaspect", sizeArea->maintainCheckBox->isChecked());
    str = sizeArea->sizeUnitComboBox->currentText().split('(')[1].split(')')[0];
    writer.writeAttribute("unit", str);
    if (sizeArea->sizeUnitComboBox->currentIndex() == 0) {
        writer.writeStartElement("pixels");
        writer.writeAttribute("width",  sizeArea->widthDoubleSpinBox->value());
        writer.writeAttribute("height", sizeArea->heightDoubleSpinBox->value());
        writer.writeEndElement(); // pixels
        writer.writeStartElement("percent");
        writer.writeAttribute("width",  ConvertSharedData::instance()->sizeWidth);
        writer.writeAttribute("height", ConvertSharedData::instance()->sizeHeight);
        writer.writeEndElement(); // percent
    }
    else {
        writer.writeStartElement("percent");
        writer.writeAttribute("width",  sizeArea->widthDoubleSpinBox->value());
        writer.writeAttribute("height", sizeArea->heightDoubleSpinBox->value());
        writer.writeEndElement(); // percent
        writer.writeStartElement("pixels");
        writer.writeAttribute("width",  ConvertSharedData::instance()->sizeWidth);
        writer.writeAttribute("height", ConvertSharedData::instance()->sizeHeight);
        writer.writeEndElement(); // pixels
    }
    writer.writeStartElement("bytes");
    writer.writeCharacters(QString::number(sizeArea->fileSizeSpinBox->value())
                           + ' ' + sizeArea->fileSizeComboBox->currentText() );
    writer.writeEndElement(); // bytes
    writer.writeEndElement(); // size

    writer.writeStartElement("options");
    writer.writeStartElement("quality");
    writer.writeValue(optionsArea->qualitySliderBox->value());
    writer.writeEndElement(); // quality
    writer.writeStartElement("progressiveWrite");
    writer.writeAttribute("enabled", optionsArea->progressiveWriteCheckBox->isChecked());
    writer.writeEndElement(); // progressiveWrite
    writer.writeStartElement("optimizedWrite");
    writer.writeAttribute("enabled", optionsArea->optimizedWriteCheckBox->isChecked());
    writer.writeEndElement(); // optimizedWrite
    writer.writeStartElement("background");
    writer.writeAttribute("enabled", optionsArea->backgroundColorCheckBox->isChecked());
    writer.writeColorElement(optionsArea->backgroundColorFrame->color());
    writer.writeEndElement(); // background
    writer.writeStartElement("rotation");
    writer.writeAttribute("enabled", optionsArea->rotateCheckBox->isChecked());
    writer.writeCharacters(QString::number(optionsArea->rotateDoubleSpinBox->value(), 'f', 1));
    writer.writeEndElement(); // rotation
    writer.writeStartElement("flip");
    writer.writeValue(optionsArea->flipComboBox->currentIndex());
    writer.writeEndElement(); // flip
    writer.writeEndElement(); // options

    collector->write(&writer);

    writer.writeStartElement("svg");
    writer.writeAttribute("save", svgArea->saveCheckBox->isChecked());
    writer.writeStartElement("remove");
    writer.writeAttribute("emptygroups", svgArea->removeGroupsCheckBox->isChecked());
    writer.writeStartElement("text");
    writer.writeAttribute("enabled", svgArea->removeTextCheckBox->isChecked());
    writer.writeCharacters(svgArea->removeTextLineEdit->text());
    writer.writeEndElement(); // text
    writer.writeEndElement(); // remove
    writer.writeEndElement(); // svg

    writer.writeEndElement(); // session
    writer.writeEndElement(); // sir
    writer.writeEndDocument();
}
Example #7
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;
}
Example #8
0
/* METAR examples
Berlin-Schoenefeld, Germany (EDDB) 52-23N 013-31E 50M
Sep 26, 2013 - 03:50 AM EDT / 2013.09.26 0750 UTC
Wind: from the NNE (020 degrees) at 13 MPH (11 KT):0
Visibility: 3 mile(s):0
Sky conditions: mostly cloudy
Weather: light drizzle
Temperature: 46 F (8 C)
Dew Point: 46 F (8 C)
Relative Humidity: 100%
Pressure (altimeter): 29.83 in. Hg (1010 hPa)
ob: EDDB 260750Z 02011KT 6000 -DZ SCT003 BKN006 08/08 Q1010 TEMPO BKN010
cycle: 8

Station name not available
Aug 18, 2013 - 09:30 PM EDT / 2013.08.19 0130 UTC
Sky conditions: partly cloudy
Temperature: 59 F (15 C)
Dew Point: 57 F (14 C)
Relative Humidity: 93%
Pressure (altimeter): 30.39 in. Hg (1029 hPa)
ob: OPSD 190130Z CALM 09KM P/CLOUDY FEW015ST SCT035 Q1029/30.41 15/14C RH 95 PERCENT A/V OH CLEAR
cycle: 1
*/
void PreFlightWeatherPage::slotNewWeaterReport( QString& file )
{
  QFile report(file);

  QString station = QFileInfo(file).baseName();

  if( file.contains("/weather/METAR/") )
    {
      if ( ! report.open( QIODevice::ReadOnly ) )
        {
          // could not open file ...
          qWarning() << "Cannot open file: " << report.fileName();
          return;
        }

      // METAR report received
      QTextStream stream( &report );
      QString line;

      QHash<QString, QString> reportItems;
      reportItems.insert( "icao", station );

      int lineNo = 0;

      int tempUnit = GeneralConfig::instance()->getUnitTemperature();
      int pressureUnit = GeneralConfig::instance()->getUnitAirPressure();

      while( !stream.atEnd() )
        {
          line = stream.readLine();
          lineNo++;

          // qDebug() << "line=" << line;

          if( line.trimmed().isEmpty() )
            {
              // ignore comment and empty lines
              continue;
            }

          if( lineNo == 1 )
            {
              // Line 1: station name
              // Berlin-Schoenefeld, Germany (EDDB) 52-23N 013-31E 50M
              // Station name not available
              if( line.startsWith( "Station name not available" ) )
                {
                  reportItems.insert( "station", tr("Station name not available") );
                  continue;
                }

              int idx = line.indexOf( "(" + station + ")" );

              if( idx > 0 )
                {
                  reportItems.insert( "station", line.left(idx - 1) );
                  continue;
                }

              reportItems.insert( "station", line );
              continue;
            }

          if( lineNo == 2 )
            {
              // Line 2: Date and time
              // Sep 26, 2013 - 11:50 AM EDT / 2013.09.26 1550 UTC
              if( line.endsWith(" UTC") )
                {
                  int idx = line.indexOf( " / " );

                  if( idx > 0 && line.size() > (idx + 3) )
                    {
                      QString date = line.mid(idx + 3, 13) + ":" +
                                     line.mid(idx + 3 + 13);

                      reportItems.insert( "date", date );
                      continue;
                    }
                }

              reportItems.insert( "date", line );
              continue;
            }

          if( line.startsWith( "Wind: ") )
            {
              // Wind: from the NW (310 degrees) at 5 MPH (4 KT):0
              // Wind: from the W (280 degrees) at 5 MPH (4 KT) (direction variable):0
              // Wind: from the ESE (120 degrees) at 20 MPH (17 KT) gusting to 32 MPH (28 KT) (direction variable):0
              line.replace( " degrees", QChar(Qt::Key_degree) );

              if( line.endsWith( ":0") )
                {
                  line.chop(2);
                }

              // Remove the line beginning.
              line = line.mid(6);
              int loop = 6;

              while( loop-- )
                {
                  QRegExp re = QRegExp("[0-9]+ MPH \\([0-9]+ KT\\)");

                  int idx1 = line.indexOf(re, 0);

                  if( idx1 == -1 )
                    {
                      // No speed value found.
                      break;
                    }

                  int idx2 = line.indexOf( "(", idx1 + 1 );
                  int idx3 = line.indexOf( " KT)", idx1 + 1 );

                  if( idx2 > 0 && idx2 < idx3 )
                    {
                      bool ok;
                      double ws = line.mid(idx2 + 1, idx3 - idx2 -1).toDouble(&ok);

                      if( ok )
                        {
                          Speed speed(0);
                          speed.setKnot( ws );

                          QString wsText = speed.getWindText( true, 0 );

                          line = line.left(idx1) + wsText + line.mid(idx3 + 4);
                        }
                    }
                }

              reportItems.insert( "wind", line );
              continue;
            }

          if( line.startsWith( "Visibility: ") )
            {
              // Visibility: greater than 7 mile(s):0
              // Visibility: less than 1 mile:0
              // Visibility: 3/4 mile(s):0
              if( line.contains( " mile") )
                {
                  int idx2  = line.lastIndexOf( " mile" );
                  int idx1  = line.lastIndexOf( " ", idx2 - 1 );

                  if( idx1 > 0 && idx1 < idx2 )
                    {
                      bool ok = false;
                      double visiDouble = 0.0;

                      QString visiText = line.mid(idx1 + 1, idx2 - idx1 -1);

                      if( visiText.contains("/") )
                        {
                          QStringList visiList = visiText.split("/");

                          if( visiList.size() == 2 )
                            {
                              double arg1 = visiList.at(0).toDouble(&ok);

                              if( ok )
                                {
                                  double arg2 = visiList.at(1).toDouble(&ok);

                                  if( ok && arg2 > 0.0 )
                                    {
                                      visiDouble = arg1 / arg2;
                                    }
                                }
                            }
                        }
                      else
                        {
                          visiDouble = visiText.toDouble( &ok );
                        }

                      if( ok )
                        {
                          Distance distance(0);
                          distance.setMiles( visiDouble );

                          QString visibility = line.mid( 12, idx1 - 11 );

                          if( distance.getKilometers() > 5 )
                            {
                              visibility += distance.getText( true, 0 );
                            }
                          else
                            {
                              visibility += distance.getText( true, 1 );
                            }

                          if( line.contains("mile(s)") )
                            {
                              // This must be tested as first to prevent wrong handling!
                              if( ! line.endsWith( "mile(s):0") )
                                {
                                  line.replace( ":0", "" );
                                  visibility += line.mid( line.indexOf( "mile(s)" ) + 7 );
                                }
                            }
                          else if( line.contains("mile") && ! line.endsWith( "mile:0") )
                            {
                              if( ! line.endsWith( "mile:0") )
                                {
                                  line.replace( ":0", "" );
                                  visibility += line.mid( line.indexOf( "mile" ) + 4 );
                                }
                            }

                          reportItems.insert( "visibility", visibility );
                          continue;
                        }
                    }
                }

              reportItems.insert( "visibility", line.mid(12) );
              continue;
            }

          if( line.startsWith( "Sky conditions: ") )
            {
              // Sky conditions: partly cloudy or mostly cloudy
              reportItems.insert( "sky", line.mid(16) );
              continue;
            }

          if( line.startsWith( "Weather: ") )
            {
              reportItems.insert( "weather", line.mid(9) );
              continue;
            }

          if( line.startsWith( "Temperature: ") )
            {
              // Temperature: 51 F (11 C)
              if( tempUnit == GeneralConfig::Fahrenheit )
                {
                  // Temperature in F
                  int idx = line.indexOf( " F (" );

                  if( idx > 0 )
                    {
                      reportItems.insert("temperature", line.mid(13, idx-13 ) + QChar(Qt::Key_degree) + "F");
                      continue;
                    }
                }
              else
                {
                  // Temperature in C
                  int idx2 = line.lastIndexOf( " C)" );
                  int idx1 = line.lastIndexOf( "(", idx2 -1 );

                  if( idx1 > 0 && idx1+1 < idx2 )
                    {
                      reportItems.insert("temperature", line.mid( idx1+1, idx2-idx1-1 ) + QChar(Qt::Key_degree) + "C");
                      continue;
                    }
                }

              reportItems.insert("temperature", line.mid( 13 ) );
              continue;
            }

          if( line.startsWith( "Dew Point: ") )
            {
              // Dew Point: 42 F (6 C)
              if( tempUnit == GeneralConfig::Fahrenheit )
                {
                  // Dew point in F
                  int idx = line.indexOf( " F (" );

                  if( idx > 0 )
                    {
                      reportItems.insert("dewPoint", line.mid(11, idx-11) + QChar(Qt::Key_degree) + "F");
                      continue;
                    }
                }
              else
                {
                  // Dew point in C
                  int idx2 = line.lastIndexOf( " C)" );
                  int idx1 = line.lastIndexOf( "(", idx2 - 1 );

                  if( idx1 > 0 && idx1+1 < idx2 )
                    {
                      reportItems.insert("dewPoint", line.mid( idx1+1, idx2-idx1-1 ) + QChar(Qt::Key_degree) + "C");
                      continue;
                    }
                }

              reportItems.insert("dewPoint", line.mid( 11 ) );
              continue;
            }

          if( line.startsWith( "Relative Humidity: ") )
            {
              // Relative Humidity: 71%
              reportItems.insert( "humidity", line.mid(19) );
              continue;
            }

          if( line.startsWith( "Pressure (altimeter): ") )
            {
              // Pressure (altimeter): 30.00 in. Hg (1016 hPa)
              if( pressureUnit == GeneralConfig::inHg )
                {
                  // QNH in inch Hg
                  int idx = line.lastIndexOf( " (" );

                  if( idx > 22 )
                    {
                      reportItems.insert("qnh", line.mid(22, idx - 22 ));
                      continue;
                    }
                }
              else
                {
                  // QHN in hPa
                  int idx2 = line.lastIndexOf( " hPa)" );
                  int idx1 = line.lastIndexOf( "(", idx2 - 1 );

                  if( idx1 > 0 && idx1+2 < idx2 )
                    {
                      reportItems.insert("qnh", line.mid( idx1 + 1, idx2 - idx1 + 3 ));
                      continue;
                    }
                }

              reportItems.insert("qnh", line.mid( 22 ));
              continue;
            }

          if( line.startsWith( "ob: ") )
            {
              // Extract the observation line from the report.
              // ob: EDDB 261550Z 31004KT 9999 FEW030 SCT056 11/06 Q1016 NOSIG
              reportItems.insert( "observation", line.mid(4) );
              continue;
            }
        }

      report.close();

      // qDebug() << "ReportItems:" << reportItems;

      m_metarReports.insert( station, reportItems );
      updateIcaoItem( station );
    }
  else if( file.contains("/weather/TAF/") )
    {
      /* TAF Example
      2013/09/26 12:29
      TAF EDDF 261100Z 2612/2718 32008KT 9999 SCT035
            BECMG 2617/2619 04005KT
      */

      // TAF report received. The whole report is stored in the hash as one string.
      if ( ! report.open( QIODevice::ReadOnly ) )
        {
          // could not open file ...
          qWarning() << "Cannot open file: " << report.fileName();
          return;
        }

      // TAF report received
      QTextStream stream( &report );
      QString line;
      QString tafReport;

      int lineNo = 0;

      while( !stream.atEnd() )
        {
          line = stream.readLine();
          lineNo++;

          if( line.trimmed().isEmpty() || lineNo == 1 )
            {
              // ignore comment and empty lines
              // ignore line 1, it contains the date and time
              continue;
            }

          if( tafReport.isEmpty() )
            {
              tafReport = line;
            }
          else
            {
              tafReport += "\n" + line;
            }
        }

      report.close();

      m_tafReports.insert( station, tafReport );

      // qDebug() << "TAFs:" << m_tafReports;
    }

  if( m_displayWidget->isVisible() )
    {
      if( m_list->topLevelItemCount() == 0 )
        {
          return;
        }

      IcaoItem *item = dynamic_cast<IcaoItem *>( m_list->currentItem() );

      if( item == 0 )
        {
          return;
        }

      if( item->getIcao() == station )
        {
          // The display widget is visible and must be updated too, if new
          // station data are available.
          slotDetails();
        }
    }
}
Example #9
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    QString nexePath;
    QStringList nexePaths;
    QString outPath;
    int logLevel = 4;

    for (int i = 1; i < argc; ++i) {
        QString arg = QString::fromLocal8Bit(argv[i]);
        qDebug() << "arg" << i << arg;
        if (arg.endsWith(".nexe")) {
            nexePaths.append(QFileInfo(arg).absoluteFilePath());
        } else if (arg.startsWith("-")) {
            if (arg.startsWith(QByteArray("-verbose"))) {
                qDebug() << "Argument found:" << arg;
                int index = arg.indexOf("=");
                bool ok = false;
                int number = arg.mid(index+1).toInt(&ok);
                if (!ok)
                    qDebug() << "Could not parse verbose level";
                else
                    logLevel = number;
            } else if (arg.startsWith("-")) {
                qDebug() << "Unknown argument" << arg << "\n";
                return 0;
            }
        } else {
            outPath = arg;
        }
    }

    bool inPlaceServe = outPath.isEmpty();

    if (inPlaceServe && nexePaths.count() > 1) {
        qDebug() << "Error: nacldeployqt can only serve one nexe using the built-in server";
        qDebug() << "Either specify one nexe or specify an out path";
    }

    if (argc < 2) {
        qDebug() << "Usage: nacldeployqt path/to/nexe [path/to/output] [options]";
        qDebug() << "";
        qDebug() << "Options:";
        qDebug() << "   -verbose=<0-3>  : 0 = no output, 1 = error/warning (default), 2 = normal, 3 = debug";
        qDebug() << "";
        qDebug() << "nacldeployqt creates server-ready Qt NaCl applications from a compiled nexe.";
        qDebug() << "";
        qDebug() << "This includes a native client manifest file (.nmf) in addition to html and javascript";
        qDebug() << "loader code. The output can be served as-is from a web server, or be used as a base for";
        qDebug() << "further modifications, for example by replacing the html but keeping the loader code.";
        qDebug() << "";

        return 0;
    }



    foreach (QString nexePath, nexePaths) {
        if (nexePath.endsWith("/"))
            nexePath.chop(1);

        if (QDir().exists(nexePath) == false) {
            qDebug() << "Error: Could not find nexe" << nexePath;
            return 0;
        }
    }

    if (outPath.endsWith("/"))
        outPath.chop(1);

    for (int i = 2; i < argc; ++i) {
     }

    QDir().mkpath(outPath);
    nexePath = QDir(nexePath).canonicalPath();
    outPath = QDir(outPath).canonicalPath();

    LogDebug() << "";
    LogDebug() << "Source file(s)     :" << nexePaths;
    LogDebug() << "Destination dir :" << outPath;
    LogDebug() << "";
    QStringList archs = findNexeArch(nexePaths);
    LogDebug() << "Arch(s)        :" << archs;
    QStringList buildTypes = getNexeBuildTypes(nexePaths);
    LogDebug() << "Build Type(s)  :" << buildTypes;
    LogDebug() << "";
    LogDebug() << "NaCl toolchain path :" << naclToolchainPath();
    QStringList naclLibPaths = naclLibraryPath(archs);
    LogDebug() << "NaCl lib path(s)       :" << naclLibPaths;
    QStringList qtLibPaths = findQtLibPath(nexePaths);
    LogDebug() << "Qt lib path(s)         :" << qtLibPaths;
    QStringList qtPluginPaths = findQtPluginPath(nexePaths);
    LogDebug() << "Qt plugin path(s)      :" << qtPluginPaths;


    QList<Deployables> deployables = getDeployables(nexePaths, naclLibPaths, qtLibPaths, qtPluginPaths);

    foreach (const Deployables &deployable, deployables) {
        LogDebug() << "";
        LogDebug() << "Deployables for nexe" << deployable.nexePath;
        LogDebug() << "Plugins           :" << deployable.pluginNames;
        LogDebug() << "Plugin paths      :" << deployable.pluginPaths;
        LogDebug() << "";
        LogDebug() << "Dependencies :" << deployable.dynamicLibraries;
        LogDebug() << "";
//        LogDebug() << "Dependencies Paths :" << deployable.dynamicLibraryPaths;
//        LogDebug() << "";
    }
Example #10
0
bool LsColXMLParser::parse( const QByteArray& xml, QHash<QString, qint64> *sizes, const QString& expectedPath)
{
    // Parse DAV response
    QXmlStreamReader reader(xml);
    reader.addExtraNamespaceDeclaration(QXmlStreamNamespaceDeclaration("d", "DAV:"));

    QStringList folders;
    QString currentHref;
    QMap<QString, QString> currentTmpProperties;
    QMap<QString, QString> currentHttp200Properties;
    bool currentPropsHaveHttp200 = false;
    bool insidePropstat = false;
    bool insideProp = false;
    bool insideMultiStatus = false;

    while (!reader.atEnd()) {
        QXmlStreamReader::TokenType type = reader.readNext();
        QString name = reader.name().toString();
        // Start elements with DAV:
        if (type == QXmlStreamReader::StartElement && reader.namespaceUri() == QLatin1String("DAV:")) {
            if (name == QLatin1String("href")) {
                // We don't use URL encoding in our request URL (which is the expected path) (QNAM will do it for us)
                // but the result will have URL encoding..
                QString hrefString = QString::fromUtf8(QByteArray::fromPercentEncoding(reader.readElementText().toUtf8()));
                if (!hrefString.startsWith(expectedPath)) {
                    qDebug() << "Invalid href" << hrefString << "expected starting with" << expectedPath;
                    return false;
                }
                currentHref = hrefString;
            } else if (name == QLatin1String("response")) {
            } else if (name == QLatin1String("propstat")) {
                insidePropstat = true;
            } else if (name == QLatin1String("status") && insidePropstat) {
                QString httpStatus = reader.readElementText();
                if (httpStatus.startsWith("HTTP/1.1 200")) {
                    currentPropsHaveHttp200 = true;
                } else {
                    currentPropsHaveHttp200 = false;
                }
            } else if (name == QLatin1String("prop")) {
                insideProp = true;
                continue;
            } else if (name == QLatin1String("multistatus")) {
                insideMultiStatus = true;
                continue;
            }
        }

        if (type == QXmlStreamReader::StartElement && insidePropstat && insideProp) {
            // All those elements are properties
            QString propertyContent = readContentsAsString(reader);
            if (name == QLatin1String("resourcetype") && propertyContent.contains("collection")) {
                folders.append(currentHref);
            } else if (name == QLatin1String("quota-used-bytes")) {
                bool ok = false;
                auto s = propertyContent.toLongLong(&ok);
                if (ok && sizes) {
                    sizes->insert(currentHref, s);
                }
            }
            currentTmpProperties.insert(reader.name().toString(), propertyContent);
        }

        // End elements with DAV:
        if (type == QXmlStreamReader::EndElement) {
            if (reader.namespaceUri() == QLatin1String("DAV:")) {
                if (reader.name() == "response") {
                    if (currentHref.endsWith('/')) {
                        currentHref.chop(1);
                    }
                    emit directoryListingIterated(currentHref, currentHttp200Properties);
                    currentHref.clear();
                    currentHttp200Properties.clear();
                } else if (reader.name() == "propstat") {
                    insidePropstat = false;
                    if (currentPropsHaveHttp200) {
                        currentHttp200Properties = QMap<QString,QString>(currentTmpProperties);
                    }
                    currentTmpProperties.clear();
                    currentPropsHaveHttp200 = false;
                } else if (reader.name() == "prop") {
                    insideProp = false;
                }
            }
        }
    }

    if (reader.hasError()) {
        // XML Parser error? Whatever had been emitted before will come as directoryListingIterated
        qDebug() << "ERROR" << reader.errorString() << xml;
        return false;
    } else if (!insideMultiStatus) {
        qDebug() << "ERROR no WebDAV response?" << xml;
        return false;
    } else {
        emit directoryListingSubfolders(folders);
        emit finishedWithoutError();
    }
    return true;

}
Example #11
0
void MpegRecorder::SetOption(const QString &opt, int value)
{
    if (opt == "width")
        width = value;
    else if (opt == "height")
        height = value;
    else if (opt == "mpeg2bitrate")
        bitrate = value;
    else if (opt == "mpeg2maxbitrate")
        maxbitrate = value;
    else if (opt == "samplerate")
        audsamplerate = value;
    else if (opt == "mpeg2audbitratel1")
    {
        int index = find_index(audRateL1, value);
        if (index >= 0)
            audbitratel1 = index + 1;
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "Audiorate(L1): " +
                QString("%1 is invalid").arg(value));
        }
    }
    else if (opt == "mpeg2audbitratel2")
    {
        int index = find_index(audRateL2, value);
        if (index >= 0)
            audbitratel2 = index + 1;
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "Audiorate(L2): " +
                    QString("%1 is invalid").arg(value));
        }
    }
    else if (opt == "mpeg2audbitratel3")
    {
        int index = find_index(audRateL3, value);
        if (index >= 0)
            audbitratel3 = index + 1;
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC + "Audiorate(L2): " +
                    QString("%1 is invalid").arg(value));
        }
    }
    else if (opt == "mpeg2audvolume")
        audvolume = value;
    else if (opt.endsWith("_mpeg4avgbitrate"))
    {
        if (opt.startsWith("low"))
            low_mpeg4avgbitrate = value;
        else if (opt.startsWith("medium"))
            medium_mpeg4avgbitrate = value;
        else if (opt.startsWith("high"))
            high_mpeg4avgbitrate = value;
        else
            V4LRecorder::SetOption(opt, value);
    }
    else if (opt.endsWith("_mpeg4peakbitrate"))
    {
        if (opt.startsWith("low"))
            low_mpeg4peakbitrate = value;
        else if (opt.startsWith("medium"))
            medium_mpeg4peakbitrate = value;
        else if (opt.startsWith("high"))
            high_mpeg4peakbitrate = value;
        else
            V4LRecorder::SetOption(opt, value);
    }
    else
        V4LRecorder::SetOption(opt, value);
}
Example #12
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);
}
Example #13
0
// static function to create a filename based on the metadata information
// if createDir is true then the directory structure will be created
QString Ripper::filenameFromMetadata(Metadata *track, bool createDir)
{
    QString musicdir = gCoreContext->GetSetting("MusicLocation");
    musicdir = QDir::cleanPath(musicdir);
    if (!musicdir.endsWith("/"))
        musicdir += "/";

    QDir directoryQD(musicdir);
    QString filename;
    QString fntempl = gCoreContext->GetSetting("FilenameTemplate");
    bool no_ws = gCoreContext->GetNumSetting("NoWhitespace", 0);

    QRegExp rx_ws("\\s{1,}");
    QRegExp rx("(GENRE|ARTIST|ALBUM|TRACK|TITLE|YEAR)");
    int i = 0;
    int old_i = 0;
    while (i >= 0)
    {
        i = rx.indexIn(fntempl, i);
        if (i >= 0)
        {
            if (i > 0)
                filename += fixFileToken_sl(fntempl.mid(old_i,i-old_i));
            i += rx.matchedLength();
            old_i = i;

            if ((rx.capturedTexts()[1] == "GENRE") && (!track->Genre().isEmpty()))
                filename += fixFileToken(track->Genre());

            if ((rx.capturedTexts()[1] == "ARTIST")
                    && (!track->FormatArtist().isEmpty()))
                filename += fixFileToken(track->FormatArtist());

            if ((rx.capturedTexts()[1] == "ALBUM") && (!track->Album().isEmpty()))
                filename += fixFileToken(track->Album());

            if ((rx.capturedTexts()[1] == "TRACK") && (track->Track() >= 0))
            {
                QString tempstr = QString::number(track->Track(), 10);
                if (track->Track() < 10)
                    tempstr.prepend('0');
                filename += fixFileToken(tempstr);
            }

            if ((rx.capturedTexts()[1] == "TITLE")
                    && (!track->FormatTitle().isEmpty()))
                filename += fixFileToken(track->FormatTitle());

            if ((rx.capturedTexts()[1] == "YEAR") && (track->Year() >= 0))
                filename += fixFileToken(QString::number(track->Year(), 10));
        }
    }

    if (no_ws)
        filename.replace(rx_ws, "_");

    if (filename == musicdir || filename.length() > FILENAME_MAX)
    {
        QString tempstr = QString::number(track->Track(), 10);
        tempstr += " - " + track->FormatTitle();
        filename = musicdir + fixFileToken(tempstr);
        LOG(VB_GENERAL, LOG_ERR, "Invalid file storage definition.");
    }

    QStringList directoryList = filename.split("/");
    for (int i = 0; i < (directoryList.size() - 1); i++)
    {
        musicdir += "/" + directoryList[i];
        if (createDir)
        {
            umask(002);
            directoryQD.mkdir(musicdir);
            directoryQD.cd(musicdir);
        }
    }

    filename = QDir::cleanPath(musicdir) + "/" + directoryList.last();

    return filename;
}
Example #14
0
AbstractCommand::ReturnCodes Push::run()
{
    if (! checkInRepository())
        return NotInRepo;
    CommandLineParser *args = CommandLineParser::instance();

    QProcess git;
    QStringList arguments;
    arguments << "config" << "-l";
    GitRunner runner(git, arguments);
    AbstractCommand::ReturnCodes rc = runner.start(GitRunner::WaitForStandardOutput);
    if (rc != Ok) {
        Logger::error() << "Vng failed; could not read configuration\n";
        return rc;
    }

    QRegExp re("remote\\.(.*)url=(.*)\n");
    QHash<QString, QString> repoNames;
    char buf[1024];
    while (true) { //read relevant lines into repoNames hash
        qint64 length = Vng::readLine(&git, buf, sizeof(buf));
        if (length < 0)
            break;
        QString line(buf);
        if (re.exactMatch(line)) {
            QString context = re.cap(1);
            if (context.endsWith("."))
                context = context.left(context.length()-1);
            repoNames.insert(context, re.cap(2));
        }
    }

    QString repo;
    if (args->arguments().count() > 1)
        repo = args->arguments()[1];

    QString url = repo;
    if (repo.isEmpty())
        repo = "default"; // the name we store the default as.
    if (repoNames.contains(repo))
        url = repoNames[repo];
    if (url.isEmpty()) { // print help
        Logger::standardOut() << "Vng failed: Missing argument [REPOSITORY]\n";
        Logger::standardOut().flush();
        args->usage(name(), argumentDescription());
        Logger::standardOut() << endl << commandDescription();
        return Ok;
    }

    Logger::warn() << "Pushing to `" << url << "'\n";
    Logger::warn().flush(); // make sure its printed before git asks for an ssh pwd.
    if (dryRun())
        return Ok;

    // TODO when not using --all ask the remote for all the refs it has and detect which ones we still have to push
    // TODO use interview to ask which refs to push instead of all below
    arguments.clear();
    arguments << "push" << url;
    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitForStandardOutput);
    if (rc != Ok) {
        Logger::error() << "Git push failed\n";
        return rc;
    }

/* TODO for some reason qprocess doesn't give me any output if the child process already finished :(
    while (true) {
        qint64 length = Vng::readLine(&git, buf, sizeof(buf));
        if (length < 0)
            break;
        Logger::info() << QString(buf);
    }
*/
    git.waitForFinished(-1);

    if ( !(args->contains("no-set-default")
            || (m_config.contains("no-set-default") && ! args->contains("set-default")))
            && repo == url) { // lets set as default
        arguments.clear();
        arguments << "config" << "--add" << "remote.default.url" << repo;
        runner.setArguments(arguments);
        rc = runner.start(GitRunner::WaitUntilFinished);
        if (rc != Ok) {
            Logger::warn() << "Could not store the default value for future reuse\n";
            return rc;
        }
    }

    return Ok;
}
Example #15
0
bool QLibraryPrivate::load_sys()
{
    QString attempt;
#if !defined(QT_NO_DYNAMIC_LIBRARY)
    QFileSystemEntry fsEntry(fileName);

    QString path = fsEntry.path();
    QString name = fsEntry.fileName();
    if (path == QLatin1String(".") && !fileName.startsWith(path))
        path.clear();
    else
        path += QLatin1Char('/');

    QStringList suffixes;
    QStringList prefixes;
    if (pluginState != IsAPlugin) {
        prefixes = prefixes_sys();
        suffixes = suffixes_sys(fullVersion);
    }
    int dlFlags = 0;
#if defined(QT_HPUX_LD)
    dlFlags = DYNAMIC_PATH | BIND_NONFATAL;
    if (loadHints & QLibrary::ResolveAllSymbolsHint) {
        dlFlags |= BIND_IMMEDIATE;
    } else {
        dlFlags |= BIND_DEFERRED;
    }
#else
    if (loadHints & QLibrary::ResolveAllSymbolsHint) {
        dlFlags |= RTLD_NOW;
    } else {
        dlFlags |= RTLD_LAZY;
    }
    if (loadHints & QLibrary::ExportExternalSymbolsHint) {
        dlFlags |= RTLD_GLOBAL;
    }
#if !defined(Q_OS_CYGWIN)
    else {
#if defined(Q_OS_MAC)
        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
#endif
        dlFlags |= RTLD_LOCAL;
    }
#endif

    // Provide access to RTLD_NODELETE flag on Unix
    // From GNU documentation on RTLD_NODELETE:
    // Do not unload the library during dlclose(). Consequently, the
    // library's specific static variables are not reinitialized if the
    // library is reloaded with dlopen() at a later time.
#ifdef RTLD_NODELETE
    if (loadHints & QLibrary::PreventUnloadHint) {
        dlFlags |= RTLD_NODELETE;
    }
#endif

#if defined(Q_OS_AIX)	// Not sure if any other platform actually support this thing.
    if (loadHints & QLibrary::LoadArchiveMemberHint) {
        dlFlags |= RTLD_MEMBER;
    }
#endif
#endif // QT_HPUX_LD

    // If the filename is an absolute path then we want to try that first as it is most likely
    // what the callee wants. If we have been given a non-absolute path then lets try the
    // native library name first to avoid unnecessary calls to dlopen().
    if (fsEntry.isAbsolute()) {
        suffixes.prepend(QString());
        prefixes.prepend(QString());
    } else {
        suffixes.append(QString());
        prefixes.append(QString());
    }

    bool retry = true;
    for(int prefix = 0; retry && !pHnd && prefix < prefixes.size(); prefix++) {
        for(int suffix = 0; retry && !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;
            if (loadHints & QLibrary::LoadArchiveMemberHint) {
                attempt = name;
                int lparen = attempt.indexOf(QLatin1Char('('));
                if (lparen == -1)
                    lparen = attempt.count();
                attempt = path + prefixes.at(prefix) + attempt.insert(lparen, suffixes.at(suffix));
            } else {
                attempt = path + prefixes.at(prefix) + name + suffixes.at(suffix);
            }
#if defined(QT_HPUX_LD)
            pHnd = (void*)shl_load(QFile::encodeName(attempt), dlFlags, 0);
#else
            pHnd = dlopen(QFile::encodeName(attempt), dlFlags);
#endif

            if (!pHnd && fileName.startsWith(QLatin1Char('/')) && QFile::exists(attempt)) {
                // We only want to continue if dlopen failed due to that the shared library did not exist.
                // However, we are only able to apply this check for absolute filenames (since they are
                // not influenced by the content of LD_LIBRARY_PATH, /etc/ld.so.cache, DT_RPATH etc...)
                // This is all because dlerror is flawed and cannot tell us the reason why it failed.
                retry = false;
            }
        }
    }

#ifdef Q_OS_MAC
    if (!pHnd) {
        QByteArray utf8Bundle = fileName.toUtf8();
        QCFType<CFURLRef> bundleUrl = CFURLCreateFromFileSystemRepresentation(NULL, reinterpret_cast<const UInt8*>(utf8Bundle.data()), utf8Bundle.length(), true);
        QCFType<CFBundleRef> bundle = CFBundleCreate(NULL, bundleUrl);
        if(bundle) {
            QCFType<CFURLRef> url = CFBundleCopyExecutableURL(bundle);
            char executableFile[FILENAME_MAX];
            CFURLGetFileSystemRepresentation(url, true, reinterpret_cast<UInt8*>(executableFile), FILENAME_MAX);
            attempt = QString::fromUtf8(executableFile);
            pHnd = dlopen(QFile::encodeName(attempt), dlFlags);
        }
    }
#endif
#endif // QT_NO_DYNAMIC_LIBRARY
    if (!pHnd) {
        errorString = QLibrary::tr("Cannot load library %1: %2").arg(fileName).arg(qdlerror());
    }
    if (pHnd) {
        qualifiedFileName = attempt;
        errorString.clear();
    }
    return (pHnd != 0);
}
Example #16
0
KEduVocDocument::FileType KEduVocDocument::detectFileType( const QString &fileName )
{
    QIODevice * f = KFilterDev::deviceForFile( fileName );
    if ( !f->open( QIODevice::ReadOnly ) ) {
        kDebug(1100) << "Warning, could not open QIODevice for file: " << fileName;
        delete f;
        return Csv;
    }

    QTextStream ts( f );
    QString line1;
    QString line2;

    line1 = ts.readLine();
    if ( !ts.atEnd() ) {
        line2 = ts.readLine();
    }

    /*
     * Vokabeln.de files:
    The header seems to be something like this:

    "Name
    Lang1 - Lang2",123,234,456
    0

    or something longer:

    "Name
    Lang1 - Lang2
    [..]
    Blah, blah, blah...",123,234,456
    0
    */

    QString tmp;

    if ( line1.startsWith(QChar::fromLatin1('"'))) {
        ts.seek(0);
        tmp = ts.readLine();
        // There shouldn't be headers longer than 10 lines.
        for ( int x=0; x < 10; x++) {
            if (tmp.contains( "\"," )) {
                tmp = ts.readLine();
                if (tmp.endsWith('0')) {
                    f->close();
                    delete f;
                    return Vokabeln;
                }
            }
            tmp = ts.readLine();
        }
    }
    f->close();
    delete f;


    if ( line1.startsWith(QString::fromLatin1("<?xml")) ) {
        if ( line2.indexOf( "pauker", 0 ) >  0 ) {
            return Pauker;
        }
        if ( line2.indexOf( "xdxf", 0 ) >  0 ) {
            return Xdxf;
        } else {
            return Kvtml;
        }
    }

    if ( line1 == WQL_IDENT ) {
        return Wql;
    }

    return Csv;
}
Example #17
0
QString Serveur::parseCommande(QString comm,bool serveur)
{
	if(comm.startsWith("/"))
	{
		comm.remove(0,1);
		QString pref=comm.split(" ").first();
		QStringList args=comm.split(" ");
		args.removeFirst();
		QString destChan=tab->tabText(tab->currentIndex());
		QString msg=args.join(" ");

		if(pref=="me")
			return "PRIVMSG "+destChan+" ACTION " + msg + "";
		else if(pref=="join")
		{
			join(msg);
			return " ";
		}
		else if(pref=="quit")
		{
			if(msg == "")
                return "QUIT "+msgQuit;
			else
				return "QUIT "+msg;
		}
		else if(pref=="part")
		{
			tab->removeTab(tab->currentIndex());

			if(msg == "")
			{
				if(msg.startsWith("#"))
					destChan=msg.split(" ").first();

				if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
				else
					return "PART "+destChan+" "+msgQuit;
			}
			else
				return "PART "+destChan+" "+msg;

			conversations.remove(destChan);
		}
		else if(pref=="kick")
		{
			QStringList tableau=msg.split(" ");
			QString c1,c2,c3;
			if(tableau.count() > 0) c1=" "+tableau.first();
			else c1="";
			if(tableau.count() > 1) c2=" "+tableau.at(1);
			else c2="";
			if(tableau.count() > 2) c3=" "+tableau.at(2);
			else c3="";

			if(c1.startsWith("#"))
				return "KICK"+c1+c2+c3;
			else
				return "KICK "+destChan+c1+c2;
		}
		else if(pref=="update")
		{
			updateUsers=true;
			return "WHO "+destChan;
		}
		else if(pref=="ns")
		{
			return "NICKSERV "+msg;
		}
		else if(pref=="nick")
		{
			emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
			return "NICK "+msg;
		}
		else
			return pref+" "+msg;
	}
	else if(!serveur)
	{
		QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

		if(comm.startsWith(":"))
			comm.insert(0,":");

		return "PRIVMSG "+destChan+" "+comm;
	}
	else
	{
		return "";
	}
}
Example #18
0
void LoginDialog::on_okButton_clicked()
{
	lgUserName = ui.UsernameEdit->text();

	if (!lgUserName.isEmpty())
	{

			lgUserPassword = ui.PasswordEdit->text();

			if (!lgUserPassword.isEmpty())
			{
                QString host = ui.HostEdit->text().replace(QString("index.php"), QString(""));
                QHttp::ConnectionMode mode;

                if (host.indexOf("https://") != -1){
                    mode = QHttp::ConnectionModeHttps;
                    host = host.replace(QString("https://"),QString(""));
                } else {
                    mode = QHttp::ConnectionModeHttp;
                    host = host.replace(QString("http://"),QString(""));
                }

                if (!host.endsWith("/")){
                    host += "/";
                }

                if (!host.isEmpty())
				{
                        PMSettings *pmsettings = new PMSettings();

                        if (ui.RememberLoginsChk->isChecked()){
                            pmsettings->setAttribute("username",lgUserName);
                            pmsettings->setAttribute("password",lgUserPassword);
                            pmsettings->setAttribute("remember","true");
                        } else {
                            pmsettings->setAttribute("username","");
                            pmsettings->setAttribute("password","");
                            pmsettings->setAttribute("remember","false");
                        }

                        pmsettings->setAttribute("host", (mode == QHttp::ConnectionModeHttp ? "http://" : "https://")+host);

                        if (ui.AutoLogincheckBox->isChecked())
							pmsettings->setAttribute("autologin","true");
						else
							pmsettings->setAttribute("autologin","false");


						pmsettings->sync();



						delete pmsettings;

                        LhcWebServiceClient *lhwsc = LhcWebServiceClient::instance();
                        lhwsc->setFetchURL(host,mode);

                        QStringList filter;
                        filter.append("username="******"password="******"/xml/checklogin/",(QObject*) this, LoginDialog::LoginCheckedCallback);

				}else {
					QMessageBox::warning(this, tr("Warning"),
								 tr("The host field is empty!"),
								 tr("&OK"), QString::null , 0, 0, 1);
					ui.HostEdit->setFocus();
				}

			}else {
                QMessageBox::warning(this, tr("Warning"),
								 tr("The password field is empty!"),
								 tr("&OK"), QString::null , 0, 0, 1);
				ui.PasswordEdit->setFocus();
			}


    } else {
		QMessageBox::warning(this, tr("Warning"),
                             tr("The username field is empty!"),
                             tr("&OK"), QString::null , 0, 0, 1);
        ui.UsernameEdit->setFocus();
	}
}
Example #19
0
bool getFileDetails(ArchiveItem *a)
{
    QString tempDir = gCoreContext->GetSetting("MythArchiveTempDir", "");

    if (!tempDir.endsWith("/"))
        tempDir += "/";

    QString inFile;
    int lenMethod = 0;
    if (a->type == "Recording")
    {
        inFile = a->filename;
        lenMethod = 2;
    }
    else
    {
        inFile = a->filename;
    }

    inFile.replace("\'", "\\\'");
    inFile.replace("\"", "\\\"");
    inFile.replace("`", "\\`");

    QString outFile = tempDir + "work/file.xml";

    // call mytharchivehelper to get files stream info etc.
    QString command = QString("mytharchivehelper --getfileinfo --infile \"%1\" "
                              "--outfile \"%2\" --method %3")
            .arg(inFile).arg(outFile).arg(lenMethod);
    command += logPropagateArgs;
    if (!logPropagateQuiet())
        command += " --quiet";

    uint flags = kMSDontBlockInputDevs | kMSDontDisableDrawing;
    if (myth_system(command, flags) != GENERIC_EXIT_OK)
        return false;

    QDomDocument doc("mydocument");
    QFile file(outFile);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    if (!doc.setContent( &file ))
    {
        file.close();
        return false;
    }
    file.close();

    // get file type and duration
    QDomElement docElem = doc.documentElement();
    QDomNodeList nodeList = doc.elementsByTagName("file");
    if (nodeList.count() < 1)
        return false;
    QDomNode n = nodeList.item(0);
    QDomElement e = n.toElement();
    a->fileCodec = e.attribute("type");
    a->duration = e.attribute("duration").toInt();
    a->cutDuration = e.attribute("cutduration").toInt();

    // get frame size and video codec
    nodeList = doc.elementsByTagName("video");
    if (nodeList.count() < 1)
        return false;
    n = nodeList.item(0);
    e = n.toElement();
    a->videoCodec = e.attribute("codec");
    a->videoWidth = e.attribute("width").toInt();
    a->videoHeight = e.attribute("height").toInt();

    return true;
}
Example #20
0
bool processPackage( QDomDocument* list, QString path )
{
	QString map = findMapInDir( path );

	if( map.isEmpty() )
	{
		printf( "no map file in dir (required for parsing)\n" );
		printf( "package path: " + path.toUtf8() + "\n" );
		return false;
	}

	QDomElement mapElement = findPackageElement( *list, "map", map );

	if( path.endsWith( "MoNav.ini" ) )
	{
		if( !mapElement.isNull() )
		{
			QString pHash = computePackageHash( path );
			if( mapElement.attribute( "hash" ) != pHash )
			{
				updateMap( list, &mapElement );
				mapElement.setAttribute( "hash", pHash );
			}
			else
				printf( "map already in list\n" );
			return false;
		}

		addMap( list, map, path );
	}

	else if( path.endsWith( ".mmm" ) )
	{
		if( mapElement.isNull() )
			addMap( list, map, path );

		QString package = path.right( path.size() - path.lastIndexOf( '/' ) - 1 );
		QStringList packageAttributes = package.split( "_" );
		QString type = packageAttributes[0];
		QString name = packageAttributes[1].replace( ".mmm", "" );

		QDomElement packageElement = findPackageElement( *list, "module", name, map );
		if( !packageElement.isNull() )
		{
			QString pHash = computePackageHash( path );
			if( packageElement.attribute( "hash" ) != pHash )
			{
				updateModule( list, &packageElement );
				packageElement.setAttribute( "hash", pHash );
			}
			else
				printf( "package already in list\n" );
			return false;
		}

		addModule( list, &mapElement, name, type, path );
	}

	else
	{
		printf( "unrecognized package format\n" );
		return false;
	}

	return true;
}
Example #21
0
QString MainWindow::formatChange(int index,QString c){
    c="\n"+c+"\n";
    QVector<QString> lines = c.split("\n").toVector();
    QString formatted = "";
    QString tmp;
    QString tmp2;
    QString tmp3;
    QString afterName = "";
    for(int i=1;i<lines.size()-1;i++){
        tmp = lines.at(i);
        tmp2 = lines.at(i+1);
        tmp3 = lines.at(i-1);
        if(tmp.startsWith("---") && tmp3.startsWith("index")){
            if(tmp.startsWith("--- a/") && tmp2.startsWith("+++ b/")){
                bool a = false;
                if(tmp.indexOf("\"")>0){
                    a = true;
                    tmp.replace("\"","");
                }
                tmp = tmp.mid(6);
                tmp = (a?"\"":"") + path + "/" + htmlEncode(tmp) + (a?"\"":"");
                tmp="<hr><p style='line-height:16px;color:#921AFF'>修改文件 : "+tmp+"</p>\n";
                formatted.append(tmp);
            }else if(tmp == "--- /dev/null"){
                bool a = false;
                if(tmp2.indexOf("\"")>0){
                    a = true;
                    tmp2.replace("\"","");
                }
                tmp2=tmp2.mid(6);
                tmp2 = (a?"\"":"") + path + "/" + htmlEncode(tmp2) + (a?"\"":"");
                tmp="<hr><p style='line-height:16px;color:#921AFF'>新建文件 : "+tmp2+"</p>\n";
                formatted.append(tmp);
            }else if(tmp2 == "+++ /dev/null"){
                bool a = false;
                if(tmp.indexOf("\"")>0){
                    a = true;
                    tmp.replace("\"","");
                }
                tmp = tmp.mid(6);
                tmp = (a?"\"":"") + path + "/" + htmlEncode(tmp) + (a?"\"":"");
                tmp="<hr><p style='line-height:16px;color:#921AFF'>删除文件 : "+tmp+"</p>\n";
                formatted.append(tmp);
            }else{
                tmp="<hr><p style='line-height:16px;color:#FF8000'>"+htmlEncode(tmp)+"</p>\n";
                formatted.append(tmp);
                tmp2="<hr><p style='line-height:16px;color:#2828FF'>"+htmlEncode(tmp2)+"</p>\n";
                formatted.append(tmp);
            }

            tmp="<p style='line-height:16px'><font style='color:#2828FF'>"+mList.at(index).at(0)+"</font> 对比于 <font style='color:#FF8000'>"+mList.at(index+1).at(0)+"</font> 的差异</p>\n";
            formatted.append(tmp);
            if(afterName!=""){
                formatted.append(afterName);
            }
            afterName="";
        }else if(tmp.startsWith("new file mode ")){
            tmp = tmp.mid(14);
            afterName="<p style='line-height:16px'>新建的文件权限 : <font style='color:#00EC00'>"+tmp+"</font></p>\n";
        }else if(tmp.startsWith("old mode ")){
            tmp = tmp.mid(9);
            tmp2 = tmp2.mid(9);
            afterName="<p style='line-height:16px'>新权限 : <font style='color:#00EC00'>"+tmp2+"</font>  旧权限 :  <font style='color:#FF9797'>"+tmp+"</font></p>\n";
        }else if(tmp.startsWith("deleted file mode ")){
            tmp = tmp.mid(18);
            afterName="<p style='line-height:16px'>删除的文件权限 : <font style='color:#FF9797'>"+tmp+"</font></p>\n";
        }else if(tmp.startsWith("+++")){
            continue;
        }else if(tmp.startsWith("+")){
            tmp="<p style='line-height:16px;color:#00BB00'>"+htmlEncode(tmp)+"</p>\n";
            formatted.append(tmp);
        }else if(tmp.startsWith("-")){
            tmp="<p style='line-height:16px;color:#FF2D2D'>"+htmlEncode(tmp)+"</p>\n";
            formatted.append(tmp);
        }else if(tmp.startsWith("@@")){

            if(tmp.endsWith("@@")){
                tmp="<p style='line-height:16px;color:#4A4AFF'>"+htmlEncode(tmp)+"</p>";
                formatted.append(tmp+"\n");
            }else{
                tmp2 = tmp.left(tmp.lastIndexOf("@@")+2);
                tmp2="<p style='line-height:16px;color:#4A4AFF'>"+htmlEncode(tmp2)+"</p>";
                formatted.append(tmp2+"\n");
                tmp2 = tmp.mid(tmp.lastIndexOf("@@")+2);
                tmp2="<p style='line-height:16px;color:#4A4AFF'>"+htmlEncode(tmp2)+"</p>";
                formatted.append(tmp2+"\n");
            }

        }else if(tmp.startsWith(" ")){
            tmp="<p style='line-height:16px;color:#000000'>"+htmlEncode(tmp)+"</p>";
            formatted.append(tmp+"\n");
        }
    }
    return "<body style='font-family:Droid Sans Mono;'>"+formatted+"</body>";
}
Example #22
0
int main( int argc, char *argv[] )
{
	QString serverPath = "";
	QString packagePath = "";
	OPERATION listOperation = DEFAULT;

	int c;
	while ( ( c = getopt( argc, argv, "c:r:a:p:d:u" ) ) != -1 )
	{
		switch(c)
		{
			case 'c':
				listOperation = CREATE_LIST;
				serverPath = optarg;
				break;
			case 'd':
				listOperation = DELETE_LIST;
				break;
			case 'a':
				listOperation = ADD_PACKAGE;
				packagePath = optarg;
				break;
			case 'r':
				listOperation = DELETE_PACKAGE;
				packagePath = optarg;
				break;
			case 'p':
				listOperation = AUTO_CREATE;
				serverPath = optarg;
				break;
			case 'u':
				listOperation = AUTO_UPDATE;
				serverPath = optarg;
				break;
			default:
				printf( "operation not recognized\n" );
				return 0;
		}
	}

	if( argc < 2 || ( argc != 3 && listOperation != DELETE_LIST ) )
	{
		printf( "usage:\n" );
		printf( "-p server_url : create list automatically by recursively parsing mapmanager directory\n" );
		printf( "-u server_url : update list automatically by recursively parsing mapmanager directory\n" );
		printf( "-c server_url : create list\n" );
		printf( "-d server_url : delete list\n" );
		printf( "-a package_path_and_name : add package to list\n" );
		printf( "-r package_path_and_name : delete package from list\n" );

		return 0;
	}

	if( !serverPath.endsWith( "/" ) )
		serverPath.append( "/" );

	if( packagePath.startsWith( "." ) )
		packagePath.remove( 0, 1 );

	if( packagePath.startsWith( "/" ) )
		packagePath.remove( 0, 1 );

	QString packageName = packagePath;
	packageName.remove( 0, packageName.lastIndexOf( '/' ) + 1 );
	packageName.truncate( packageName.lastIndexOf( '.' ) );

	QDomDocument list;
	QFile listFile( "packageList.xml" );

	if( listOperation == CREATE_LIST )
		return createList( &list, &listFile, serverPath );

	if( listOperation == AUTO_CREATE )
	{
		if( !createList( &list, &listFile, serverPath ) )
			return 0;

		QStringList localPackages = parseForPackages( QDir() );

		foreach( QString packagePath, localPackages )
			processPackage( &list, packagePath );
	}

	else
	{
		if ( !listFile.exists() )
		{
			printf( "create list file first using -c or -p\n" );
			return 0;
		}

		if( listOperation == DELETE_LIST )
		{
			if ( !listFile.remove() )
			{
				printf( "error deleting list file\n" );
				return 0;
			}

			printf( "deleted list\n" );
			return 1;
		}


		if ( !listFile.open( QIODevice::ReadOnly ) )
		{
			printf( "failed to open list file\n" );
			return 0;
		}

		if ( !list.setContent( &listFile ) )
		{
			printf("error parsing list file\n");
			listFile.close();
			return 0;
		}
		listFile.close();
	}

	if( listOperation == DELETE_PACKAGE )
	{
		if ( !deletePackage( &list, packagePath ) )
			return 0;
	}

	if( listOperation == ADD_PACKAGE )
	{
		if ( !processPackage( &list, packagePath ) )
			return 0;
	}

	if( listOperation == AUTO_UPDATE )
	{
		QStringList localPackages = parseForPackages( QDir() );

		foreach( QString packagePath, localPackages )
			processPackage( &list, packagePath );
	}

	if (!listFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) return 1;
	listFile.write(list.toString().toUtf8());
	listFile.close();

	return 1;
}
Example #23
0
int main(int argc, char **argv)
{
    QtSingleApplication app("quimup", argc, argv);
    bool b_multiple_instances = false;
    QString locale = "xx";
    QString message;
    int filecount = 0;
    // handle command line args
    for (int a = 1; a < argc; ++a)
    {
        QString msg = QString::fromUtf8(argv[a]);

        if ( msg == "-p" || msg == "-play")
        {
            message = "-play:" + message;
        }
        else
        if ( msg == "-i" || msg == "-instance")
        {
            b_multiple_instances = true;
        }
        else
        if ( msg == "-l"  || msg == "-locale" )
        {
            if (a < (argc-1) )
            {
                locale = argv[a+1];
                // possible stray '-l'
                if ( locale.startsWith("-") || locale.startsWith("file") )
                    locale = "xx";
                else
                    a++;
            }
        }
        else
        if (msg == "-h" || msg == "-help")
        {
            printf ("----\nQuimup version 1.4.0\n"); // VERSION //
            printf ("© 2008-2014 Johan Spee <*****@*****.**>\n");
            printf ("This program is licensed by the GPL and distributed in the hope that it will be useful, but without any warranty.\n");
            printf ("----\ncommand line parameters:\n");
            printf (" -h(elp)           show this information and exit\n");
            printf (" -i(nstance)       force a new instance of Quimup\n");
            printf (" -l(ocale) xx      use locale 'xx' (fr, po, en_GB, etc) or 'none' to force internal locale\n");
            printf (" -l(ocale) file    use locale from full path to quimup_xx.qm file\n");
            printf (" -p(lay) %%U        play files in %%U (or %%F) in new playlist\n");
            printf ("  %%U               append files in %%U (or %%F) to the playlist\n----\n");
            return 0;
        }
        else // if URL
        if ( msg.startsWith("file://"))
        {
            // we have a string in URL format, so convert special chars:
            msg = ( QUrl::fromEncoded ((const char*)msg.toUtf8()) ).toString();
            message.append(msg);
            filecount++;
        }
        else //  if plain path
        if (msg.startsWith("/") )
        {
            msg = "file://" + msg; // used as separator
            message.append(msg);
            filecount++;
        }
    }

    // send the args (and find out if a previous instance exists)
    if (!b_multiple_instances && app.sendMessage(message))
    {
        printf ("Quimup : already running (use '-i' to force a new instance)\n");
        return 0;
    }

    printf ("Quimup : starting new instance\n");

    //// Localization start >
    QTranslator trnsltr;
    //QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
    bool b_locale_loaded = false;
    bool b_locale_default = true;
    if (locale == "xx") // no -l parameter was passed
        locale = QLocale::system().name();
    else
        b_locale_default = false;

    if (locale != "none")
    {
        if (!b_locale_default)
        {
            printf ("Locale : '%s': ", (const char*)locale.toUtf8());
            if ( locale.startsWith("/") && locale.endsWith(".qm")) // full path to a file
            {
                if ( trnsltr.load(locale) )
                {
                   printf ("OK\n");
                   b_locale_loaded = true;
                }
                else
                   printf ("failed! (using none)\n");
            }
            else // first try installation path, next default path
            {
                QDir dir(QApplication::applicationDirPath());

                if ( trnsltr.load(QString("quimup_") + locale, dir.absolutePath()) )
                {
                    printf ("OK (from %s)\n", (const char*)dir.absolutePath().toUtf8());
                    b_locale_loaded = true;
                }
                else
                {
                    if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) )
                    {
                        printf ("OK (from default location)\n");
                        b_locale_loaded = true;
                    }
                    else
                         printf ("failed! (using none)\n");
                }
            }

        }
        else // locale file in defaut system location
        {
            printf ("Locale : ");
            if ( trnsltr.load(QString("quimup_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) )
            {
                printf ("using default (%s)\n", (const char*)locale.toUtf8());
                b_locale_loaded = true;
            }
            else
                printf ("using none\n");
        }
    }
    else
       printf ("Locale : using none (requested)\n");

    if (b_locale_loaded)
        app.installTranslator(&trnsltr);

    //// < end Localization

    qm_core *core = new qm_core();

    // handle files
    if (filecount > 0)
    {
        core->player->browser_window->plist_view->on_open_with_request(message);
    }

    QObject::connect(&app, SIGNAL(messageReceived(const QString&)), core, SLOT(on_message_from_2nd_instance(const QString&)));
    QObject::connect(&app, SIGNAL(aboutToQuit()), core, SLOT(on_system_quit()));

    return app.exec();
}
void MultipleParameterWindowWidget::saveAllPanelsToFile() {

	//do not write anything if reduced file writing mode is active.
// 	if(Core::getInstance()->isUsingReducedFileWriting()) {
// 		return;
// 	}

	Properties &props = Core::getInstance()->getProperties();

	QString fileChooserDirectory = ".";
	if(props.hasProperty("CurrentFileChooserPath")) {
		fileChooserDirectory = props.getProperty("CurrentFileChooserPath");
	}

	QString fileName = QFileDialog::getSaveFileName(this,
       tr("Save settings"), fileChooserDirectory);

	if(fileName == "") {
		return;
	}
	fileChooserDirectory = fileName.mid(0, fileName.lastIndexOf("/"));
	props.setProperty("CurrentFileChooserPath", fileChooserDirectory);

	if(!fileName.endsWith(".val")) {
		fileName.append(".val");
	}

	QFile file(fileName);

	int dirIndex = fileName.lastIndexOf("/");
	if(dirIndex > 0) {
		Core::getInstance()->enforceDirectoryPath(file.fileName().mid(0, dirIndex));
	}

	if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
		Core::log(QString("Could not open file ").append(fileName).append(" to write Values."));
		file.close();
		return;
	}

	QTextStream output(&file);
	output << "#NERD Values" << "\n";
	output << "#Saved at: " << QDate::currentDate().toString("dd.MM.yyyy")
					<< "  " << QTime::currentTime().toString("hh:mm:ss") << "\n";

	for(int i = 0; i < mTabWidget->count(); ++i) {
		ParameterVisualizationWindow *visu = dynamic_cast<ParameterVisualizationWindow*>(
				mTabWidget->widget(i));

		if(visu == 0) {
			continue;
		}

		QString newFileName = fileName;
		newFileName = newFileName.mid(0, fileName.size() - 4)
						.append("_").append(QString::number(i)).append(".val");

		output << "#include " << newFileName << endl;

		visu->saveCurrentParameters(newFileName, true);
	}
	file.close();
}
Example #25
0
void VtkVisPipeline::loadFromFile(QString filename)
{
#ifndef NDEBUG
	QTime myTimer;
	myTimer.start();
	std::cout << "VTK Read: " << filename.toStdString() <<
	std::endl << std::flush;
#endif

	if (filename.size() > 0)
	{
		vtkXMLDataReader* reader;
		if (filename.endsWith("vti"))
			reader = vtkXMLImageDataReader::New();
		else if (filename.endsWith("vtr"))
			reader = vtkXMLRectilinearGridReader::New();
		else if (filename.endsWith("vts"))
			reader = vtkXMLStructuredGridReader::New();
		else if (filename.endsWith("vtp"))
			reader = vtkXMLPolyDataReader::New();
		else if (filename.endsWith("vtu"))
			reader = vtkXMLUnstructuredGridReader::New();
		else if (filename.endsWith("vtk"))
		{
			vtkGenericDataObjectReader* oldStyleReader =
			        vtkGenericDataObjectReader::New();
			oldStyleReader->SetFileName(filename.toStdString().c_str());
			oldStyleReader->ReadAllFieldsOn();
			oldStyleReader->ReadAllScalarsOn();
			oldStyleReader->Update();
			vtkDataSet* dataSet = vtkDataSet::SafeDownCast(oldStyleReader->GetOutput());
			if (dataSet)
			{
				this->listArrays(dataSet);
				addPipelineItem(oldStyleReader);
			}
			else
				std::cout << "Error loading vtk file: not a valid vtkDataSet." <<
				std::endl;

			return;
		}
		else
			return;

		reader->SetFileName(filename.toStdString().c_str());
		// TODO: insert ReadAllScalarsOn()-equivalent for xml-file-reader here, otherwise arrays are not available in GUI!
		reader->Update();
		//std::cout << "#cell scalars: " << reader->GetNumberOfCellArrays() << std::endl;
		//std::cout << "#point scalars: " << reader->GetNumberOfPointArrays() << std::endl;

		vtkDataSet* dataSet = reader->GetOutputAsDataSet();
		if (dataSet)
		{
			this->listArrays(dataSet);
			addPipelineItem(reader);
		}
		else
			std::cout << "Error loading vtk file: not a valid vtkDataSet." << std::endl;

		//reader->Delete();
	}

#ifndef NDEBUG
	std::cout << myTimer.elapsed() << " ms" << std::endl;
#endif
}
Example #26
0
bool AirportsData::import(QProgressDialog &progress, MainObject *mainObject){


    QHash<QString, QString> airports;
    QString msg;
    QTime tm;
    int ms;

    progress.setValue(0);
    progress.setWindowTitle("Scanning Airport Directories");
    progress.setRange(0, 50000);


    int c = 0;
    int found = 0;
    int air_added = 0;
    ms = tm.restart();
	
    // Removing cache file, if exists()
    if (QFile::exists(mainObject->data_file("airports.txt"))) {
            outLog("*** FGx airportsdata reload: cache file exists!");
            QFile::remove(mainObject->data_file("airports.txt"));
            outLog("*** FGx airportsdata reload: REMOVED AIRPORTS CACHE FILE");
    }

    //= Cache File
    QFile cacheFile( mainObject->data_file("airports.txt") );
    if(!cacheFile.open(QIODevice::WriteOnly | QIODevice::Text)){
            //qDebug() << "TODO Open error cachce file=";
            return true;
    }
    QTextStream out(&cacheFile);


    //================================================
    //* Lets Loop the directories
    //* Get out aiports path from setings and get the the subdir also
    QDirIterator loopAirportsFiles( mainObject->X->airports_path(), QDirIterator::Subdirectories );
    QString xFileName;

    msg = "FGx airportsdata reload: Scanning XML files in "+mainObject->X->airports_path();
    outLog(msg);
    progress.setWindowTitle(msg);
    progress.setRange(0, 50000);

    // Check the fgfs additional argument list,
    // and/or any additional scenery path inputs
    // *** take care NOT to duplicate ***
    QStringList fgfs_args = mainObject->X->get_fgfs_args();
    int i, ind;
    QDir d;
    QString path;
#ifdef Q_OS_WIN
    QChar psep(';');
#else
    QChar psep(':');
#endif
	
    // AIIIIII, found the doubler !, said yves very very loud - well done said pete ;-)
    for (i = 0; i < fgfs_args.size(); i++) {
        msg = fgfs_args.at(i);
        ind = msg.indexOf(QChar('"'));
        if (ind == 0)
            msg = msg.mid(1,msg.length()-2);
        if (msg.indexOf("--fg-scenery=") == 0) {
            // got a scenery folder to scan
            msg = msg.mid(13);
            ind = msg.indexOf(QChar('"'));
            if (ind == 0)
                msg = msg.mid(1,msg.length()-2);
            QStringList path_list = msg.split(psep);
            int pathnumber = 0;
            for( QStringList::ConstIterator entry = path_list.begin(); entry != path_list.end(); entry++) {
                path = *entry;
				pathnumber = pathnumber + 1;
                if (d.exists(path)) {
                    // we have a PATH to check, but we are ONLY checking 'Airports'
                    if ( !(path.indexOf(QChar('/')) == (path.size()-1)) &&
                         !(path.indexOf(QChar('\\')) == (path.size()-1)) )
                        path.append("/");
                    path.append("Airports"); // XML is only in here
                    if (!d.exists(path))
                        continue;
                    QDirIterator loopFiles( path, QDirIterator::Subdirectories );
                    while (loopFiles.hasNext()) {

                        //= Get file handle if there is one
                        xFileName = loopFiles.next();

                        //= Check if file entry is a *.threshold.xml - cos this is what we want
                        if(xFileName.endsWith(".threshold.xml") ){

                            //= Split out "CODE.threshold.xml" with a "."
                            QFileInfo fileInfoThreshold(xFileName);
                            QString airport_code = fileInfoThreshold.fileName().split(".").at(0);

                            //* Update progress
                            if(c % 100 == 0){
                                progress.setValue(c);
                                progress.setLabelText(xFileName);
                                progress.repaint();
                            }

                            QString airport_name("");
                            if(airports.contains(airport_code)){
                                airport_name = airports.value(airport_code);
                            }

                            QStringList cols; // missing in middle is description ??
                            cols << airport_code << airport_name << fileInfoThreshold.absoluteDir().absolutePath() << QString::number(pathnumber);

                            out << cols.join("\t").append("\n");
                            air_added++;

                            found++;
                        }

                        if(progress.wasCanceled()){
                            progress.hide();
                            return true;
                        }
                        c++;
                    }
                }
            }
        }
    }


    cacheFile.close();

    msg.sprintf("*** FGx airportsdata reload: Walked %d files, found %d threshold.xml, appended %d to cache",
                c, found, air_added);
    outLog(msg+", in "+getElapTimeStg(tm.elapsed()));
    progress.hide();
    return false;
}
bool PiwigoTalker::addPhoto(int   albumId,
                            const QString& mediaPath,
                            bool  rescale,
                            int   maxWidth,
                            int   maxHeight,
                            int   quality)
{
    m_job         = 0;
    m_state       = GE_CHECKPHOTOEXIST;
    m_talker_buffer.resize(0);

    m_path    = mediaPath; // By default, m_path contains the original file
    m_tmpPath = QStringLiteral(""); // By default, no temporary file (except with rescaling)
    m_albumId = albumId;

    m_md5sum  = computeMD5Sum(mediaPath);

    qCDebug(KIPIPLUGINS_LOG) << mediaPath << " " << m_md5sum.toHex();

    if (mediaPath.endsWith(QStringLiteral(".mp4"))  || mediaPath.endsWith(QStringLiteral(".MP4")) ||
        mediaPath.endsWith(QStringLiteral(".ogg"))  || mediaPath.endsWith(QStringLiteral(".OGG")) ||
        mediaPath.endsWith(QStringLiteral(".webm")) || mediaPath.endsWith(QStringLiteral(".WEBM")))
    {
        // Video management
        // Nothing to do
    }
    else
    {
        // Image management
        QImage image;

        if (m_iface)
        {
            QPointer<RawProcessor> rawdec = m_iface->createRawProcessor();

            // check if its a RAW file.
            if (rawdec && rawdec->isRawFile(QUrl::fromLocalFile(mediaPath)))
            {
                rawdec->loadRawPreview(QUrl::fromLocalFile(mediaPath), image);
            }
        }

        if (image.isNull())
        {
            image.load(mediaPath);
        }

        if (image.isNull())
        {
            // Invalid image
            return false;
        }

        if (!rescale)
        {
            qCDebug(KIPIPLUGINS_LOG) << "Upload the original version: " << m_path;
        }
        else
        {
            // Rescale the image
            if (image.width() > maxWidth || image.height() > maxHeight)
            {
                image = image.scaled(maxWidth, maxHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            }

            m_path = m_tmpPath = makeTemporaryDir("kipi-piwigo").filePath(QUrl::fromLocalFile(mediaPath).fileName());
            image.save(m_path, "JPEG", quality);

            qCDebug(KIPIPLUGINS_LOG) << "Upload a resized version: " << m_path ;

            // Restore all metadata with EXIF
            // in the resized version
            if (m_iface)
            {
                QPointer<MetadataProcessor> meta = m_iface->createMetadataProcessor();
            
                if (meta && meta->load(QUrl::fromLocalFile(mediaPath)))
                {
                    meta->setImageProgramId(QStringLiteral("Kipi-plugins"), kipipluginsVersion());
                    meta->setImageDimensions(image.size());
                    meta->save(QUrl::fromLocalFile(m_path));
                }
                else
                {
                    qCDebug(KIPIPLUGINS_LOG) << "Image " << mediaPath << " has no exif data";
                }
            }
        }
    }

    // Metadata management

    // Complete name and comment for summary sending
    QFileInfo fi(mediaPath);
    m_title   = fi.completeBaseName();
    m_comment = QStringLiteral("");
    m_author  = QStringLiteral("");
    m_date    = fi.created();

    // Look in the Kipi host database
    KPImageInfo info(QUrl::fromLocalFile(mediaPath));

    if (info.hasTitle() && !info.title().isEmpty())
        m_title = info.title();

    if (info.hasDescription() && !info.description().isEmpty())
        m_comment = info.description();

    if (info.hasCreators() && !info.creators().isEmpty())
        m_author = info.creators().join(QStringLiteral(" / "));

    if (info.hasDate())
        m_date = info.date();

    qCDebug(KIPIPLUGINS_LOG) << "Title: " << m_title;
    qCDebug(KIPIPLUGINS_LOG) << "Comment: " << m_comment;
    qCDebug(KIPIPLUGINS_LOG) << "Author: " << m_author;
    qCDebug(KIPIPLUGINS_LOG) << "Date: " << m_date;

    QStringList qsl;
    qsl.append(QLatin1String("method=pwg.images.exist"));
    qsl.append(QLatin1String("md5sum_list=") + QString::fromLatin1(m_md5sum.toHex()));
    QString dataParameters = qsl.join(QLatin1String("&"));
    QByteArray buffer;
    buffer.append(dataParameters.toUtf8());

    m_job = KIO::http_post(m_url, buffer, KIO::HideProgressInfo);
    m_job->addMetaData(QStringLiteral("content-type"),
                       QStringLiteral("Content-Type: application/x-www-form-urlencoded"));
    m_job->addMetaData(QStringLiteral("customHTTPHeader"),
                       QStringLiteral("Authorization: ") + s_authToken);

    emit signalProgressInfo( i18n("Check if %1 already exists", QUrl(mediaPath).fileName()) );

    connect(m_job, SIGNAL(data(KIO::Job*,QByteArray)),
            this, SLOT(slotTalkerData(KIO::Job*,QByteArray)));

    connect(m_job, SIGNAL(result(KJob*)),
            this, SLOT(slotResult(KJob*)));

    emit signalBusy(true);

    return true;
}
Example #28
0
void TilesetDock::exportTileset()
{
    Tileset *tileset = currentTileset();
    if (!tileset)
        return;

    if (tileset->isExternal())
        return;

    int mapTilesetIndex = mMapDocument->map()->tilesets().indexOf(tileset->sharedPointer());
    if (mapTilesetIndex == -1)
        return;

    // To export a tileset we clone it, since the tileset could now be used by
    // other maps. This ensures undo can take the map back to using an embedded
    // tileset, without affecting those other maps.
    SharedTileset externalTileset = tileset->clone();

    FormatHelper<TilesetFormat> helper(FileFormat::ReadWrite);

    Preferences *prefs = Preferences::instance();

    QString suggestedFileName = prefs->lastPath(Preferences::ExternalTileset);
    suggestedFileName += QLatin1Char('/');
    suggestedFileName += externalTileset->name();

    const QLatin1String extension(".tsx");
    if (!suggestedFileName.endsWith(extension))
        suggestedFileName.append(extension);

    // todo: remember last used filter
    QString selectedFilter = TsxTilesetFormat().nameFilter();
    const QString fileName =
            QFileDialog::getSaveFileName(this, tr("Export Tileset"),
                                         suggestedFileName,
                                         helper.filter(), &selectedFilter);

    if (fileName.isEmpty())
        return;

    prefs->setLastPath(Preferences::ExternalTileset,
                       QFileInfo(fileName).path());

    TilesetFormat *format = helper.formatByNameFilter(selectedFilter);
    if (!format)
        return;     // can't happen

    if (!format->write(*externalTileset, fileName)) {
        QString error = format->errorString();
        QMessageBox::critical(window(),
                              tr("Export Tileset"),
                              tr("Error saving tileset: %1").arg(error));
        return;
    }

    externalTileset->setFileName(fileName);
    externalTileset->setFormat(format);

    QUndoCommand *command = new ReplaceTileset(mMapDocument,
                                               mapTilesetIndex,
                                               externalTileset);
    mMapDocument->undoStack()->push(command);

    // Make sure the external tileset is selected
    int externalTilesetIndex = mTilesets.indexOf(externalTileset);
    if (externalTilesetIndex != -1)
        mTabBar->setCurrentIndex(externalTilesetIndex);
}
void Utils::unCommentSelection(QPlainTextEdit *edit, const CommentDefinition &definition)
{
    if (!definition.hasSingleLineStyle() && !definition.hasMultiLineStyle())
        return;

    QTextCursor cursor = edit->textCursor();
    QTextDocument *doc = cursor.document();
    cursor.beginEditBlock();

    int pos = cursor.position();
    int anchor = cursor.anchor();
    int start = qMin(anchor, pos);
    int end = qMax(anchor, pos);
    bool anchorIsStart = (anchor == start);

    QTextBlock startBlock = doc->findBlock(start);
    QTextBlock endBlock = doc->findBlock(end);

    if (end > start && endBlock.position() == end) {
        --end;
        endBlock = endBlock.previous();
    }

    bool doMultiLineStyleUncomment = false;
    bool doMultiLineStyleComment = false;
    bool doSingleLineStyleUncomment = false;

    bool hasSelection = cursor.hasSelection();

    if (hasSelection && definition.hasMultiLineStyle()) {

        QString startText = startBlock.text();
        int startPos = start - startBlock.position();
        const int multiLineStartLength = definition.multiLineStart().length();
        bool hasLeadingCharacters = !startText.left(startPos).trimmed().isEmpty();

        if (startPos >= multiLineStartLength
            && isComment(startText,
                         startPos - multiLineStartLength,
                         definition,
                         &CommentDefinition::multiLineStart)) {
            startPos -= multiLineStartLength;
            start -= multiLineStartLength;
        }

        bool hasSelStart = (startPos <= startText.length() - multiLineStartLength
                            && isComment(startText,
                                         startPos,
                                         definition,
                                         &CommentDefinition::multiLineStart));

        QString endText = endBlock.text();
        int endPos = end - endBlock.position();
        const int multiLineEndLength = definition.multiLineEnd().length();
        bool hasTrailingCharacters =
                !endText.left(endPos).remove(definition.singleLine()).trimmed().isEmpty()
                && !endText.mid(endPos).trimmed().isEmpty();

        if (endPos <= endText.length() - multiLineEndLength
            && isComment(endText, endPos, definition, &CommentDefinition::multiLineEnd)) {
            endPos += multiLineEndLength;
            end += multiLineEndLength;
        }

        bool hasSelEnd = (endPos >= multiLineEndLength
                          && isComment(endText,
                                       endPos - multiLineEndLength,
                                       definition,
                                       &CommentDefinition::multiLineEnd));

        doMultiLineStyleUncomment = hasSelStart && hasSelEnd;
        doMultiLineStyleComment = !doMultiLineStyleUncomment
                                  && (hasLeadingCharacters
                                      || hasTrailingCharacters
                                      || !definition.hasSingleLineStyle());
    } else if (!hasSelection && !definition.hasSingleLineStyle()) {

        QString text = startBlock.text().trimmed();
        doMultiLineStyleUncomment = text.startsWith(definition.multiLineStart())
                                    && text.endsWith(definition.multiLineEnd());
        doMultiLineStyleComment = !doMultiLineStyleUncomment && !text.isEmpty();

        start = startBlock.position();
        end = endBlock.position() + endBlock.length() - 1;

        if (doMultiLineStyleUncomment) {
            int offset = 0;
            text = startBlock.text();
            const int length = text.length();
            while (offset < length && text.at(offset).isSpace())
                ++offset;
            start += offset;
        }
    }

    if (doMultiLineStyleUncomment) {
        cursor.setPosition(end);
        cursor.movePosition(QTextCursor::PreviousCharacter,
                            QTextCursor::KeepAnchor,
                            definition.multiLineEnd().length());
        cursor.removeSelectedText();
        cursor.setPosition(start);
        cursor.movePosition(QTextCursor::NextCharacter,
                            QTextCursor::KeepAnchor,
                            definition.multiLineStart().length());
        cursor.removeSelectedText();
    } else if (doMultiLineStyleComment) {
        cursor.setPosition(end);
        cursor.insertText(definition.multiLineEnd());
        cursor.setPosition(start);
        cursor.insertText(definition.multiLineStart());
    } else {
        endBlock = endBlock.next();
        doSingleLineStyleUncomment = true;
        for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
            QString text = block.text().trimmed();
            if (!text.isEmpty() && !text.startsWith(definition.singleLine())) {
                doSingleLineStyleUncomment = false;
                break;
            }
        }

        const int singleLineLength = definition.singleLine().length();
        for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
            if (doSingleLineStyleUncomment) {
                QString text = block.text();
                int i = 0;
                while (i <= text.size() - singleLineLength) {
                    if (isComment(text, i, definition, &CommentDefinition::singleLine)) {
                        cursor.setPosition(block.position() + i);
                        cursor.movePosition(QTextCursor::NextCharacter,
                                            QTextCursor::KeepAnchor,
                                            singleLineLength);
                        cursor.removeSelectedText();
                        break;
                    }
                    if (!text.at(i).isSpace())
                        break;
                    ++i;
                }
            } else {
                QString text = block.text();
                foreach (QChar c, text) {
                    if (!c.isSpace()) {
                        if (definition.isAfterWhiteSpaces())
                            cursor.setPosition(block.position() + text.indexOf(c));
                        else
                            cursor.setPosition(block.position());
                        cursor.insertText(definition.singleLine());
                        break;
                    }
                }
            }
        }
    }

    // adjust selection when commenting out
    if (hasSelection && !doMultiLineStyleUncomment && !doSingleLineStyleUncomment) {
        cursor = edit->textCursor();
        if (!doMultiLineStyleComment)
            start = startBlock.position(); // move the comment into the selection
        int lastSelPos = anchorIsStart ? cursor.position() : cursor.anchor();
        if (anchorIsStart) {
            cursor.setPosition(start);
            cursor.setPosition(lastSelPos, QTextCursor::KeepAnchor);
        } else {
            cursor.setPosition(lastSelPos);
            cursor.setPosition(start, QTextCursor::KeepAnchor);
        }
        edit->setTextCursor(cursor);
    }

    cursor.endEditBlock();
}
Example #30
0
QString KTnef::msTNEFToVPart( const QByteArray &tnef )
{
  bool bOk = false;

  KTNEFParser parser;
  QByteArray b( tnef );
  QBuffer buf( &b );
  MemoryCalendar::Ptr cal( new MemoryCalendar( KDateTime::UTC ) );
  KABC::Addressee addressee;
  ICalFormat calFormat;
  Event::Ptr event( new Event() );

  if ( parser.openDevice( &buf ) ) {
    KTNEFMessage *tnefMsg = parser.message();
    //QMap<int,KTNEFProperty*> props = parser.message()->properties();

    // Everything depends from property PR_MESSAGE_CLASS
    // (this is added by KTNEFParser):
    QString msgClass = tnefMsg->findProp( 0x001A, QString(), true ).toUpper();
    if ( !msgClass.isEmpty() ) {
      // Match the old class names that might be used by Outlook for
      // compatibility with Microsoft Mail for Windows for Workgroups 3.1.
      bool bCompatClassAppointment = false;
      bool bCompatMethodRequest = false;
      bool bCompatMethodCancled = false;
      bool bCompatMethodAccepted = false;
      bool bCompatMethodAcceptedCond = false;
      bool bCompatMethodDeclined = false;
      if ( msgClass.startsWith( QLatin1String( "IPM.MICROSOFT SCHEDULE." ) ) ) {
        bCompatClassAppointment = true;
        if ( msgClass.endsWith( QLatin1String( ".MTGREQ" ) ) ) {
          bCompatMethodRequest = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGCNCL" ) ) ) {
          bCompatMethodCancled = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPP" ) ) ) {
          bCompatMethodAccepted = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPA" ) ) ) {
          bCompatMethodAcceptedCond = true;
        }
        if ( msgClass.endsWith( QLatin1String( ".MTGRESPN" ) ) ) {
          bCompatMethodDeclined = true;
        }
      }
      bool bCompatClassNote = ( msgClass == "IPM.MICROSOFT MAIL.NOTE" );

      if ( bCompatClassAppointment || "IPM.APPOINTMENT" == msgClass ) {
        // Compose a vCal
        bool bIsReply = false;
        QString prodID = "-//Microsoft Corporation//Outlook ";
        prodID += tnefMsg->findNamedProp( "0x8554", "9.0" );
        prodID += "MIMEDIR/EN\n";
        prodID += "VERSION:2.0\n";
        calFormat.setApplication( "Outlook", prodID );

        iTIPMethod method;
        if ( bCompatMethodRequest ) {
          method = iTIPRequest;
        } else if ( bCompatMethodCancled ) {
          method = iTIPCancel;
        } else if ( bCompatMethodAccepted || bCompatMethodAcceptedCond ||
                 bCompatMethodDeclined ) {
          method = iTIPReply;
          bIsReply = true;
        } else {
          // pending(khz): verify whether "0x0c17" is the right tag ???
          //
          // at the moment we think there are REQUESTS and UPDATES
          //
          // but WHAT ABOUT REPLIES ???
          //
          //

          if ( tnefMsg->findProp(0x0c17) == "1" ) {
            bIsReply = true;
          }
          method = iTIPRequest;
        }

        /// ###  FIXME Need to get this attribute written
        ScheduleMessage schedMsg( event, method, ScheduleMessage::Unknown );

        QString sSenderSearchKeyEmail( tnefMsg->findProp( 0x0C1D ) );

        if ( !sSenderSearchKeyEmail.isEmpty() ) {
          int colon = sSenderSearchKeyEmail.indexOf( ':' );
          // May be e.g. "SMTP:[email protected]"
          if ( sSenderSearchKeyEmail.indexOf( ':' ) == -1 ) {
            sSenderSearchKeyEmail.remove( 0, colon+1 );
          }
        }

        QString s( tnefMsg->findProp( 0x8189 ) );
        const QStringList attendees = s.split( ';' );
        if ( attendees.count() ) {
          for ( QStringList::const_iterator it = attendees.begin();
               it != attendees.end(); ++it ) {
            // Skip all entries that have no '@' since these are
            // no mail addresses
            if ( (*it).indexOf( '@' ) == -1 ) {
              s = (*it).trimmed();

              Attendee::Ptr attendee( new Attendee( s, s, true ) );
              if ( bIsReply ) {
                if ( bCompatMethodAccepted ) {
                  attendee->setStatus( Attendee::Accepted );
                }
                if ( bCompatMethodDeclined ) {
                  attendee->setStatus( Attendee::Declined );
                }
                if ( bCompatMethodAcceptedCond ) {
                  attendee->setStatus( Attendee::Tentative );
                }
              } else {
                attendee->setStatus( Attendee::NeedsAction );
                attendee->setRole( Attendee::ReqParticipant );
              }
              event->addAttendee( attendee );
            }
          }
        } else {
          // Oops, no attendees?
          // This must be old style, let us use the PR_SENDER_SEARCH_KEY.
          s = sSenderSearchKeyEmail;
          if ( !s.isEmpty() ) {
            Attendee::Ptr attendee( new Attendee( QString(), QString(), true ) );
            if ( bIsReply ) {
              if ( bCompatMethodAccepted ) {
                attendee->setStatus( Attendee::Accepted );
              }
              if ( bCompatMethodAcceptedCond ) {
                attendee->setStatus( Attendee::Declined );
              }
              if ( bCompatMethodDeclined ) {
                attendee->setStatus( Attendee::Tentative );
              }
            } else {
              attendee->setStatus( Attendee::NeedsAction );
              attendee->setRole( Attendee::ReqParticipant );
            }
            event->addAttendee( attendee );
          }
        }
        s = tnefMsg->findProp( 0x3ff8 ); // look for organizer property
        if ( s.isEmpty() && !bIsReply ) {
          s = sSenderSearchKeyEmail;
        }
        // TODO: Use the common name?
        if ( !s.isEmpty() ) {
          event->setOrganizer( s );
        }

        s = tnefMsg->findProp( 0x819b ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        event->setDtStart( KDateTime::fromString( s ) ); // ## Format??

        s = tnefMsg->findProp( 0x819c ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        event->setDtEnd( KDateTime::fromString( s ) );

        s = tnefMsg->findProp( 0x810d );
        event->setLocation( s );
        // is it OK to set this to OPAQUE always ??
        //vPart += "TRANSP:OPAQUE\n"; ###FIXME, portme!
        //vPart += "SEQUENCE:0\n";

        // is "0x0023" OK  -  or should we look for "0x0003" ??
        s = tnefMsg->findProp( 0x0023 );
        event->setUid( s );

        // PENDING(khz): is this value in local timezone? Must it be
        // adjusted? Most likely this is a bug in the server or in
        // Outlook - we ignore it for now.
        s = tnefMsg->findProp( 0x8202 ).remove( QChar( '-' ) ).remove( QChar( ':' ) );
        // ### kcal always uses currentDateTime()
        // event->setDtStamp( QDateTime::fromString( s ) );

        s = tnefMsg->findNamedProp( "Keywords" );
        event->setCategories( s );

        s = tnefMsg->findProp( 0x1000 );
        event->setDescription( s );

        s = tnefMsg->findProp( 0x0070 );
        event->setSummary( s );

        s = tnefMsg->findProp( 0x0026 );
        event->setPriority( s.toInt() );
        // is reminder flag set ?
        if ( !tnefMsg->findProp( 0x8503 ).isEmpty() ) {
          Alarm::Ptr alarm( new Alarm( event.data() ) ); // TODO: fix when KCalCore::Alarm is fixed
          KDateTime highNoonTime =
            pureISOToLocalQDateTime( tnefMsg->findProp( 0x8502 ).
                                     remove( QChar( '-' ) ).remove( QChar( ':' ) ) );
          KDateTime wakeMeUpTime =
            pureISOToLocalQDateTime( tnefMsg->findProp( 0x8560, "" ).
                                     remove( QChar( '-' ) ).remove( QChar( ':' ) ) );
          alarm->setTime( wakeMeUpTime );

          if ( highNoonTime.isValid() && wakeMeUpTime.isValid() ) {
            alarm->setStartOffset( Duration( highNoonTime, wakeMeUpTime ) );
          } else {
            // default: wake them up 15 minutes before the appointment
            alarm->setStartOffset( Duration( 15 * 60 ) );
          }
          alarm->setDisplayAlarm( i18n( "Reminder" ) );

          // Sorry: the different action types are not known (yet)
          //        so we always set 'DISPLAY' (no sounds, no images...)
          event->addAlarm( alarm );
        }
        //ensure we have a uid for this event
        if ( event->uid().isEmpty() ) {
          event->setUid( CalFormat::createUniqueId() );
        }
        cal->addEvent( event );
        bOk = true;
        // we finished composing a vCal
      } else if ( bCompatClassNote || "IPM.CONTACT" == msgClass ) {
        addressee.setUid( stringProp( tnefMsg, attMSGID ) );
        addressee.setFormattedName( stringProp( tnefMsg, MAPI_TAG_PR_DISPLAY_NAME ) );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL1EMAILADDRESS ), true );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL2EMAILADDRESS ), false );
        addressee.insertEmail( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_EMAIL3EMAILADDRESS ), false );
        addressee.insertCustom( "KADDRESSBOOK", "X-IMAddress",
                                sNamedProp( tnefMsg, MAPI_TAG_CONTACT_IMADDRESS ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-SpousesName",
                                stringProp( tnefMsg, MAPI_TAG_PR_SPOUSE_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-ManagersName",
                                stringProp( tnefMsg, MAPI_TAG_PR_MANAGER_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-AssistantsName",
                                stringProp( tnefMsg, MAPI_TAG_PR_ASSISTANT ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Department",
                                stringProp( tnefMsg, MAPI_TAG_PR_DEPARTMENT_NAME ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Office",
                                stringProp( tnefMsg, MAPI_TAG_PR_OFFICE_LOCATION ) );
        addressee.insertCustom( "KADDRESSBOOK", "X-Profession",
                                stringProp( tnefMsg, MAPI_TAG_PR_PROFESSION ) );

        QString s = tnefMsg->findProp( MAPI_TAG_PR_WEDDING_ANNIVERSARY ).
                    remove( QChar( '-' ) ).remove( QChar( ':' ) );
        if ( !s.isEmpty() ) {
          addressee.insertCustom( "KADDRESSBOOK", "X-Anniversary", s );
        }

        addressee.setUrl( KUrl( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_WEBPAGE ) ) );

        // collect parts of Name entry
        addressee.setFamilyName( stringProp( tnefMsg, MAPI_TAG_PR_SURNAME ) );
        addressee.setGivenName( stringProp( tnefMsg, MAPI_TAG_PR_GIVEN_NAME ) );
        addressee.setAdditionalName( stringProp( tnefMsg, MAPI_TAG_PR_MIDDLE_NAME ) );
        addressee.setPrefix( stringProp( tnefMsg, MAPI_TAG_PR_DISPLAY_NAME_PREFIX ) );
        addressee.setSuffix( stringProp( tnefMsg, MAPI_TAG_PR_GENERATION ) );

        addressee.setNickName( stringProp( tnefMsg, MAPI_TAG_PR_NICKNAME ) );
        addressee.setRole( stringProp( tnefMsg, MAPI_TAG_PR_TITLE ) );
        addressee.setOrganization( stringProp( tnefMsg, MAPI_TAG_PR_COMPANY_NAME ) );
        /*
        the MAPI property ID of this (multiline) )field is unknown:
        vPart += stringProp(tnefMsg, "\n","NOTE", ... , "" );
        */

        KABC::Address adr;
        adr.setPostOfficeBox( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_PO_BOX ) );
        adr.setStreet( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_STREET ) );
        adr.setLocality( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_CITY ) );
        adr.setRegion( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_STATE_OR_PROVINCE ) );
        adr.setPostalCode( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_POSTAL_CODE ) );
        adr.setCountry( stringProp( tnefMsg, MAPI_TAG_PR_HOME_ADDRESS_COUNTRY ) );
        adr.setType( KABC::Address::Home );
        addressee.insertAddress( adr );

        adr.setPostOfficeBox( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSPOBOX ) );
        adr.setStreet( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSSTREET ) );
        adr.setLocality( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSCITY ) );
        adr.setRegion( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSSTATE ) );
        adr.setPostalCode( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSPOSTALCODE ) );
        adr.setCountry( sNamedProp( tnefMsg, MAPI_TAG_CONTACT_BUSINESSADDRESSCOUNTRY ) );
        adr.setType( KABC::Address::Work );
        addressee.insertAddress( adr );

        adr.setPostOfficeBox( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_PO_BOX ) );
        adr.setStreet( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_STREET ) );
        adr.setLocality( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_CITY ) );
        adr.setRegion( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_STATE_OR_PROVINCE ) );
        adr.setPostalCode( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_POSTAL_CODE ) );
        adr.setCountry( stringProp( tnefMsg, MAPI_TAG_PR_OTHER_ADDRESS_COUNTRY ) );
        adr.setType( KABC::Address::Dom );
        addressee.insertAddress( adr );

        // problem: the 'other' address was stored by KOrganizer in
        //          a line looking like the following one:
        // vPart += "\nADR;TYPE=dom;TYPE=intl;TYPE=parcel;TYPE=postal;TYPE=work;"
        //          "TYPE=home:other_pobox;;other_str1\nother_str2;other_loc;other_region;"
        //          "other_pocode;other_country"

        QString nr;
        nr = stringProp( tnefMsg, MAPI_TAG_PR_HOME_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Home ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_BUSINESS_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Work ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_MOBILE_TELEPHONE_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Cell ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_HOME_FAX_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Fax | KABC::PhoneNumber::Home ) );
        nr = stringProp( tnefMsg, MAPI_TAG_PR_BUSINESS_FAX_NUMBER );
        addressee.insertPhoneNumber(
          KABC::PhoneNumber( nr, KABC::PhoneNumber::Fax | KABC::PhoneNumber::Work ) );

        s = tnefMsg->findProp( MAPI_TAG_PR_BIRTHDAY ).
            remove( QChar( '-' ) ).remove( QChar( ':' ) );
        if ( !s.isEmpty() ) {
          addressee.setBirthday( QDateTime::fromString( s ) );
        }

        bOk = ( !addressee.isEmpty() );
      } else if ( "IPM.NOTE" == msgClass ) {

      } // else if ... and so on ...
    }
  }

  // Compose return string
  // KDAB_TODO: Interesting, without the explicit QString the toString call is
  //            reported to be ambigious with toString( const Incidence::Ptr & ).
  const QString iCal = calFormat.toString( cal, QString() );
  if ( !iCal.isEmpty() ) {
    // This was an iCal
    return iCal;
  }

  // Not an iCal - try a vCard
  KABC::VCardConverter converter;
  return QString::fromUtf8( converter.createVCard( addressee ) );
}