예제 #1
0
void ProjectNewLocal::slotInsertFolderAfterCopying(const KURL::List& a_urlList)
{
  KURL::List::ConstIterator it;
  KURL dirURL;
  for (it = a_urlList.begin(); it != a_urlList.end(); ++it)
  {
    dirURL = *it;
   // dirURL.adjustPath(1);
    KURL::List files = QExtFileInfo::allFilesRelative(dirURL, "*", this, false);
    progressBar->setTotalSteps(files.count() - 1);
    progressBar->setTextEnabled(true);
    KURL u;
    for (uint i = 0; i < files.count(); i++)
    {
      u = files[i];
      if ( !fileList.contains(u) && u.path() != "." && u.path() != ".." )
      {
        fileList.append(u);
        listView->addItem(u, KFileItem(KFileItem::Unknown, KFileItem::Unknown, KURL()));
        QListViewItem *it = listView->itemByUrl(u);
        if (it)
        {
          it->setSelected(true);
          listView->slotSelectFile(it);
        }
        progressBar->setValue(i);
      }
    }
    //listView->selectAll(false);
    progressBar->setTotalSteps(1);
    progressBar->setValue(0);
    progressBar->setTextEnabled(false);
  }
}
예제 #2
0
/** No descriptions */
void ProjectNewLocal::slotAddFiles()
{
  QExtFileInfo::createDir(baseURL, this);
  KURL::List list = KFileDialog::getOpenURLs(
    baseURL.url(),  i18n("*"), this, i18n("Insert Files in Project"));

  if ( !list.isEmpty() )
  {
    KURL u = list.first();

    u = QExtFileInfo::toRelative( u, baseURL, false );

    if ( u.path().startsWith("..") || u.path().startsWith("/"))
    {
      KURLRequesterDlg *urlRequesterDlg = new KURLRequesterDlg( baseURL.prettyURL(), this, "");
      urlRequesterDlg->setCaption(i18n("Files: Copy to Project"));
      urlRequesterDlg->urlRequester()->setMode( KFile::Directory | KFile::ExistingOnly);
      urlRequesterDlg->exec();
      KURL destination = urlRequesterDlg->selectedURL();
      delete urlRequesterDlg;

      if ( !destination.isEmpty())
      {
        CopyTo *dlg = new CopyTo( baseURL);
        connect(dlg, SIGNAL(addFilesToProject(const KURL::List&)),
                     SLOT  (slotInsertFilesAfterCopying(const KURL::List&)));
        connect(dlg, SIGNAL(deleteDialog(CopyTo *)),
                     SLOT  (slotDeleteCopyToDialog(CopyTo *)));
        list = dlg->copy( list, destination );
        return;
      } else
      {
        return;
      }
    }

    progressBar->setTotalSteps(list.count() - 1);
    progressBar->setTextEnabled(true);
    for (uint i = 0; i < list.count(); i++)
    {
       list[i] = QExtFileInfo::toRelative(list[i], baseURL, false);
       if (!fileList.contains(list[i]))
       {
         fileList.append(list[i]);
         QListViewItem *it = listView->addItem(list[i], KFileItem(KFileItem::Unknown, KFileItem::Unknown, KURL()));
         if (it)  it->setSelected(true);
         progressBar->setValue(i);
       }
    }
    progressBar->setTotalSteps(1);
    progressBar->setValue(0);
    progressBar->setTextEnabled(false);
  }
}
예제 #3
0
void URLUtil::dump( const KURL::List &urls, const QString &aMessage )
{
  if (!aMessage.isNull())
  {
    kdDebug(9000) << aMessage << endl;
  }
  kdDebug(9000) << " List has " << urls.count() << " elements." << endl;

  for (size_t i = 0; i<urls.count(); ++i)
  {
    KURL url = urls[ i ];
//    kdDebug(9000) << " * Element = "  << url.path() << endl;
  }
}
예제 #4
0
파일: kfwin.cpp 프로젝트: Fat-Zer/tdebase
TQDragObject * KfindWindow::dragObject()
{
  KURL::List uris;
  TQPtrList<TQListViewItem> selected = selectedItems();

  // create a list of URIs from selection
  for ( uint i = 0; i < selected.count(); i++ )
  {
    KfFileLVI *item = (KfFileLVI *) selected.at( i );
    if (item)
    {
      uris.append( item->fileitem.url() );
    }
  }

  if ( uris.count() <= 0 )
     return 0;

  TQUriDrag *ud = new KURLDrag( uris, (TQWidget *) this, "kfind uridrag" );

  const TQPixmap *pix = currentItem()->pixmap(0);
  if ( pix && !pix->isNull() )
    ud->setPixmap( *pix );

  return ud;
}
예제 #5
0
void SaverConfig::add()
{
    KURL::List files = KFileDialog::getOpenURLs( TQString(), TQString(),
                                                 this, i18n("Select Media Files") );
    for( unsigned int n=0; n<files.count(); n++ )
        m_files->insertItem( files[n].prettyURL(), -1 );
}
예제 #6
0
void ProjectNewLocal::slotInsertFilesAfterCopying(const KURL::List& a_urlList)
{
  KURL::List::ConstIterator it;
  KURL u;
  progressBar->setTotalSteps(a_urlList.count() - 1);
  progressBar->setTextEnabled(true);
  for (it = a_urlList.begin(); it != a_urlList.end(); ++it)
  {
    u = QExtFileInfo::toRelative(*it, baseURL, false);
    if ( !fileList.contains(u))
    {
      fileList.append(u);
      QListViewItem *it = listView->addItem(u, KFileItem(KFileItem::Unknown, KFileItem::Unknown, KURL()));
      if (it)
      {
         it->setSelected(true);
         listView->slotSelectFile(it);
      }
      progressBar->advance(1);
    }
  }
  progressBar->setTotalSteps(1);
  progressBar->setValue(0);
  progressBar->setTextEnabled(false);
}
예제 #7
0
KURL *decodeImgDrop(QDropEvent *e, QWidget *wdg)
{
    KURL::List uris;

    if (KURLDrag::decode(e, uris) && (uris.count() > 0)) {
	KURL *url = new KURL(uris.first());

	KImageIO::registerFormats();
	if( KImageIO::canRead(KImageIO::type(url->fileName())) )
	    return url;

	QStringList qs = QStringList::split('\n', KImageIO::pattern());
	qs.remove(qs.begin());

	QString msg = i18n( "%1 "
			    "does not appear to be an image file.\n"
			    "Please use files with these extensions:\n"
			    "%2")
			    .arg(url->fileName())
			    .arg(qs.join("\n"));
	KMessageBox::sorry( wdg, msg);
	delete url;
    }
    return 0;
}
void
RadialMap::Widget::dropEvent( QDropEvent *e )
{
    DEBUG_ANNOUNCE

    KURL::List urls;
    if (KURLDrag::decode( e, urls ) && urls.count())
        emit giveMeTreeFor( urls.first() );
}
예제 #9
0
int K3bDataUrlAddingDialog::addUrls( const KURL::List& urls,
				     K3bDirItem* dir,
				     QWidget* parent )
{
  if( urls.isEmpty() )
    return 0;

  //
  // A common mistake by beginners is to try to burn an iso image
  // with a data project. Let's warn them
  //
  if( urls.count() == 1 ) {
    K3bIso9660 isoF( urls.first().path() );
    if( isoF.open() ) {
     if( KMessageBox::warningYesNo( parent,
				    i18n("<p>The file you are about to add to the project is an ISO9660 image. As such "
					 "it can be burned to a medium directly since it already contains a file "
					 "system.<br>"
					 "Are you sure you want to add this file to the project?"),
				    i18n("Adding image file to project"),
				    i18n("Add the file to the project"),
				    i18n("Burn the image directly") ) == KMessageBox::No ) {
       // very rough dvd image size test
       if( K3b::filesize( urls.first() ) > 1000*1024*1024 )
	 k3bappcore->k3bMainWindow()->slotWriteDvdIsoImage( urls.first() );
       else
	 k3bappcore->k3bMainWindow()->slotWriteCdImage( urls.first() );
       return 0;
     }
    }
  }

  K3bDataUrlAddingDialog dlg( dir->doc(), parent );
  dlg.m_urls = urls;
  for( KURL::List::ConstIterator it = urls.begin(); it != urls.end(); ++it )
    dlg.m_urlQueue.append( qMakePair( K3b::convertToLocalUrl(*it), dir ) );

  dlg.slotAddUrls();
  int ret = QDialog::Accepted;
  if( !dlg.m_urlQueue.isEmpty() ) {
    dlg.m_dirSizeJob->setUrls( urls );
    dlg.m_dirSizeJob->setFollowSymlinks( dir->doc()->isoOptions().followSymbolicLinks() );
    dlg.m_dirSizeJob->start();
    ret = dlg.exec();
  }

  // make sure the dir size job is finished
  dlg.m_dirSizeJob->cancel();
  K3bSignalWaiter::waitForJob( dlg.m_dirSizeJob );

  QString message = dlg.resultMessage();
  if( !message.isEmpty() )
    KMessageBox::detailedSorry( parent, i18n("Problems while adding files to the project."), message );

  return ret;
}
예제 #10
0
inline void
FSBrowser::contextMenuActivated( int id )
{
    switch( id )
    {
    case MakePlaylist:
        Playlist::instance()->insertMedia( selectedItems(), Playlist::Replace );
        break;

    case SavePlaylist:
        playlistFromURLs( selectedItems() );
        break;

    case AppendToPlaylist:
        Playlist::instance()->insertMedia( selectedItems() );
        break;

    case EditTags:
        {
            KURL::List list = selectedItems();
            TagDialog *dialog = NULL;
            if( list.count() == 1 )
            {
                dialog = new TagDialog( list.first(), this );
            }
            else
            {
                dialog = new TagDialog( list, this );
            }
            dialog->show();
        }
        break;

    case CopyToCollection:
        CollectionView::instance()->organizeFiles( selectedItems(), i18n( "Copy Files To Collection" ), true );
        break;

    case MoveToCollection:
        CollectionView::instance()->organizeFiles( selectedItems(), i18n( "Move Files To Collection" ), false );
        break;


    case CopyMediaDevice:
        MediaBrowser::queue()->addURLs( selectedItems() );
        break;

    case SelectAllFiles:
        selectAll();
        break;

    case BurnCd:
        K3bExporter::instance()->exportTracks( selectedItems() );
        break;
    }
}
예제 #11
0
QStringList URLUtil::toRelativePaths( const QString &baseDir, const KURL::List &urls)
{
  QStringList paths;

  for (size_t i=0; i<urls.count(); ++i)
  {
    paths << extractPathNameRelative( baseDir, urls[i] );
  }

  return paths;
}
예제 #12
0
void BGMonitor::dropEvent(QDropEvent *e)
{
    if (!KURLDrag::canDecode(e))
        return;

    KURL::List uris;
    if (KURLDrag::decode(e, uris) && (uris.count() > 0)) {
        // TODO: Download remote file
        if (uris.first().isLocalFile())
           emit imageDropped(uris.first().path());
    }
}
예제 #13
0
TagDialog::TagDialog( const KURL::List list, QWidget* parent )
    : TagDialogBase( parent )
    , m_bundle()
    , m_score ( 0 )
    , m_firstPlay ( QDateTime() )
    , m_lastPlay ( QDateTime()  )
    , m_playlistItem( 0 )
    , m_urlList( list )
    , m_currentCover( 0 )
{
    setCaption( kapp->makeStdCaption( i18n("1 Track", "Information for %n Tracks", list.count()) ) );
    init();
}
예제 #14
0
KIO_EXPORT QString KIO::pasteActionText()
{
    QMimeSource *data = QApplication::clipboard()->data();
    KURL::List urls;
    if(KURLDrag::canDecode(data) && KURLDrag::decode(data, urls))
    {
        if(urls.isEmpty())
            return QString::null; // nothing to paste
        else if(urls.first().isLocalFile())
            return i18n("&Paste File", "&Paste %n Files", urls.count());
        else
            return i18n("&Paste URL", "&Paste %n URLs", urls.count());
    }
    else if(data->format(0) != 0)
    {
        return i18n("&Paste Clipboard Contents");
    }
    else
    {
        return QString::null;
    }
}
예제 #15
0
void DeleteWidget::setFiles(const KURL::List &files)
{
    ddFileList->clear();
//    ddFileList->insertStringList(files);
    for( KURL::List::ConstIterator it = files.begin(); it != files.end(); it++)
    {
        if( (*it).isLocalFile() ) //path is nil for non-local
            ddFileList->insertItem( (*it).path() );
        else
            ddFileList->insertItem( (*it).url() );
    }
    ddNumFiles->setText(i18n("<b>1</b> file selected.", "<b>%n</b> files selected.", files.count()));
}
예제 #16
0
void KgpgLibrary::slotFileEnc(KURL::List urls,QStringList opts,QStringList defaultKey,KShortcut goDefaultKey)
{
        /////////////////////////////////////////////////////////////////////////  encode file file
        if (!urls.empty()) {
                urlselecteds=urls;
                if (defaultKey.isEmpty()) {
			QString fileNames=urls.first().fileName();
			if (urls.count()>1) fileNames+=",...";
                        popupPublic *dialogue=new popupPublic(0,"Public keys",fileNames,true,goDefaultKey);
                        connect(dialogue,SIGNAL(selectedKey(QStringList,QStringList,bool,bool)),this,SLOT(startencode(QStringList,QStringList,bool,bool)));
                        dialogue->exec();
                        delete dialogue;
                } else
예제 #17
0
void subversionCore::commit( const KURL::List& list, bool recurse, bool keeplocks ) {
	KURL servURL = m_part->baseURL();
	if ( servURL.isEmpty() ) servURL="kdevsvn+svn://blah/";
	if ( ! servURL.protocol().startsWith( "kdevsvn+" ) ) {
		servURL.setProtocol( "kdevsvn+" + servURL.protocol() ); //make sure it starts with "svn"
	}
	kdDebug(9036) << "servURL : " << servURL.prettyURL() << endl;
	QByteArray parms;
	QDataStream s( parms, IO_WriteOnly );
	int cmd = 103;
 	s << cmd << recurse << keeplocks;
	for ( QValueListConstIterator<KURL> it = list.begin(); it != list.end() ; ++it ) {
		kdDebug(9036) << "adding to list: " << (*it).prettyURL() << endl;
		s << *it;
	}
	SimpleJob * job = KIO::special(servURL, parms, false);
	connect( job, SIGNAL( result( KIO::Job * ) ), this, SLOT( slotResult( KIO::Job * ) ) );
	if( list.count() == 1 )
		initProcessDlg( (KIO::Job*)job, (*(list.begin())).prettyURL() , i18n("Commit to remote repository") );
	else if( list.count() > 1 )
		initProcessDlg( (KIO::Job*)job, i18n("From working copy") , i18n("Commit to remote repository") );
}
예제 #18
0
void FSBrowser::playlistFromURLs( const KURL::List &urls )
{
    QString suggestion;
    if( urls.count() == 1 && QFileInfo( urls.first().path() ).isDir() )
        suggestion = urls.first().fileName();
    else
        suggestion = i18n( "Untitled" );
    const QString path = PlaylistDialog::getSaveFileName( suggestion );
    if( path.isEmpty() )
        return;

    if( PlaylistBrowser::savePlaylist( path, urls ) )
        PlaylistWindow::self()->showBrowser( "PlaylistBrowser" );
}
예제 #19
0
void ProjectNewLocal::slotSetFiles(bool)
{
  if ( checkInsert->isChecked() )
  {
    KURL::List files = projectFiles();
    progressBar->setTotalSteps(files.count() - 1);
    progressBar->setTextEnabled(true);
    for (uint i = 0; i < files.count(); i++)
    {
       if ( !fileList.contains(files[i]))
       {
         fileList.append(files[i]);
         QListViewItem *it = listView->addItem(files[i], KFileItem(KFileItem::Unknown, KFileItem::Unknown, KURL()));
         if (it)  it->setSelected(true);
         progressBar->setValue(i);
       }
    }
    progressBar->setTotalSteps(1);
    progressBar->setValue(0);
    progressBar->setTextEnabled(false);
    listView->checkboxTree();
  }
}
예제 #20
0
// The main method for pasting
KIO_EXPORT KIO::Job *KIO::pasteClipboard(const KURL &dest_url, bool move)
{
    if(!dest_url.isValid())
    {
        KMessageBox::error(0L, i18n("Malformed URL\n%1").arg(dest_url.url()));
        return 0;
    }

#ifndef QT_NO_MIMECLIPBOARD
    QMimeSource *data = QApplication::clipboard()->data();

    // First check for URLs.
    KURL::List urls;
    if(KURLDrag::canDecode(data) && KURLDrag::decode(data, urls))
    {
        if(urls.count() == 0)
        {
            KMessageBox::error(0L, i18n("The clipboard is empty"));
            return 0;
        }

        KIO::Job *res = 0;
        if(move)
            res = KIO::move(urls, dest_url);
        else
            res = KIO::copy(urls, dest_url);

        // If moving, erase the clipboard contents, the original files don't exist anymore
        if(move)
            QApplication::clipboard()->clear();
        return res;
    }
    return pasteMimeSource(data, dest_url, QString::null, 0 /*TODO parent widget*/, true /*clipboard*/);
#else
    QByteArray ba;
    QTextStream txtStream(ba, IO_WriteOnly);
    QStringList data = QStringList::split("\n", QApplication::clipboard()->text());
    KURL::List urls;
    KURLDrag::decode(data, urls);
    QStringList::Iterator end(data.end());
    for(QStringList::Iterator it = data.begin(); it != end; ++it)
        txtStream << *it;
    if(ba.size() == 0)
    {
        KMessageBox::sorry(0, i18n("The clipboard is empty"));
        return 0;
    }
    return pasteDataAsync(dest_url, ba);
#endif
}
예제 #21
0
void FileBrowser::playlistFromURLs( const KURL::List &urls )
{
    QString suggestion;
    if( urls.count() == 1 && QFileInfo( urls.first().path() ).isDir() )
        suggestion = urls.first().fileName();
    else
        suggestion = i18n( "Untitled" );
    const QString path = PlaylistDialog::getSaveFileName( suggestion );
    if( path.isEmpty() )
        return;

    if( PlaylistBrowser::savePlaylist( path, urls ) )
    {
        //FIXME: uncomment after string freeze
        //Pana::StatusBar::instance()->shortMessage( "Playlist saved to playlist browser" );
    }
}
예제 #22
0
void ViewManager::dropped(QDropEvent *e)
{
    kdDebug(5720) << "ViewManager::dropped: got a drop event" << endl;

    // don't allow drops from our own drags
    if(e->source() == this)
        return;

    QString clipText, vcards;
    KURL::List urls;

    if(KURLDrag::decode(e, urls))
    {
        KURL::List::ConstIterator it = urls.begin();
        int c = urls.count();
        if(c > 1)
        {
            QString questionString = i18n("Import one contact into your addressbook?", "Import %n contacts into your addressbook?", c);
            if(KMessageBox::questionYesNo(this, questionString, i18n("Import Contacts?"), i18n("Import"), i18n("Do Not Import")) == KMessageBox::Yes)
            {
                for(; it != urls.end(); ++it)
                    emit urlDropped(*it);
            }
        }
        else if(c == 1)
            emit urlDropped(*it);
    }
    else if(KVCardDrag::decode(e, vcards))
    {
        KABC::VCardConverter converter;

        const KABC::Addressee::List list = converter.parseVCards(vcards);
        KABC::Addressee::List::ConstIterator it;
        for(it = list.begin(); it != list.end(); ++it)
        {
            KABC::Addressee a = mCore->addressBook()->findByUid((*it).uid());
            if(a.isEmpty())      // not yet in address book
            {
                mCore->addressBook()->insertAddressee(*it);
                emit modified();
            }
        }

        mActiveView->refresh();
    }
}
예제 #23
0
RenameDialog::RenameDialog(const KURL::List& items) :
    KDialogBase(Plain, i18n("Rename Items"),
                Ok|Cancel, Ok)
{
    setButtonOK(KGuiItem(i18n("Rename"), "apply"));

    QVBoxLayout* topLayout = new QVBoxLayout(plainPage(), 0, spacingHint());
    topLayout->setMargin(KDialog::marginHint());

    const int itemCount = items.count();
    QLabel* editLabel = new QLabel(i18n("Rename the %n selected items to:", "Rename the %n selected items to:", itemCount),
                                   plainPage());

    m_lineEdit = new KLineEdit(plainPage());
    m_newName = i18n("New name #");
    assert(itemCount > 1);
    QString postfix(items[0].prettyURL().section('.',1));
    if (postfix.length() > 0) {
        // The first item seems to have a postfix (e. g. 'jpg' or 'txt'). Now
        // check whether all other items have the same postfix. If this is the
        // case, add this postfix to the name suggestion.
        postfix.insert(0, '.');
        for (int i = 1; i < itemCount; ++i) {
            if (!items[i].prettyURL().contains(postfix)) {
                // at least one item does not have the same postfix
                postfix.truncate(0);
                break;
            }
        }
    }

    const int selectionLength = m_newName.length();
    if (postfix.length() > 0) {
        m_newName.append(postfix);
    }
    m_lineEdit->setText(m_newName);
    m_lineEdit->setSelection(0, selectionLength - 1);
    m_lineEdit->setFocus();

    QLabel* infoLabel = new QLabel(i18n("(# will be replaced by ascending numbers)"), plainPage());

    topLayout->addWidget(editLabel);
    topLayout->addWidget(m_lineEdit);
    topLayout->addWidget(infoLabel);
}
예제 #24
0
KURL::List CopyTo::copy(const KURL::List& sourceList, const KURL& destination )
{
    m_listCopy = true;
    m_destList.clear();
    KURL targetDirURL = KURL();
    if ( destination.isEmpty() )
    {
        targetDirURL = m_InitialDirUrl;
    } else
    {
        targetDirURL = destination;
    }
    bool doCopy = true;
    if (!QExtFileInfo::exists(targetDirURL, false, 0L))
    {
        doCopy = QExtFileInfo::createDir(targetDirURL, 0L);
    }

    KIO::UDSEntry entry;
    if (doCopy)
    {
        QString path;
        for (uint i = 0; i < sourceList.count(); i++)
        {
            KURL srcURL = sourceList[i];
            KIO::NetAccess::stat(srcURL, entry, 0);
            KFileItem item(entry, srcURL, false, true);
            KURL u = targetDirURL;
            u.setPath(targetDirURL.path(1) + srcURL.fileName());
            if (item.isDir())
                u.adjustPath(1);
            path = u.path();
            if (path != "." && path != "..")
                m_destList.append(u);
        }

        KIO::CopyJob *job = KIO::copy(sourceList, targetDirURL, true);
        connect( job, SIGNAL(result( KIO::Job *)),
                 SLOT  (slotResult( KIO::Job *)));
    }

    return m_destList;

}
예제 #25
0
TQDragObject *KFileDetailView::dragObject()
{
    // create a list of the URL:s that we want to drag
    KURL::List urls;
    KFileItemListIterator it( * KFileView::selectedItems() );
    for ( ; it.current(); ++it ){
        urls.append( (*it)->url() );
    }
    TQPixmap pixmap;
    if( urls.count() > 1 )
        pixmap = DesktopIcon( "tdemultiple", TDEIcon::SizeSmall );
    if( pixmap.isNull() )
        pixmap = currentFileItem()->pixmap( TDEIcon::SizeSmall );

    TQPoint hotspot;
    hotspot.setX( pixmap.width() / 2 );
    hotspot.setY( pixmap.height() / 2 );
    TQDragObject* myDragObject = new KURLDrag( urls, widget() );
    myDragObject->setPixmap( pixmap, hotspot );
    return myDragObject;
}
예제 #26
0
//-----------------------------------------------
void KFileDnDDetailView::startDrag(){

    kdDebug (9020) << "KFileDnDDetailView::startDrag()" << endl;

	// create a list of the URL:s that we want to drag
	KURL::List urls;
	KFileItemListIterator it( * KFileView::selectedItems() );
	for ( ; it.current(); ++it ){
		urls.append( (*it)->url() );
	}
	QPixmap pixmap;
	if( urls.count() > 1 ){
		pixmap = DesktopIcon( "kmultiple", 16 );
	}
	if( pixmap.isNull() )
		pixmap = currentFileItem()->pixmap( 16 );	
	QPoint hotspot;
	hotspot.setX( pixmap.width() / 2 );
	hotspot.setY( pixmap.height() / 2 );
	m_dragObject = KURLDrag::newDrag( urls, widget() );
	m_dragObject->setPixmap( pixmap, hotspot );
	m_dragObject->drag();   // start the drag
}
예제 #27
0
// private slot
void kpMainWindow::slotPasteFromFile ()
{
#if DEBUG_KP_MAIN_WINDOW
    kdDebug () << "kpMainWindow::slotPasteFromFile()" << endl;
#endif

    if (toolHasBegunShape ())
        tool ()->endShapeInternal ();


    KURL::List urls = askForOpenURLs (i18n ("Paste From File"),
                                      m_lastPasteFromURL.url (),
                                      false/*only 1 URL*/);

    if (urls.count () != 1)
        return;

    KURL url = urls.first ();
    m_lastPasteFromURL = url;


    QPixmap pixmap = kpDocument::getPixmapFromFile (url,
        false/*show error message if doesn't exist*/,
        this);


    if (pixmap.isNull ())
        return;


    addRecentURL (url);

    paste (kpSelection (kpSelection::Rectangle,
                        QRect (0, 0, pixmap.width (), pixmap.height ()),
                        pixmap,
                        selectionTransparency ()));
}
예제 #28
0
void PrintWrapper::slotPrint()
{
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
    struct sigaction action;
#endif /* HAVE_SIGACTION && !HAVE_SIGSET*/

    // read variables from command line
    QString printer = args->getOption("d");
    QString title = args->getOption("t");
    int ncopies = QString(args->getOption("n")).toInt();
    QString job_mode = args->getOption("j");
    QString system = args->getOption("system");
    KStringList optlist = args->getOptionList("o");
    QMap< QString, QString > opts;
    KURL::List files;
    QStringList filestoprint;
    force_stdin = args->isSet("stdin");
    docopy = args->isSet("c");
    bool nodialog = !(args->isSet("dialog"));

    if(isatty(0))
    {
        kdDebug(500) << "stdin is a terminal, disabling it" << endl;
        check_stdin = false;
    }

    // parse options
    for(KStringList::ConstIterator it = optlist.begin(); it != optlist.end(); ++it)
    {
        QStringList l = QStringList::split('=', QString(*it), false);
        if(l.count() >= 1)
            opts[l[0]] = (l.count() == 2 ? l[1] : QString::null);
    }

    // read file list
    for(int i = 0; i < args->count(); i++)
        files.append(args->url(i));

    // some clean-up
    args->clear();

    // set default values if necessary
    if(job_mode == "console")
        job_output = 1;
    else if(job_mode == "none")
        job_output = 2;
    else
        job_output = 0;

    // some checking
    if(files.count() > 0)
    {
        check_stdin = false;

        if(force_stdin)
        {
            showmsg(i18n("A file has been specified on the command line. Printing from STDIN will be disabled."), 1);
            force_stdin = false;
        }
    }
    if(nodialog && files.count() == 0 && !force_stdin && !check_stdin)
    {
        errormsg(i18n("When using '--nodialog', you must at least specify one file to print or use the '--stdin' flag."));
    }

    if(check_stdin)
    { // check if there's any input on stdin
        fd_set in;
        struct timeval tm;
        tm.tv_sec = 0;
        tm.tv_usec = 0;
        FD_ZERO(&in);
        FD_SET(0, &in);
        if(select(1, &in, NULL, NULL, &tm))
        { // we have data on stdin
            if(read(0, &readchar, 1) > 0)
            {
                force_stdin = true;
                check_stdin = false;
                dataread = true;
                kdDebug(500) << "input detected on stdin" << endl;
            }
            else
            {
                force_stdin = check_stdin = false;
                kdDebug(500) << "stdin closed and empty" << endl;
            }
        }
        else
            kdDebug(500) << "no input on stdin at startup" << endl;
    }

    // force_stdin ? or also check_stdin ?
    KPrinter::ApplicationType dialog_mode = (force_stdin || nodialog ? KPrinter::StandAlone : KPrinter::StandAlonePersistent);
    KPrinter::setApplicationType(dialog_mode);
    if(!force_stdin)
        KPrinter::addStandardPage(KPrinter::FilesPage);

    KPrinter kprinter;
    if(nodialog)
    {
        KMPrinter *prt(0);
        KMManager *mgr = KMManager::self();

        mgr->printerList(false);
        if(!printer.isEmpty())
            prt = mgr->findPrinter(printer);
        else
            prt = mgr->defaultPrinter();

        if(prt == 0)
            errormsg(i18n("The specified printer or the default printer could not be found."));
        else if(!prt->autoConfigure(&kprinter))
            errormsg(i18n("Operation aborted."));
    }
    else if(!printer.isEmpty())
        kprinter.setSearchName(printer);
    kprinter.setDocName(title);
    kprinter.initOptions(opts);
    kprinter.setOption("kde-filelist", files.toStringList().join("@@"));
    kdDebug(500) << kprinter.option("kde-filelist") << endl;
    if(ncopies > 0)
        kprinter.setNumCopies(ncopies);

    if(nodialog)
        slotPrintRequested(&kprinter);
    else
    {
        dlg = KPrintDialog::printerDialog(&kprinter, 0);
        if(dlg)
        {
            connect(dlg, SIGNAL(printRequested(KPrinter *)), SLOT(slotPrintRequested(KPrinter *)));
            if(check_stdin)
            {
                notif = new QSocketNotifier(0, QSocketNotifier::Read, this);
                connect(notif, SIGNAL(activated(int)), this, SLOT(slotGotStdin()));
                kdDebug(500) << "waiting for input on stdin" << endl;
            }
            dlg->exec();
            delete dlg;
        }
        else
            errormsg(i18n("Unable to construct the print dialog."));
    }
int main( int argc, char** argv ) {

  KAboutData aboutData( "test_cryptoconfig", 0, ki18n("CryptoConfig Test"), "0.1" );
  KCmdLineArgs::init( argc, argv, &aboutData );
  KApplication app( false );

  Kleo::CryptoConfig * config = new QGpgMECryptoConfig();

  // Dynamic querying of the options
  cout << "Components:" << endl;
  QStringList components = config->componentList();

  for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) {
    cout << "Component " << (*compit).toLocal8Bit().constData() << ":" << endl;
    const Kleo::CryptoConfigComponent* comp = config->component( *compit );
    assert( comp );
    QStringList groups = comp->groupList();
    for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) {
      const Kleo::CryptoConfigGroup* group = comp->group( *groupit );
      assert( group );
      cout << " Group " << (*groupit).toLocal8Bit().constData() << ": descr=\"" << group->description().toLocal8Bit().constData() << "\""
           << " level=" << group->level() << endl;
      QStringList entries = group->entryList();
      for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) {
        const Kleo::CryptoConfigEntry* entry = group->entry( *entryit );
        assert( entry );
        cout << "  Entry " << (*entryit).toLocal8Bit().constData() << ":"
             << " descr=\"" << entry->description().toLocal8Bit().constData() << "\""
             << " " << ( entry->isSet() ? "is set" : "is not set" );
        if ( !entry->isList() )
          switch( entry->argType() ) {
          case Kleo::CryptoConfigEntry::ArgType_None:
            break;
          case Kleo::CryptoConfigEntry::ArgType_Int:
            cout << " int value=" << entry->intValue();
            break;
          case Kleo::CryptoConfigEntry::ArgType_UInt:
            cout << " uint value=" << entry->uintValue();
            break;
          case Kleo::CryptoConfigEntry::ArgType_LDAPURL:
          case Kleo::CryptoConfigEntry::ArgType_URL:
            cout << " URL value=" << entry->urlValue().prettyUrl().toLocal8Bit().constData();
            // fallthrough
          case Kleo::CryptoConfigEntry::ArgType_Path:
            // fallthrough
          case Kleo::CryptoConfigEntry::ArgType_DirPath:
            // fallthrough
          case Kleo::CryptoConfigEntry::ArgType_String:

            cout << " string value=" << entry->stringValue().toLocal8Bit().constData();
            break;
          case Kleo::CryptoConfigEntry::NumArgType:
            // just metadata and should never actually occur in the switch
            break;
          }
        else // lists
        {
          switch( entry->argType() ) {
          case Kleo::CryptoConfigEntry::ArgType_None: {
            cout << " set " << entry->numberOfTimesSet() << " times";
            break;
          }
          case Kleo::CryptoConfigEntry::ArgType_Int: {
            assert( entry->isOptional() ); // empty lists must be allowed (see issue121)
            Q3ValueList<int> lst = entry->intValueList();
            QString str;
            for( Q3ValueList<int>::Iterator it = lst.begin(); it != lst.end(); ++it ) {
              str += QString::number( *it );
            }
            cout << " int values=" << str.toLocal8Bit().constData();
            break;
          }
          case Kleo::CryptoConfigEntry::ArgType_UInt: {
            assert( entry->isOptional() ); // empty lists must be allowed (see issue121)
            Q3ValueList<uint> lst = entry->uintValueList();
            QString str;
            for( Q3ValueList<uint>::Iterator it = lst.begin(); it != lst.end(); ++it ) {
              str += QString::number( *it );
            }
            cout << " uint values=" << str.toLocal8Bit().constData();
            break;
          }
          case Kleo::CryptoConfigEntry::ArgType_LDAPURL:
          case Kleo::CryptoConfigEntry::ArgType_URL: {
              assert( entry->isOptional() ); // empty lists must be allowed (see issue121)
              KUrl::List urls = entry->urlValueList();
              cout << " url values=" << urls.toStringList().join(" ").toLocal8Bit().constData() << "\n    ";
          }
            // fallthrough
          case Kleo::CryptoConfigEntry::ArgType_Path:
            // fallthrough
          case Kleo::CryptoConfigEntry::ArgType_DirPath:
            // fallthrough
          case Kleo::CryptoConfigEntry::ArgType_String: {
            assert( entry->isOptional() ); // empty lists must be allowed (see issue121)
            QStringList lst = entry->stringValueList();
            cout << " string values=" << lst.join(" ").toLocal8Bit().constData();
            break;
          }
          case Kleo::CryptoConfigEntry::NumArgType:
            // just metadata and should never actually occur in the switch
            break;
          }
        }
        cout << endl;
      }
      // ...
    }
  }

  {
    // Static querying of a single boolean option
    static const char* s_groupName = "Monitor";
    static const char* s_entryName = "quiet";
    Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
    if ( entry ) {
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None );
      bool val = entry->boolValue();
      cout << "quiet option initially: " << ( val ? "is set" : "is not set" ) << endl;

      entry->setBoolValue( !val );
      assert( entry->isDirty() );
      config->sync( true );

      // Clear cached values!
      config->clear();

      // Check new value
      Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
      assert( entry );
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_None );
      cout << "quiet option now: " << ( val ? "is set" : "is not set" ) << endl;
      assert( entry->boolValue() == !val );

      // Set to default
      entry->resetToDefault();
      assert( entry->boolValue() == false ); // that's the default
      assert( entry->isDirty() );
      assert( !entry->isSet() );
      config->sync( true );
      config->clear();

      // Check value
      entry = config->entry( "dirmngr", s_groupName, s_entryName );
      assert( !entry->isDirty() );
      assert( !entry->isSet() );
      cout << "quiet option reset to default: " << ( entry->boolValue() ? "is set" : "is not set" ) << endl;
      assert( entry->boolValue() == false );

      // Reset old value
      entry->setBoolValue( val );
      assert( entry->isDirty() );
      config->sync( true );

      cout << "quiet option reset to initial: " << ( val ? "is set" : "is not set" ) << endl;
    }
    else
      cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl;
  }

  {
    // Static querying and setting of a single int option
    static const char* s_groupName = "LDAP";
    static const char* s_entryName = "ldaptimeout";
    Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
    if ( entry ) {
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt );
      uint val = entry->uintValue();
      cout << "LDAP timeout initially: " << val << " seconds." << endl;

      // Test setting the option directly, then querying again
      //system( "echo 'ldaptimeout:0:101' | gpgconf --change-options dirmngr" );
      // Now let's do it with the C++ API instead
      entry->setUIntValue( 101 );
      assert( entry->isDirty() );
      config->sync( true );

      // Clear cached values!
      config->clear();

      // Check new value
      Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
      assert( entry );
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_UInt );
      cout << "LDAP timeout now: " << entry->uintValue() << " seconds." << endl;
      assert( entry->uintValue() == 101 );

      // Set to default
      entry->resetToDefault();
      assert( entry->uintValue() == 100 );
      assert( entry->isDirty() );
      assert( !entry->isSet() );
      config->sync( true );
      config->clear();

      // Check value
      entry = config->entry( "dirmngr", s_groupName, s_entryName );
      assert( !entry->isDirty() );
      assert( !entry->isSet() );
      cout << "LDAP timeout reset to default, " << entry->uintValue() << " seconds." << endl;
      assert( entry->uintValue() == 100 );

      // Reset old value
      entry->setUIntValue( val );
      assert( entry->isDirty() );
      config->sync( true );

      cout << "LDAP timeout reset to initial " << val << " seconds." << endl;
    }
    else
      cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl;
  }

  {
    // Static querying and setting of a single string option
    static const char* s_groupName = "Debug";
    static const char* s_entryName = "log-file";
    Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
    if ( entry ) {
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path );
      QString val = entry->stringValue();
      cout << "Log-file initially: " << val.toLocal8Bit().constData() << endl;

      // Test setting the option, sync'ing, then querying again
      entry->setStringValue( QString::fromUtf8( "/tmp/test:%e5ä" ) );
      assert( entry->isDirty() );
      config->sync( true );

      // Let's see how it prints it
      system( "gpgconf --list-options dirmngr | grep log-file" );

      // Clear cached values!
      config->clear();

      // Check new value
      Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
      assert( entry );
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_Path );
      cout << "Log-file now: " << entry->stringValue().toLocal8Bit().constData() << endl;
      assert( entry->stringValue() == QString::fromUtf8( "/tmp/test:%e5ä" ) ); // (or even with %e5 decoded)

      // Reset old value
