void Docbook2XhtmlGeneratorJob::run()
{
  UMLDoc* umlDoc = UMLApp::app()->document();
  xsltStylesheetPtr cur = NULL;
  xmlDocPtr doc, res;

  const char *params[16 + 1];
  int nbparams = 0;
  params[nbparams] = NULL;

  umlDoc->writeToStatusBar(i18n("Exporting to XHTML..."));

  QString xsltFileName(KGlobal::dirs()->findResource("appdata", QLatin1String("docbook2xhtml.xsl")));
  uDebug() << "XSLT file is'" << xsltFileName << "'";
  QFile xsltFile(xsltFileName);
  xsltFile.open(QIODevice::ReadOnly);
  QString xslt = QString::fromLatin1(xsltFile.readAll());
  uDebug() << "XSLT is'" << xslt << "'";
  xsltFile.close();

  QString localXsl = KGlobal::dirs()->findResource("data", QLatin1String("ksgmltools2/docbook/xsl/html/docbook.xsl"));
  uDebug() << "Local xsl is'" << localXsl << "'";
  if (!localXsl.isEmpty())
  {
    localXsl = QLatin1String("href=\"file://") + localXsl + QLatin1String("\"");
    xslt.replace(QRegExp(QLatin1String("href=\"http://[^\"]*\"")), localXsl);
  }
  KTemporaryFile tmpXsl;
  tmpXsl.setAutoRemove(false);
  tmpXsl.open();
  QTextStream str (&tmpXsl);
  str << xslt;
  str.flush();

  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 1;
  uDebug() << "Parsing stylesheet " << tmpXsl.fileName();
  cur = xsltParseStylesheetFile((const xmlChar *)tmpXsl.fileName().toLatin1().constData());
  uDebug() << "Parsing file " << m_docbookUrl.path();
  doc = xmlParseFile((const char*)(m_docbookUrl.path().toUtf8()));
  uDebug() << "Applying stylesheet ";
  res = xsltApplyStylesheet(cur, doc, params);

  KTemporaryFile tmpXhtml;
  tmpXhtml.setAutoRemove(false);
  tmpXhtml.open();

  uDebug() << "Writing HTML result to temp file: " << tmpXhtml.fileName();
  xsltSaveResultToFd(tmpXhtml.handle(), res, cur);

  xsltFreeStylesheet(cur);
  xmlFreeDoc(res);
  xmlFreeDoc(doc);

  xsltCleanupGlobals();
  xmlCleanupParser();

  emit xhtmlGenerated(tmpXhtml.fileName());
}
Example #2
0
bool NetAccess::download(const KUrl& u, QString & target, QWidget* window)
{
  if (u.isLocalFile()) {
    // file protocol. We do not need the network
    target = u.toLocalFile();
    bool accessible = KStandardDirs::checkAccess(target, R_OK);
    if(!accessible)
    {
        if(!lastErrorMsg)
            lastErrorMsg = new QString;
        *lastErrorMsg = i18n("File '%1' is not readable", target);
        lastErrorCode = ERR_COULD_NOT_READ;
    }
    return accessible;
  }

  if (target.isEmpty())
  {
      KTemporaryFile tmpFile;
      tmpFile.setAutoRemove(false);
      tmpFile.open();
      target = tmpFile.fileName();
      if (!tmpfiles)
          tmpfiles = new QStringList;
      tmpfiles->append(target);
  }

  NetAccess kioNet;
  KUrl dest;
  dest.setPath( target );
  return kioNet.filecopyInternal( u, dest, -1, KIO::Overwrite, window, false /*copy*/);
}
Example #3
0
void BinaryWidget::setData( const QByteArray &data )
{
  delete mMainWidget;

  QString mimetype;
  KMimeType::Ptr mime = KMimeType::findByContent( data );
  if ( mime && !mime->isDefault() )
    mimetype = mime->name();

  if ( !mimetype.isEmpty() ) {
    KParts::ReadOnlyPart *part = KParts::ComponentFactory::createPartInstanceFromQuery<KParts::ReadOnlyPart>( mimetype, QString(), this, this );
    if ( part ) {
      KTemporaryFile file;
      file.setAutoRemove(false);
      file.open();
      file.write( data );
      file.flush();
      part->openUrl( KUrl( file.fileName() ) );
      mMainWidget = part->widget();
    } else {
      mMainWidget = new QLabel( i18n( "No part found for visualization of mimetype %1", mimetype ), this );
    }

    mData = data;
    mSaveButton->setEnabled( true );
  } else {
    mMainWidget = new QLabel( i18n( "Got data of unknown mimetype" ), this );
  }

  mLayout->addWidget( mMainWidget, 0, 0, 3, 1);
  mMainWidget->show();
}
Example #4
0
bool DjVuGenerator::print( QPrinter& printer )
{
    bool result = false;

    // Create tempfile to write to
    KTemporaryFile tf;
    tf.setSuffix( ".ps" );
    if ( !tf.open() )
        return false;

    QMutexLocker locker( userMutex() );
    QList<int> pageList = Okular::FilePrinter::pageList( printer, m_djvu->pages().count(),
                                                         document()->currentPage() + 1,
                                                         document()->bookmarkedPageList() );

    if ( m_djvu->exportAsPostScript( &tf, pageList ) )
    {
        tf.setAutoRemove( false );
        const QString fileName = tf.fileName();
        tf.close();
        int ret = Okular::FilePrinter::printFile( printer, fileName, document()->orientation(),
                                                  Okular::FilePrinter::SystemDeletesFiles,
                                                  Okular::FilePrinter::ApplicationSelectsPages,
                                                  document()->bookmarkedPageRange() );
        result = ( ret >=0 );
    }

    return result;
}
KJotsBook* KnowItImporter::importFromUrl( KUrl url )
{
  KJotsBook *book = new KJotsBook();
  buildNoteTree(url);

//   foreach ()
//   kDebug();
  buildDomDocument();


  KTemporaryFile file;
  file.setPrefix( KStandardDirs::locateLocal( "data", "kjots/" ) );
  file.setSuffix( ".book" );
  file.setAutoRemove( false );

  if ( file.open() ) {
    file.write( "<?xml version='1.0' encoding='UTF-8' ?>\n<!DOCTYPE KJots>\n<KJots>\n" );
    file.write( m_domDoc.toByteArray() );
    file.write( "</KJots>\n" );
    kDebug() << file.fileName();
    QString newFileName = file.fileName();
    file.close();
    book->openBook( newFileName );
  }


  return book;
}
void ReportGenerator::slotConvertTemplate( const QString& templ )
{
  // kDebug() << "Report BASE:\n" << templ;

  if ( ! templ.isEmpty() ) {
    KTemporaryFile temp;
    temp.setSuffix( ".trml" );
    temp.setAutoRemove( false );

    if ( temp.open() ) {
      QTextStream s(&temp);

      // The following explicit coding settings were needed for Qt 4.7.3, former Qt versions
      // seemed to default on UTF-8. Try to comment the following two lines for older Qt versions
      // if needed and see if the trml file on the disk still is UTF-8 encoded.
      QTextCodec *codec = QTextCodec::codecForName("UTF-8");
      s.setCodec( codec );

      s << templ;
    } else {
      kDebug() << "ERROR: Could not open temporar file";
    }

    kDebug() << "Wrote rml to " << temp.fileName();

    QString dId( mDocId );

    if ( mDocId.isEmpty() ) {
      dId = ArchiveMan::self()->documentID( mArchId );
    }
    runTrml2Pdf( temp.fileName(), dId, mArchId.toString() );
  }
}
Example #7
0
bool FileProvider::get( const QString &url, QString &target )
{
  if ( !mFileName.isEmpty() )
    cleanUp();

  if ( target.isEmpty() ) {
    KTemporaryFile tmpFile;
    tmpFile.setAutoRemove(false);
    tmpFile.open();
    target = tmpFile.fileName();
    mFileName = target;
  }

  mData.truncate( 0 );

  qDebug( "Downloading external schema '%s'", qPrintable( url ) );

  KIO::TransferJob* job = KIO::get( KUrl( url ), KIO::NoReload, KIO::HideProgressInfo );
  connect( job, SIGNAL( data( KIO::Job*, const QByteArray& ) ),
           this, SLOT( slotData( KIO::Job*, const QByteArray& ) ) );
  connect( job, SIGNAL( result( KJob* ) ),
           this, SLOT( slotResult( KJob* ) ) );

  mBlocked = true;
  while ( mBlocked ) {
    QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
    usleep( 500 );
  }

  return true;
}
QString KCheckGmailTray::takeScreenshotOfTrayIcon()
{
    // Process the events else the icon will not be there and the screenie will fail!
    kapp->processEvents();

    // Taken from Akregator TrayIcon::takeScreenshot()
    const QRect rect = geometry();
    const QPoint g = rect.topLeft();
    int desktopWidth  = kapp->desktop()->width();
    int desktopHeight = kapp->desktop()->height();
    int tw = rect.width();
    int th = rect.height();
    int w = desktopWidth / 4;
    int h = desktopHeight / 9;
    int x = g.x() + tw/2 - w/2; // Center the rectange in the systray icon
    int y = g.y() + th/2 - h/2;
    if (x < 0)
        x = 0; // Move the rectangle to stay in the desktop limits
    if (y < 0)
        y = 0;
    if (x + w > desktopWidth)
        x = desktopWidth - w;
    if (y + h > desktopHeight)
        y = desktopHeight - h;

    // Grab the desktop and draw a circle around the icon:
    QPixmap shot = QPixmap::grabWindow(QApplication::desktop()->winId(), x, y, w, h);
    QPainter painter(&shot);
    painter.setRenderHint( QPainter::Antialiasing );
    const int MARGINS = 6;
    const int WIDTH   = 3;
    int ax = g.x() - x - MARGINS -1;
    int ay = g.y() - y - MARGINS -1;
    painter.setPen( QPen(Qt::red/*KApplication::palette().active().highlight()*/, WIDTH) );
    painter.drawArc(ax, ay, tw + 2*MARGINS, th + 2*MARGINS, 0, 16*360);
    painter.end();

    // Paint the border
    const int BORDER = 1;
    QPixmap finalShot(w + 2*BORDER, h + 2*BORDER);
    finalShot.fill( KApplication::palette().color( QPalette::Foreground ));
    painter.begin(&finalShot);
    painter.drawPixmap(BORDER, BORDER, shot);
    painter.end();
//	return shot; // not finalShot?? -fo

    // End of Taken from Akregator

    QString filename;
    KTemporaryFile* tmpfile = new KTemporaryFile;
    tmpfile->setAutoRemove(false);
    if (tmpfile->open()) {
        filename = tmpfile->fileName();
        shot.save(tmpfile, "png");
        tmpfile->close();
    }
    return filename;
}
Example #9
0
bool SSMLConvert::transform(const QString &text, const QString &xsltFilename) {
    m_xsltFilename = xsltFilename;
    /// Write @param text to a temporary file.
    KTemporaryFile inFile;
    inFile.setPrefix(QLatin1String( "kttsd-" ));
    inFile.setSuffix(QLatin1String( ".ssml" ));
    inFile.setAutoRemove(false);
    inFile.open();
    m_inFilename = inFile.fileName();
    QTextStream wstream (&inFile);
    // TODO: Is encoding an issue here?
    // TODO: It would be nice if we detected whether the XML is properly formed
    // with the required xml processing instruction and encoding attribute.  If
    // not wrap it in such.  But maybe this should be handled by SpeechData::setText()?
    wstream << text;
    inFile.flush();

    // Get a temporary output file name.
    KTemporaryFile outFile;
    outFile.setPrefix(QLatin1String( "kttsd-" ));
    outFile.setSuffix(QLatin1String( ".output" ));
    outFile.setAutoRemove(false);
    outFile.open();
    m_outFilename = outFile.fileName();

    /// Spawn an xsltproc process to apply our stylesheet to our SSML file.
	QStringList args;
    m_xsltProc = new QProcess;
    args << QLatin1String( "-o" ) << m_outFilename  << QLatin1String( "--novalid" )
        << m_xsltFilename << m_inFilename;
    // Warning: This won't compile under KDE 3.2.  See FreeTTS::argsToStringList().
    // kDebug() << "SSMLConvert::transform: executing command: " <<
    //     m_xsltProc->args() << endl;

    connect(m_xsltProc, SIGNAL(finished(int,QProcess::ExitStatus)),
        this, SLOT(slotProcessExited()));
    if (!m_xsltProc->execute(QLatin1String("xsltproc"), args))
    {
        kDebug() << "SSMLConvert::transform: Error starting xsltproc";
        return false;
    }
    m_state = tsTransforming;
    return true;
}
Example #10
0
//static
void DrKonqi::saveReport(const QString & reportText, QWidget *parent)
{
    if (KCmdLineArgs::parsedArgs()->isSet("safer")) {
        KTemporaryFile tf;
        tf.setSuffix(".kcrash.txt");
        tf.setAutoRemove(false);

        if (tf.open()) {
            QTextStream textStream(&tf);
            textStream << reportText;
            textStream.flush();
            KMessageBox::information(parent, i18nc("@info",
                                                   "Report saved to <filename>%1</filename>.",
                                                   tf.fileName()));
        } else {
            KMessageBox::sorry(parent, i18nc("@info","Could not create a file in which to save the report."));
        }
    } else {
        QString defname = getSuggestedKCrashFilename(crashedApplication());

        QWeakPointer<KFileDialog> dlg = new KFileDialog(defname, QString(), parent);
        dlg.data()->setSelection(defname);
        dlg.data()->setCaption(i18nc("@title:window","Select Filename"));
        dlg.data()->setOperationMode(KFileDialog::Saving);
        dlg.data()->setMode(KFile::File);
        dlg.data()->setConfirmOverwrite(true);
        dlg.data()->exec();

        if (dlg.isNull()) {
            //Dialog is invalid, it was probably deleted (ex. via DBus call)
            //return and do not crash
            return;
        }

        KUrl fileUrl = dlg.data()->selectedUrl();
        delete dlg.data();

        if (fileUrl.isValid()) {
            KTemporaryFile tf;
            if (tf.open()) {
                QTextStream ts(&tf);
                ts << reportText;
                ts.flush();
            } else {
                KMessageBox::sorry(parent, i18nc("@info","Cannot open file <filename>%1</filename> "
                                                         "for writing.", tf.fileName()));
                return;
            }

            if (!KIO::NetAccess::upload(tf.fileName(), fileUrl, parent)) {
                KMessageBox::sorry(parent, KIO::NetAccess::lastErrorString());
            }
        }
    }
}
Example #11
0
void TutorialTester::sendTutorialToTargetApplication() {
    disconnect(TargetApplication::self(), SIGNAL(started()),
               this, SLOT(sendTutorialToTargetApplication()));

    //As this TutorialTester is set as parent of the KTemporaryFile object, the
    //file will be automatically removed when this TutorialTester is destroyed
    KTemporaryFile* temporaryFile = new KTemporaryFile();
    temporaryFile->setAutoRemove(true);
    temporaryFile->setParent(this);
    temporaryFile->setSuffix(".js");
    temporaryFile->open();

    const Tutorial* tutorial = mTutorialEditor->tutorial();
    try {
        Serialization(mTutorialEditor).
                    exportTutorial(tutorial, "*.js", temporaryFile->fileName());
    } catch (IOException e) {
        QString text = i18nc("@label", "There was a problem when trying to "
"save the tutorial to a temporary file (to be used by the target application "
"to test the tutorial):<nl/>%1", e.message());
        QString caption = i18nc("@title:window", "Tutorial could not be saved");
        KMessageBox::error(mTutorialEditor, text, caption);
        delete temporaryFile;
        return;
    }

    try {
        if (mStepId.isEmpty()) {
            TargetApplication::self()->remoteEditorSupport()->
                                testScriptedTutorial(temporaryFile->fileName());
        } else {
            TargetApplication::self()->remoteEditorSupport()->
                    testScriptedTutorial(temporaryFile->fileName(), mStepId);
        }
    } catch (DBusException e) {
        QString text = i18nc("@label", "There was a problem when trying to "
"tell the target application to start the tutorial:<nl/>%1", e.message());
        QString caption = i18nc("@title:window", "Tutorial could not be "
"started");
        KMessageBox::error(mTutorialEditor, text, caption);
    }
}
    KUrl tempFileForAttachment( KCal::Attachment *attachment )
    {
      if ( mTempFiles.contains( attachment ) ) {
        return mTempFiles.value( attachment );
      }
      KTemporaryFile *file = new KTemporaryFile();
      file->setParent( this );

      QStringList patterns = KMimeType::mimeType( attachment->mimeType() )->patterns();

      if ( !patterns.empty() ) {
        file->setSuffix( QString( patterns.first() ).remove( '*' ) );
      }
      file->setAutoRemove( true );
      file->open();
      // read-only not to give the idea that it could be written to
      file->setPermissions( QFile::ReadUser );
      file->write( QByteArray::fromBase64( attachment->data() ) );
      mTempFiles.insert( attachment, file->fileName() );
      file->close();
      return mTempFiles.value( attachment );
    }
