Пример #1
0
QString DolphinView::selectionStatusBarText() const
{
    QString text;
    const KFileItemList* list = selectedItems();
    assert((list != 0) && !list->isEmpty());

    int fileCount = 0;
    int folderCount = 0;
    KIO::filesize_t byteSize = 0;
    for (KFileItemListIterator it(*list); it.current() != 0; ++it) {
        KFileItem* item = it.current();
        if (item->isDir()) {
            ++folderCount;
        }
        else {
            ++fileCount;
            byteSize += item->size();
        }
    }

    if (folderCount>0) {
        text = i18n("1 Folder selected","%n Folders selected", folderCount);
    }

    if ((fileCount > 0) && (folderCount > 0)) {
        text += ", ";
    }

    if (fileCount > 0) {
        const QString sizeText(KIO::convertSize(byteSize));
        text += i18n("1 File selected (%1)", "%n Files selected (%1)", fileCount).arg(sizeText);
    }

    return text;
}
Пример #2
0
void AsyncFileTester::checkIfFolder(const QModelIndex &index, QObject *object, const char *method)
{
    if (!index.isValid()) {
        callResultMethod(object, method, index, false);
        return;
    }

    KFileItem item = static_cast<const ProxyModel*>(index.model())->itemForIndex(index);
    KUrl url = item.targetUrl();
    
    if (item.isDir()) {
        callResultMethod(object, method, index, true);
        return;
    }
    
    if (item.isDesktopFile()) {
        // Check if the desktop file is a link to a local folder
        KDesktopFile file(url.path());
        if (file.readType() == "Link") {
            url = file.readUrl();
            if (url.isLocalFile()) {
                KFileItem destItem(KFileItem::Unknown, KFileItem::Unknown, url);
                callResultMethod(object, method, index, destItem.isDir());
                return;
            }
            
            if (KProtocolInfo::protocolClass(url.protocol()) == QString(":local")) {
                AsyncFileTester *tester = new AsyncFileTester(index, object, method);
                tester->delayedFolderCheck(url);
                return;
            }
        }
    }
    callResultMethod(object, method, index, false);
}
void View::openIndex(const QModelIndex &index)
{
  KFileItem item = index.data(DirModel::FileItemRole).value<KFileItem>();
  
  if (item.isDir()) {
    m_freezeUrlUpdates = true;
    openUrl(item.url());
  }
}
Пример #4
0
void DolphinView::slotCompleted()
{
    m_refreshing = true;

    KFileView* view = fileView();
    view->clearView();

    // TODO: in Qt4 the code should get a lot
    // simpler and nicer due to Interview...
    if (m_iconsView != 0) {
        m_iconsView->beginItemUpdates();
    }
    if (m_detailsView != 0) {
        m_detailsView->beginItemUpdates();
    }

    if (m_showProgress) {
        m_statusBar->setProgressText(QString::null);
        m_statusBar->setProgress(100);
        m_showProgress = false;
    }

    KFileItemList items(m_dirLister->items());
    KFileItemListIterator it(items);

    m_fileCount = 0;
    m_folderCount = 0;

    KFileItem* item = 0;
    while ((item = it.current()) != 0) {
        view->insertItem(item);
        if (item->isDir()) {
            ++m_folderCount;
        }
        else {
            ++m_fileCount;
        }
        ++it;
    }

    updateStatusBar();

    if (m_iconsView != 0) {
        // Prevent a flickering of the icon view widget by giving a small
        // timeslot to swallow asynchronous update events.
        m_iconsView->setUpdatesEnabled(false);
        QTimer::singleShot(10, this, SLOT(slotDelayedUpdate()));
    }

    if (m_detailsView != 0) {
        m_detailsView->endItemUpdates();
        m_refreshing = false;
    }
}
Пример #5
0
void DolphinView::updateURL()
{
    KFileView* fileView = (m_iconsView != 0) ? static_cast<KFileView*>(m_iconsView) :
                                               static_cast<KFileView*>(m_detailsView);

    KFileItem* fileItem = fileView->currentFileItem();
    if (fileItem == 0) {
        return;
    }

    if (fileItem->isDir()) {
        // Prefer the local path over the URL. This assures that the
        // volume space information is correct. Assuming that the URL is media:/sda1,
        // and the local path is /windows/C: For the URL the space info is related
        // to the root partition (and hence wrong) and for the local path the space
        // info is related to the windows partition (-> correct).
        const QString localPath(fileItem->localPath());
        if (localPath.isEmpty()) {
            setURL(fileItem->url());
        }
        else {
            setURL(KURL(localPath));
        }
    }
    else if (fileItem->isFile()) {
       // allow to browse through ZIP and tar files
       KMimeType::Ptr mime = fileItem->mimeTypePtr();
       if (mime->is("application/x-zip")) {
           KURL url = fileItem->url();
           url.setProtocol("zip");
           setURL(url);
       }
       else if (mime->is("application/x-tar") ||
                mime->is("application/x-tarz") ||
                mime->is("application/x-tbz") ||
                mime->is("application/x-tgz") ||
                mime->is("application/x-tzo")) {
           KURL url = fileItem->url();
           url.setProtocol("tar");
           setURL(url);
       }
       else {
           fileItem->run();
       }
    }
    else {
        fileItem->run();
    }
}
Пример #6
0
void KFileDetailView::slotAutoOpen()
{
    d->autoOpenTimer.stop();
    if( !d->dropItem )
        return;

    KFileItem *fileItem = d->dropItem->fileInfo();
    if (!fileItem)
        return;

    if( fileItem->isFile() )
        return;

    if ( fileItem->isDir() || fileItem->isLink())
        sig->activate( fileItem );
}
void InformationPanelContent::showItem(const KFileItem& item)
{
    m_pendingPreview = false;

    const KUrl itemUrl = item.url();
    const bool isSearchUrl = itemUrl.protocol().contains("search") && item.nepomukUri().isEmpty();
    if (!applyPlace(itemUrl)) {
        setNameLabelText(item.text());
        if (isSearchUrl) {
            // in the case of a search-URL the URL is not readable for humans
            // (at least not useful to show in the Information Panel)
            KIconLoader iconLoader;
            QPixmap icon = iconLoader.loadIcon("nepomuk",
                                               KIconLoader::NoGroup,
                                               KIconLoader::SizeEnormous);
            m_preview->setPixmap(icon);
        } else {
            // try to get a preview pixmap from the item...
            m_pendingPreview = true;

            // Mark the currently shown preview as outdated. This is done
            // with a small delay to prevent a flickering when the next preview
            // can be shown within a short timeframe. This timer is not started
            // for directories, as directory previews might fail and return the
            // same icon.
            if (!item.isDir()) {
                m_outdatedPreviewTimer->start();
            }

            KIO::PreviewJob* job = KIO::filePreview(KFileItemList() << item, QSize(m_preview->width(), m_preview->height()));
            job->setScaleType(KIO::PreviewJob::Unscaled);

            connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)),
                    this, SLOT(showPreview(const KFileItem&, const QPixmap&)));
            connect(job, SIGNAL(failed(const KFileItem&)),
                    this, SLOT(showIcon(const KFileItem&)));
        }
    }