#if 0
      QString arg( val );
      if ( !arg.isEmpty() )
        arg.prepend( '"' );
      Q3CString sys;
      sys.sprintf( "echo 'log-file:%s' | gpgconf --change-options dirmngr", arg.local8Bit().data() );
      system( sys.data() );
#endif
      entry->setStringValue( val );
      assert( entry->isDirty() );
      config->sync( true );

      cout << "Log-file reset to initial " << val.toLocal8Bit().constData() << endl;
    }
    else
      cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl;
  }

  {
    // Static querying and setting of the LDAP URL list option
    static const char* s_groupName = "LDAP";
    static const char* s_entryName = "LDAP Server";
    Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
    if ( entry ) {
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_LDAPURL );
      assert( entry->isList() );
      KUrl::List val = entry->urlValueList();
      cout << "URL list initially: " << val.toStringList().join(", ").toLocal8Bit().constData() << endl;

      // Test setting the option, sync'ing, then querying again
      KUrl::List lst;
      // We use non-empty paths to workaround a bug in KUrl (kdelibs-3.2)
      lst << KUrl( "ldap://a:389/?b" );
      // Test with query containing a literal ':' (KUrl supports this)
      // and a ' ' (KUrl will escape it, see issue119)
      lst << KUrl( "ldap://foo:389/?a:b c" );
      lst << KUrl( "ldap://server:389/?a%3db,c=DE" ); // the query contains a literal ','
      //cout << " trying to set: " << lst.toStringList().join(", ").local8Bit() << endl;
      assert( lst[0].query() == "?b" );
      assert( lst[1].query() == "?a:b%20c" ); // see, the space got escaped
      entry->setURLValueList( lst );
      assert( entry->isDirty() );
      config->sync( true );

      // Let's see how it prints it
      system( "gpgconf --list-options dirmngr | grep 'LDAP Server'" );

      // Clear cached values!
      config->clear();

      // Check new value
      Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", s_groupName, s_entryName );
      assert( entry );
      assert( entry->argType() == Kleo::CryptoConfigEntry::ArgType_LDAPURL );
      assert( entry->isList() );
      // Get raw a:b:c:d:e form
      QStringList asStringList = entry->stringValueList();
      assert( asStringList.count() == 3 );
      cout << "asStringList[0]=" << asStringList[0].toLocal8Bit().constData() << endl;
      cout << "asStringList[1]=" << asStringList[1].toLocal8Bit().constData() << endl;
      cout << "asStringList[2]=" << asStringList[2].toLocal8Bit().constData() << endl;
      assert( asStringList[0] == "a:389:::b" );
      assert( asStringList[1] == "foo:389:::a%3ab c" ); // the space must be decoded (issue119)
      assert( asStringList[2] == "server:389:::a=b,c=DE" ); // all decoded
      // Get KUrl form
      KUrl::List newlst = entry->urlValueList();
      cout << "URL list now: " << newlst.toStringList().join(", ").toLocal8Bit().constData() << endl;
      assert( newlst.count() == 3 );
      //cout << "newlst[0]=" << newlst[0].url().local8Bit() << endl;
      //cout << "lst[0]=" << lst[0].url().local8Bit() << endl;
      assert( newlst[0] == lst[0] );
      assert( newlst[1] == lst[1] );
      assert( newlst[2].url() == "ldap://server:389/?a=b,c=DE" ); // != lst[2] due to the encoded =

      // Reset old value
      entry->setURLValueList( val );
      assert( entry->isDirty() );
      config->sync( true );

      cout << "URL list reset to initial: " << val.toStringList().join(", ").toLocal8Bit().constData() << endl;
    }
    else
      cout << "Entry 'dirmngr/" << s_groupName << "/" << s_entryName << "' not found" << endl;
  }

  cout << "Done." << endl;
}
예제 #30
0
void DolphinView::renameSelectedItems()
{
    const KURL::List urls = selectedURLs();
    if (urls.count() > 1) {
        // More than one item has been selected for renaming. Open
        // a rename dialog and rename all items afterwards.
        RenameDialog dialog(urls);
        if (dialog.exec() == QDialog::Rejected) {
            return;
        }

        DolphinView* view = Dolphin::mainWin().activeView();
        const QString& newName = dialog.newName();
        if (newName.isEmpty()) {
            view->statusBar()->setMessage(i18n("The new item name is invalid."),
                                          DolphinStatusBar::Error);
        }
        else {
            UndoManager& undoMan = UndoManager::instance();
            undoMan.beginMacro();

            assert(newName.contains('#'));

            const int urlsCount = urls.count();
            ProgressIndicator* progressIndicator =
                new  ProgressIndicator(i18n("Renaming items..."),
                                       i18n("Renaming finished."),
                                       urlsCount);

            // iterate through all selected items and rename them...
            const int replaceIndex = newName.find('#');
            assert(replaceIndex >= 0);
            for (int i = 0; i < urlsCount; ++i) {
                const KURL& source = urls[i];
                QString name(newName);
                name.replace(replaceIndex, 1, renameIndexPresentation(i + 1, urlsCount));

                if (source.fileName() != name) {
                    KURL dest(source.upURL());
                    dest.addPath(name);

                    const bool destExists = KIO::NetAccess::exists(dest, false, view);
                    if (destExists) {
                        delete progressIndicator;
                        progressIndicator = 0;
                        view->statusBar()->setMessage(i18n("Renaming failed (item '%1' already exists).").arg(name),
                                                      DolphinStatusBar::Error);
                        break;
                    }
                    else if (KIO::NetAccess::file_move(source, dest)) {
                        // TODO: From the users point of view he executed one 'rename n files' operation,
                        // but internally we store it as n 'rename 1 file' operations for the undo mechanism.
                        DolphinCommand command(DolphinCommand::Rename, source, dest);
                        undoMan.addCommand(command);
                    }
                }

                progressIndicator->execOperation();
            }
            delete progressIndicator;
            progressIndicator = 0;

            undoMan.endMacro();
        }
    }
    else {
        // Only one item has been selected for renaming. Use the custom
        // renaming mechanism from the views.
        assert(urls.count() == 1);
        if (m_mode == DetailsView) {
            QListViewItem* item = m_detailsView->firstChild();
            while (item != 0) {
                if (item->isSelected()) {
                    m_detailsView->rename(item, DolphinDetailsView::NameColumn);
                    break;
                }
                item = item->nextSibling();
            }
        }
        else {
            KFileIconViewItem* item = static_cast<KFileIconViewItem*>(m_iconsView->firstItem());
            while (item != 0) {
                if (item->isSelected()) {
                    item->rename();
                    break;
                }
                item = static_cast<KFileIconViewItem*>(item->nextItem());
            }
        }
    }
}