コード例 #1
0
void BaseTreeView::slotCreateFile()
{
  bool ok;
  QString fileName = KInputDialog::getText(i18n("Create New File"), i18n("File name:"), "", &ok, this);
  if (ok)
  {
    KURL url = currentURL();
    if (currentKFileTreeViewItem()->isDir())
      url.setPath(url.path() + "/" + fileName);
    else
      url.setPath(url.directory() + "/" + fileName);
    if (QExtFileInfo::exists(url, false, this))
    {
      KMessageBox::error(this, i18n("<qt>Cannot create file, because a file named <b>%1</b> already exists.</qt>").arg(fileName), i18n("Error Creating File"));
      return;
    }
    KTempFile *tempFile = new KTempFile(tmpDir);
    tempFile->setAutoDelete(true);
    tempFile->close();
    if (QuantaNetAccess::copy(KURL::fromPathOrURL(tempFile->name()), url, this))
    {
      emit openFile(url);
    }
    delete tempFile;
  }
}
コード例 #2
0
ファイル: gmx_xxport.cpp プロジェクト: iegor/kdesktop
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;
  }
}
コード例 #3
0
ファイル: kgpgeditor.cpp プロジェクト: Fat-Zer/tdeutils
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);
}
コード例 #4
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);
}
コード例 #5
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() ) );
}
コード例 #6
0
ファイル: svnhandler.cpp プロジェクト: serghei/kde-kdesdk
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 );
}
コード例 #7
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() );
}
コード例 #8
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);
}
コード例 #9
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;
}
コード例 #10
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;
}
コード例 #11
0
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;
}
コード例 #12
0
ファイル: ksaneocr.cpp プロジェクト: serghei/kde3-kdegraphics
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;
}
コード例 #13
0
void subversionCore::diff( const KURL::List& list, const QString& where){
	kdDebug(9036) << "diff " << list << endl;
	KURL servURL = "kdevsvn+svn://this_is_a_fake_URL_and_this_is_normal/";
	for ( QValueListConstIterator<KURL> it = list.begin(); it != list.end() ; ++it ) {
		QByteArray parms;
		QDataStream s( parms, IO_WriteOnly );
		int cmd = 13;
		kdDebug(9036) << "diffing : " << (*it).prettyURL() << endl;
		int rev1=-1;
		int rev2=-1;
		QString revkind1 = where;
		QString revkind2 = "WORKING";
		s << cmd << *it << *it << rev1 << revkind1 << rev2 << revkind2 << true ;
		KIO::SimpleJob * job = KIO::special(servURL, parms, true);
		connect( job, SIGNAL( result( KIO::Job * ) ), this, SLOT( slotResult( KIO::Job * ) ) );
		KIO::NetAccess::synchronousRun( job, 0 );
		if ( diffresult.count() > 0 ) {
			//check kompare is available
			if ( !KStandardDirs::findExe( "kompare" ).isNull() ) {
				if (!KStandardDirs::findExe("patch").isNull()){
					// we have patch - so can merge
					KTempDir tmpDir = KTempDir(diffTmpDir->name());
					KTempFile tmpPatch = KTempFile(tmpDir.name());

					// write the patch
					QTextStream *stream = tmpPatch.textStream();
					stream->setCodec( QTextCodec::codecForName( "utf8" ) );
					for ( QStringList::Iterator it2 = diffresult.begin();it2 != diffresult.end() ; ++it2 ) {
						( *stream ) << ( *it2 ) << "\n";
					}
					tmpPatch.close();

					QString ourCopy = tmpDir.name()+(*it).fileName();

					KProcess copy;
					copy << "cp" << (*it).prettyURL(0,KURL::StripFileProtocol) <<  tmpDir.name();
					copy.start(KProcess::Block);

					KProcess patch;
					patch.setWorkingDirectory(tmpDir.name());
					patch << "patch" << "-R" << ourCopy << tmpPatch.name();
					patch.start(KProcess::Block, KProcess::All);

					KProcess *p = new KProcess;
					*p << "kompare" << ourCopy << (*it).prettyURL();
					p->start();
				}
				else{
					// only diff
					KTempFile *tmp = new KTempFile;
					tmp->setAutoDelete(true);
					QTextStream *stream = tmp->textStream();
					stream->setCodec( QTextCodec::codecForName( "utf8" ) );
					for ( QStringList::Iterator it2 = diffresult.begin();it2 != diffresult.end() ; ++it2 ) {
						( *stream ) << ( *it2 ) << "\n";
					}
					tmp->close();
					KProcess *p = new KProcess;
					*p << "kompare" << "-n" << "-o" << tmp->name();
					p->start();
				}
			} else { //else do it with message box
				Subversion_Diff df;
				for ( QStringList::Iterator it2 = diffresult.begin();it2 != diffresult.end() ; ++it2 ) {
					df.text->append( *it2 );
				}
				QFont f = df.font();
				f.setFixedPitch( true );
				df.text->setFont( f );
				df.exec();
			}
		}
		else{
			QString diffTo = i18n("the local disk checked out copy.");
			if ( where=="HEAD"){
				diffTo=i18n("the current svn HEAD version.");
			}
			KMessageBox::information( 0, i18n("No differences between the file and %1").arg(diffTo), i18n("No difference") );
		}
		diffresult.clear();
	}
}
コード例 #14
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;
}
コード例 #15
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;
}
コード例 #16
0
QByteArray KstViewObjectImageDrag::encodedData(const char *mimeType) const {
  if (!_mimeTypes.contains(QString::fromLatin1(mimeType))) {
    return QByteArray();
  }

  QRect geom(0, 0, 0, 0);
  for (KstViewObjectList::ConstIterator i = _objects.begin(); i != _objects.end(); ++i) {
    geom = geom.unite((*i)->geometry());
  }

  QPixmap pm;
  pm.resize(geom.size());
  pm.fill();

  int prog = 0;
  bool cancelled = false;
  KstPainter p(KstPainter::P_EXPORT);
  p.begin(&pm);
  p.setClipping(true);
  KProgressDialog *dlg = new KProgressDialog(0, 0, QString::null, i18n("Generating and storing images of objects..."), true);
  dlg->setAllowCancel(true);
  dlg->progressBar()->setTotalSteps(_objects.count());
  dlg->progressBar()->setValue(prog);
  dlg->show();

  for (KstViewObjectList::Iterator i = _objects.begin(); i != _objects.end(); ++i) {
    p.setClipRect((*i)->geometry());
    p.setViewport((*i)->geometry());
    (*i)->paint(p, QRegion());
    if (dlg->wasCancelled()) {
      cancelled = true;
      break;
    }
    dlg->progressBar()->setValue(++prog);
    kapp->eventLoop()->processEvents(QEventLoop::ExcludeSocketNotifiers);
  }
  p.end();

  delete dlg;

  if (cancelled) {
    return QByteArray();
  }

  QByteArray rc;
#if QT_VERSION < 0x030200
  KTempFile tf;
  pm.save(tf.name(), KImageIO::typeForMime(mimeType).latin1());
  tf.close();
  QFile f(tf.name());
  if (f.open(IO_ReadOnly)) {
    rc = f.readAll();
    f.close();
  }
  QFile::remove(tf.name());
#else
  QDataStream ds(rc, IO_WriteOnly);
  pm.save(ds.device(), KImageIO::typeForMime(mimeType).latin1());
#endif

  return rc;
}
コード例 #17
0
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;
}
コード例 #18
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*/);
}