Пример #8
0
void DolphinViewContainer::slotItemTriggered(const KFileItem& item)
{
    KUrl url = item.targetUrl();

    if (item.isDir()) {
        m_view->setUrl(url);
        return;
    }

    const GeneralSettings* settings = DolphinSettings::instance().generalSettings();
    const bool browseThroughArchives = settings->browseThroughArchives();
    if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
        // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
        // zip:/<path>/ when clicking on a zip file, etc.
        // The .protocol file specifies the mimetype that the kioslave handles.
        // Note that we don't use mimetype inheritance since we don't want to
        // open OpenDocument files as zip folders...
        const QString protocol = KProtocolManager::protocolForArchiveMimetype(item.mimetype());
        if (!protocol.isEmpty()) {
            url.setProtocol(protocol);
            m_view->setUrl(url);
            return;
        }
    }

    if (item.mimetype() == "application/x-desktop") {
        // redirect to the url in Type=Link desktop files
        KDesktopFile desktopFile(url.toLocalFile());
        if (desktopFile.hasLinkType()) {
            url = desktopFile.readUrl();
            m_view->setUrl(url);
            return;
        }
    }

    item.run();
}
bool
DirPlaylistTrackFilterProxyModel::filterAcceptsRow( int source_row,
                                                    const QModelIndex& source_parent ) const
{
    QModelIndex index = sourceModel()->index( source_row, 0, source_parent );

    QVariant qvar = index.data( KDirModel::FileItemRole );
    if( !qvar.canConvert<KFileItem>() )
        return false;

    KFileItem item = qvar.value<KFileItem>();

    if( item.name() == "." )
        return false;

    if( item.isDir() ||
        Playlists::isPlaylist( item.url() ) ||
        MetaFile::Track::isTrack( item.url() ) )
    {
        return QSortFilterProxyModel::filterAcceptsRow( source_row, source_parent );
    }

    return false;
}
Пример #10
0
void QExtFileInfo::slotNewEntries(KIO::Job *job, const KIO::UDSEntryList& udsList)
{
  KURL url = static_cast<KIO::ListJob *>(job)->url();
  url.adjustPath(-1);
  // avoid creating these QStrings again and again
  static const QString& dot = KGlobal::staticQString(".");
  static const QString& dotdot = KGlobal::staticQString("..");

  KIO::UDSEntryListConstIterator it = udsList.begin();
  KIO::UDSEntryListConstIterator end = udsList.end();
  KURL itemURL;
  for ( ; it != end; ++it )
  {
    QString name;

    // find out about the name
    KIO::UDSEntry::ConstIterator entit = (*it).begin();
    for( ; entit != (*it).end(); ++entit )
      if ( (*entit).m_uds == KIO::UDS_NAME )
      {
        name = (*entit).m_str;
        break;
      }

    if ( ! name.isEmpty() && name != dot && name != dotdot)
    {
      KFileItem* item = new KFileItem( *it, url, false, true );
      itemURL = item->url();
      if (item->isDir()) itemURL.adjustPath(1);
      for ( QPtrListIterator<QRegExp> filterIt( lstFilters ); filterIt.current(); ++filterIt )
      if ( filterIt.current()->exactMatch( item->text() ) )
           dirListItems.append(itemURL);
      delete item;
    }
  }
}
Пример #11
0
void ThumbView::slNewFileItems( const KFileItemList& items )
{
   kdDebug(28000) << "Creating thumbnails for fileItemList" << endl;

   /* Fill the pending jobs list. */
   KFileItemListIterator it( items );
   KFileItem *item = 0;
   for ( ; (item = it.current()); ++it )
   {
      QString filename = item->url().prettyURL();
      if( item->isDir() )
      {
	 /* create a dir pixmap */
      }
      else
      {
	 QPixmap p(m_basePix) ;
	 QPixmap mime( item->pixmap(0) );

	 if( p.width() > mime.width() && p.height() > mime.height() )
	 {
	    QPainter paint( &p );
	    paint.drawPixmap( (p.width()-mime.width())/2,
			      (p.height()-mime.height())/2,
			      mime );
	    paint.flush();
	 }

	 /* Create a new empty preview pixmap and store the pointer to it */
	 ThumbViewItem *newIconViewIt = new ThumbViewItem( m_iconView,
							   item->url().filename(),
							   createPixmap( p ),
							   item );

	 newIconViewIt->setItemUrl( item->url() );

	 /* tell the file item about the iconView-representation */
	 item->setExtraData( this, newIconViewIt );

	 m_pendingJobs.append( item );
      }
   }

   /*
     From a mail from Waldo Bastian pointing out problems with thumbview:

     2) I think you may end up creating two PreviewJob's in parallel
        when the slNewFileItems() function is called two times in
        quick succession. The current code doesn't seem to expect
        that, given the comment in slPreviewResult(). In the light of
        1) it might become fatal since you will not be able to call
        PreviewJob::removeItem on the proper job. I suggest to queue
        new items when a job is already running and start a new job
        once the first one is finished when there are any items left
        in the queue. Don't forget to delete items from the queue if
        they get deleted in the mean time.

        The strategy is as follows: In the global list m_pendingJobs
        the jobs to start are appended. Only if m_job is zero (no job
        is running) a job is started on the current m_pendingJobs list.
        The m_pendingJobs list is clear afterwords.
   */

   if( ! m_job && m_pendingJobs.count() > 0 )
   {
      /* Progress-Bar */
      m_progress->show();
      m_progress->setTotalSteps(m_pendingJobs.count());
      m_cntJobsStarted = 0;

      /* start a preview-job */
      m_job = KIO::filePreview(m_pendingJobs, m_pixWidth, m_pixHeight );

      if( m_job )
      {
	 connect( m_job, SIGNAL( result( KIO::Job * )),
		  this, SLOT( slPreviewResult( KIO::Job * )));
	 connect( m_job, SIGNAL( gotPreview( const KFileItem*, const QPixmap& )),
		  SLOT( slGotPreview( const KFileItem*, const QPixmap& ) ));

         m_pendingJobs.clear();

         /* KIO::Jo result is called in any way: Success, Failed, Error,
	  * thus connecting the failed is not really necessary.
	  */
        // connect( job, SIGNAL( failed( const KFileItem* )),
        //          this, SLOT( slotFailed( const KFileItem* ) ));

      }
   }
Пример #12
0
void KFileTreeBranch::addItems( const KFileItemList& list )
{
    KFileItemListIterator it( list );
    kdDebug(250) << "Adding " << list.count() << " items !" << endl;
    KFileItem *currItem;
    KFileTreeViewItemList treeViewItList;
    KFileTreeViewItem *parentItem = 0;

    while ( (currItem = it.current()) != 0 )
    {
        parentItem = parentKFTVItem( currItem );


        /* Only create a new KFileTreeViewItem if it does not yet exist */
        KFileTreeViewItem *newKFTVI =
            static_cast<KFileTreeViewItem *>(currItem->extraData( this ));

        if( ! newKFTVI )
        {
            newKFTVI = createTreeViewItem( parentItem, currItem );
            if (!newKFTVI)
            {
                // TODO: Don't fail if parentItem == 0
                ++it;
                continue;
            }
            currItem->setExtraData( this, newKFTVI );

            /* Cut off the file extension in case it is not a directory */
            if( !m_showExtensions && !currItem->isDir() )	/* Need to cut the extension */
            {
                TQString name = currItem->text();
                int mPoint = name.findRev( '.' );
                if( mPoint > 0 )
                    name = name.left( mPoint );
                newKFTVI->setText( 0, name );
            }
        }

        /* Now try to find out if there are children for dirs in the treeview */
        /* This stats a directory on the local file system and checks the */
        /* hardlink entry in the stat-buf. This works only for local directories. */
        if( dirOnlyMode() && !m_recurseChildren && currItem->isLocalFile( ) && currItem->isDir() )
        {
            KURL url = currItem->url();
            TQString filename = url.directory( false, true ) + url.fileName();
            /* do the stat trick of Carsten. The problem is, that the hardlink
             *  count only contains directory links. Thus, this method only seem
             * to work in dir-only mode */
            kdDebug(250) << "Doing stat on " << filename << endl;
            KDE_struct_stat statBuf;
            if( KDE_stat( TQFile::encodeName( filename ), &statBuf ) == 0 )
            {
                int hardLinks = statBuf.st_nlink;  /* Count of dirs */
                kdDebug(250) << "stat succeeded, hardlinks: " << hardLinks << endl;
                // If the link count is > 2, the directory likely has subdirs. If it's < 2
                // it's something weird like a mounted SMB share. In that case we don't know
                // if there are subdirs, thus show it as expandable.

                if( hardLinks != 2 )
                {
                    newKFTVI->setExpandable(true);
                }
                else
                {
                    newKFTVI->setExpandable(false);
                }
                if( hardLinks >= 2 ) // "Normal" directory with subdirs
                {
                    kdDebug(250) << "Emitting for " << url.prettyURL() << endl;
                    emit( directoryChildCount( newKFTVI, hardLinks-2)); // parentItem, hardLinks-1 ));
                }
            }
            else
            {
                kdDebug(250) << "stat of " << filename << " failed !" << endl;
            }
        }
        ++it;

        treeViewItList.append( newKFTVI );
    }

    emit newTreeViewItems( this, treeViewItList );
}
Пример #13
0
void KFileDetailView::slotSortingChanged( int col )
{
    // col is the section here, not the index!
    
    TQDir::SortSpec sort = sorting();
    int sortSpec = -1;
    bool reversed = (col == m_sortingCol) && (sort & TQDir::Reversed) == 0;
    m_sortingCol = col;

    switch( col ) {
        case COL_NAME:
            sortSpec = (sort & ~TQDir::SortByMask | TQDir::Name);
            break;
        case COL_SIZE:
            sortSpec = (sort & ~TQDir::SortByMask | TQDir::Size);
            break;
        case COL_DATE:
            sortSpec = (sort & ~TQDir::SortByMask | TQDir::Time);
            break;

        // the following columns have no equivalent in TQDir, so we set it
        // to TQDir::Unsorted and remember the column (m_sortingCol)
        case COL_OWNER:
        case COL_GROUP:
        case COL_PERM:
            // grmbl, TQDir::Unsorted == SortByMask.
            sortSpec = (sort & ~TQDir::SortByMask);// | TQDir::Unsorted;
            break;
        default:
            break;
    }

    if ( reversed )
        sortSpec |= TQDir::Reversed;
    else
        sortSpec &= ~TQDir::Reversed;

    if ( sort & TQDir::IgnoreCase )
        sortSpec |= TQDir::IgnoreCase;
    else
        sortSpec &= ~TQDir::IgnoreCase;


    KFileView::setSorting( static_cast<TQDir::SortSpec>( sortSpec ) );

    KFileItem *item;
    KFileItemListIterator it( *items() );

    if ( sortSpec & TQDir::Time ) {
        for ( ; (item = it.current()); ++it )
            viewItem(item)->setKey( sortingKey( item->time( TDEIO::UDS_MODIFICATION_TIME ), item->isDir(), sortSpec ));
    }

    else if ( sortSpec & TQDir::Size ) {
        for ( ; (item = it.current()); ++it )
            viewItem(item)->setKey( sortingKey( item->size(), item->isDir(),
                                                sortSpec ));
    }
    else { // Name or Unsorted -> use column text
        for ( ; (item = it.current()); ++it ) {
            KFileListViewItem *i = viewItem( item );
            i->setKey( sortingKey( i->text(m_sortingCol), item->isDir(),
                                   sortSpec ));
        }
    }

    TDEListView::setSorting( m_sortingCol, !reversed );
    TDEListView::sort();

    if ( !m_blockSortingSignal )
        sig->changeSorting( static_cast<TQDir::SortSpec>( sortSpec ) );
}
Пример #14
0
void InformationPanelContent::showItem(const KFileItem& item)
{
    // If there is a preview job, kill it to prevent that we have jobs for
    // multiple items running, and thus a race condition (bug 250787).
    if (m_previewJob) {
        m_previewJob->kill();
    }

    const QUrl itemUrl = item.url();
    const bool isSearchUrl = itemUrl.scheme().contains(QStringLiteral("search")) && item.localPath().isEmpty();
    if (!applyPlace(itemUrl)) {
        setNameLabelText(item.text());
        if (isSearchUrl) {
            // in the case of a search-URL the URL is not readable for humans
            // (at least not useful to show in the Information Panel)
            KIconLoader iconLoader;
            QPixmap icon = iconLoader.loadIcon(QStringLiteral("nepomuk"),
                                               KIconLoader::NoGroup,
                                               KIconLoader::SizeEnormous);
            m_preview->setPixmap(icon);
        } else {
            // try to get a preview pixmap from the item...

            // Mark the currently shown preview as outdated. This is done
            // with a small delay to prevent a flickering when the next preview
            // can be shown within a short timeframe. This timer is not started
            // for directories, as directory previews might fail and return the
            // same icon.
            if (!item.isDir()) {
                m_outdatedPreviewTimer->start();
            }

            m_previewJob = new KIO::PreviewJob(KFileItemList() << item, QSize(m_preview->width(), m_preview->height()));
            m_previewJob->setScaleType(KIO::PreviewJob::Unscaled);
            m_previewJob->setIgnoreMaximumSize(item.isLocalFile());
            if (m_previewJob->ui()) {
                KJobWidgets::setWindow(m_previewJob, this);
            }

            connect(m_previewJob.data(), &KIO::PreviewJob::gotPreview,
                    this, &InformationPanelContent::showPreview);
            connect(m_previewJob.data(), &KIO::PreviewJob::failed,
                    this, &InformationPanelContent::showIcon);
        }
    }

    if (m_metaDataWidget) {
        m_metaDataWidget->show();
        m_metaDataWidget->setItems(KFileItemList() << item);
    }

    if (InformationPanelSettings::previewsShown()) {
        const QString mimeType = item.mimetype();
        const bool usePhonon = mimeType.startsWith(QLatin1String("audio/")) || mimeType.startsWith(QLatin1String("video/"));
        if (usePhonon) {
            m_phononWidget->show();
            m_phononWidget->setUrl(item.targetUrl());
            if (m_preview->isVisible()) {
                m_phononWidget->setVideoSize(m_preview->size());
            }
        } else {
            m_phononWidget->hide();
            m_preview->setVisible(true);
        }
    } else {
        m_phononWidget->hide();
    }

    m_item = item;
}
Пример #15
0
void ServiceLoader::loadServices(const KFileItem item, DOM::DOMString &html, int &count)
{
  popups.clear();
  
  KURL url = item.url();
  QString mimeType = item.mimetype();
  QString mimeGroup = mimeType.left(mimeType.find('/'));
  
  urlList.clear();
  urlList.append(url);
  
  QStringList dirs = KGlobal::dirs()->findDirs( "data", "konqueror/servicemenus/" );
  KConfig config("metabarrc", true, false);
  config.setGroup("General");
  int maxActions = config.readNumEntry("MaxActions");
  bool matchAll = false; // config.readBoolEntry("MatchAll");
  
  int id = 0;
  QString idString;
  
  for(QStringList::Iterator dit = dirs.begin(); dit != dirs.end(); ++dit){
    idString.setNum(id);
  
    QDir dir(*dit);
    QStringList entries = dir.entryList("*.desktop", QDir::Files);
    
    for(QStringList::Iterator eit = entries.begin(); eit != entries.end(); ++eit){
      KSimpleConfig cfg( *dit + *eit, true );
      cfg.setDesktopGroup();
      
      if(cfg.hasKey("X-KDE-ShowIfRunning" )){
        const QString app = cfg.readEntry( "X-KDE-ShowIfRunning" );
        if(!kapp->dcopClient()->isApplicationRegistered(app.utf8())){
          continue;
        }
      }

      if(cfg.hasKey("X-KDE-Protocol")){
        const QString protocol = cfg.readEntry( "X-KDE-Protocol" );
        if(protocol != url.protocol()){
          continue;
        }
      }
      
      else if(url.protocol() == "trash"){
        continue;
      }

      if(cfg.hasKey("X-KDE-Require")){
        const QStringList capabilities = cfg.readListEntry( "X-KDE-Require" );
        if (capabilities.contains( "Write" )){
          continue;
        }
      }

      if ( cfg.hasKey( "Actions" ) && cfg.hasKey( "ServiceTypes" ) ){
          const QStringList types = cfg.readListEntry( "ServiceTypes" );
          const QStringList excludeTypes = cfg.readListEntry( "ExcludeServiceTypes" );
          bool ok = false;

          for (QStringList::ConstIterator it = types.begin(); it != types.end() && !ok; ++it){
            bool checkTheMimetypes = false;
          
            if(matchAll){
            // first check if we have an all mimetype
              if (*it == "all/all" || *it == "allfiles"){
                checkTheMimetypes = true;
              }
  
              // next, do we match all files?
              if (!ok && !item.isDir() && *it == "all/allfiles"){
                checkTheMimetypes = true;
              }
            }

            // if we have a mimetype, see if we have an exact or a type globbed match
            if(!ok && (!mimeType.isEmpty() && *it == mimeType) ||
              (!mimeGroup.isEmpty() && ((*it).right(1) == "*" && (*it).left((*it).find('/')) == mimeGroup)))
            {
              checkTheMimetypes = true;
            }

            if(checkTheMimetypes){
              ok = true;
              
              for(QStringList::ConstIterator itex = excludeTypes.begin(); itex != excludeTypes.end(); ++itex){
                if( ((*itex).right(1) == "*" && (*itex).left((*itex).find('/')) == mimeGroup) ||
                    ((*itex) == mimeType))
                {
                  ok = false;
                  break;
                }
              }
            }
          }
        if (ok){
          const QString priority = cfg.readEntry("X-KDE-Priority");
          const QString submenuName = cfg.readEntry( "X-KDE-Submenu" );
          bool usePopup = false;
          KPopupMenu *popup;
          
          if(!submenuName.isEmpty()){
            usePopup = true;
            
            if(popups[submenuName]){
              popup = popups[submenuName];
            }
            else{              
              MetabarWidget::addEntry(html, submenuName, "servicepopup://" + idString, "1rightarrow", "popup" + idString, count < maxActions ? QString::null : QString("hiddenaction"), count >= maxActions);
              
              popup = new KPopupMenu();
              popups.insert(idString, popup);
              
              count++;
            }
          }
          
          QValueList<KDEDesktopMimeType::Service> list = KDEDesktopMimeType::userDefinedServices( *dit + *eit, url.isLocalFile());
          
          for (QValueList<KDEDesktopMimeType::Service>::iterator it = list.begin(); it != list.end(); ++it){
          
            if(usePopup){
              KAction *action = new KAction((*it).m_strName, (*it).m_strIcon, KShortcut(), this, SLOT(runAction()), popup, idString.utf8());
              action->plug(popup);
            }
            else{
              MetabarWidget::addEntry(html, (*it).m_strName, "service://" + idString, (*it).m_strIcon, QString::null, count < maxActions ? QString::null : QString("hiddenaction"), count >= maxActions);
              count++;
            }
            
            services.insert(idString, *it);
            id++;
            idString.setNum(id);
          }
        }
      }
    }
  }
}
void InformationPanelContent::showItem(const KFileItem& item)
{
    m_pendingPreview = false;

    const KUrl itemUrl = item.url();
    const bool isSearchUrl = itemUrl.protocol().contains("search") && item.nepomukUri().isEmpty();
    if (!applyPlace(itemUrl)) {
        setNameLabelText(item.text());
        if (isSearchUrl) {
            // in the case of a search-URL the URL is not readable for humans
            // (at least not useful to show in the Information Panel)
            KIconLoader iconLoader;
            QPixmap icon = iconLoader.loadIcon("nepomuk",
                                               KIconLoader::NoGroup,
                                               KIconLoader::SizeEnormous);
            m_preview->setPixmap(icon);
        } else {
            // try to get a preview pixmap from the item...
            m_pendingPreview = true;

            // Mark the currently shown preview as outdated. This is done
            // with a small delay to prevent a flickering when the next preview
            // can be shown within a short timeframe. This timer is not started
            // for directories, as directory previews might fail and return the
            // same icon.
            if (!item.isDir()) {
                m_outdatedPreviewTimer->start();
            }

            KIO::PreviewJob* job = new KIO::PreviewJob(KFileItemList() << item, QSize(m_preview->width(), m_preview->height()));
            job->setScaleType(KIO::PreviewJob::Unscaled);
            job->setIgnoreMaximumSize(item.isLocalFile());
            if (job->ui()) {
                job->ui()->setWindow(this);
            }

            connect(job, SIGNAL(gotPreview(KFileItem,QPixmap)),
                    this, SLOT(showPreview(KFileItem,QPixmap)));
            connect(job, SIGNAL(failed(KFileItem)),
                    this, SLOT(showIcon(KFileItem)));
        }
    }

    if (m_metaDataWidget) {
        m_metaDataWidget->show();
        m_metaDataWidget->setItems(KFileItemList() << item);
    }

    if (InformationPanelSettings::previewsShown()) {
        const QString mimeType = item.mimetype();
        const bool usePhonon = mimeType.startsWith("audio/") || mimeType.startsWith("video/");
        if (usePhonon) {
            m_phononWidget->show();
            m_phononWidget->setUrl(item.targetUrl());
            if (m_preview->isVisible()) {
                m_phononWidget->setVideoSize(m_preview->size());
            }
        } else {
            m_phononWidget->hide();
            m_preview->setVisible(true);
        }
    } else {
        m_phononWidget->hide();
    }

    m_item = item;
}
void DolphinContextMenu::insertActionItems(KPopupMenu* popup,
                                           QValueVector<KDEDesktopMimeType::Service>& actionsVector)
{
    KPopupMenu* actionsMenu = new KPopupMenu();

    int actionsIndex = 0;

    QStringList dirs = KGlobal::dirs()->findDirs("data", "d3lphin/servicemenus/");

    KPopupMenu* menu = 0;
    for (QStringList::ConstIterator dirIt = dirs.begin(); dirIt != dirs.end(); ++dirIt) {
        QDir dir(*dirIt);
        QStringList entries = dir.entryList("*.desktop", QDir::Files);

        for (QStringList::ConstIterator entryIt = entries.begin(); entryIt != entries.end(); ++entryIt) {
            KSimpleConfig cfg(*dirIt + *entryIt, true);
            cfg.setDesktopGroup();
            if ((cfg.hasKey("Actions") || cfg.hasKey("X-KDE-GetActionMenu")) && cfg.hasKey("ServiceTypes")) {
                const QStringList types = cfg.readListEntry("ServiceTypes");
                for (QStringList::ConstIterator it = types.begin(); it != types.end(); ++it) {
                    // check whether the mime type is equal or whether the
                    // mimegroup (e. g. image/*) is supported

                    bool insert = false;
                    if ((*it) == "all/allfiles") {
                        // The service type is valid for all files, but not for directories.
                        // Check whether the selected items only consist of files...
                        const KFileItemList* list = m_dolphinView->selectedItems();
                        assert(list != 0);

                        KFileItemListIterator mimeIt(*list);
                        KFileItem* item = 0;
                        insert = true;
                        while (insert && ((item = mimeIt.current()) != 0)) {
                            insert = !item->isDir();
                            ++mimeIt;
                        }
                    }

                    if (!insert) {
                        // Check whether the MIME types of all selected files match
                        // to the mimetype of the service action. As soon as one MIME
                        // type does not match, no service menu is shown at all.
                        const KFileItemList* list = m_dolphinView->selectedItems();
                        assert(list != 0);

                        KFileItemListIterator mimeIt(*list);
                        KFileItem* item = 0;
                        insert = true;
                        while (insert && ((item = mimeIt.current()) != 0)) {
                            const QString mimeType((*mimeIt)->mimetype());
                            const QString mimeGroup(mimeType.left(mimeType.find('/')));

                            insert  = (*it == mimeType) ||
                                      ((*it).right(1) == "*") &&
                                      ((*it).left((*it).find('/')) == mimeGroup);
                            ++mimeIt;
                        }
                    }

                    if (insert) {
                        menu = actionsMenu;

                        const QString submenuName = cfg.readEntry( "X-KDE-Submenu" );
                        if (!submenuName.isEmpty()) {
                            menu = new KPopupMenu();
                            actionsMenu->insertItem(submenuName, menu, submenuID);
                        }

                        QValueList<KDEDesktopMimeType::Service> userServices =
                            KDEDesktopMimeType::userDefinedServices(*dirIt + *entryIt, true);

                        QValueList<KDEDesktopMimeType::Service>::Iterator serviceIt;
                        for (serviceIt = userServices.begin(); serviceIt != userServices.end(); ++serviceIt) {
                            KDEDesktopMimeType::Service service = (*serviceIt);
                            if (!service.m_strIcon.isEmpty()) {
                                menu->insertItem(SmallIcon(service.m_strIcon),
                                                 service.m_strName,
                                                 actionsIDStart + actionsIndex);
                            }
                            else {
                                menu->insertItem(service.m_strName,
                                                 actionsIDStart + actionsIndex);
                            }
                            actionsVector.append(service);
                            ++actionsIndex;
                        }
                    }
                }
            }
        }
    }

    const int itemsCount = actionsMenu->count();
    if (itemsCount == 0) {
        // no actions are available at all, hence show the "Actions"
        // submenu disabled
        actionsMenu->setEnabled(false);
    }

    if (itemsCount == 1) {
        // Exactly one item is available. Instead of showing a sub menu with
        // only one item, show the item directly in the root menu.
        if (menu == actionsMenu) {
            // The item is an action, hence show the action in the root menu.
            const int id = actionsMenu->idAt(0);
            const QString text(actionsMenu->text(id));
            const QIconSet* iconSet = actionsMenu->iconSet(id);
            if (iconSet == 0) {
                popup->insertItem(text, id);
            }
            else {
                popup->insertItem(*iconSet, text, id);
            }
        }
        else {
            // The item is a sub menu, hence show the sub menu in the root menu.
            popup->insertItem(actionsMenu->text(submenuID), menu);
        }
        actionsMenu->deleteLater();
        actionsMenu = 0;
    }
    else {
        popup->insertItem(i18n("Actions"), actionsMenu);
    }
}
Пример #18
0
void KonqOperations::asyncDrop( const KFileItem & destItem )
{
    assert(m_info); // setDropInfo should have been called before asyncDrop
    bool m_destIsLocal = false;
    m_destUrl = destItem.mostLocalUrl(m_destIsLocal); // #168154

    //kDebug(1203) << "destItem->mode=" << destItem->mode() << " url=" << m_destUrl;
    // Check what the destination is
    if ( destItem.isDir() )
    {
        doDropFileCopy();
        return;
    }
    if ( !m_destIsLocal )
    {
        // We dropped onto a remote URL that is not a directory!
        // (e.g. an HTTP link in the sidebar).
        // Can't do that, but we can't prevent it before stating the dest....
        kWarning(1203) << "Cannot drop onto " << m_destUrl ;
        deleteLater();
        return;
    }
    if ( destItem.isDesktopFile() )
    {
        // Local .desktop file. What type ?
        KDesktopFile desktopFile( m_destUrl.path() );
        KConfigGroup desktopGroup = desktopFile.desktopGroup();
        if ( desktopFile.hasApplicationType() )
        {
            QString error;
            const QStringList urlStrList = m_info->urls.toStringList();
            if ( KToolInvocation::startServiceByDesktopPath( m_destUrl.path(), urlStrList, &error ) > 0 )
                KMessageBox::error( parentWidget(), error );
        }
        else
        {
            // Device or Link -> adjust dest
            if ( desktopFile.hasDeviceType() && desktopGroup.hasKey("MountPoint") ) {
                QString point = desktopGroup.readEntry( "MountPoint" );
                m_destUrl.setPath( point );
                QString dev = desktopFile.readDevice();
                KMountPoint::Ptr mp = KMountPoint::currentMountPoints().findByDevice( dev );
                // Is the device already mounted ?
                if ( mp ) {
                    doDropFileCopy();
                }
                else
                {
                    const bool ro = desktopGroup.readEntry( "ReadOnly", false );
                    const QByteArray fstype = desktopGroup.readEntry( "FSType" ).toLatin1();
                    KAutoMount* am = new KAutoMount( ro, fstype, dev, point, m_destUrl.path(), false );
                    connect( am, SIGNAL(finished()), this, SLOT(doDropFileCopy()) );
                }
                return;
            }
            else if ( desktopFile.hasLinkType() && desktopGroup.hasKey("URL") ) {
                m_destUrl = desktopGroup.readPathEntry("URL", QString());
                doDropFileCopy();
                return;
            }
            // else, well: mimetype, service, servicetype or .directory. Can't really drop anything on those.
        }
    }
    else
    {
        // Should be a local executable
        // (If this fails, there is a bug in KFileItem::acceptsDrops / KDirModel::flags)
        kDebug(1203) << m_destUrl.path() << "should be an executable";
        Q_ASSERT ( access( QFile::encodeName(m_destUrl.path()), X_OK ) == 0 );
        // Launch executable for each of the files
        QStringList args;
        const KUrl::List lst = m_info->urls;
        KUrl::List::ConstIterator it = lst.begin();
        for ( ; it != lst.end() ; it++ )
            args << (*it).path(); // assume local files
        kDebug(1203) << "starting " << m_destUrl.path() << " with " << lst.count() << " arguments";
        QProcess::startDetached( m_destUrl.path(), args );
    }
    deleteLater();
}