Example #13
0
void ExporterPluginView::exportToFile()
{
  KUrl url = KFileDialog::getSaveUrl(m_view->document()->documentName(), "text/html",
                                     m_view, i18n("Export File as HTML"));

  if ( url.isEmpty() ) {
    return;
  }

  QString filename;

  if ( url.isLocalFile() ) {
    filename = url.toLocalFile();
  } else {
    ///TODO: cleanup! don't let the temp files lay around
    KTemporaryFile tmp; // ### only used for network export
    tmp.setAutoRemove(false);
    tmp.open();
    filename = tmp.fileName();
  }

  KSaveFile savefile(filename);
  if (savefile.open()) {
    QTextStream outputStream ( &savefile );

    exportData(false, outputStream);

    savefile.finalize(); //check error?
  }
//     else
//       {/*ERROR*/}

  if ( !url.isLocalFile() ) {
    KIO::NetAccess::upload( filename, url, 0 );
  }
}
Example #14
0
void KonfUpdate::gotScript(const QString &_script)
{
    QString script, interpreter;
    int i = _script.indexOf(',');
    if (i == -1) {
        script = _script.trimmed();
    } else {
        script = _script.left(i).trimmed();
        interpreter = _script.mid(i + 1).trimmed();
    }


    if (script.isEmpty()) {
        logFileError() << "Script fails to specify filename";
        m_skip = true;
        return;
    }



    QString path = KStandardDirs::locate("data", "kconf_update/" + script);
    if (path.isEmpty()) {
        if (interpreter.isEmpty()) {
            path = KStandardDirs::locate("lib", "kconf_update_bin/" + script);
        }

        if (path.isEmpty()) {
            logFileError() << "Script '" << script << "' not found" << endl;
            m_skip = true;
            return;
        }
    }

    if (!m_arguments.isNull()) {
        log() << m_currentFilename << ": Running script '" << script << "' with arguments '" << m_arguments << "'" << endl;
    } else {
        log() << m_currentFilename << ": Running script '" << script << "'" << endl;
    }

    QString cmd;
    if (interpreter.isEmpty()) {
        cmd = path;
    } else {
        cmd = interpreter + ' ' + path;
    }

    if (!m_arguments.isNull()) {
        cmd += ' ';
        cmd += m_arguments;
    }

    KTemporaryFile scriptIn;
    scriptIn.open();
    KTemporaryFile scriptOut;
    scriptOut.open();
    KTemporaryFile scriptErr;
    scriptErr.open();

    int result;
    if (m_oldConfig1) {
        if (m_debug) {
            scriptIn.setAutoRemove(false);
            log() << "Script input stored in " << scriptIn.fileName() << endl;
        }
        KConfig cfg(scriptIn.fileName(), KConfig::SimpleConfig);

        if (m_oldGroup.isEmpty()) {
            // Write all entries to tmpFile;
            const QStringList grpList = m_oldConfig1->groupList();
            for (QStringList::ConstIterator it = grpList.begin();
                    it != grpList.end();
                    ++it) {
                copyGroup(m_oldConfig1, *it, &cfg, *it);
            }
        } else {
            KConfigGroup cg1 = KConfigUtils::openGroup(m_oldConfig1, m_oldGroup);
            KConfigGroup cg2(&cfg, QString());
            copyGroup(cg1, cg2);
        }
        cfg.sync();
#ifndef _WIN32_WCE
        result = system(QFile::encodeName(QString("%1 < %2 > %3 2> %4").arg(cmd, scriptIn.fileName(), scriptOut.fileName(), scriptErr.fileName())));
#else
        QString path_ = QDir::convertSeparators ( QFileInfo ( cmd ).absoluteFilePath() );
        QString file_ = QFileInfo ( cmd ).fileName();
        SHELLEXECUTEINFO execInfo;
        memset ( &execInfo,0,sizeof ( execInfo ) );
        execInfo.cbSize = sizeof ( execInfo );
        execInfo.fMask =  SEE_MASK_FLAG_NO_UI;
        execInfo.lpVerb = L"open";
        execInfo.lpFile = (LPCWSTR) path_.utf16();
        execInfo.lpDirectory = (LPCWSTR) file_.utf16();
        execInfo.lpParameters = (LPCWSTR) QString(" < %1 > %2 2> %3").arg( scriptIn.fileName(), scriptOut.fileName(), scriptErr.fileName()).utf16();
        result = ShellExecuteEx ( &execInfo );
        if (result != 0)
        {
            result = 0;
        }
        else
        {
            result = -1;
        }
#endif
    } else {
        // No config file
#ifndef _WIN32_WCE
        result = system(QFile::encodeName(QString("%1 2> %2").arg(cmd, scriptErr.fileName())));
#else
        QString path_ = QDir::convertSeparators ( QFileInfo ( cmd ).absoluteFilePath() );
        QString file_ = QFileInfo ( cmd ).fileName();
        SHELLEXECUTEINFO execInfo;
        memset ( &execInfo,0,sizeof ( execInfo ) );
        execInfo.cbSize = sizeof ( execInfo );
        execInfo.fMask =  SEE_MASK_FLAG_NO_UI;
        execInfo.lpVerb = L"open";
        execInfo.lpFile = (LPCWSTR) path_.utf16();
        execInfo.lpDirectory = (LPCWSTR) file_.utf16();
        execInfo.lpParameters = (LPCWSTR) QString(" 2> %1").arg( scriptErr.fileName()).utf16();
        result = ShellExecuteEx ( &execInfo );
        if (result != 0)
        {
            result = 0;
        }
        else
        {
            result = -1;
        }
#endif
    }

    // Copy script stderr to log file
    {
        QFile output(scriptErr.fileName());
        if (output.open(QIODevice::ReadOnly)) {
            QTextStream ts(&output);
            ts.setCodec(QTextCodec::codecForName("UTF-8"));
            while (!ts.atEnd()) {
                QString line = ts.readLine();
                log() << "[Script] " << line << endl;
            }
        }
    }

    if (result) {
        log() << m_currentFilename << ": !! An error occurred while running '" << cmd << "'" << endl;
        return;
    }

    if (!m_oldConfig1) {
        return; // Nothing to merge
    }

    if (m_debug) {
        scriptOut.setAutoRemove(false);
        log() << "Script output stored in " << scriptOut.fileName() << endl;
    }

    // Deleting old entries
    {
        QStringList group = m_oldGroup;
        QFile output(scriptOut.fileName());
        if (output.open(QIODevice::ReadOnly)) {
            QTextStream ts(&output);
            ts.setCodec(QTextCodec::codecForName("UTF-8"));
            while (!ts.atEnd()) {
                QString line = ts.readLine();
                if (line.startsWith('[')) {
                    group = parseGroupString(line);
                } else if (line.startsWith(QLatin1String("# DELETE "))) {
                    QString key = line.mid(9);
                    if (key[0] == '[') {
                        int j = key.lastIndexOf(']') + 1;
                        if (j > 0) {
                            group = parseGroupString(key.left(j));
                            key = key.mid(j);
                        }
                    }
                    KConfigGroup cg = KConfigUtils::openGroup(m_oldConfig2, group);
                    cg.deleteEntry(key);
                    log() << m_currentFilename << ": Script removes " << m_oldFile << ":" << group << ":" << key << endl;
                    /*if (m_oldConfig2->deleteGroup(group, KConfig::Normal)) { // Delete group if empty.
                       log() << m_currentFilename << ": Removing empty group " << m_oldFile << ":" << group << endl;
                    } (this should be automatic)*/
                } else if (line.startsWith(QLatin1String("# DELETEGROUP"))) {
                    QString str = line.mid(13).trimmed();
                    if (!str.isEmpty()) {
                        group = parseGroupString(str);
                    }
                    KConfigGroup cg = KConfigUtils::openGroup(m_oldConfig2, group);
                    cg.deleteGroup();
                    log() << m_currentFilename << ": Script removes group " << m_oldFile << ":" << group << endl;
                }
            }
        }
    }

    // Merging in new entries.
    KConfig scriptOutConfig(scriptOut.fileName(), KConfig::NoGlobals);
    if (m_newGroup.isEmpty()) {
        // Copy "default" keys as members of "default" keys
        copyGroup(&scriptOutConfig, QString(), m_newConfig, QString());
    } else {
        // Copy default keys as members of m_newGroup
        KConfigGroup srcCg = KConfigUtils::openGroup(&scriptOutConfig, QStringList());
        KConfigGroup dstCg = KConfigUtils::openGroup(m_newConfig, m_newGroup);
        copyGroup(srcCg, dstCg);
    }
    Q_FOREACH(const QString &group, scriptOutConfig.groupList()) {
        copyGroup(&scriptOutConfig, group, m_newConfig, group);
    }
}
Example #15
0
bool KWebPage::handleReply(QNetworkReply* reply, QString* contentType, KIO::MetaData* metaData)
{
    // Reply url...
    const KUrl replyUrl (reply->url());

    // Get suggested file name...
    const KIO::MetaData& data = reply->attribute(static_cast<QNetworkRequest::Attribute>(KIO::AccessManager::MetaData)).toMap();
    const QString suggestedFileName = data.value(QL1S("content-disposition-filename"));
    if (metaData) {
        *metaData = data;
    }

    // Get the mime-type...
    QString mimeType;
    extractMimeType(reply, mimeType);
    if (contentType) {
        *contentType = mimeType;
    }

    // Let the calling function deal with handling empty or inode/* mimetypes...
    if (mimeType.isEmpty() || mimeType.startsWith(QL1S("inode/"), Qt::CaseInsensitive)) {
        return false;
    }

    // Convert executable text files to plain text...
    if (KParts::BrowserRun::isTextExecutable(mimeType))
        mimeType = QL1S("text/plain");

    //kDebug(800) << "Content-disposition:" << suggestedFileName;
    //kDebug(800) << "Got unsupported content of type:" << mimeType << "URL:" << replyUrl;
    //kDebug(800) << "Error code:" << reply->error() << reply->errorString();

    if (isReplyStatusOk(reply)) {
        while (true) {
            KParts::BrowserOpenOrSaveQuestion::Result result;
            KParts::BrowserOpenOrSaveQuestion dlg(d->windowWidget(), replyUrl, mimeType);
            dlg.setSuggestedFileName(suggestedFileName);
            dlg.setFeatures(KParts::BrowserOpenOrSaveQuestion::ServiceSelection);
            result = dlg.askOpenOrSave();

            switch (result) {
            case KParts::BrowserOpenOrSaveQuestion::Open:
                // Handle Post operations that return content...
                if (reply->operation() == QNetworkAccessManager::PostOperation) {
                    d->mimeType = mimeType;
                    QFileInfo finfo (suggestedFileName.isEmpty() ? replyUrl.fileName() : suggestedFileName);
                    KTemporaryFile tempFile;
                    tempFile.setSuffix(QL1C('.') + finfo.suffix());
                    tempFile.setAutoRemove(false);
                    tempFile.open();
                    KUrl destUrl;
                    destUrl.setPath(tempFile.fileName());
                    KIO::Job *job = KIO::file_copy(replyUrl, destUrl, 0600, KIO::Overwrite);
                    job->ui()->setWindow(d->windowWidget());
                    job->ui()->setAutoErrorHandlingEnabled(true);
                    connect(job, SIGNAL(result(KJob*)),
                            this, SLOT(_k_copyResultToTempFile(KJob*)));
                    return true;
                }

                // Ask before running any executables...
                if (KParts::BrowserRun::allowExecution(mimeType, replyUrl)) {
                    KService::Ptr offer = dlg.selectedService();
                    // HACK: The check below is necessary to break an infinite
                    // recursion that occurs whenever this function is called as a result
                    // of receiving content that can be rendered by the app using this engine.
                    // For example a text/html header that containing a content-disposition
                    // header is received by the app using this class.
                    if (isMimeTypeAssociatedWithSelf(offer)) {
                        reloadRequestWithoutDisposition(reply);
                    } else {
                        KUrl::List list;
                        list.append(replyUrl);
                        bool success = false;
                        // kDebug(800) << "Suggested file name:" << suggestedFileName;
                        if (offer) {
                            success = KRun::run(*offer, list, d->windowWidget() , false, suggestedFileName);
                        } else {
                            success = KRun::displayOpenWithDialog(list, d->windowWidget(), false, suggestedFileName);
                            if (!success)
                                break;
                        }
                        // For non KIO apps and cancelled Open With dialog, remove slave on hold.
                        if (!success || (offer && !offer->categories().contains(QL1S("KDE")))) {
                            KIO::SimpleJob::removeOnHold(); // Remove any slave-on-hold...
                        }
                    }
                    return true;
                }
                // TODO: Instead of silently failing when allowExecution fails, notify
                // the user why the requested action cannot be fulfilled...
                return false;
            case KParts::BrowserOpenOrSaveQuestion::Save:
                // Do not download local files...
                if (!replyUrl.isLocalFile()) {
                    QString downloadCmd (reply->property("DownloadManagerExe").toString());
                    if (!downloadCmd.isEmpty()) {
                        downloadCmd += QLatin1Char(' ');
                        downloadCmd += KShell::quoteArg(replyUrl.url());
                        if (!suggestedFileName.isEmpty()) {
                            downloadCmd += QLatin1Char(' ');
                            downloadCmd += KShell::quoteArg(suggestedFileName);
                        }
                        // kDebug(800) << "download command:" << downloadCmd;
                        if (KRun::runCommand(downloadCmd, view()))
                            return true;
                    }
                    if (!downloadResource(replyUrl, suggestedFileName, d->windowWidget()))
                        break;
                }
                return true;
            case KParts::BrowserOpenOrSaveQuestion::Cancel:
            default:
                KIO::SimpleJob::removeOnHold(); // Remove any slave-on-hold...
                return true;
            }
        }
    } else {
Example #16
0
void FileProtocol::mount( bool _ro, const char *_fstype, const QString& _dev, const QString& _point )
{
    kDebug(7101) << "fstype=" << _fstype;

#ifndef _WIN32_WCE
#ifdef HAVE_VOLMGT
	/*
	 *  support for Solaris volume management
	 */
	QString err;
	QByteArray devname = QFile::encodeName( _dev );

	if( volmgt_running() ) {
//		kDebug(7101) << "VOLMGT: vold ok.";
		if( volmgt_check( devname.data() ) == 0 ) {
			kDebug(7101) << "VOLMGT: no media in "
					<< devname.data();
			err = i18n("No Media inserted or Media not recognized.");
			error( KIO::ERR_COULD_NOT_MOUNT, err );
			return;
		} else {
			kDebug(7101) << "VOLMGT: " << devname.data()
				<< ": media ok";
			finished();
			return;
		}
	} else {
		err = i18n("\"vold\" is not running.");
		kDebug(7101) << "VOLMGT: " << err;
		error( KIO::ERR_COULD_NOT_MOUNT, err );
		return;
	}
#else


    KTemporaryFile tmpFile;
    tmpFile.setAutoRemove(false);
    tmpFile.open();
    QByteArray tmpFileName = QFile::encodeName(tmpFile.fileName());
    QByteArray dev;
    if (_dev.startsWith(QLatin1String("LABEL="))) { // turn LABEL=foo into -L foo (#71430)
        QString labelName = _dev.mid( 6 );
        dev = "-L ";
        dev += QFile::encodeName( KShell::quoteArg( labelName ) ); // is it correct to assume same encoding as filesystem?
    } else if (_dev.startsWith(QLatin1String("UUID="))) { // and UUID=bar into -U bar
        QString uuidName = _dev.mid( 5 );
        dev = "-U ";
        dev += QFile::encodeName( KShell::quoteArg( uuidName ) );
    }
    else
        dev = QFile::encodeName( KShell::quoteArg(_dev) ); // get those ready to be given to a shell

    QByteArray point = QFile::encodeName( KShell::quoteArg(_point) );
    bool fstype_empty = !_fstype || !*_fstype;
    QByteArray fstype = KShell::quoteArg(QString::fromLatin1(_fstype)).toLatin1(); // good guess
    QByteArray readonly = _ro ? "-r" : "";
    QString epath = QString::fromLocal8Bit(qgetenv("PATH"));
    QString path = QLatin1String("/sbin:/bin");
    if(!epath.isEmpty())
        path += QLatin1String(":") + epath;
    QByteArray mountProg = KGlobal::dirs()->findExe(QLatin1String("mount"), path).toLocal8Bit();
    if (mountProg.isEmpty()){
      error( KIO::ERR_COULD_NOT_MOUNT, i18n("Could not find program \"mount\""));
      return;
    }

    // Two steps, in case mount doesn't like it when we pass all options
    for ( int step = 0 ; step <= 1 ; step++ )
    {
        QByteArray buffer = mountProg + ' ';
        // Mount using device only if no fstype nor mountpoint (KDE-1.x like)
        if ( !dev.isEmpty() && _point.isEmpty() && fstype_empty )
            buffer += dev;
        else
          // Mount using the mountpoint, if no fstype nor device (impossible in first step)
          if ( !_point.isEmpty() && dev.isEmpty() && fstype_empty )
              buffer += point;
          else
            // mount giving device + mountpoint but no fstype
            if ( !_point.isEmpty() && !dev.isEmpty() && fstype_empty )
                buffer += readonly + ' ' + dev + ' ' + point;
            else
              // mount giving device + mountpoint + fstype
#if defined(__svr4__) && defined(Q_OS_SOLARIS) // MARCO for Solaris 8 and I
                // believe this is true for SVR4 in general
                buffer += "-F " + fstype + ' ' + (_ro ? "-oro" : "") + ' ' + dev + ' ' + point;
#else
                buffer += readonly + " -t " + fstype + ' ' + dev + ' ' + point;
#endif
        buffer += " 2>" + tmpFileName;
        kDebug(7101) << buffer;

        int mount_ret = system( buffer.constData() );

        QString err = testLogFile( tmpFileName );
        if ( err.isEmpty() && mount_ret == 0)
        {
            finished();
            return;
        }
        else
        {
            // Didn't work - or maybe we just got a warning
            KMountPoint::Ptr mp = KMountPoint::currentMountPoints().findByDevice( _dev );
            // Is the device mounted ?
            if ( mp && mount_ret == 0)
            {
                kDebug(7101) << "mount got a warning:" << err;
                warning( err );
                finished();
                return;
            }
            else
            {
                if ( (step == 0) && !_point.isEmpty())
                {
                    kDebug(7101) << err;
                    kDebug(7101) << "Mounting with those options didn't work, trying with only mountpoint";
                    fstype = "";
                    fstype_empty = true;
                    dev = "";
                    // The reason for trying with only mountpoint (instead of
                    // only device) is that some people (hi Malte!) have the
                    // same device associated with two mountpoints
                    // for different fstypes, like /dev/fd0 /mnt/e2floppy and
                    // /dev/fd0 /mnt/dosfloppy.
                    // If the user has the same mountpoint associated with two
                    // different devices, well they shouldn't specify the
                    // mountpoint but just the device.
                }
                else
                {
                    error( KIO::ERR_COULD_NOT_MOUNT, err );
                    return;
                }
            }
        }
    }
#endif /* ! HAVE_VOLMGT */
#else
    QString err;
    err = i18n("mounting is not supported by wince.");
    error( KIO::ERR_COULD_NOT_MOUNT, err );
#endif

}
Example #17
0
void FileProtocol::unmount( const QString& _point )
{
#ifndef _WIN32_WCE
    QByteArray buffer;

    KTemporaryFile tmpFile;
    tmpFile.setAutoRemove(false);
    tmpFile.open();
    QByteArray tmpFileName = QFile::encodeName(tmpFile.fileName());
    QString err;

#ifdef HAVE_VOLMGT
	/*
	 *  support for Solaris volume management
	 */
	char *devname;
	char *ptr;
	FILE *mnttab;
	struct mnttab mnt;

	if( volmgt_running() ) {
		kDebug(7101) << "VOLMGT: looking for "
			<< _point.toLocal8Bit();

		if( (mnttab = KDE_fopen( MNTTAB, "r" )) == NULL ) {
			err = QLatin1String("could not open mnttab");
			kDebug(7101) << "VOLMGT: " << err;
			error( KIO::ERR_COULD_NOT_UNMOUNT, err );
			return;
		}

		/*
		 *  since there's no way to derive the device name from
		 *  the mount point through the volmgt library (and
		 *  media_findname() won't work in this case), we have to
		 *  look ourselves...
		 */
		devname = NULL;
		rewind( mnttab );
		while( getmntent( mnttab, &mnt ) == 0 ) {
			if( strcmp( _point.toLocal8Bit(), mnt.mnt_mountp ) == 0 ){
				devname = mnt.mnt_special;
				break;
			}
		}
		fclose( mnttab );

		if( devname == NULL ) {
			err = QLatin1String("not in mnttab");
			kDebug(7101) << "VOLMGT: "
				<< QFile::encodeName(_point).data()
				<< ": " << err;
			error( KIO::ERR_COULD_NOT_UNMOUNT, err );
			return;
		}

		/*
		 *  strip off the directory name (volume name)
		 *  the eject(1) command will handle unmounting and
		 *  physically eject the media (if possible)
		 */
		ptr = strrchr( devname, '/' );
		*ptr = '\0';
                QByteArray qdevname(QFile::encodeName(KShell::quoteArg(QFile::decodeName(QByteArray(devname)))).data());
		buffer = "/usr/bin/eject " + qdevname + " 2>" + tmpFileName;
		kDebug(7101) << "VOLMGT: eject " << qdevname;

		/*
		 *  from eject(1): exit status == 0 => need to manually eject
		 *                 exit status == 4 => media was ejected
		 */
		if( WEXITSTATUS( system( buffer.constData() )) == 4 ) {
			/*
			 *  this is not an error, so skip "testLogFile()"
			 *  to avoid wrong/confusing error popup. The
			 *  temporary file is removed by KTemporaryFile's
			 *  destructor, so don't do that manually.
			 */
			finished();
			return;
		}
	} else {
		/*
		 *  eject(1) should do its job without vold(1M) running,
		 *  so we probably could call eject anyway, but since the
		 *  media is mounted now, vold must've died for some reason
		 *  during the user's session, so it should be restarted...
		 */
		err = i18n("\"vold\" is not running.");
		kDebug(7101) << "VOLMGT: " << err;
		error( KIO::ERR_COULD_NOT_UNMOUNT, err );
		return;
	}
#else
    QString epath = QString::fromLocal8Bit(qgetenv("PATH"));
    QString path = QLatin1String("/sbin:/bin");
    if (!epath.isEmpty())
       path += QLatin1Char(':') + epath;
    QByteArray umountProg = KGlobal::dirs()->findExe(QLatin1String("umount"), path).toLocal8Bit();

    if (umountProg.isEmpty()) {
        error( KIO::ERR_COULD_NOT_UNMOUNT, i18n("Could not find program \"umount\""));
        return;
    }
    buffer = umountProg + ' ' + QFile::encodeName(KShell::quoteArg(_point)) + " 2>" + tmpFileName;
    system( buffer.constData() );
#endif /* HAVE_VOLMGT */

    err = testLogFile( tmpFileName );
    if ( err.isEmpty() )
        finished();
    else
        error( KIO::ERR_COULD_NOT_UNMOUNT, err );
#else
    QString err;
    err = i18n("unmounting is not supported by wince.");
    error( KIO::ERR_COULD_NOT_MOUNT, err );
#endif
}
Example #18
0
void ghostscript_interface::gs_generate_graphics_file(const PageNumber& page, const QString& filename, long magnification) {
#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << "ghostscript_interface::gs_generate_graphics_file( " << page << ", " << filename << " )";
#endif

  if (knownDevices.isEmpty()) {
    kError(kvs::dvi) << "No known devices found" << endl;
    return;
  }

  pageInfo *info = pageList.value(page);

  // Generate a PNG-file
  // Step 1: Write the PostScriptString to a File
  KTemporaryFile PSfile;
  PSfile.setAutoRemove(false);
  PSfile.setSuffix(".ps");
  PSfile.open();
  const QString PSfileName = PSfile.fileName();

  QTextStream os(&PSfile);
  os << "%!PS-Adobe-2.0\n"
     << "%%Creator: kdvi\n"
     << "%%Title: KDVI temporary PostScript\n"
     << "%%Pages: 1\n"
     << "%%PageOrder: Ascend\n"
        // HSize and VSize in 1/72 inch
     << "%%BoundingBox: 0 0 "
     << (qint32)(72*(pixel_page_w/resolution)) << ' '
     << (qint32)(72*(pixel_page_h/resolution)) << '\n'
     << "%%EndComments\n"
     << "%!\n"
     << psheader
     << "TeXDict begin "
        // HSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_w/resolution)) << ' '
        // VSize in (1/(65781.76*72))inch
     << (qint32)(72*65781*(pixel_page_h/resolution)) << ' '
        // Magnification
     << (qint32)(magnification)
        // dpi and vdpi
     << " 300 300"
        // Name
     << " (test.dvi)"
     << " @start end\n"
     << "TeXDict begin\n"
        // Start page
     << "1 0 bop 0 0 a \n";

  if (!PostScriptHeaderString->toLatin1().isNull())
    os << PostScriptHeaderString->toLatin1();

  if (info->background != Qt::white) {
    QString colorCommand = QString("gsave %1 %2 %3 setrgbcolor clippath fill grestore\n").
      arg(info->background.red()/255.0).
      arg(info->background.green()/255.0).
      arg(info->background.blue()/255.0);
    os << colorCommand.toLatin1();
  }

  if (!info->PostScriptString->isNull())
    os << *(info->PostScriptString);

  os << "end\n"
     << "showpage \n";

  PSfile.close();

  // Step 2: Call GS with the File
  QFile::remove(filename.toAscii());
  KProcess proc;
  proc.setOutputChannelMode(KProcess::SeparateChannels);
  QStringList argus;
  argus << "gs";
  argus << "-dSAFER" << "-dPARANOIDSAFER" << "-dDELAYSAFER" << "-dNOPAUSE" << "-dBATCH";
  argus << QString("-sDEVICE=%1").arg(*gsDevice);
  argus << QString("-sOutputFile=%1").arg(filename);
  argus << QString("-sExtraIncludePath=%1").arg(includePath);
  argus << QString("-g%1x%2").arg(pixel_page_w).arg(pixel_page_h); // page size in pixels
  argus << QString("-r%1").arg(resolution);                       // resolution in dpi
  argus << "-dTextAlphaBits=4 -dGraphicsAlphaBits=2"; // Antialiasing
  argus << "-c" << "<< /PermitFileReading [ ExtraIncludePath ] /PermitFileWriting [] /PermitFileControl [] >> setuserparams .locksafe";
  argus << "-f" << PSfileName;

#ifdef DEBUG_PSGS
  kDebug(kvs::dvi) << argus.join(" ");
#endif
 
  proc << argus;
  int res = proc.execute();
  
  if ( res ) {
    // Starting ghostscript did not work. 
    // TODO: Issue error message, switch PS support off.
    kError(kvs::dvi) << "ghostview could not be started" << endl;
  } 

  PSfile.remove();

 // Check if gs has indeed produced a file.
  if (QFile::exists(filename) == false) {
    kError(kvs::dvi) << "GS did not produce output." << endl;

    // No. Check is the reason is that the device is not compiled into
    // ghostscript. If so, try again with another device.
    QString GSoutput;
    proc.setReadChannel(QProcess::StandardOutput);
    while(proc.canReadLine()) {
      GSoutput = QString::fromLocal8Bit(proc.readLine());
      if (GSoutput.contains("Unknown device")) {
	kDebug(kvs::dvi) << QString("The version of ghostview installed on this computer does not support "
                                     "the '%1' ghostview device driver.").arg(*gsDevice) << endl;
	knownDevices.erase(gsDevice);
	gsDevice = knownDevices.begin();
	if (knownDevices.isEmpty())
	  // TODO: show a requestor of some sort.
#if 0
	  KMessageBox::detailedError(0, 
				     i18n("<qt>The version of Ghostview that is installed on this computer does not contain "
					  "any of the Ghostview device drivers that are known to Okular. PostScript "
					  "support has therefore been turned off in Okular.</qt>"), 
				     i18n("<qt><p>The Ghostview program, which Okular uses internally to display the "
					  "PostScript graphics that is included in this DVI file, is generally able to "
					  "write its output in a variety of formats. The sub-programs that Ghostview uses "
					  "for these tasks are called 'device drivers'; there is one device driver for "
					  "each format that Ghostview is able to write. Different versions of Ghostview "
					  "often have different sets of device drivers available. It seems that the "
					  "version of Ghostview that is installed on this computer does not contain "
					  "<strong>any</strong> of the device drivers that are known to Okular.</p>"
					  "<p>It seems unlikely that a regular installation of Ghostview would not contain "
					  "these drivers. This error may therefore point to a serious misconfiguration of "
					  "the Ghostview installation on your computer.</p>"
					  "<p>If you want to fix the problems with Ghostview, you can use the command "
					  "<strong>gs --help</strong> to display the list of device drivers contained in "
					  "Ghostview. Among others, Okular can use the 'png256', 'jpeg' and 'pnm' "
					  "drivers. Note that Okular needs to be restarted to re-enable PostScript support."
					  "</p></qt>"));
#else
	{}
#endif
	else {
	  kDebug(kvs::dvi) << QString("Okular will now try to use the '%1' device driver.").arg(*gsDevice);
	  gs_generate_graphics_file(page, filename, magnification);
	}
	return;
      }
Example #19
0
bool Utils::updateMetadataImageMagick(const QString& src, QString& err)
{
    QFileInfo finfo(src);
    if (src.isEmpty() || !finfo.isReadable())
    {
        err = i18n("unable to open source file");
        return false;
    }

    QImage img(src);
    QImage iptcPreview   = img.scaled(1280, 1024, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QImage exifThumbnail = iptcPreview.scaled(160, 120, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    KExiv2Iface::KExiv2 meta;
    meta.load(src);
    meta.setImageOrientation(KExiv2Iface::KExiv2::ORIENTATION_NORMAL);
    meta.setImageProgramId(QString("Kipi-plugins"), QString(kipiplugins_version));
    meta.setImageDimensions(img.size());
    meta.setExifThumbnail(exifThumbnail);
    meta.setImagePreview(iptcPreview);

#if KEXIV2_VERSION >= 0x010000
    QByteArray exifData = meta.getExifEncoded(true);
#else
    QByteArray exifData = meta.getExif(true);
#endif

    QByteArray iptcData = meta.getIptc(true);
    QByteArray xmpData  = meta.getXmp();

    KTemporaryFile exifTemp;
    exifTemp.setSuffix(QString("kipipluginsexif.app1"));
    exifTemp.setAutoRemove(true);
    if ( !exifTemp.open() )
    {
        err = i18n("unable to open temp file");
        return false;
    }
    QString exifFile = exifTemp.fileName();
    QDataStream streamExif( &exifTemp );
    streamExif.writeRawData(exifData.data(), exifData.size());
    exifTemp.close();

    KTemporaryFile iptcTemp;
    iptcTemp.setSuffix(QString("kipipluginsiptc.8bim"));
    iptcTemp.setAutoRemove(true);
    iptcTemp.open();
    if ( !iptcTemp.open() )
    {
        err = i18n("Cannot rotate: unable to open temp file");
        return false;
    }
    QString iptcFile = iptcTemp.fileName();
    QDataStream streamIptc( &iptcTemp );
    streamIptc.writeRawData(iptcData.data(), iptcData.size());
    iptcTemp.close();

    KTemporaryFile xmpTemp;
    xmpTemp.setSuffix(QString("kipipluginsxmp.xmp"));
    xmpTemp.setAutoRemove(true);
    if ( !xmpTemp.open() )
    {
        err = i18n("unable to open temp file");
        return false;
    }
    QString xmpFile = xmpTemp.fileName();
    QDataStream streamXmp( &xmpTemp );
    streamXmp.writeRawData(xmpData.data(), xmpData.size());
    xmpTemp.close();

    KProcess process;
    process.clearProgram();
    process << "mogrify";

    process << "-profile";
    process << exifFile;

    process << "-profile";
    process << iptcFile;

    process << "-profile";
    process << xmpFile;

    process << src + QString("[0]");

    kDebug() << "ImageMagick Command line: " << process.program();

    process.start();

    if (!process.waitForFinished())
        return false;

    if (process.exitStatus() != QProcess::NormalExit)
        return false;

    switch (process.exitCode())
    {
        case 0:  // Process finished successfully !
        {
            return true;
            break;
        }
        case 15: //  process aborted !
        {
            return false;
            break;
        }
    }

    // Processing error !
    m_stdErr = process.readAllStandardError();
    err      = i18n("Cannot update metadata: %1", m_stdErr.replace('\n', ' '));
    return false;
}
Example #20
0
void
Crash::crashHandler(int /*signal*/)
{
#ifndef Q_WS_WIN 
    // we need to fork to be able to get a
    // semi-decent bt - I dunno why
    const pid_t pid = ::fork();

    if (pid <= 0) {
        // we are the child process (the result of the fork)
//            debug() << "amaroK is crashing...\n";

        QString subject = "[basket-crash] " VERSION " ";
        QString body = i18n(
                           "%1 has crashed! We're sorry about this.\n"
                           "\n"
                           "But, all is not lost! You could potentially help us fix the crash. "
                           "Information describing the crash is below, so just click send, "
                           "or if you have time, write a brief description of how the crash happened first.\n\n"
                           "Many thanks.", KGlobal::mainComponent().aboutData()->programName()) + "\n\n";
        body += "\n\n\n\n\n\n" + i18n(
                    "The information below is to help the developers identify the problem, "
                    "please do not modify it.") + "\n\n\n\n";


        body += "======== DEBUG INFORMATION  =======\n"
                "Version:    " VERSION "\n"
                "CC version: " __VERSION__ "\n" //assuming we're using GCC
                "KDElibs:    " KDE_VERSION_STRING "\n"
                ;//                    "TagLib:     %2.%3.%4\n";

        /*            body = body
                            .arg( TAGLIB_MAJOR_VERSION )
                            .arg( TAGLIB_MINOR_VERSION )
                            .arg( TAGLIB_PATCH_VERSION );*/

#ifdef NDEBUG
        body += "NDEBUG:     true";
#endif
        body += "\n";

        /// obtain the backtrace with gdb

	KTemporaryFile temp;
	temp.open();	
        temp.setAutoRemove(true);

        const int handle = temp.handle();

//             QCString gdb_command_string =
//                     "file amarokapp\n"
//                     "attach " + QCString().setNum( ::getppid() ) + "\n"
//                     "bt\n" "echo \\n\n"
//                     "thread apply all bt\n";

        const QByteArray gdb_batch =
            "bt\n"
            "echo \\n\\n\n"
            "bt full\n"
            "echo \\n\\n\n"
            "echo ==== (gdb) thread apply all bt ====\\n\n"
            "thread apply all bt\n";

        ::write(handle, gdb_batch, gdb_batch.length());
        ::fsync(handle);

        // so we can read stderr too
        ::dup2(fileno(stdout), fileno(stderr));

        QByteArray gdb;
        gdb  = "gdb --nw -n --batch -x ";
        gdb += temp.fileName().toLatin1();
        gdb += " ";
	gdb += KCmdLineArgs::qtArgv()[0];
	gdb += " ";
        gdb += QByteArray().setNum(::getppid());

 
       QString bt = runCommand(gdb);

        /// clean up
        bt.remove("(no debugging symbols found)...");
        bt.remove("(no debugging symbols found)\n");
        bt.replace(QRegExp("\n{2,}"), "\n");   //clean up multiple \n characters
        bt.trimmed();

        /// analyze usefulness
        bool useful = true;
        const QString fileCommandOutput = runCommand("file `which basket`");

        if (fileCommandOutput.indexOf("not stripped") == -1)
            subject += "[___stripped]"; //same length as below
        else
            subject += "[NOTstripped]";

        if (!bt.isEmpty()) {
            const int invalidFrames = bt.count(QRegExp("\n#[0-9]+\\s+0x[0-9A-Fa-f]+ in \\?\\?"));
            const int validFrames = bt.count(QRegExp("\n#[0-9]+\\s+0x[0-9A-Fa-f]+ in [^?]"));
            const int totalFrames = invalidFrames + validFrames;

            if (totalFrames > 0) {
                const double validity = double(validFrames) / totalFrames;
                subject += QString("[validity: %1]").arg(validity, 0, 'f', 2);
                if (validity <= 0.5) useful = false;
            }
            subject += QString("[frames: %1]").arg(totalFrames, 3 /*padding*/);

            if (bt.indexOf(QRegExp(" at \\w*\\.cpp:\\d+\n")) != -1)
                subject += "[line numbers]";
        } else
            useful = false;

//            subject += QString("[%1]").arg( AmarokConfig::soundSystem().remove( QRegExp("-?engine") ) );

//            debug() << subject << endl;

        //TODO -fomit-frame-pointer buggers up the backtrace, so detect it
        //TODO -O optimization can rearrange execution and stuff so show a warning for the developer
        //TODO pass the CXXFLAGS used with the email

        if (useful) {
            body += "==== file `which basket` ==========\n";
            body += fileCommandOutput + "\n";
            body += "==== (gdb) bt =====================\n";
            body += bt;//+ "\n\n";
//                body += "==== kBacktrace() ================\n";
//                body += kBacktrace();

            //TODO startup notification
            KToolInvocation::invokeMailer(
                /*to*/          "*****@*****.**",
                /*cc*/          QString(),
                /*bcc*/         QString(),
                /*subject*/     subject,
                /*body*/        body,
                /*messageFile*/ QString(),
                /*attachURLs*/  QStringList(),
                /*startup_id*/  "");
        } else {
            kDebug() << "\n" + i18n("%1 has crashed! We're sorry about this.\n\n"
                                    "But, all is not lost! Perhaps an upgrade is already available "
                                    "which fixes the problem. Please check your distribution's software repository.",
                                    KGlobal::mainComponent().aboutData()->programName());
        }

        //_exit() exits immediately, otherwise this
        //function is called repeatedly ad finitum
        ::_exit(255);
    }

    else {
        // we are the process that crashed
        
        ::alarm(0);

        // wait for child to exit
        ::waitpid(pid, NULL, 0);
        ::_exit(253);
    }
#endif //#ifndef Q_WS_WIN 
}
Example #21
0
void WebPage::handleUnsupportedContent(QNetworkReply *reply)
{
    Q_ASSERT(reply);

    // Put the job on hold...
#if KDE_IS_VERSION( 4, 5, 96)
    kDebug() << "PUT REPLY ON HOLD...";
    KIO::Integration::AccessManager::putReplyOnHold(reply);
#else
    reply->abort();
#endif

    // This is probably needed just in ONE stupid case..
    if (_protHandler.postHandling(reply->request(), mainFrame()))
    {
        kDebug() << "POST HANDLING the unsupported...";
        return;
    }

    if (reply->error() != QNetworkReply::NoError)
        return;

    // get reply url...
    KUrl replyUrl = reply->url();

    bool isLocal = replyUrl.isLocalFile();
    if(isLocal && KProtocolInfo::isKnownProtocol(replyUrl))
    {
        kDebug() << "WARNING: launching a new app...";
        new KRun(replyUrl, rApp->mainWindow());  // No need to delete KRun, it autodeletes itself
        return;
    }

    // Get suggested file name...
    extractSuggestedFileName(reply, _suggestedFileName);

    // Get mimeType...
    extractMimeType(reply, _mimeType);

    // Convert executable text files to plain text...
    if (KParts::BrowserRun::isTextExecutable(_mimeType))
        _mimeType = QL1S("text/plain");

    kDebug() << "Detected MimeType = " << _mimeType;
    kDebug() << "Suggested File Name = " << _suggestedFileName;
    // ------------------------------------------------

    KService::Ptr appService = KMimeTypeTrader::self()->preferredService(_mimeType);

    if (appService.isNull())  // no service can handle this. We can just download it..
    {
        kDebug() << "no service can handle this. We can just download it..";

        isLocal
        ? KMessageBox::sorry(view(), i18n("No service can handle this file."))
        : downloadReply(reply, _suggestedFileName);

        return;
    }

    if (!isLocal)
    {
        KParts::BrowserOpenOrSaveQuestion dlg(rApp->mainWindow(), replyUrl, _mimeType);
        if (!_suggestedFileName.isEmpty())
            dlg.setSuggestedFileName(_suggestedFileName);

        switch (dlg.askEmbedOrSave())
        {
        case KParts::BrowserOpenOrSaveQuestion::Save:
            kDebug() << "user choice: no services, just download!";
            downloadReply(reply, _suggestedFileName);
            return;

        case KParts::BrowserOpenOrSaveQuestion::Cancel:
            return;

        default: // non extant case
            break;
        }
    }

    // Handle Post operations that return content...
    if (reply->operation() == QNetworkAccessManager::PostOperation)
    {
        kDebug() << "POST OPERATION: downloading file...";
        QFileInfo finfo(_suggestedFileName.isEmpty() ? _loadingUrl.fileName() : _suggestedFileName);
        KTemporaryFile tempFile;
        tempFile.setSuffix(QL1C('.') + finfo.suffix());
        tempFile.setAutoRemove(false);
        tempFile.open();
        KUrl destUrl;
        destUrl.setPath(tempFile.fileName());
        kDebug() << "First save content to" << destUrl;
        KIO::Job *job = KIO::file_copy(_loadingUrl, destUrl, 0600, KIO::Overwrite);
        job->ui()->setWindow(rApp->mainWindow());
        connect(job, SIGNAL(result(KJob *)), this, SLOT(copyToTempFileResult(KJob*)));
        return;
    }
void TodoPlugin::processDropEvent( QDropEvent *event )
{
  const QMimeData *md = event->mimeData();

  if ( KABC::VCardDrag::canDecode( md ) ) {
    KABC::Addressee::List contacts;

    KABC::VCardDrag::fromMimeData( md, contacts );

    KABC::Addressee::List::Iterator it;

    QStringList attendees;
    for ( it = contacts.begin(); it != contacts.end(); ++it ) {
      QString email = (*it).fullEmail();
      if ( email.isEmpty() ) {
        attendees.append( (*it).realName() + "<>" );
      } else {
        attendees.append( email );
      }
    }

    interface()->openTodoEditor( i18nc( "@item", "Meeting" ),
                                 QString(), QStringList(), attendees );
    return;
  }

  if ( KCalUtils::ICalDrag::canDecode( event->mimeData() ) ) {
    KCalCore::MemoryCalendar::Ptr cal( new KCalCore::MemoryCalendar( KSystemTimeZones::local() ) );
    if ( KCalUtils::ICalDrag::fromMimeData( event->mimeData(), cal ) ) {
      KCalCore::Incidence::List incidences = cal->incidences();
      Q_ASSERT( incidences.count() );
      if ( !incidences.isEmpty() ) {
        event->accept();
        KCalCore::Incidence::Ptr i = incidences.first();
        QString summary;
        if ( i->type() == KCalCore::Incidence::TypeJournal ) {
          summary = i18nc( "@item", "Note: %1", i->summary() );
        } else {
          summary = i->summary();
        }
        interface()->openTodoEditor( summary, i->description(), QStringList() );
        return;
      }
      // else fall through to text decoding
    }
  }

  if ( md->hasText() ) {
    QString text = md->text();
    interface()->openTodoEditor( text );
    return;
  }

  if ( KPIM::MailList::canDecode( md ) ) {
    KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
    event->accept();
    if ( mails.count() != 1 ) {
      KMessageBox::sorry(
        core(),
        i18nc( "@info", "Dropping multiple mails is not supported." ) );
    } else {
      KPIM::MailSummary mail = mails.first();
      QString txt = i18nc( "@item", "From: %1\nTo: %2\nSubject: %3",
                           mail.from(), mail.to(), mail.subject() );
      QString uri = QLatin1String( "kmail:" ) +
                    QString::number( mail.serialNumber() ) + '/' +
                    mail.messageId();
      KTemporaryFile tf;
      tf.setAutoRemove( true );
      tf.write( event->encodedData( "message/rfc822" ) );
      interface()->openTodoEditor(
        i18nc( "@item", "Mail: %1", mail.subject() ),
        txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
      tf.close();
    }
    return;
  }

  kWarning() << QString( "Cannot handle drop events of type '%1'." ).arg( event->format() );
}
Example #23
0
//bool xBaseConnectionInternal::db_connect(QCString host, QCString user,
//  QCString password, unsigned short int port, QString socket)
bool xBaseConnectionInternal::db_connect(const Predicate::ConnectionData& data)
{
  // we have to migrate the xbase source database into a .kexi file
  // xbase source database directory will be in connectiondata
  // we can choose a KTemporaryFile for the destination .kexi file

  KexiMigration::MigrateManager xBase2KexiMigrateManager;

  // create a temporary .kexi file
  KTemporaryFile temporaryKexiFile;
  temporaryKexiFile.setSuffix( ".kexi" );
  temporaryKexiFile.setAutoRemove( false );

  if ( !temporaryKexiFile.open() ) {
    PreDrvDbg<<"Couldn't create .kexi file for exporting from xBase to .kexi";
    return false;
  }

        tempDatabase = temporaryKexiFile.fileName();

  Predicate::ConnectionData* kexiConnectionData = 0;
  kexiConnectionData = new Predicate::ConnectionData();

  // set destination file name here.
  kexiConnectionData->driverName = Predicate::defaultFileBasedDriverName();
  kexiConnectionData->setFileName( tempDatabase );
  PreDrvDbg << "Current file name: " << tempDatabase;


  QString sourceDriverName = "xbase";
  // get the source migration driver
  KexiMigration::KexiMigrate* sourceDriver = 0;
  sourceDriver = xBase2KexiMigrateManager.driver( sourceDriverName );
  if(!sourceDriver || xBase2KexiMigrateManager.error()) {
    PreDrvDbg << "Import migrate driver error...";
    return false;
  }

  KexiMigration::Data* md = new KexiMigration::Data();
  md->keepData = true;
  md->destination = new KexiProjectData(*kexiConnectionData, tempDatabase);

  // Setup XBase connection data from input connection data passed
  //! TODO Check sanity of this
  md->source = new Predicate::ConnectionData(data);
  md->sourceName = "";

  sourceDriver->setData(md);
  if ( !sourceDriver->performImport() ) {
    PreDrvDbg<<"Import failed";
    return false;
  }

  // finished transferring xBase database into .kexi file

  // Get a driver to the destination database

  if ( internalDriver )
    internalConn = internalDriver->createConnection(*kexiConnectionData);
  else
    return false;

  if (!internalConn || internalDriver->error()) {
    internalDriver->debugError();
    return false;
  }
  if (!internalConn->connect()) {
    internalConn->debugError();
    storeResult();
    return false;
  }

        if (!internalConn->useDatabase(tempDatabase)) {
                internalConn->debugError();
                storeResult();
                return false;
        }

  // store mapping from xbase directory to .kexi file name for future use
  // Note: When a directory is specified ( as has to be done for xBase ), fileName()
  // will give directory name with an additional forward slash. dbPath() won't do so.
  // Need some more maintainable solution.

  dbMap[data.fileName()] = tempDatabase;

  return true;
}
Example #24
0
QString PostscriptDialog::buildTempfile()
{
	// build command
	m_program = "pstops";          // default
	m_param = "";

	switch (m_PostscriptDialog.m_cbTask->currentIndex()) {
		case PS_A5_EMPTY:      m_param = "1:0L(29.7cm,0cm)";
		                       break;
		case PS_A5_DUPLICATE:  m_param = "1:0L(29.7cm,0cm)+0L(29.7cm,14.85cm)";
		                       break;
		case PS_2xA5:          m_param = "2:0L(29.7cm,0cm)+1L(29.7cm,14.85cm)";
		                       break;
		case PS_2xA5L:         break;
		case PS_4xA5:          m_param = "4:[email protected](0cm,8.7cm)"
		                                 "[email protected](10.5cm,8.7cm)"
		                                 "[email protected](0cm,-6.15cm)"
		                                 "[email protected](10.5cm,-6.15cm)";
		                       break;
		case PS_A4_EMPTY:      m_param = "1:[email protected](21cm,0cm)";
		                       break;
		case PS_A4_DUPLICATE:  m_param = "1:[email protected](21cm,0cm)[email protected](21cm,14.85cm)";
		                       break;
		case PS_2xA4:          m_param = "2:[email protected](21cm,0cm)[email protected](21cm,14.85cm)";
		                       break;
		case PS_2xA4L:         m_param = "2:[email protected](0cm,29.7cm)[email protected](0cm,14.85cm)";
		                       break;
		case PS_EVEN:          m_program = "psselect";
		                       m_param = "-e";
		                       break;
		case PS_ODD:           m_program = "psselect";
		                       m_param = "-o";
		                       break;
		case PS_EVEN_REV:      m_program = "psselect";
		                       m_param = "-e -r";
		                       break;
		case PS_ODD_REV:       m_program = "psselect";
		                       m_param = "-o -r";
		                       break;
		case PS_REVERSE:       m_program = "psselect";
		                       m_param = "-r";
		                       break;
		case PS_COPY_SORTED:   m_program = "psselect";
		                       m_param = "-p" + duplicateParameter("1-");
		                       break;
		case PS_COPY_UNSORTED: m_param = "1:" + duplicateParameter("0");
		                       break;
		case PS_PSTOPS_FREE:   m_param = m_PostscriptDialog.m_edParameter->text();
		                       break;
		case PS_PSSELECT_FREE: m_program = "psselect";
		                       m_param = m_PostscriptDialog.m_edParameter->text();
		                       break;
	}

	// create a temporary file
	KTemporaryFile temp;
	temp.setSuffix(".sh");
	temp.setAutoRemove(false);
	if(!temp.open()) {
		KILE_DEBUG() << "Could not create tempfile in QString PostscriptDialog::buildTempfile()" ;
		return QString();
	}
	QString tempname = temp.fileName();
	
	QTextStream stream(&temp);
	stream << "#! /bin/sh" << endl;

	// accept only ".ps" or ".ps.gz" as an input file
	QFileInfo fi(m_PostscriptDialog.m_edInfile->lineEdit()->text());
	bool zipped_psfile = (fi.completeSuffix() == "ps.gz") ? true : false;

	// there are four possible cases
	//         outfile view
	//     1)    +      +        pstops/psselect + okular
	//     2)    +      -        pstops/psselect
	//     3)    -      +        pstops/psselect | okular (nur Shell)
	//     4)    -      -        error (already detected by checkParameter())

	// some files, which are used
	QString command    = m_program + " \"" + m_param + "\"";
	QString inputfile  = "\"" + m_PostscriptDialog.m_edInfile->lineEdit()->text() + "\"";
	QString outputfile = "\"" + m_PostscriptDialog.m_edOutfile->lineEdit()->text() + "\"";
	bool viewer = m_PostscriptDialog.m_cbView->isChecked();
	
	bool equalfiles = false;
	if (inputfile == outputfile) {
		outputfile = tempname + ".tmp";
		equalfiles = true;
	}
	
	if (!zipped_psfile) {                                       // unzipped ps files
		if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular
			stream << command << " " << inputfile << " | okular -" << endl;
			viewer = false;
		} else {                                                    // pstops/psselect
			stream << command << " " << inputfile << " " << outputfile << endl;
		}
	} else {                                                      // zipped ps files
		if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular
			stream << "gunzip -c " << inputfile
			       << " | " << command
			       << " | okular -"
			       << endl;
			viewer = false;
		} else {
			stream << "gunzip -c " << inputfile                    // pstops/psselect
			       << " | " << command
			       << " > " << outputfile
			       << endl;
		}
	}

	// check, if we should stop
	if ( equalfiles || viewer ) {
		stream << "if [ $? != 0 ]; then" << endl;
		stream << "   exit 1" << endl;
		stream << "fi" << endl;
	}

	// replace the original file
	if ( equalfiles ) {
		stream << "rm " << inputfile << endl;
		stream << "mv " << outputfile << " " << inputfile << endl;
	}

	// viewer
	if ( viewer ) {                                                // viewer: okular
		stream << "okular" << " " 
		       << ((equalfiles) ? inputfile : outputfile) << endl;
	}

	// everything is prepared to do the job
	temp.close();

	return(tempname);
}