void KMoneyThingMainWidget::slotSave()
{
  KTempFile temp;
  QString fileName = mCurrentFile->kurl().path();
  
  if (fileName == "")
  {
    slotSaveAs();
    return;
  }
  
  if (!mCurrentFile->kurl().isLocalFile())
  {
    fileName = temp.name();
  }
  
  emit(setStatus(i18n("Saving file...")));
  QByteArray dump = qCompress(mCurrentFile->dump());
  QFile file(fileName);
  file.open(IO_WriteOnly);
  QDataStream stream(&file);
  stream << (QString) "KMoneyThingFile" << dump;
  file.close();
  
  if (!mCurrentFile->kurl().isLocalFile())
  {
    emit(setStatus(i18n("Uploading file...")));
    if (!KIO::NetAccess::upload(fileName, mCurrentFile->kurl(), this))
      KMessageBox::error(this, i18n("Failed to upload file."));
  }
  
  temp.unlink();
  
  emit(setStatus(i18n("Ready.")));
}
Beispiel #2
0
void KJumpingCube::saveGame(bool saveAs)
{
   if(saveAs || gameURL.isEmpty())
   {
      int result=0;
      KURL url;

      do
      {
         url = KFileDialog::getSaveURL(gameURL.url(),"*.kjc",this,0);

         if(url.isEmpty())
            return;

         // check filename
         QRegExp pattern("*.kjc",true,true);
         if(!pattern.exactMatch(url.filename()))
         {
            url.setFileName( url.filename()+".kjc" );
         }

         if(KIO::NetAccess::exists(url,false,this))
         {
            QString mes=i18n("The file %1 exists.\n"
               "Do you want to overwrite it?").arg(url.url());
            result = KMessageBox::warningContinueCancel(this, mes, QString::null, i18n("Overwrite"));
            if(result==KMessageBox::Cancel)
               return;
         }
      }
      while(result==KMessageBox::No);

      gameURL=url;
   }

   KTempFile tempFile;
   tempFile.setAutoDelete(true);
   KSimpleConfig config(tempFile.name());

   config.setGroup("KJumpingCube");
   config.writeEntry("Version",KJC_VERSION);
   config.setGroup("Game");
   view->saveGame(&config);
   config.sync();

   if(KIO::NetAccess::upload( tempFile.name(),gameURL,this ))
   {
      QString s=i18n("game saved as %1");
      s=s.arg(gameURL.url());
      statusBar()->message(s,MESSAGE_TIME);
   }
   else
   {
      KMessageBox::sorry(this,i18n("There was an error in saving file\n%1").arg(gameURL.url()));
   }
}
Beispiel #3
0
// The finaly step: write _data to tempfile and move it to neW_url
static KIO::CopyJob *pasteDataAsyncTo(const KURL &new_url, const QByteArray &_data)
{
    KTempFile tempFile;
    tempFile.dataStream()->writeRawBytes(_data.data(), _data.size());
    tempFile.close();

    KURL orig_url;
    orig_url.setPath(tempFile.name());

    return KIO::move(orig_url, new_url);
}
Beispiel #4
0
void KOrganizerPlugin::processDropEvent( QDropEvent *event )
{
  QString text;

  KABC::VCardConverter converter;
  if ( KVCardDrag::canDecode( event ) && KVCardDrag::decode( event, text ) ) {
    KABC::Addressee::List contacts = converter.parseVCards( text );
    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()->openEventEditor( i18n( "Meeting" ), QString::null, QString::null,
                                  attendees );
    return;
  }

  if ( QTextDrag::decode( event, text ) ) {
    kdDebug(5602) << "DROP:" << text << endl;
    interface()->openEventEditor( text );
    return;
  }

  KPIM::MailList mails;
  if ( KPIM::MailListDrag::decode( event, mails ) ) {
    if ( mails.count() != 1 ) {
      KMessageBox::sorry( core(),
                          i18n("Drops of multiple mails are not supported." ) );
    } else {
      KPIM::MailSummary mail = mails.first();
      QString txt = i18n("From: %1\nTo: %2\nSubject: %3").arg( mail.from() )
                    .arg( mail.to() ).arg( mail.subject() );

      KTempFile tf;
      tf.setAutoDelete( true );
      QString uri = QString::fromLatin1("kmail:") + QString::number( mail.serialNumber() );
      tf.file()->writeBlock( event->encodedData( "message/rfc822" ) );
      tf.close();
      interface()->openEventEditor( i18n("Mail: %1").arg( mail.subject() ), txt,
                                    uri, tf.name(), QStringList(), "message/rfc822" );
    }
    return;
  }

  KMessageBox::sorry( core(), i18n("Cannot handle drop events of type '%1'.")
                              .arg( event->format() ) );
}
Beispiel #5
0
void SVNHandler::processDiff( QString output )
{
  output.remove( QRegExp( "\\[ .* \\]$" ));
  output.remove( QRegExp( "^" + i18n("[ Starting command ]" ).replace("[","\\[").replace("]","\\]")));

  KTempFile tmpFile;
  *(tmpFile.textStream()) << output;
  tmpFile.close();

  QString error;
  if ( KApplication::startServiceByName( "Kompare", tmpFile.name(), &error ) )
    KMessageBox::error( 0, error );
}
Beispiel #6
0
bool VCardXXPort::doExport( const KURL &url, const QString &data )
{
  KTempFile tmpFile;
  tmpFile.setAutoDelete( true );

  QTextStream stream( tmpFile.file() );
  stream.setEncoding( QTextStream::UnicodeUTF8 );

  stream << data;
  tmpFile.close();

  return KIO::NetAccess::upload( tmpFile.name(), url, parentWidget() );
}
Beispiel #7
0
KIO_EXPORT void KIO::pasteData(const KURL &u, const QByteArray &_data)
{
    KURL new_url = getNewFileName(u, QString::null);
    // We could use KIO::put here, but that would require a class
    // for the slotData call. With NetAccess, we can do a synchronous call.

    if(new_url.isEmpty())
        return;

    KTempFile tempFile;
    tempFile.setAutoDelete(true);
    tempFile.dataStream()->writeRawBytes(_data.data(), _data.size());
    tempFile.close();

    (void)KIO::NetAccess::upload(tempFile.name(), new_url, 0);
}
Beispiel #8
0
TarArch::TarArch( ArkWidget *_gui,
                  const QString & _filename, const QString & _openAsMimeType)
  : Arch( _gui, _filename), m_tmpDir( 0 ), createTmpInProgress(false),
    updateInProgress(false), deleteInProgress(false), fd(0),
    m_pTmpProc( 0 ), m_pTmpProc2( 0 ), failed( false ), 
    m_dotslash( false ), m_listingThread( 0 )
{
    m_filesToAdd = m_filesToRemove = QStringList();
    m_archiver_program = m_unarchiver_program = ArkSettings::tarExe();
    verifyCompressUtilityIsAvailable( m_archiver_program );
    verifyUncompressUtilityIsAvailable( m_unarchiver_program );

    m_fileMimeType = _openAsMimeType;
    if ( m_fileMimeType.isNull() )
        m_fileMimeType = KMimeType::findByPath( _filename )->name();

    kdDebug(1601) << "TarArch::TarArch:  mimetype is " << m_fileMimeType << endl;

    if ( m_fileMimeType == "application/x-tbz2" )
    {
        // ark treats .tar.bz2 as x-tbz, instead of duplicating the mimetype
        // let's just alias it to the one we already handle.
        m_fileMimeType = "application/x-tbz";
    }

    if ( m_fileMimeType == "application/x-tar" )
    {
        compressed = false;
    }
    else
    {
        compressed = true;
        m_tmpDir = new KTempDir( _gui->tmpDir()
                                 + QString::fromLatin1( "temp_tar" ) );
        m_tmpDir->setAutoDelete( true );
        m_tmpDir->qDir()->cd( m_tmpDir->name() );
        // build the temp file name
        KTempFile *pTempFile = new KTempFile( m_tmpDir->name(),
                QString::fromLatin1(".tar") );

        tmpfile = pTempFile->name();
        delete pTempFile;

        kdDebug(1601) << "Tmpfile will be " << tmpfile << "\n" << endl;
    }
}
Beispiel #9
0
void KPrWebPresentation::createMainPage( KProgress *progressBar )
{
    QTextCodec *codec = KGlobal::charsets()->codecForName( m_encoding );
    KTempFile tmp;
    QString dest = QString( "%1/index.html" ).arg( path );
    QFile file( tmp.name() );
    file.open( IO_WriteOnly );
    QTextStream streamOut( &file );
    streamOut.setCodec( codec );

    writeStartOfHeader( streamOut, codec, i18n("Table of Contents"), QString() );
    streamOut << "</head>\n";

    streamOut << "<body bgcolor=\"" << backColor.name() << "\" text=\"" << textColor.name() << "\">\n";

    streamOut << "<h1 align=\"center\"><font color=\"" << titleColor.name()
              << "\">" << title << "</font></h1>";

    streamOut << "<p align=\"center\"><a href=\"html/slide_1.html\">";
    streamOut << i18n("Click here to start the Slideshow");
    streamOut << "</a></p>\n";

    streamOut << "<p><b>" << i18n("Table of Contents") << "</b></p>\n";

    // create list of slides (with proper link)
    streamOut << "<ol>\n";
    for ( unsigned int i = 0; i < slideInfos.count(); i++ )
        streamOut << "  <li><a href=\"html/slide_" << i+1 << ".html\">" << slideInfos[ i ].slideTitle << "</a></li>\n";
    streamOut << "</ol>\n";

    // footer: author name, e-mail
    QString htmlAuthor = email.isEmpty() ? escapeHtmlText( codec, author ) :
                         QString("<a href=\"mailto:%1\">%2</a>").arg( escapeHtmlText( codec, email )).arg( escapeHtmlText( codec, author ));
    streamOut << EscapeEncodingOnly ( codec, i18n( "Created on %1 by <i>%2</i> with <a href=\"http://www.koffice.org/kpresenter\">KPresenter</a>" )
                                      .arg( KGlobal::locale()->formatDate ( QDate::currentDate() ) ).arg( htmlAuthor ) );

    streamOut << "</body>\n</html>\n";
    file.close();

    KIO::NetAccess::file_move( tmp.name(), dest, -1, true /*overwrite*/);


    progressBar->setProgress( progressBar->totalSteps() );
    kapp->processEvents();
}
Beispiel #10
0
QString copyfile(const QString &filename)
{
    kdDebug(500) << "Copying file " << filename << endl;
    QString result;
    QFile f(filename);
    if(f.open(IO_ReadOnly))
    {
        KTempFile temp;
        temp.setAutoDelete(false);
        QFile *tf = temp.file();
        if(tf)
        {
            char buffer[0xFFFF];
            int b = 0;
            while((b = f.readBlock(buffer, 0xFFFF)) > 0)
            {
                if(tf->writeBlock(buffer, b) != b)
                    break;
            }
            tf->close();
            if(b > 0)
                temp.setAutoDelete(true);
            else
            {
                kdDebug(500) << "File copied to " << temp.name() << endl;
                result = temp.name();
            }
        }
        else
            temp.setAutoDelete(true);
        f.close();
    }
    return result;
}
Beispiel #11
0
bool SambaFile::load()
{
  if (path.isNull() || path.isEmpty())
      return false;
      
  kdDebug(FILESHARE_DEBUG) << "SambaFile::load: path=" << path << endl;
  KURL url(path);

  if (!url.isLocalFile()) {
    KTempFile tempFile;
    localPath = tempFile.name();
    KURL destURL;
    destURL.setPath( localPath );
    KIO::FileCopyJob * job =  KIO::file_copy( url, destURL, 0600, true, false, true );
//    emit started( d->m_job );
    connect( job, SIGNAL( result( KIO::Job * ) ), this, SLOT( slotJobFinished ( KIO::Job * ) ) );
    return true;
  } else {
Beispiel #12
0
bool KMiniEdit::saveFile(KURL newurl)
{
  if (newurl.isEmpty())
    newurl = KFileDialog::getSaveURL();

  if (newurl.isEmpty())
    return false;

  if (newurl.isMalformed())
  {
    QString text = i18n("<b>THe URL %1 is not correct!</b>");
    KMessageBox::sorry(this, text.arg(newurl.prettyURL()));
    return false;
  }

  if (newurl.isLocalFile())
  {
    QFile file(newurl.path());
    file.open(IO_WriteOnly);
    saveToLocalFile(&file);
  }

  else
  {
    KTempFile tempfile;
    saveToLocalFile(tempfile.file());
    if (!KIO::NetAccess::upload(tempfile.name(), newurl))
    {
      QString text = i18n("<b>Error uploading %1!</b>");
      KMessageBox::sorry(this, text.arg(newurl.prettyURL()));
      tempfile.unlink();
      return false;
    }

    tempfile.unlink();
  }

  url = newurl;
  
  addURLtoRecent();
  
  resetEdited();
  return true;
}
Beispiel #13
0
void ImageLabel::setValue(QString fn)
{
  // use the first line
  QStringList sList = QStringList::split( "\n", fn );
  QString fileName = *sList.begin();
  KURL url(fileName);
  QRegExp rx("^[a-zA-Z]{1,5}:/",false);
  bool protocol = (rx.search(fileName)!=-1)?true:false;
  QPixmap pm;

  if(protocol && url.isLocalFile() == false)
  {
    KTempFile tmpFile;
    KIO::FileCopyJob* copy = KIO::file_copy(fileName, tmpFile.name(), 0600,
                                            true, false, false);
    connect(copy, SIGNAL(result(KIO::Job*)),
            this, SLOT(slotCopyResult(KIO::Job*)));
    return;
  }
Beispiel #14
0
void PreviewJob::getOrCreateThumbnail()
{
    // We still need to load the orig file ! (This is getting tedious) :)
    const KFileItem* item = d->currentItem.item;
    const TQString localPath = item->localPath();
    if ( !localPath.isEmpty() )
        createThumbnail( localPath );
    else
    {
        d->state = PreviewJobPrivate::STATE_GETORIG;
        KTempFile localFile;
        KURL localURL;
        localURL.setPath( d->tempName = localFile.name() );
        const KURL currentURL = item->url();
        TDEIO::Job * job = TDEIO::file_copy( currentURL, localURL, -1, true,
                                         false, false /* No GUI */ );
        job->addMetaData("thumbnail","1");
        addSubjob(job);
    }
}
Beispiel #15
0
bool GMXXXPort::exportContacts( const KABC::AddresseeList &list, const QString& )
{
  KURL url = KFileDialog::getSaveURL( ":xxport_gmx", GMX_FILESELECTION_STRING );
  if ( url.isEmpty() )
      return true;

  if ( !url.isLocalFile() ) {
    KTempFile tmpFile;
    if ( tmpFile.status() != 0 ) {
      QString txt = i18n( "<qt>Unable to open file <b>%1</b>.%2.</qt>" );
      KMessageBox::error( parentWidget(), txt.arg( url.url() )
                          .arg( strerror( tmpFile.status() ) ) );
      return false;
    }

    doExport( tmpFile.file(), list );
    tmpFile.close();

    return KIO::NetAccess::upload( tmpFile.name(), url, parentWidget() );
  } else {
    QString filename = url.path();
    QFile file( filename );

    if ( !file.open( IO_WriteOnly ) ) {
      QString txt = i18n( "<qt>Unable to open file <b>%1</b>.</qt>" );
      KMessageBox::error( parentWidget(), txt.arg( filename ) );
      return false;
    }

    doExport( &file, list );
    file.close();

    return true;
  }
}
Beispiel #16
0
void KPrWebPresentation::createSlidesPictures( KProgress *progressBar )
{
    if ( slideInfos.isEmpty() )
        return;
    QPixmap pix( 10, 10 );
    QString filename;
    int p;
    for ( unsigned int i = 0; i < slideInfos.count(); i++ ) {
        int pgNum = slideInfos[i].pageNumber;
        view->getCanvas()->drawPageInPix( pix, pgNum, zoom, true /*force real variable value*/ );
        filename = QString( "%1/pics/slide_%2.png" ).arg( path ).arg( i + 1 );

        KTempFile tmp;
        pix.save( tmp.name(), "PNG" );

        KIO::NetAccess::file_move( tmp.name(), filename, -1, true /*overwrite*/);

        p = progressBar->progress();
        progressBar->setProgress( ++p );
        kapp->processEvents();
    }
}
Beispiel #17
0
void KPrMSPresentation::createSlidesPictures( KProgress *progressBar )
{
    if ( slideInfos.isEmpty() )
        return;
    QString filename;
    int p;
    for ( unsigned int i = 0; i < slideInfos.count(); i++ ) {
        int pgNum = slideInfos[i].pageNumber;
        filename.sprintf("/SPJP%04i.JPG", i+3);

        KTempFile tmp;

        view->getCanvas()->exportPage( pgNum, 1023, 767,
                                       tmp.name(), "JPEG" );

        KIO::NetAccess::file_move( tmp.name(), ( path + slidePath + filename ), -1, true /*overwrite*/);

        p = progressBar->progress();
        progressBar->setProgress( ++p );
        kapp->processEvents();
    }
}
Beispiel #18
0
void KgpgApp::slotFileSave()
{
    TQString filn=Docname.path();
    if (filn.isEmpty()) {
    	slotFileSaveAs();
    	return;
    }
    TQTextCodec*cod=TQTextCodec::codecForName (textEncoding.ascii());
        // slotStatusMsg(i18n("Saving file..."));
    if (!checkEncoding(cod)) {
	KMessageBox::sorry(this,i18n("The document could not been saved, as the selected encoding cannot encode every unicode character in it."));
	return;
    }

    KTempFile tmpfile;
    if (Docname.isLocalFile()) {
    TQFile f(filn);
    if ( !f.open( IO_WriteOnly ) ) {
	KMessageBox::sorry(this,i18n("The document could not be saved, please check your permissions and disk space."));
        return;
    }
    TQTextStream t( &f );
    t.setCodec(cod);
    //t.setEncoding( TQTextStream::Latin1 );
    t << view->editor->text();//.utf8();
    f.close();
    }
    else {
	/*FIXME  use following code:
	 TQFile f( fName );
00983         if ( !f.open( IO_ReadOnly ) )
00984             return;
00985         TQFileInfo info ( f );
00986         smModificationTime = new TQTime( info.lastModified().time() );
00987         TQTextStream t(&f);
00988         t.setEncoding( TQTextStream::Latin1 );
00989         TQString s = t.readLine();
00990         f.close();

*/
	TQTextStream *stream = tmpfile.textStream();
	stream->setCodec(cod);
    	*stream << view->editor->text();//.utf8();
   	tmpfile.close();
	if(!TDEIO::NetAccess::upload(tmpfile.name(), Docname,this)) {
	    KMessageBox::sorry(this,i18n("The document could not be saved, please check your permissions and disk space."));
	    tmpfile.unlink();
            return;
	}
	tmpfile.unlink();
    }

    fileSave->setEnabled(false);
    setCaption(Docname.fileName(),false);
}
Beispiel #19
0
bool KSnapshot::save( const KURL& url )
{
    if ( KIO::NetAccess::exists( url, false, this ) ) {
        const QString title = i18n( "File Exists" );
        const QString text = i18n( "<qt>Do you really want to overwrite <b>%1</b>?</qt>" ).arg(url.prettyURL());
        if (KMessageBox::Continue != KMessageBox::warningContinueCancel( this, text, title, i18n("Overwrite") ) ) 
        {
            return false;
        }
    }

    QString type( KImageIO::type(url.path()) );
    if ( type.isNull() )
	type = "PNG";

    bool ok = false;

    if ( url.isLocalFile() ) {
	KSaveFile saveFile( url.path() );
	if ( saveFile.status() == 0 ) {
	    if ( snapshot.save( saveFile.file(), type.latin1() ) )
		ok = saveFile.close();
	}
    }
    else {
	KTempFile tmpFile;
        tmpFile.setAutoDelete( true );
	if ( tmpFile.status() == 0 ) {
	    if ( snapshot.save( tmpFile.file(), type.latin1() ) ) {
		if ( tmpFile.close() )
		    ok = KIO::NetAccess::upload( tmpFile.name(), url, this );
	    }
	}
    }

    QApplication::restoreOverrideCursor();
    if ( !ok ) {
	kdWarning() << "KSnapshot was unable to save the snapshot" << endl;

	QString caption = i18n("Unable to save image");
	QString text = i18n("KSnapshot was unable to save the image to\n%1.")
	               .arg(url.prettyURL());
	KMessageBox::error(this, text, caption);
    }

    return ok;
}
Beispiel #20
0
bool KSnapshot::save( const KURL& url )
{
    QString type( KImageIO::type(url.path()) );
    if ( type.isNull() )
        type = "PNG";

    bool ok = false;

    if ( url.isLocalFile() ) {
        KSaveFile saveFile( url.path() );
        if ( saveFile.status() == 0 ) {
            if ( snapshot.save( saveFile.file(), type.latin1() ) )
                ok = saveFile.close();
        }
    }
    else {
        KTempFile tmpFile;
        tmpFile.setAutoDelete( true );
        if ( tmpFile.status() == 0 ) {
            if ( snapshot.save( tmpFile.file(), type.latin1() ) ) {
                if ( tmpFile.close() )
                    ok = KIO::NetAccess::upload( tmpFile.name(), url, this );
            }
        }
    }

    QApplication::restoreOverrideCursor();
    if ( !ok ) {
        kdWarning() << "KSnapshot was unable to save the snapshot" << endl;

        QString caption = i18n("Unable to Save Image");
        QString text = i18n("KSnapshot was unable to save the image to\n%1.")
            .arg(url.prettyURL());
        KMessageBox::error(this, text, caption);
    }

    return ok;
}
bool Q3DGraph::save(const KURL& url)
{
	if ( KIO::NetAccess::exists( url, false, this ) ) //The file already exist
		return false;

	QString type(KImageIO::type(url.path()));
	if (type.isNull())
		type = "PNG";

	bool ok = false;

	if(url.isLocalFile()) {
		KSaveFile saveFile(url.path());
		if ( saveFile.status() == 0 ) {
			if (toPixmap().save( saveFile.file(), type.latin1() ) )
				ok = saveFile.close();
		}
	} else {
		KTempFile tmpFile;
		tmpFile.setAutoDelete(true);
		if(tmpFile.status()==0) {
			if(toPixmap().save( tmpFile.file(), type.latin1())) {
				if(tmpFile.close())
					ok = KIO::NetAccess::upload( tmpFile.name(), url, this );
			}
		}
	}
	
//	QApplication::restoreOverrideCursor();
	
	if (!ok) {
		qDebug("Was unable to save it");
	}

	return ok;
}
Beispiel #22
0
void KPrMSPresentation::createIndexFile( KProgress *progressBar )
{
    int p;
    KTempFile sppFile;

    QString filenameStore = (path + "/MSSONY/PJ/" + title + ".SPP");

    QDataStream sppStream( sppFile.file() );
    sppStream.setByteOrder(QDataStream::LittleEndian);
    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    // We are doing little endian
    sppStream << (Q_UINT32)0x00505053; // SPP magic header
    sppStream << (Q_UINT32)0x00000000; // four null bytes
    sppStream << (Q_UINT32)0x30303130; // version(?) 0100
    sppStream << (Q_UINT32)0x00000000; // more nulls
    sppStream << (Q_UINT32)(slideInfos.count());

    // DCIM path 1, 68 bytes null padded
    char buff[68];
    strncpy( buff, QString("%1").arg(slidePath).ascii(), 67 );
    buff[67] = 0x00;
    sppStream.writeRawBytes( buff, 68 );
    sppStream << (Q_UINT32)0x00000001; // fixed value
    sppStream << (Q_UINT32)0x00000005; // fixed value
    sppStream << (Q_UINT32)0x00000000; // more nulls
    sppStream << (Q_UINT32)0x00000000; // more nulls
    sppStream << (Q_UINT32)0x00000000; // more nulls
    sppStream << (Q_UINT32)0x00000000; // more nulls
    sppStream << (Q_UINT32)0x00000000; // more nulls
    sppStream << (Q_UINT32)0x00000000; // more nulls
    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    // title 1, 16 bytes null padded
    strncpy( buff, "SPJT0001.JPG", 15 );
    buff[15] = 0x00;
    sppStream.writeRawBytes( buff, 16 );

    // title 2, 16 bytes null padded
    strncpy( buff, "SPJT0002.JPG", 15 );
    buff[15] = 0x00;
    sppStream.writeRawBytes( buff, 16 );


    // type face (?), 44 bytes null padded
    strncpy( buff, "MS Sans Serif", 43 );
    buff[44] = 0x00;
    sppStream.writeRawBytes( buff, 44 );

    //not really sure what this is about
    sppStream << (Q_UINT32)0xffff0000;
    sppStream << (Q_UINT32)0xffff00ff;
    sppStream << (Q_UINT32)0xffff00ff;
    sppStream << (Q_UINT32)0x000000ff;
    sppStream << (Q_UINT32)0x00000002;
    for (int i = 0; i < (296/4); i++) {
        sppStream << (Q_UINT32)0x00000000;
    }
    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    // Add in the slide filenames
    QString filename;
    for ( unsigned int i = 0; i < slideInfos.count(); i++ ) {
        filename.sprintf("SPJP%04i.JPG", i+3);
        strncpy( buff, filename.ascii(), 63 );
        buff[64] = 0x00;
        sppStream.writeRawBytes( buff, 64 );
        p = progressBar->progress();
        progressBar->setProgress( ++p );
        kapp->processEvents();
    }

    // OK, now we need to fill to 16384 bytes
    // the logic is 16384 bytes total, lead in is 512 bytes, and there
    // is 64 bytes for each real slide
    for(unsigned int i = 0;  i < (16384-512-64*(slideInfos.count()))/4; i++) {
        sppStream << (Q_UINT32)0x00000000;
    }

    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    sppFile.close();
    KIO::NetAccess::file_move( sppFile.name(), filenameStore, -1, true /*overwrite*/);
}
Beispiel #23
0
void EventArchiver::archiveIncidences( Calendar* calendar, const QDate& /*limitDate*/, QWidget* widget, const Incidence::List& incidences, bool /*withGUI*/)
{
  FileStorage storage( calendar );

  // Save current calendar to disk
  KTempFile tmpFile;
  tmpFile.setAutoDelete(true);
  storage.setFileName( tmpFile.name() );
  if ( !storage.save() ) {
    kdDebug(5850) << "EventArchiver::archiveEvents(): Can't save calendar to temp file" << endl;
    return;
  }

  // Duplicate current calendar by loading in new calendar object
  CalendarLocal archiveCalendar( KOPrefs::instance()->mTimeZoneId );

  FileStorage archiveStore( &archiveCalendar );
  archiveStore.setFileName( tmpFile.name() );
  if (!archiveStore.load()) {
    kdDebug(5850) << "EventArchiver::archiveEvents(): Can't load calendar from temp file" << endl;
    return;
  }

  // Strip active events from calendar so that only events to be archived
  // remain. This is not really efficient, but there is no other easy way.
  QStringList uids;
  Incidence::List allIncidences = archiveCalendar.rawIncidences();
  Incidence::List::ConstIterator it;
  for( it = incidences.begin(); it != incidences.end(); ++it ) {
    uids << (*it)->uid();
  }
  for( it = allIncidences.begin(); it != allIncidences.end(); ++it ) {
    if ( !uids.contains( (*it)->uid() ) ) {
      archiveCalendar.deleteIncidence( *it );
    }
  }

  // Get or create the archive file
  KURL archiveURL( KOPrefs::instance()->mArchiveFile );
  QString archiveFile;

  if ( KIO::NetAccess::exists( archiveURL, true, widget ) ) {
    if( !KIO::NetAccess::download( archiveURL, archiveFile, widget ) ) {
      kdDebug(5850) << "EventArchiver::archiveEvents(): Can't download archive file" << endl;
      return;
    }
    // Merge with events to be archived.
    archiveStore.setFileName( archiveFile );
    if ( !archiveStore.load() ) {
      kdDebug(5850) << "EventArchiver::archiveEvents(): Can't merge with archive file" << endl;
      return;
    }
  } else {
    archiveFile = tmpFile.name();
  }

  // Save archive calendar
  if ( !archiveStore.save() ) {
    KMessageBox::error(widget,i18n("Cannot write archive file %1.").arg( archiveStore.fileName() ));
    return;
  }

  // Upload if necessary
  KURL srcUrl;
  srcUrl.setPath(archiveFile);
  if (srcUrl != archiveURL) {
    if ( !KIO::NetAccess::upload( archiveFile, archiveURL, widget ) ) {
      KMessageBox::error(widget,i18n("Cannot write archive to final destination."));
      return;
    }
  }

  KIO::NetAccess::removeTempFile(archiveFile);

  // Delete archived events from calendar
  for( it = incidences.begin(); it != incidences.end(); ++it ) {
    calendar->deleteIncidence( *it );
  }
  emit eventsDeleted();
}
Beispiel #24
0
void KSANEOCR::startOCRAD( )
{
    ocradDialog *ocrDia = static_cast<ocradDialog*>(m_ocrProcessDia);

    m_ocrResultImage = ocrDia->orfUrl();
    const QString cmd = ocrDia->getOCRCmd();

    // if( m_ocrResultImage.isEmpty() )
    {
	/* The url is empty. Start the program to fill up a temp file */
	m_ocrResultImage = ImgSaver::tempSaveImage( m_img, "BMP", 8 ); // m_tmpFile->name();
	kdDebug(28000) << "The new image name is <" << m_ocrResultImage << ">" << endl;
    }

    m_ocrImagePBM = ImgSaver::tempSaveImage( m_img, "PBM", 1 );

    /* temporar file for orf result */
    KTempFile *tmpOrf = new KTempFile( QString(), ".orf" );
    tmpOrf->setAutoDelete( false );
    tmpOrf->close();
    m_tmpOrfName = QFile::encodeName(tmpOrf->name());


    if( daemon )
    {
	delete( daemon );
	daemon = 0;
    }

    daemon = new KProcess;
    Q_CHECK_PTR(daemon);

    *daemon << cmd;
    *daemon << QString("-x");
    *daemon <<  m_tmpOrfName;                   // the orf result file
    *daemon << QFile::encodeName( m_ocrImagePBM );      // The name of the image
    *daemon << QString("-l");
    *daemon << QString::number( ocrDia->layoutDetectionMode());

    KConfig *konf = KGlobal::config ();
    KConfigGroupSaver( konf, CFG_GROUP_OCRAD );

    QString format = konf->readEntry( CFG_OCRAD_FORMAT, "utf8");
    *daemon << QString("-F");
    *daemon << format;

    QString charset = konf->readEntry( CFG_OCRAD_CHARSET, "iso-8859-15");
    *daemon << QString("-c");
    *daemon << charset;


    QString addArgs = konf->readEntry( CFG_OCRAD_EXTRA_ARGUMENTS, QString() );

    if( !addArgs.isEmpty() )
    {
	kdDebug(28000) << "Setting additional args from config for ocrad: " << addArgs << endl;
	*daemon << addArgs;
    }

    m_ocrResultText = "";

    connect(daemon, SIGNAL(processExited(KProcess *)),
	    this,   SLOT(  ocradExited(KProcess*)));
    connect(daemon, SIGNAL(receivedStdout(KProcess *, char*, int)),
	    this,   SLOT(  ocradStdIn(KProcess*, char*, int)));
    connect(daemon, SIGNAL(receivedStderr(KProcess *, char*, int)),
	    this,   SLOT(  ocradStdErr(KProcess*, char*, int)));

    if (!daemon->start(KProcess::NotifyOnExit, KProcess::All))
    {
	kdDebug(28000) <<  "Error starting ocrad-daemon!" << endl;
    }
    else
    {
	kdDebug(28000) << "Start OK" << endl;

    }
    delete tmpOrf;
}
Beispiel #25
0
KdeSudo::KdeSudo(QWidget *parent, const char *name,const QString& icon, const QString& generic, bool withIgnoreButton)
	: KPasswordDialog(KPasswordDialog::Password, false, (withIgnoreButton ? User1: false), icon, parent, name)
{
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	QString defaultComment = i18n("<b>%1</b> needs administrative privileges. Please enter your password for verification.");
	p=NULL;
	bError=false;

	m_pCookie = new KCookie;

	// Set vars
	bool newDcop = args->isSet("newdcop");
	bool realtime = args->isSet("r");
	bool priority = args->isSet("p");
	bool showCommand = (!args->isSet("d"));
	bool changeUID = true;
	bool noExec = false;
	keepPwd = (!args->isSet("n"));
	emptyPwd = args->isSet("s");
	QString runas = args->getOption("u");
	QString cmd;

	if (!args->isSet("c") && !args->count() && (!args->isSet("s")))
	{
		KMessageBox::information(NULL, i18n("No command arguments supplied!\nUsage: kdesudo [-u <runas>] <command>\nKdeSudo will now exit..."));
		noExec = true;
	}

	p = new KProcess;
	p->clearArguments();

	// Parsins args

	/* Get the comment out of cli args */
	QByteArray commentBytes = args->getOption("comment");
	QTextCodec* tCodecConv = QTextCodec::codecForLocale();
	QString comment = tCodecConv->toUnicode(commentBytes, commentBytes.size());

	if (args->isSet("f"))
	{
		// If file is writeable, do not change uid
		QString filename = QFile::decodeName(args->getOption("f"));
		QString file = filename;
		if (!file.isEmpty())
		{
			if (file.at(0) != '/')
			{
				KStandardDirs dirs;
				dirs.addKDEDefaults();
				file = dirs.findResource("config", file);
				if (file.isEmpty())
				{
					kdError(1206) << "Config file not found: " << file << "\n";
					exit(1);
				}
			}
			QFileInfo fi(file);
			if (!fi.exists())
			{
				kdError(1206) << "File does not exist: " << file << "\n";
				exit(1);
			}
			if (fi.isWritable())
			{
				changeUID = false;
			}
		}
	}

	if (withIgnoreButton)
	{
		setButtonText(User1, i18n("&Ignore"));
	}

	// Apologies for the C code, taken from kdelibs/kdesu/kdesu_stub.c
	// KControl and other places need to use the user's existing DCOP server
	// For that we set DCOPSERVER.  Create a file in /tmp and use iceauth to add magic cookies
	// from the existing server and set ICEAUTHORITY to point to the file
	if (!newDcop) {
		dcopServer = m_pCookie->dcopServer();
		QCString dcopAuth = m_pCookie->dcopAuth();
		QCString iceAuth = m_pCookie->iceAuth();

		FILE *fout;
		char iceauthority[200];
		char *host, *auth;
		host = qstrdup(dcopServer);
		auth = qstrdup(iceAuth);
		int tempfile;
		int oldumask = umask(077);

		strcpy(iceauthority, "/tmp/iceauth.XXXXXXXXXX");
		tempfile = mkstemp(iceauthority);
		umask(oldumask);
		if (tempfile == -1) {
			kdError() << "error in kdesudo mkstemp" << endl;
			exit(1);
		} else {
			// close(tempfile); //FIXME why does this make the connect() call later crash?
		}
		iceauthorityFile = iceauthority;
		//FIXME we should change owner of iceauthority file, but don't have permissions
		setenv("ICEAUTHORITY", iceauthorityFile, 1);
	
		fout = popen("iceauth >/dev/null 2>&1", "w");
		if (!fout) {
			kdError() << "error in kdesudo running iceauth" << endl;
			exit(1);
		}
		fprintf(fout, "add ICE \"\" %s %s\n", host, auth);
		auth = qstrdup(dcopAuth);
		//auth = xstrsep(params[P_DCOP_AUTH].value);
		fprintf(fout, "add DCOP \"\" %s %s\n", host, auth);
		unsetenv("ICEAUTHORITY");
		pclose(fout);
	}

	connect( p, SIGNAL(receivedStdout(KProcess*, char*, int)), this, SLOT(receivedOut(KProcess*, char*, int)) );
	connect( p, SIGNAL(receivedStderr(KProcess*, char*, int)), this, SLOT(receivedOut(KProcess*, char*, int)) );
	connect( p, SIGNAL(processExited (KProcess *)), this, SLOT(procExited(KProcess*)));

	QString xauthenv = QString(getenv("HOME")) + "/.Xauthority";
	p->setEnvironment("XAUTHORITY", xauthenv);

	// Generate the xauth cookie and put it in a tempfile
	// set the environment variables to reflect that.
	// Default cookie-timeout is 60 sec. .
	// 'man xauth' for more info on xauth cookies.
	
	KTempFile temp = KTempFile("/tmp/kdesudo-","-xauth");
	m_tmpname = temp.name();
	
	FILE *f;
	char buf[1024];
	
	QCString disp = m_pCookie->display();
	// command: xauth -q -f m_tmpname generate $DISPLAy . trusted timeout 60
	QString c = "/usr/bin/xauth -q -f " + m_tmpname + " generate " 
		+ QString::fromLocal8Bit(disp) + " . trusted timeout 60";
	blockSigChild(); // pclose uses waitpid()
	
	if (!(f = popen(c, "r"))) {
		kdWarning() << k_lineinfo << "Cannot run: " << c << "\n";
		unblockSigChild();
		return;
	}
	
	// non root users need to be able to read the xauth file.
	// the xauth file is deleted when kdesudo exits. security?
	QFile tf(m_tmpname);
	if (!runas.isEmpty() && runas != "root" && tf.exists())
		chmod(m_tmpname.ascii(),0644);
	
	QCStringList output;
	while (fgets(buf, 1024, f) > 0)
		output += buf; 
	if (pclose(f) < 0) {
		kdError() << k_lineinfo << "Could not run xauth.\n";
		unblockSigChild();
		return;
	}
	unblockSigChild();
	
	p->setEnvironment("DISPLAY", disp); 
	p->setEnvironment("XAUTHORITY", m_tmpname);

	if (emptyPwd)
		*p << "sudo" << "-k";
	else
	{
		if (changeUID)
		{
			*p << "sudo" << "-H" << "-S" << "-p" << "passprompt";

			if (!runas.isEmpty())
				*p << "-u" << runas;
		}

		if (!dcopServer.isEmpty())
			*p << "DCOPSERVER=" + dcopServer;

		if (!iceauthorityFile.isEmpty())
			*p << "ICEAUTHORITY=" + iceauthorityFile;

		if (realtime)
		{
			*p << "nice" << "-n" << "10";
			addLine(i18n("Priority:"), i18n("realtime:") + QChar(' ') + QString("50/100"));
		}
		else if (priority)
		{
			QString n = args->getOption("p");
			int intn = atoi(n);
			intn =  (intn * 40 / 100) - (20 + 0.5);
		
			QString strn;
			strn.sprintf("%d",intn);

			*p << "nice" << "-n" << strn;
			addLine(i18n("Priority:"), n + QString("/100"));
		}

		*p << "--";

		if (args->isSet("c"))
		{
			QString command = args->getOption("c");
			QStringList commandSplit = QStringList::split(" ", command);
			for (int i = 0; i < commandSplit.count(); i++)
			{
				QString toto = validArg(commandSplit[i]);
				*p << toto;
				cmd += validArg(commandSplit[i]) + QChar(' ');
			}
		}
		else if (args->count())
		{
			for (int i = 0; i < args->count(); i++)
			{
				if (i==0)
				{
					QStringList argsSplit = QStringList::split(" ", args->arg(i));
					for (int i = 0; i < argsSplit.count(); i++)
					{
						*p << validArg(argsSplit[i]);
						cmd += validArg(argsSplit[i]) + QChar(' ');
					}
				}
				else
				{
					*p << validArg(args->arg(i));
					cmd += validArg(args->arg(i)) + QChar(' ');
				}
			}
		}
		// strcmd needs to be defined
		if (showCommand && !cmd.isEmpty())
			addLine(i18n("Command:"), cmd);
	}

	if (comment.isEmpty())
	{
		if (!generic.isEmpty())
			setPrompt(defaultComment.arg(generic));
		else
			setPrompt(defaultComment.arg(cmd));
	}
	else
		setPrompt(comment);

	if (noExec)
		exit(0);
	else
		p->start( KProcess::NotifyOnExit, KProcess::All );
}
Beispiel #26
0
void BaseTreeView::slotCreateSiteTemplate()
{
   QString startDir;
   if (Project::ref()->hasProject())
   {
     startDir = Project::ref()->templateURL().url();
   } else
   {
     startDir = locateLocal("data", resourceDir + "templates/");
   }
   KURL targetURL;
   bool valid;
   do {
     valid = false;
     targetURL = KFileDialog::getSaveURL(startDir, "*.tgz", this, i18n("Create Site Template File"));
     if (targetURL.isEmpty())
       return;
     if (targetURL.url().startsWith(KURL::fromPathOrURL(locateLocal("data", resourceDir + "templates/")).url()))
       valid = true;
    if (Project::ref()->hasProject() && targetURL.url().startsWith(Project::ref()->templateURL().url()))
      valid = true;
    if (!valid)
      KMessageBox::error(this, i18n("Templates should be saved to the local or project template folder."));
   }while (!valid);

   KURL url = currentURL();
   //TODO: Implement creation from remote folders as well. Requires downloading of the files to a
   //temporary directory
   if (url.protocol() != "file")
   {
       KMessageBox::sorry(this, i18n("Currently you can create site templates only from local folders."), i18n("Unsupported Feature"));
       return;
   }

   KTempFile *tempFile = new KTempFile(tmpDir);
   tempFile->setAutoDelete(true);
   tempFile->close();
   KTar tar(tempFile->name(), "application/x-gzip");
   bool error = false;
   if (tar.open(IO_WriteOnly))
   {
      KURL::List fileList = QExtFileInfo::allFiles(url, "*", this);
      for (KURL::List::Iterator it = fileList.begin(); it != fileList.end(); ++it)
      {
         if (!(*it).path().endsWith("/"))
         {
           QFile f((*it).path());
           if (f.open(IO_ReadOnly))
           {
              QByteArray buffer(f.readAll());
              if (!tar.writeFile((*it).path().remove(url.path()), "user", "group", buffer.size(), buffer.data()))
              {
                  error = true;
              }
              f.close();
           } else
             error = true;
         }
      }
      tar.close();
   } else
      error = true;
   if (!QuantaNetAccess::copy(KURL::fromPathOrURL(tempFile->name()), targetURL, m_parent, false))
     error = true;

   if (error)
     KMessageBox::error(this, i18n("<qt>There was an error while creating the site template tarball.<br>Check that you can read the files from <i>%1</i>, you have write access to <i>%2</i> and that you have enough free space in your temporary folder.</qt>").arg(url.prettyURL(0, KURL::StripFileProtocol)).arg(targetURL.prettyURL(0, KURL::StripFileProtocol)), i18n("Template Creation Error"));
   delete tempFile;
}
    void
    Crash::crashHandler( int /*signal*/ )
    {
        // we need to fork to be able to get a
        // semi-decent bt - I dunno why
        const pid_t pid = ::fork();

        if( pid < 0 )
        {
            std::cout << "forking crash reporter failed\n";
            // continuing now can't do no good
            _exit( 1 );
        }
        else if ( pid == 0 )
        {
            // we are the child process (the result of the fork)
            std::cout << "Pana is crashing...sorry this will be a minute...\n";

            QString subject = APP_VERSION " ";
            QString body = i18n(
                    "Pana has crashed.\n\n"
                    "Please help us fix it by clicking send on the crash report, "
                    "If you have time please add a brief description of what was happening just before the crash.\n\n"
                    "Thank you very much.\n\n" );
            body += i18n( "\n\n\n\n\n\n"
                    "The information below is to help identify the problem.\n\n\n ");


            body += "=== Debug information ===\n"
                    "Version:    " APP_VERSION "\n"
                    "Engine:     %1\n"
                    "Build date: " __DATE__ "\n"
                    "CC version: " __VERSION__ "\n"
                    "KDElibs:    " KDE_VERSION_STRING "\n"
                    "Qt:         %2\n"
                    "TagLib:     %3.%4.%5\n"
                    "CPU count:  %6\n";

            QString cpucount = "unknown";
#ifdef __linux__
            QString line;
            uint cpuCount = 0;
            QFile cpuinfo( "/proc/cpuinfo" );
            if ( cpuinfo.open( IO_ReadOnly ) ) {
                while ( cpuinfo.readLine( line, 20000 ) != -1 ) {
                    if ( line.startsWith( "processor" ) ) {
                        ++cpuCount;
                    }
                }
            }
            cpucount = QString::number( cpuCount );
#endif


            body = body.arg( PanaConfig::soundSystem() )
                    .arg( qVersion() )
                    .arg( TAGLIB_MAJOR_VERSION )
                    .arg( TAGLIB_MINOR_VERSION )
                    .arg( TAGLIB_PATCH_VERSION )
                    .arg( cpucount );

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

            /// obtain the backtrace with gdb

            KTempFile temp;
            temp.setAutoDelete( true );

            const int handle = temp.handle();

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

            const QCString 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 ) );


            QCString gdb;
            gdb  = "gdb --nw -n --batch -x ";
            gdb += temp.name().latin1();
            gdb += " panaapp ";
            gdb += QCString().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.stripWhiteSpace();

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

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

            if( !bt.isEmpty() ) {
                const int invalidFrames = bt.contains( QRegExp("\n#[0-9]+\\s+0x[0-9A-Fa-f]+ in \\?\\?") );
                const int validFrames = bt.contains( 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.find( QRegExp(" at \\w*\\.cpp:\\d+\n") ) >= 0 )
                    subject += "[line numbers]";
            }
            else
                useful = false;

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

            std::cout << subject.latin1() << std::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 panaapp` =======\n";
                body += fileCommandOutput + "\n\n";
                body += "==== (gdb) bt =====================\n";
                body += bt + "\n\n";
                body += "==== kdBacktrace() ================\n";
                body += kdBacktrace();

                //TODO startup notification
                kapp->invokeMailer(
                        /*to*/          "*****@*****.**",
                        /*cc*/          QString(),
                        /*bcc*/         QString(),
                        /*subject*/     subject,
                        /*body*/        body,
                        /*messageFile*/ QString(),
                        /*attachURLs*/  QStringList(),
                        /*startup_id*/  "" );
            }
            else {
                std::cout << i18n( "\nPana has crashed.\n\n"
                                   "Perhaps an upgrade is already available "
                                   "which fixes the problem. Please check your distribution's software repository.\n" ).local8Bit();
            }

            //_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 );
        }
    }
Beispiel #28
0
KDE_EXPORT void kimgio_eps_read(QImageIO *image)
{
    kdDebug(399) << "kimgio EPS: starting..." << endl;

    FILE *ghostfd;
    int x1, y1, x2, y2;
    // QTime dt;
    // dt.start();

    QString cmdBuf;
    QString tmp;

    QIODevice *io = image->ioDevice();
    Q_UINT32 ps_offset, ps_size;

    // find start of PostScript code
    if(!seekToCodeStart(io, ps_offset, ps_size))
        return;

    // find bounding box
    if(!bbox(io, &x1, &y1, &x2, &y2))
    {
        kdError(399) << "kimgio EPS: no bounding box found!" << endl;
        return;
    }

    KTempFile tmpFile;
    tmpFile.setAutoDelete(true);

    if(tmpFile.status() != 0)
    {
        kdError(399) << "kimgio EPS: no temp file!" << endl;
        return;
    }
    tmpFile.close(); // Close the file, we just want the filename

    // x1, y1 -> translation
    // x2, y2 -> new size

    x2 -= x1;
    y2 -= y1;
    // kdDebug(399) << "origin point: " << x1 << "," << y1 << "  size:" << x2 << "," << y2 << endl;
    double xScale = 1.0;
    double yScale = 1.0;
    bool needsScaling = false;
    int wantedWidth = x2;
    int wantedHeight = y2;

    if(image->parameters())
    {
        // Size forced by the caller
        QStringList params = QStringList::split(':', image->parameters());
        if(params.count() >= 2 && x2 != 0.0 && y2 != 0.0)
        {
            wantedWidth = params[0].toInt();
            xScale = (double)wantedWidth / (double)x2;
            wantedHeight = params[1].toInt();
            yScale = (double)wantedHeight / (double)y2;
            // kdDebug(399) << "wanted size:" << wantedWidth << "x" << wantedHeight << endl;
            // kdDebug(399) << "scaling:" << xScale << "," << yScale << endl;
            needsScaling = true;
        }
    }

    // create GS command line

    cmdBuf = "gs -sOutputFile=";
    cmdBuf += tmpFile.name();
    cmdBuf += " -q -g";
    tmp.setNum(wantedWidth);
    cmdBuf += tmp;
    tmp.setNum(wantedHeight);
    cmdBuf += "x";
    cmdBuf += tmp;
    cmdBuf +=
        " -dSAFER -dPARANOIDSAFER -dNOPAUSE -sDEVICE=ppm -c "
        "0 0 moveto "
        "1000 0 lineto "
        "1000 1000 lineto "
        "0 1000 lineto "
        "1 1 254 255 div setrgbcolor fill "
        "0 0 0 setrgbcolor - -c showpage quit";

    // run ghostview

    ghostfd = popen(QFile::encodeName(cmdBuf), "w");

    if(ghostfd == 0)
    {
        kdError(399) << "kimgio EPS: no GhostScript?" << endl;
        return;
    }

    fprintf(ghostfd, "\n%d %d translate\n", -qRound(x1 * xScale), -qRound(y1 * yScale));
    if(needsScaling)
        fprintf(ghostfd, "%g %g scale\n", xScale, yScale);

    // write image to gs

    io->reset();       // Go back to start of file to give all the file to GhostScript
    if(ps_offset > 0L) // We have an offset
        io->at(ps_offset);
    QByteArray buffer(io->readAll());

    // If we have no MS-DOS EPS file or if the size seems wrong, then choose the buffer size
    if(ps_size <= 0L || ps_size > buffer.size())
        ps_size = buffer.size();

    fwrite(buffer.data(), sizeof(char), ps_size, ghostfd);
    buffer.resize(0);

    pclose(ghostfd);

    // load image
    QImage myimage;
    if(myimage.load(tmpFile.name()))
    {
        image->setImage(myimage);
        image->setStatus(0);
        kdDebug(399) << "kimgio EPS: success!" << endl;
    }
    else
        kdError(399) << "kimgio EPS: no image!" << endl;

    // kdDebug(399) << "Loading EPS took " << (float)(dt.elapsed()) / 1000 << " seconds" << endl;
    return;
}
const KstTimezones::ZoneMap KstTimezones::allZones()
{
    // Have we already done all the hard work? If not, create the cache.
    if (m_zones)
        return *m_zones;
    m_zones = new ZoneMap();

    // Go read the database.
    //
    // On Windows, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones
    // is the place to look. The TZI binary value is the TIME_ZONE_INFORMATION structure.
    //
    // For Unix its all easy except knowing where to look. Try the LSB location first.
    QFile f;
    m_zoneinfoDir = "/usr/share/zoneinfo";
    f.setName(m_zoneinfoDir + "/zone.tab");
    if (!f.open(IO_ReadOnly))
    {
        m_zoneinfoDir = "/usr/lib/zoneinfo";
        f.setName(m_zoneinfoDir + "/zone.tab");
        if (!f.open(IO_ReadOnly))
        {
            m_zoneinfoDir = ::getenv("TZDIR");
            f.setName(m_zoneinfoDir + "/zone.tab");
            if (m_zoneinfoDir.isEmpty() || !f.open(IO_ReadOnly))
            {
                // Solaris support. Synthesise something that looks like a zone.tab.
                //
                // /bin/grep -h ^Zone /usr/share/lib/zoneinfo/src/* | /bin/awk '{print "??\t+9999+99999\t" $2}'
                //
                // where the country code is set to "??" and the lattitude/longitude
                // values are dummies.
                m_zoneinfoDir = "/usr/share/lib/zoneinfo";
                KTempFile temp;
                KShellProcess reader;
                reader << "/bin/grep" << "-h" << "^Zone" << m_zoneinfoDir << "/src/*" << temp.name() << "|" <<
                    "/bin/awk" << "'{print \"??\\t+9999+99999\\t\" $2}'";
                // Note the use of blocking here...it is a trivial amount of data!
                temp.close();
                reader.start(KProcess::Block);
                f.setName(temp.name());
                if (!temp.status() || !f.open(IO_ReadOnly))
                {
                    return *m_zones;
                }
            }
        }
    }

    // Parse the zone.tab.
    QTextStream str(&f);
    QRegExp lineSeparator("[ \t]");
    QRegExp ordinateSeparator("[+-]");
    KSharedPtr<KstTimezoneSource> db(new KstTimezoneSource(m_zoneinfoDir));
    while (!str.atEnd())
    {
        QString line = str.readLine();
        if (line.isEmpty() || '#' == line[0])
            continue;
        QStringList tokens = KStringHandler::perlSplit(lineSeparator, line, 4);
        if (tokens.count() < 3)
        {
            continue;
        }

        // Got three tokens. Now check for two ordinates plus first one is "".
        QStringList ordinates = KStringHandler::perlSplit(ordinateSeparator, tokens[1], 2);
        if (ordinates.count() < 2)
        {
            continue;
        }

        float latitude = convertCoordinate(ordinates[1]);
        float longitude = convertCoordinate(ordinates[2]);

        // Add entry to list.
        if (tokens[0] == "??")
            tokens[0] = "";
        KstTimezone *timezone = new KstTimezone(db, tokens[2], tokens[0], latitude, longitude, tokens[3]);
        add(timezone);
    }
    f.close();
    return *m_zones;
}
Beispiel #30
0
void KPrMSPresentation::initCreation( KProgress *progressBar )
{
    int p;

    // the title images, and the subsequent real images need to
    // be in a file under DCIM/, and they start at 101MSPJP, so
    // we create the DCIM file, and then iterate through looking
    // for the next "available" directory slot
    KURL str(  path + "/DCIM"  );
    KIO::NetAccess::mkdir( str,( QWidget* )0L  );

    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    for (int dirNum = 101; dirNum < 999; dirNum++) {
        slidePath = QString("/DCIM/%1MSPJP").arg(dirNum);
        if (! KIO::NetAccess::exists(( path + slidePath), true, ( QWidget* )0L) )
            break;
    }

    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    str = (  path + slidePath );
    KIO::NetAccess::mkdir( str,( QWidget* )0L  );
    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    // now do the SPP file directory
    str = (  path + "/MSSONY" );
    KIO::NetAccess::mkdir( str,( QWidget* )0L  );

    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();
    str = (  path + "/MSSONY/PJ" );
    KIO::NetAccess::mkdir( str,( QWidget* )0L  );


    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    // create the title slides
    QPixmap titleSlide( 1024, 768 );
    titleSlide.fill( backColour );
    QPainter painter( &titleSlide );

    //the second title is just blank, so create that now
    KTempFile tmp;
    QString filename = path + slidePath + "/SPJT0002.JPG";
    titleSlide.save( tmp.name(), "JPEG" );
    KIO::NetAccess::file_move( tmp.name(), filename, -1, true /*overwrite*/);

    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

    // and put the specified title string on the first slide
    QFont textFont( "SansSerif", 96 );
    painter.setFont( textFont );
    painter.setPen( textColour );
    painter.drawText( titleSlide.rect(), Qt::AlignCenter | Qt::WordBreak, title );
    filename = path + slidePath + "/SPJT0001.JPG";

    KTempFile tmp2;
    titleSlide.save( tmp2.name(), "JPEG" );
    KIO::NetAccess::file_move( tmp2.name(), filename, -1, true /*overwrite*/);

    p = progressBar->progress();
    progressBar->setProgress( ++p );
    kapp->processEvents();

}