Esempio n. 1
0
bool TrashImpl::move( const TQString& src, const TQString& dest )
{
    if ( directRename( src, dest ) ) {
        // This notification is done by TDEIO::moveAs when using the code below
        // But if we do a direct rename we need to do the notification ourselves
        KDirNotify_stub allDirNotify( "*", "KDirNotify*" );
        KURL urlDest; urlDest.setPath( dest );
        urlDest.setPath( urlDest.directory() );
        allDirNotify.FilesAdded( urlDest );
        return true;
    }
    if ( m_lastErrorCode != TDEIO::ERR_UNSUPPORTED_ACTION )
        return false;

    KURL urlSrc, urlDest;
    urlSrc.setPath( src );
    urlDest.setPath( dest );
    kdDebug() << k_funcinfo << urlSrc << " -> " << urlDest << endl;
    TDEIO::CopyJob* job = TDEIO::moveAs( urlSrc, urlDest, false );
#ifdef TDEIO_COPYJOB_HAS_SETINTERACTIVE
    job->setInteractive( false );
#endif
    connect( job, TQT_SIGNAL( result(TDEIO::Job *) ),
             this, TQT_SLOT( jobFinished(TDEIO::Job *) ) );
    tqApp->eventLoop()->enterLoop();

    return m_lastErrorCode == 0;
}
Esempio n. 2
0
AtomicURL::AtomicURL( const KURL &url )
{
    if( url.isEmpty() )
        return;

    QString s = url.protocol() + "://";
    QString host = url.host();
    if( url.hasUser() )
    {
        s += url.user();
        host.prepend("@");
    }
    if( url.hasPass() )
        s += ':' + url.pass();
    if( url.port() )
        host += QString(":") + QString::number( url.port() );

    m_beginning = s + host;
    m_directory = url.directory();
    m_filename = url.fileName();
    m_end = url.query();
    if( url.hasRef() )
        m_end += QString("#") + url.ref();
    if (url != this->url())
    {
        debug() << "from: " << url << endl;
        debug() << "to:   " << this->url() << endl;
    }
}
Esempio n. 3
0
void TrashProtocol::mkdir( const KURL& url, int /*permissions*/ )
{
    INIT_IMPL;
    // create info about deleted dir
    // ############ Problem: we don't know the original path.
    // Let's try to avoid this case (we should get to copy() instead, for local files)
    kdDebug() << "mkdir: " << url << endl;
    QString dir = url.directory();

    if ( dir.length() <= 1 ) // new toplevel entry
    {
        // ## we should use TrashImpl::parseURL to give the right filename to createInfo
        int trashId;
        QString fileId;
        if ( !impl.createInfo( url.path(), trashId, fileId ) ) {
            error( impl.lastErrorCode(), impl.lastErrorMessage() );
        } else {
            if ( !impl.mkdir( trashId, fileId, permissions ) ) {
                (void)impl.deleteInfo( trashId, fileId );
                error( impl.lastErrorCode(), impl.lastErrorMessage() );
            } else
                finished();
        }
    } else {
        // Well it's not allowed to add a directory to an existing deleted directory.
        error( KIO::ERR_ACCESS_DENIED, url.prettyURL() );
    }
}
Esempio n. 4
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;
  }
}
Esempio n. 5
0
void SearchManager::startSearch(KURL const& root, SearchMode const& modo)
{
    canceled_ = false;

    //time_.restart();
    time_.start();

    Q_ASSERT(root.isValid());
    //Q_ASSERT(root.protocol() == "http" || root.protocol() == "https");

    if(root.hasHost() && (domain_.isNull() || domain_.isEmpty()))
    {
        setDomain(root.host() + root.directory());
        kdDebug(23100) << "Domain: " << domain_ << endl;
    }
    root_.setIsRoot(true);
    root_.setDepth(0);
    root_.setOriginalUrl(root.prettyURL());
    root_.setAbsoluteUrl(root);
    root_.setOnlyCheckHeader(false);
    root_.setRootUrl(root);

    search_mode_ = modo;
    if(modo == depth)
        Q_ASSERT(depth_ != -1);
    else if(modo == domain)
        Q_ASSERT(depth_ == -1);
    else
        Q_ASSERT(depth_ != -1);

    searching_ = true;

    //Q_ASSERT(domain_ != QString::null);
    checkRoot();
}
Esempio n. 6
0
void KImGalleryPlugin::deleteCancelledGallery(const KURL& url, const QString& sourceDirName, int recursionLevel, const QString& imageFormat)
{
    if (m_recurseSubDirectories && (recursionLevel >= 0)) {
        QStringList subDirList;
        QDir toplevel_dir = QDir( sourceDirName );
        toplevel_dir.setFilter( QDir::Dirs );
        subDirList = toplevel_dir.entryList();

        for (QStringList::ConstIterator it = subDirList.begin(); it != subDirList.end(); it++) {
            if (*it == "." || *it == ".." || *it == "thumbs" || (m_copyFiles && *it == "images")) {
                continue; //disregard the "." and ".." directories
            }
            deleteCancelledGallery( KURL( url.directory() + "/" + *it + "/" + url.fileName() ),
                                    sourceDirName + "/" + *it,
                                    recursionLevel > 1 ? recursionLevel - 1 : 0, imageFormat);
        }
    }

    const QString imgGalleryDir = url.directory();
    QDir thumb_dir( imgGalleryDir + QString::fromLatin1("/thumbs/"));
    QDir images_dir( imgGalleryDir + QString::fromLatin1("/images/"));
    QDir imageDir( sourceDirName, "*.png *.PNG *.gif *.GIF *.jpg *.JPG *.jpeg *.JPEG *.bmp *.BMP",
                   QDir::Name|QDir::IgnoreCase, QDir::Files|QDir::Readable);
    QFile file( url.path() );

    // Remove the image file ..
    file.remove();
    // ..all the thumbnails ..
    for (uint i=0; i < imageDir.count(); i++) {
        const QString imgName = imageDir[i];
        const QString imgNameFormat = imgName + extension(imageFormat);
        bool isRemoved = thumb_dir.remove(imgNameFormat);
        kdDebug(90170) << "removing: " << thumb_dir.path() << "/" << imgNameFormat << "; "<< isRemoved << endl;
    }
    // ..and the thumb directory
    thumb_dir.rmdir(thumb_dir.path());

    // ..and the images directory if images were to be copied
    if (m_copyFiles) {
        for (uint i=0; i < imageDir.count(); i++) {
            const QString imgName = imageDir[i];
            bool isRemoved = images_dir.remove(imgName);
            kdDebug(90170) << "removing: " << images_dir.path() << "/" << imgName << "; "<< isRemoved << endl;
        }
        images_dir.rmdir(images_dir.path());
    }
}
Esempio n. 7
0
void KexiImageContextMenu::saveAs()
{
	QString origFilename, fileExtension;
	bool dataIsEmpty = false;
	emit aboutToSaveAsRequested(origFilename, fileExtension, dataIsEmpty);

	if (dataIsEmpty) {
		kdWarning() << "KexiImageContextMenu::saveAs(): no data!" << endl;
		return;
	}
	if (!origFilename.isEmpty())
		origFilename = QString("/") + origFilename;

	if (fileExtension.isEmpty()) {
		// PNG data is the default
		fileExtension = "png";
	}
	
#ifdef Q_WS_WIN
	QString recentDir;
	QString fileName = QFileDialog::getSaveFileName(
		KFileDialog::getStartURL(":LastVisitedImagePath", recentDir).path() + origFilename,
		convertKFileDialogFilterToQFileDialogFilter(KImageIO::pattern(KImageIO::Writing)), 
		this, 0, i18n("Save Image to File"));
#else
	//! @todo add originalFileName! (requires access to KRecentDirs)
	QString fileName = KFileDialog::getSaveFileName(
		":LastVisitedImagePath", KImageIO::pattern(KImageIO::Writing), this, i18n("Save Image to File"));
#endif
	if (fileName.isEmpty())
		return;
	
	if (QFileInfo(fileName).extension().isEmpty())
		fileName += (QString(".")+fileExtension);
	kdDebug() << fileName << endl;
	KURL url;
	url.setPath( fileName );

#ifdef Q_WS_WIN
	//save last visited path
	if (url.isLocalFile())
		KRecentDirs::add(":LastVisitedImagePath", url.directory());
#endif

	QFile f(fileName);
	if (f.exists() && KMessageBox::Yes != KMessageBox::warningYesNo(this, 
		"<qt>"+i18n("File \"%1\" already exists."
		"<p>Do you want to replace it with a new one?")
		.arg(QDir::convertSeparators(fileName))+"</qt>",0, 
		KGuiItem(i18n("&Replace")), KGuiItem(i18n("&Don't Replace"))))
	{
		return;
	}

//! @todo use KURL?
	emit saveAsRequested(fileName);
}
Esempio n. 8
0
void Project::insertFile(const KURL& nameURL, bool repaint )
{
  if (d->excludeRx.exactMatch(nameURL.path()))
      return;
  KURL url = nameURL;

  if ( !d->baseURL.isParentOf(url) )
  {
    KURLRequesterDlg *urlRequesterDlg = new KURLRequesterDlg( d->baseURL.prettyURL(), d->m_mainWindow, "");
    urlRequesterDlg->setCaption(i18n("%1: Copy to Project").arg(nameURL.prettyURL(0, KURL::StripFileProtocol)));
    urlRequesterDlg->urlRequester()->setMode( KFile::Directory | KFile::ExistingOnly);
    urlRequesterDlg->exec();
    KURL destination = urlRequesterDlg->selectedURL();
    if (destination.isLocalFile())
    {
      QDir dir(destination.path());
      destination.setPath(dir.canonicalPath());
    }
    delete urlRequesterDlg;
    if ( !destination.isEmpty() )
    {
      CopyTo *dlg = new CopyTo(d->baseURL);
      connect(dlg, SIGNAL(deleteDialog(CopyTo*)), d,
                   SLOT(slotDeleteCopytoDlg(CopyTo*)));
      url = dlg->copy( nameURL, destination );
    }
    else  // Copy canceled, addition aborted
    {
      return;
    }
  }
  QDomElement  el;
  while ( d->baseURL.isParentOf(url) )
  {
    if ( !d->m_projectFiles.contains(url) )
    {
      el = d->dom.createElement("item");
      el.setAttribute("url", QuantaCommon::qUrl( QExtFileInfo::toRelative(url, d->baseURL) ));
      d->dom.firstChild().firstChild().appendChild( el );
      KURL u = url.upURL();
      ProjectURL *parentURL = d->m_projectFiles.find(u);
      int uploadStatus = 1;
      if (parentURL)
        uploadStatus = parentURL->uploadStatus;
      d->m_projectFiles.insert( new ProjectURL(url, "", uploadStatus, false, el) );
    }
    url.setPath(url.directory(false));
  }
  emit eventHappened("after_project_add", url.url(), QString::null);
  setModified();
  if ( repaint )
  {
    emit reloadTree( &(d->m_projectFiles), false, QStringList());
    emit newStatus();
  }
}
Esempio n. 9
0
KURL Proxy::realStreamUrl( KURL fakeStream, int sessionId )
{
    KURL realStream;
    realStream.setProtocol( "http" );
    realStream.setHost(fakeStream.host());
    realStream.setPort(fakeStream.port());
    realStream.setPath( "/databases" + fakeStream.directory() + "/items/" + fakeStream.fileName() );
    realStream.setQuery( QString("?session-id=") + QString::number(sessionId) );
    return realStream;
}
Esempio n. 10
0
void
ScriptManager::slotConfigureScript()
{
    const QString name = m_gui->listView->currentItem()->text( 0 );
    if( !m_scripts[name].process ) return;

    const KURL url = m_scripts[name].url;
    QDir::setCurrent( url.directory() );

    m_scripts[name].process->writeStdin( "configure" );
}
Esempio n. 11
0
void AtomicURL::setPath( const QString &path )
{
    KURL url;
    url.setPath( path );
    if( m_beginning->isEmpty() )
        *this = url;
    else
    {
        m_directory = url.directory();
        m_filename = url.fileName();
    }
}
Esempio n. 12
0
void FilePreview::showPreview(const KURL &url)
{
    if (!url.isLocalFile()){
        showPreview(NULL);
        return;
    }
    QString fileName = url.directory(false, false);
    if (!fileName.isEmpty() && (fileName[fileName.length() - 1] != '/'))
        fileName += '/';
    fileName += url.fileName(false);
    showPreview((const char*)fileName.local8Bit());
}
Esempio n. 13
0
void BaseTreeView::slotCreateFolder()
{
  bool ok;
  QString folderName = KInputDialog::getText(i18n("Create New Folder"), i18n("Folder name:"), "", &ok, this);
  if (ok)
  {
    KURL url = currentURL();
    if (currentKFileTreeViewItem()->isDir())
      url.setPath(url.path() + "/" + folderName + "/");
    else
      url.setPath(url.directory() + "/" + folderName +"/");
    QuantaNetAccess::mkdir(url, this, -1);
  }
}
Esempio n. 14
0
void KonqSidebarTree::addURL(KonqSidebarTreeTopLevelItem* item, const KURL & url)
{
    QString path;
    if (item)
       path = item->path();
    else
       path = m_dirtreeDir.dir.path();

    KURL destUrl;

    if (url.isLocalFile() && url.fileName().endsWith(".desktop"))
    {
       QString filename = findUniqueFilename(path, url.fileName());
       destUrl.setPath(filename);
       KIO::NetAccess::copy(url, destUrl, this);
    }
    else
    {
       QString name = url.host();
       if (name.isEmpty())
          name = url.fileName();
       QString filename = findUniqueFilename(path, name);
       destUrl.setPath(filename);

       KDesktopFile cfg(filename);
       cfg.writeEntry("Encoding", "UTF-8");
       cfg.writeEntry("Type","Link");
       cfg.writeEntry("URL", url.url());
       QString icon = "folder";
       if (!url.isLocalFile())
          icon = KMimeType::favIconForURL(url);
       if (icon.isEmpty())
          icon = KProtocolInfo::icon( url.protocol() );
       cfg.writeEntry("Icon", icon);
       cfg.writeEntry("Name", name);
       cfg.writeEntry("Open", false);
       cfg.sync();
    }

    KDirNotify_stub allDirNotify( "*", "KDirNotify*" );
    destUrl.setPath( destUrl.directory() );
    allDirNotify.FilesAdded( destUrl );

    if (item)
       item->setOpen(true);
}
Esempio n. 15
0
void KexiImageContextMenu::insertFromFile()
{
//	QWidget *focusWidget = qApp->focusWidget();
#ifdef Q_WS_WIN
	QString recentDir;
	QString fileName = QFileDialog::getOpenFileName(
		KFileDialog::getStartURL(":LastVisitedImagePath", recentDir).path(), 
		convertKFileDialogFilterToQFileDialogFilter(KImageIO::pattern(KImageIO::Reading)), 
		this, 0, i18n("Insert Image From File"));
	KURL url;
	if (!fileName.isEmpty())
		url.setPath( fileName );
#else
	KURL url( KFileDialog::getImageOpenURL(
		":LastVisitedImagePath", this, i18n("Insert Image From File")) );
//	QString fileName = url.isLocalFile() ? url.path() : url.prettyURL();

	//! @todo download the file if remote, then set fileName properly
#endif
	if (!url.isValid()) {
		//focus the app again because to avoid annoying the user with unfocused main window
		if (qApp->mainWidget()) {
			//focusWidget->raise();
			//focusWidget->setFocus();
			qApp->mainWidget()->raise();
		}
		return;
	}
	kexipluginsdbg << "fname=" << url.prettyURL() << endl;

#ifdef Q_WS_WIN
	//save last visited path
//	KURL url(fileName);
	if (url.isLocalFile())
		KRecentDirs::add(":LastVisitedImagePath", url.directory());
#endif

	emit insertFromFileRequested(url);
	if (qApp->mainWidget()) {
//		focusWidget->raise();
//		focusWidget->setFocus();
		qApp->mainWidget()->raise();
	}
}
Esempio n. 16
0
void KateFileSelector::kateViewChanged()
{
  if ( autoSyncEvents & DocumentChanged )
  {
//     kdDebug(13001)<<"KateFileSelector::do a sync ()"<<endl;
    // if visible, sync
    if ( isVisible() ) {
      setActiveDocumentDir();
      waitingUrl = TQString::null;
    }
    // else set waiting url
    else {
      KURL u = mainwin->activeDocumentUrl();
      if (!u.isEmpty())
        waitingUrl = u.directory();
    }
  }

  // TODO: make sure the button is disabled if the directory is unreadable, eg
  //       the document URL has protocol http
  acSyncDir->setEnabled( ! mainwin->activeDocumentUrl().directory().isEmpty() );
}
Esempio n. 17
0
void TrashProtocol::restore(const KURL &trashURL)
{
    int trashId;
    QString fileId, relativePath;
    bool ok = TrashImpl::parseURL(trashURL, trashId, fileId, relativePath);
    if(!ok)
    {
        error(KIO::ERR_SLAVE_DEFINED, i18n("Malformed URL %1").arg(trashURL.prettyURL()));
        return;
    }
    TrashedFileInfo info;
    ok = impl.infoForFile(trashId, fileId, info);
    if(!ok)
    {
        error(impl.lastErrorCode(), impl.lastErrorMessage());
        return;
    }
    KURL dest;
    dest.setPath(info.origPath);
    if(!relativePath.isEmpty())
        dest.addPath(relativePath);

    // Check that the destination directory exists, to improve the error code in case it doesn't.
    const QString destDir = dest.directory();
    KDE_struct_stat buff;
    if(KDE_lstat(QFile::encodeName(destDir), &buff) == -1)
    {
        error(KIO::ERR_SLAVE_DEFINED,
              i18n("The directory %1 does not exist anymore, so it is not possible to restore this item to its original location. "
                   "You can either recreate that directory and use the restore operation again, or drag the item anywhere else to restore it.")
                  .arg(destDir));
        return;
    }

    copyOrMove(trashURL, dest, false /*overwrite*/, Move);
}
Esempio n. 18
0
TQCString KRemoteEncoding::directory(const KURL& url, bool ignore_trailing_slash) const
{
  TQString dir = url.directory(true, ignore_trailing_slash);

  return encode(dir);
}
Esempio n. 19
0
bool KConfigINIBackEnd::parseConfigFiles()
{
    // Check if we can write to the local file.
    mConfigState = KConfigBase::ReadOnly;
    if(!mLocalFileName.isEmpty() && !pConfig->isReadOnly())
    {
        if(checkAccess(mLocalFileName, W_OK))
        {
            mConfigState = KConfigBase::ReadWrite;
        }
        else
        {
            // Create the containing dir, maybe it wasn't there
            KURL path;
            path.setPath(mLocalFileName);
            QString dir = path.directory();
            KStandardDirs::makeDir(dir);

            if(checkAccess(mLocalFileName, W_OK))
            {
                mConfigState = KConfigBase::ReadWrite;
            }
        }
        QFileInfo info(mLocalFileName);
        d->localLastModified = info.lastModified();
        d->localLastSize = info.size();
    }

    // Parse all desired files from the least to the most specific.
    bFileImmutable = false;

    // Parse the general config files
    if(useKDEGlobals)
    {
        QStringList kdercs = KGlobal::dirs()->findAllResources("config", QString::fromLatin1("kdeglobals"));

        QString etc_kderc = QString::fromLatin1("/etc/kderc");

        if(checkAccess(etc_kderc, R_OK))
            kdercs += etc_kderc;

        kdercs += KGlobal::dirs()->findAllResources("config", QString::fromLatin1("system.kdeglobals"));

        QStringList::ConstIterator it;

        for(it = kdercs.fromLast(); it != kdercs.end(); --it)
        {

            QFile aConfigFile(*it);
            if(!aConfigFile.open(IO_ReadOnly))
                continue;
            parseSingleConfigFile(aConfigFile, 0L, true, (*it != mGlobalFileName));
            aConfigFile.close();
            if(bFileImmutable)
                break;
        }
    }

    bool bReadFile = !mfileName.isEmpty();
    while(bReadFile)
    {
        bReadFile = false;
        QString bootLanguage;
        if(useKDEGlobals && localeString.isEmpty() && !KGlobal::_locale)
        {
            // Boot strap language
            bootLanguage = KLocale::_initLanguage(pConfig);
            setLocaleString(bootLanguage.utf8());
        }

        bFileImmutable = false;
        QStringList list;
        if(!QDir::isRelativePath(mfileName))
            list << mfileName;
        else
            list = KGlobal::dirs()->findAllResources(resType, mfileName);

        QStringList::ConstIterator it;

        for(it = list.fromLast(); it != list.end(); --it)
        {

            QFile aConfigFile(*it);
            // we can already be sure that this file exists
            bool bIsLocal = (*it == mLocalFileName);
            if(aConfigFile.open(IO_ReadOnly))
            {
                parseSingleConfigFile(aConfigFile, 0L, false, !bIsLocal);
                aConfigFile.close();
                if(bFileImmutable)
                    break;
            }
        }
        if(KGlobal::dirs()->isRestrictedResource(resType, mfileName))
            bFileImmutable = true;
        QString currentLanguage;
        if(!bootLanguage.isEmpty())
        {
            currentLanguage = KLocale::_initLanguage(pConfig);
            // If the file changed the language, we need to read the file again
            // with the new language setting.
            if(bootLanguage != currentLanguage)
            {
                bReadFile = true;
                setLocaleString(currentLanguage.utf8());
            }
        }
    }
    if(bFileImmutable)
        mConfigState = KConfigBase::ReadOnly;

    return true;
}
Esempio n. 20
0
KURL QExtFileInfo::path( const KURL &url )
{
  KURL result = url;
  result.setPath(result.directory(false,false));
  return result;
}
Esempio n. 21
0
void
Amarok::coverContextMenu( QWidget *parent, QPoint point, const QString &artist, const QString &album, bool showCoverManager )
{
        KPopupMenu menu;
        enum { SHOW, FETCH, CUSTOM, DELETE, MANAGER };

        menu.insertTitle( i18n( "Cover Image" ) );

        menu.insertItem( SmallIconSet( Amarok::icon( "zoom" ) ), i18n( "&Show Fullsize" ), SHOW );
        menu.insertItem( SmallIconSet( Amarok::icon( "download" ) ), i18n( "&Fetch From amazon.%1" ).arg( CoverManager::amazonTld() ), FETCH );
        menu.insertItem( SmallIconSet( Amarok::icon( "files" ) ), i18n( "Set &Custom Cover" ), CUSTOM );
        bool disable = !album.isEmpty(); // disable setting covers for unknown albums
        menu.setItemEnabled( FETCH, disable );
        menu.setItemEnabled( CUSTOM, disable );
        menu.insertSeparator();

        menu.insertItem( SmallIconSet( Amarok::icon( "remove" ) ), i18n( "&Unset Cover" ), DELETE );
        if ( showCoverManager ) {
            menu.insertSeparator();
            menu.insertItem( SmallIconSet( Amarok::icon( "covermanager" ) ), i18n( "Cover &Manager" ), MANAGER );
        }
        #ifndef AMAZON_SUPPORT
        menu.setItemEnabled( FETCH, false );
        #endif
        disable = !CollectionDB::instance()->albumImage( artist, album, 0 ).contains( "nocover" );
        menu.setItemEnabled( SHOW, disable );
        menu.setItemEnabled( DELETE, disable );

        switch( menu.exec( point ) )
        {
        case SHOW:
            CoverManager::viewCover( artist, album, parent );
            break;

        case DELETE:
        {
            const int button = KMessageBox::warningContinueCancel( parent,
                i18n( "Are you sure you want to remove this cover from the Collection?" ),
                QString::null,
                KStdGuiItem::del() );

            if ( button == KMessageBox::Continue )
                CollectionDB::instance()->removeAlbumImage( artist, album );
            break;
        }

        case FETCH:
        #ifdef AMAZON_SUPPORT
            CollectionDB::instance()->fetchCover( parent, artist, album, false );
            break;
        #endif

        case CUSTOM:
        {
            QString artist_id; artist_id.setNum( CollectionDB::instance()->artistID( artist ) );
            QString album_id; album_id.setNum( CollectionDB::instance()->albumID( album ) );
            QStringList values = CollectionDB::instance()->albumTracks( artist_id, album_id );
            QString startPath = ":homedir";

            if ( !values.isEmpty() ) {
                KURL url;
                url.setPath( values.first() );
                startPath = url.directory();
            }

            KURL file = KFileDialog::getImageOpenURL( startPath, parent, i18n("Select Cover Image File") );
            if ( !file.isEmpty() )
                CollectionDB::instance()->setAlbumImage( artist, album, file );
            break;
        }

        case MANAGER:
            CoverManager::showOnce( album );
            break;
        }
}
Esempio n. 22
0
void KImGalleryPlugin::createBody(QTextStream& stream, const QString& sourceDirName, const QStringList& subDirList,
                                  const QDir& imageDir, const KURL& url, const QString& imageFormat)
{
    int numOfImages = imageDir.count();
    const QString imgGalleryDir = url.directory();
    const QString today(KGlobal::locale()->formatDate(QDate::currentDate()));

    stream << "<body>\n<h1>" << QStyleSheet::escape(m_configDlg->getTitle()) << "</h1><p>" << endl;
    stream << i18n("<i>Number of images</i>: %1").arg(numOfImages) << "<br/>" << endl;
    stream << i18n("<i>Created on</i>: %1").arg(today) << "</p>" << endl;

    stream << "<hr/>" << endl;

    if (m_recurseSubDirectories && subDirList.count() > 2) { //subDirList.count() is always >= 2 because of the "." and ".." directories
        stream << i18n("<i>Subfolders</i>:") << "<br>" << endl;
        for (QStringList::ConstIterator it = subDirList.begin(); it != subDirList.end(); it++) {
            if (*it == "." || *it == "..")
                continue; //disregard the "." and ".." directories
            stream << "<a href=\"" << *it << "/" << url.fileName()
                   << "\">" << *it << "</a><br>" << endl;
        }
        stream << "<hr/>" << endl;
    }

    stream << "<table>" << endl;

    //table with images
    int imgIndex;
    QFileInfo imginfo;
    QPixmap  imgProp;
    for (imgIndex = 0; !m_cancelled && (imgIndex < numOfImages);) {
        stream << "<tr>" << endl;

        for (int col=0; !m_cancelled && (col < m_imagesPerRow) && (imgIndex < numOfImages); col++) {
            const QString imgName = imageDir[imgIndex];

            if (m_copyFiles) {
                stream << "<td align='center'>\n<a href=\"images/" << imgName << "\">";
            } else {
                stream << "<td align='center'>\n<a href=\"" << imgName << "\">";
            }


            if (createThumb(imgName, sourceDirName, imgGalleryDir, imageFormat)) {
                const QString imgPath("thumbs/" + imgName + extension(imageFormat));
                stream << "<img src=\"" << imgPath << "\" width=\"" << m_imgWidth << "\" ";
                stream << "height=\"" << m_imgHeight << "\" alt=\"" << imgPath << "\"/>";
                m_progressDlg->setLabelText( i18n("Created thumbnail for: \n%1").arg(imgName) );
            } else {
                kdDebug(90170) << "Creating thumbnail for " << imgName << " failed" << endl;
                m_progressDlg->setLabelText( i18n("Creating thumbnail for: \n%1\n failed").arg(imgName) );
            }
            stream << "</a>" << endl;

            if (m_configDlg->printImageName()) {
                stream << "<div>" << imgName << "</div>" << endl;
            }

            if (m_configDlg->printImageProperty()) {
                imgProp.load( imageDir.absFilePath(imgName,true) );
                stream << "<div>" << imgProp.width() << " x " << imgProp.height() << "</div>" << endl;
            }

            if (m_configDlg->printImageSize()) {
                imginfo.setFile( imageDir, imgName );
                stream << "<div>(" << (imginfo.size() / 1024) << " " <<  i18n("KB") << ")" << "</div>" << endl;
            }

            if (m_useCommentFile) {
                QString imgComment = (*m_commentMap)[imgName];
                stream << "<div>" << QStyleSheet::escape(imgComment) << "</div>" << endl;
            }
            stream << "</td>" << endl;

            m_progressDlg->setTotalSteps( numOfImages );
            m_progressDlg->setProgress( imgIndex );
            kapp->processEvents();
            imgIndex++;
        }
        stream << "</tr>" << endl;
    }
    //close the HTML
    stream << "</table>\n</body>\n</html>" << endl;
}
Esempio n. 23
0
bool KImGalleryPlugin::createHtml(const KURL& url, const QString& sourceDirName, int recursionLevel, const QString& imageFormat)
{
    if(m_cancelled) return false;


    if( !parent() || !parent()->inherits("KonqDirPart"))
        return false;
    KonqDirPart * part = static_cast<KonqDirPart *>(parent());

    QStringList subDirList;
    if (m_recurseSubDirectories && (recursionLevel >= 0)) { //recursionLevel == 0 means endless
        QDir toplevel_dir = QDir( sourceDirName );
        toplevel_dir.setFilter( QDir::Dirs | QDir::Readable | QDir::Writable );
        subDirList = toplevel_dir.entryList();

        for (QStringList::ConstIterator it = subDirList.begin(); it != subDirList.end() && !m_cancelled; it++) {
            const QString currentDir = *it;
            if (currentDir == "." || currentDir == "..") { continue;} //disregard the "." and ".." directories
            QDir subDir = QDir( url.directory() + "/" + currentDir );
            if (!subDir.exists()) {
                subDir.setPath( url.directory() );
                if (!(subDir.mkdir(currentDir, false))) {
                    KMessageBox::sorry(part->widget(), i18n("Couldn't create folder: %1").arg(subDir.path()));
                    continue;
                } else {
                    subDir.setPath( url.directory() + "/" + currentDir );
                }
            }
            if(!createHtml( KURL( subDir.path() + "/" + url.fileName() ), sourceDirName + "/" + currentDir,
                            recursionLevel > 1 ? recursionLevel - 1 : 0, imageFormat)) { return false; }
        }
    }

    if (m_useCommentFile) {
        loadCommentFile();
    }

    kdDebug(90170) << "sourceDirName: " << sourceDirName << endl;
    //We're interested in only the patterns, so look for the first |
    //#### perhaps an accessor should be added to KImageIO instead?
    QString filter = KImageIO::pattern(KImageIO::Reading).section('|', 0, 0);

    QDir imageDir( sourceDirName, filter.latin1(),
                   QDir::Name|QDir::IgnoreCase, QDir::Files|QDir::Readable);

    const QString imgGalleryDir = url.directory();
    kdDebug(90170) << "imgGalleryDir: " << imgGalleryDir << endl;

    // Create the "thumbs" subdirectory if necessary
    QDir thumb_dir( imgGalleryDir + QString::fromLatin1("/thumbs/"));
    if (createDirectory(thumb_dir, imgGalleryDir, "thumbs") == false)
        return false;

    // Create the "images" subdirectory if necessary
    QDir images_dir( imgGalleryDir + QString::fromLatin1("/images/"));
    if (m_copyFiles) {
        if (createDirectory(images_dir, imgGalleryDir, "images") == false)
            return false;
    }

    QFile file( url.path() );
    kdDebug(90170) << "url.path(): " << url.path() << ", thumb_dir: "<< thumb_dir.path()
              << ", imageDir: "<< imageDir.path() << endl;

    if ( imageDir.exists() && file.open(IO_WriteOnly) ) {
        QTextStream stream(&file);
        stream.setEncoding(QTextStream::Locale);

        createHead(stream);
        createBody(stream, sourceDirName, subDirList, imageDir, url, imageFormat); //ugly

        file.close();

        return !m_cancelled;

    } else {
        KMessageBox::sorry(m_part->widget(),i18n("Couldn't open file: %1").arg(url.path(+1)));
        return false;
    }
}
Esempio n. 24
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 );
}
Esempio n. 25
0
void KConfigINIBackEnd::sync(bool bMerge)
{
    // write-sync is only necessary if there are dirty entries
    if(!pConfig->isDirty())
        return;

    bool bEntriesLeft = true;

    // find out the file to write to (most specific writable file)
    // try local app-specific file first

    if(!mfileName.isEmpty())
    {
        // Create the containing dir if needed
        if((resType != "config") && !QDir::isRelativePath(mLocalFileName))
        {
            KURL path;
            path.setPath(mLocalFileName);
            QString dir = path.directory();
            KStandardDirs::makeDir(dir);
        }

        // Can we allow the write? We can, if the program
        // doesn't run SUID. But if it runs SUID, we must
        // check if the user would be allowed to write if
        // it wasn't SUID.
        if(checkAccess(mLocalFileName, W_OK))
        {
            // File is writable
            KLockFile::Ptr lf;

            bool mergeLocalFile = bMerge;
            // Check if the file has been updated since.
            if(mergeLocalFile)
            {
                lf = lockFile(false); // Lock file for local file
                if(lf && lf->isLocked())
                    lf = 0; // Already locked, we don't need to lock/unlock again

                if(lf)
                {
                    lf->lock(KLockFile::LockForce);
                    // But what if the locking failed? Ignore it for now...
                }

                QFileInfo info(mLocalFileName);
                if((d->localLastSize == info.size()) && (d->localLastModified == info.lastModified()))
                {
                    // Not changed, don't merge.
                    mergeLocalFile = false;
                }
                else
                {
                    // Changed...
                    d->localLastModified = QDateTime();
                    d->localLastSize = 0;
                }
            }

            bEntriesLeft = writeConfigFile(mLocalFileName, false, mergeLocalFile);

            // Only if we didn't have to merge anything can we use our in-memory state
            // the next time around. Otherwise the config-file may contain entries
            // that are different from our in-memory state which means we will have to
            // do a merge from then on.
            // We do not automatically update the in-memory state with the on-disk
            // state when writing the config to disk. We only do so when
            // KCOnfig::reparseConfiguration() is called.
            // For KDE 4.0 we may wish to reconsider that.
            if(!mergeLocalFile)
            {
                QFileInfo info(mLocalFileName);
                d->localLastModified = info.lastModified();
                d->localLastSize = info.size();
            }
            if(lf)
                lf->unlock();
        }
    }

    // only write out entries to the kdeglobals file if there are any
    // entries marked global (indicated by bEntriesLeft) and
    // the useKDEGlobals flag is set.
    if(bEntriesLeft && useKDEGlobals)
    {

        // can we allow the write? (see above)
        if(checkAccess(mGlobalFileName, W_OK))
        {
            KLockFile::Ptr lf = lockFile(true); // Lock file for global file
            if(lf && lf->isLocked())
                lf = 0; // Already locked, we don't need to lock/unlock again

            if(lf)
            {
                lf->lock(KLockFile::LockForce);
                // But what if the locking failed? Ignore it for now...
            }
            writeConfigFile(mGlobalFileName, true, bMerge); // Always merge
            if(lf)
                lf->unlock();
        }
    }
}
Esempio n. 26
0
void TrashProtocol::copyOrMove(const KURL &src, const KURL &dest, bool overwrite, CopyOrMove action)
{
    if(src.protocol() == "trash" && dest.isLocalFile())
    {
        // Extracting (e.g. via dnd). Ignore original location stored in info file.
        int trashId;
        QString fileId, relativePath;
        bool ok = TrashImpl::parseURL(src, trashId, fileId, relativePath);
        if(!ok)
        {
            error(KIO::ERR_SLAVE_DEFINED, i18n("Malformed URL %1").arg(src.prettyURL()));
            return;
        }
        const QString destPath = dest.path();
        if(QFile::exists(destPath))
        {
            if(overwrite)
            {
                ok = QFile::remove(destPath);
                Q_ASSERT(ok); // ### TODO
            }
            else
            {
                error(KIO::ERR_FILE_ALREADY_EXIST, destPath);
                return;
            }
        }

        if(action == Move)
        {
            kdDebug() << "calling moveFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
            ok = impl.moveFromTrash(destPath, trashId, fileId, relativePath);
        }
        else
        { // Copy
            kdDebug() << "calling copyFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
            ok = impl.copyFromTrash(destPath, trashId, fileId, relativePath);
        }
        if(!ok)
        {
            error(impl.lastErrorCode(), impl.lastErrorMessage());
        }
        else
        {
            if(action == Move && relativePath.isEmpty())
                (void)impl.deleteInfo(trashId, fileId);
            finished();
        }
        return;
    }
    else if(src.isLocalFile() && dest.protocol() == "trash")
    {
        QString dir = dest.directory();
        // kdDebug() << "trashing a file to " << dir << endl;
        // Trashing a file
        // We detect the case where this isn't normal trashing, but
        // e.g. if kwrite tries to save (moving tempfile over destination)
        if(dir.length() <= 1 && src.fileName() == dest.fileName()) // new toplevel entry
        {
            const QString srcPath = src.path();
            // In theory we should use TrashImpl::parseURL to give the right filename to createInfo,
            // in case the trash URL didn't contain the same filename as srcPath.
            // But this can only happen with copyAs/moveAs, not available in the GUI
            // for the trash (New/... or Rename from iconview/listview).
            int trashId;
            QString fileId;
            if(!impl.createInfo(srcPath, trashId, fileId))
            {
                error(impl.lastErrorCode(), impl.lastErrorMessage());
            }
            else
            {
                bool ok;
                if(action == Move)
                {
                    kdDebug() << "calling moveToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
                    ok = impl.moveToTrash(srcPath, trashId, fileId);
                }
                else
                { // Copy
                    kdDebug() << "calling copyToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
                    ok = impl.copyToTrash(srcPath, trashId, fileId);
                }
                if(!ok)
                {
                    (void)impl.deleteInfo(trashId, fileId);
                    error(impl.lastErrorCode(), impl.lastErrorMessage());
                }
                else
                {
                    // Inform caller of the final URL. Used by konq_undo.
                    const KURL url = impl.makeURL(trashId, fileId, QString::null);
                    setMetaData("trashURL-" + srcPath, url.url());
                    finished();
                }
            }
            return;
        }
        else
        {
            kdDebug() << "returning KIO::ERR_ACCESS_DENIED, it's not allowed to add a file to an existing trash directory" << endl;
            // It's not allowed to add a file to an existing trash directory.
            error(KIO::ERR_ACCESS_DENIED, dest.prettyURL());
            return;
        }
    }
    else
        error(KIO::ERR_UNSUPPORTED_ACTION, "should never happen");
}
Esempio n. 27
0
bool DTD::parseDTD(const KURL &url)
{
 QString fileName = QString::null;
 if (!KIO::NetAccess::download(url, fileName))
 {
   KMessageBox::error(0, i18n("<qt>Cannot download the DTD from <b>%1</b>.</qt>").arg(url.prettyURL(0, KURL::StripFileProtocol)));
   return false;
 }
  QFile file(fileName);
  if (file.open(IO_ReadOnly))
  {
    QTextStream fileStream(&file);
    fileStream.setEncoding(QTextStream::UnicodeUTF8);
    QString entireDTD = fileStream.read();
    file.close();
    removeComments(entireDTD);

    QString line;
    QStringList lines = QStringList::split("\n",entireDTD);
    QStringList::Iterator it = lines.begin();
    while (it != lines.end()) {
      line = *it;

      if (line.startsWith("<")) {
        while (!line.endsWith(">") && it != lines.end()) {
          ++it;
          line += " \\end" + *it;
        }
      } else if (line.startsWith("%")) {
        while (!line.endsWith(";") && it != lines.end()) {
          ++it;
          line += *it;
        }
      }

      line = line.stripWhiteSpace();
      line = line.simplifyWhiteSpace();

      //kdDebug(24000) << "Parsed line is: " << line << endl;

      if ( line.startsWith("<!ENTITY") && line.endsWith(">"))
      {
        parseDTDEntity(line);
      }
      else
      if (line.startsWith("<!ELEMENT") && line.endsWith(">"))
      {
        parseDTDElement(line);
      }
      else
      if (line.startsWith("<!ATTLIST") && line.endsWith(">"))
      {
        parseDTDAttlist(line);
      }
      else
      if (line.startsWith("%") && line.endsWith(";"))
      {
        line.remove(0,1);
        line.truncate(line.length()-1);
        KURL entityURL = url;
        entityURL.setPath(url.directory()+ "/" + line + ".ent");
        parseDTD(entityURL);
      } else
      {
        kdDebug(24000) << QString("Unknown tag: [%1]").arg(line) << endl;
      }

      if (it != lines.end()) ++it;
    }
  }
}
Esempio n. 28
0
bool KoApplication::start()
{
    ResetStarting resetStarting; // reset m_starting to false when we're done
    Q_UNUSED( resetStarting );

    // Find the *.desktop file corresponding to the kapp instance name
    KoDocumentEntry entry = KoDocumentEntry( KoDocument::readNativeService() );
    if ( entry.isEmpty() )
    {
        kdError( 30003 ) << instanceName() << "part.desktop not found." << endl;
        kdError( 30003 ) << "Run 'kde-config --path services' to see which directories were searched, assuming kde startup had the same environment as your current shell." << endl;
        kdError( 30003 ) << "Check your installation (did you install KOffice in a different prefix than KDE, without adding the prefix to /etc/kderc ?)" << endl;
        return false;
    }

    // Get the command line arguments which we have to parse
    KCmdLineArgs *args= KCmdLineArgs::parsedArgs();
    int argsCount = args->count();

    KCmdLineArgs *koargs = KCmdLineArgs::parsedArgs("koffice");
    QCString dpiValues = koargs->getOption( "dpi" );
    if ( !dpiValues.isEmpty() ) {
        int sep = dpiValues.find( QRegExp( "[x, ]" ) );
        int dpiX;
        int dpiY = 0;
        bool ok = true;
        if ( sep != -1 ) {
            dpiY = dpiValues.mid( sep+1 ).toInt( &ok );
            dpiValues.truncate( sep );
        }
        if ( ok ) {
            dpiX = dpiValues.toInt( &ok );
            if ( ok ) {
                if ( !dpiY ) dpiY = dpiX;
                KoGlobal::setDPI( dpiX, dpiY );
            }
        }
    }

    // No argument -> create an empty document
    if ( !argsCount ) {
        KoDocument* doc = entry.createDoc( 0, "Document" );
        if ( !doc )
            return false;
        KoMainWindow *shell = new KoMainWindow( doc->instance() );
        shell->show();
        QObject::connect(doc, SIGNAL(sigProgress(int)), shell, SLOT(slotProgress(int)));
        // for initDoc to fill in the recent docs list
        // and for KoDocument::slotStarted
        doc->addShell( shell );

        if ( doc->checkAutoSaveFile() ) {
          shell->setRootDocument( doc );
        } else {
          doc->showStartUpWidget( shell );
        }

        // FIXME This needs to be moved someplace else
	QObject::disconnect(doc, SIGNAL(sigProgress(int)), shell, SLOT(slotProgress(int)));
    } else {
        bool print = koargs->isSet("print");
	bool doTemplate = koargs->isSet("template");
        koargs->clear();

        // Loop through arguments

        short int n=0; // number of documents open
        short int nPrinted = 0;
        for(int i=0; i < argsCount; i++ )
        {
            // For now create an empty document
            KoDocument* doc = entry.createDoc( 0 );
            if ( doc )
            {
                // show a shell asap
                KoMainWindow *shell = new KoMainWindow( doc->instance() );
                if (!print)
                    shell->show();
		// are we just trying to open a template?
		if ( doTemplate ) {
		  QStringList paths;
		  if ( args->url(i).isLocalFile() && QFile::exists(args->url(i).path()) )
		  {
		    paths << QString(args->url(i).path());
		    kdDebug(30003) << "using full path..." << endl;
		  } else {
		     QString desktopName(args->arg(i));
		     QString appName = KGlobal::instance()->instanceName();

		     paths = KGlobal::dirs()->findAllResources("data", appName +"/templates/*/" + desktopName );
		     if ( paths.isEmpty()) {
			   paths = KGlobal::dirs()->findAllResources("data", appName +"/templates/" + desktopName );
	             }
		     if ( paths.isEmpty()) {
		        KMessageBox::error(0L, i18n("No template found for: %1 ").arg(desktopName) );
		        delete shell;
		     } else if ( paths.count() > 1 ) {
		        KMessageBox::error(0L,  i18n("Too many templates found for: %1").arg(desktopName) );
		        delete shell;
		     }
		  }

                  if ( !paths.isEmpty() ) {
		     KURL templateBase;
		     templateBase.setPath(paths[0]);
		     KDesktopFile templateInfo(paths[0]);

		     QString templateName = templateInfo.readURL();
		     KURL templateURL;
		     templateURL.setPath( templateBase.directory() + "/" + templateName );
		     if ( shell->openDocument(doc, templateURL )) {
		       doc->resetURL();
		       doc->setEmpty();
                       doc->setTitleModified();
		       kdDebug(30003) << "Template loaded..." << endl;
		       n++;
		     } else {
		        KMessageBox::error(0L, i18n("Template %1 failed to load.").arg(templateURL.prettyURL()) );
 		        delete shell;
		     }
		  }
                // now try to load
                } else if ( shell->openDocument( doc, args->url(i) ) ) {
                    if ( print ) {
                        shell->print(false /*we want to get the dialog*/);
                        // delete shell; done by ~KoDocument
                        nPrinted++;
		    } else {
                        // Normal case, success
                        n++;
                    }
                } else {
                    // .... if failed
                    // delete doc; done by openDocument
                    // delete shell; done by ~KoDocument
                }
            }
        }
        if ( print )
            return nPrinted > 0;
        if (n == 0) // no doc, e.g. all URLs were malformed
            return false;
    }

    args->clear();
    // not calling this before since the program will quit there.
    return true;
}
Esempio n. 29
0
bool TrashImpl::createInfo( const TQString& origPath, int& trashId, TQString& fileId )
{
    kdDebug() << k_funcinfo << origPath << endl;
    // Check source
    const TQCString origPath_c( TQFile::encodeName( origPath ) );
    KDE_struct_stat buff_src;
    if ( KDE_lstat( origPath_c.data(), &buff_src ) == -1 ) {
        if ( errno == EACCES )
           error( TDEIO::ERR_ACCESS_DENIED, origPath );
        else
           error( TDEIO::ERR_DOES_NOT_EXIST, origPath );
        return false;
    }

    // Choose destination trash
    trashId = findTrashDirectory( origPath );
    if ( trashId < 0 ) {
        kdWarning() << "OUCH - internal error, TrashImpl::findTrashDirectory returned " << trashId << endl;
        return false; // ### error() needed?
    }
    kdDebug() << k_funcinfo << "trashing to " << trashId << endl;

    // Grab original filename
    KURL url;
    url.setPath( origPath );
    const TQString origFileName = url.fileName();

    // Make destination file in info/
    url.setPath( infoPath( trashId, origFileName ) ); // we first try with origFileName
    KURL baseDirectory;
    baseDirectory.setPath( url.directory() );
    // Here we need to use O_EXCL to avoid race conditions with other tdeioslave processes
    int fd = 0;
    do {
        kdDebug() << k_funcinfo << "trying to create " << url.path()  << endl;
        fd = ::open( TQFile::encodeName( url.path() ), O_WRONLY | O_CREAT | O_EXCL, 0600 );
        if ( fd < 0 ) {
            if ( errno == EEXIST ) {
                url.setFileName( TDEIO::RenameDlg::suggestName( baseDirectory, url.fileName() ) );
                // and try again on the next iteration
            } else {
                error( TDEIO::ERR_COULD_NOT_WRITE, url.path() );
                return false;
            }
        }
    } while ( fd < 0 );
    const TQString infoPath = url.path();
    fileId = url.fileName();
    Q_ASSERT( fileId.endsWith( ".trashinfo" ) );
    fileId.truncate( fileId.length() - 10 ); // remove .trashinfo from fileId

    FILE* file = ::fdopen( fd, "w" );
    if ( !file ) { // can't see how this would happen
        error( TDEIO::ERR_COULD_NOT_WRITE, infoPath );
        return false;
    }

    // Contents of the info file. We could use KSimpleConfig, but that would
    // mean closing and reopening fd, i.e. opening a race condition...
    TQCString info = "[Trash Info]\n";
    info += "Path=";
    // Escape filenames according to the way they are encoded on the filesystem
    // All this to basically get back to the raw 8-bit representation of the filename...
    if ( trashId == 0 ) // home trash: absolute path
        info += KURL::encode_string( origPath, m_mibEnum ).latin1();
    else
        info += KURL::encode_string( makeRelativePath( topDirectoryPath( trashId ), origPath ), m_mibEnum ).latin1();
    info += "\n";
    info += "DeletionDate=";
    info += TQDateTime::currentDateTime().toString( Qt::ISODate ).latin1();
    info += "\n";
    size_t sz = info.size() - 1; // avoid trailing 0 from QCString

    size_t written = ::fwrite(info.data(), 1, sz, file);
    if ( written != sz ) {
        ::fclose( file );
        TQFile::remove( infoPath );
        error( TDEIO::ERR_DISK_FULL, infoPath );
        return false;
    }

    ::fclose( file );

    kdDebug() << k_funcinfo << "info file created in trashId=" << trashId << " : " << fileId << endl;
    return true;
}
Esempio n. 30
0
/** Properties dialog addon*/
FileInfoDlg* BaseTreeView::addFileInfoPage(KPropertiesDialog* propDlg)
{
  //If the item is a file, add the Quanta file info page
  FileInfoDlg *quantaFileProperties = 0L;
  if ( !currentKFileTreeViewItem()->isDir() )
  {

    QFrame *quantaFilePage = propDlg->addPage(i18n("Quanta File Info"));
    QVBoxLayout *topLayout = new QVBoxLayout( quantaFilePage);
    quantaFileProperties = new FileInfoDlg( quantaFilePage, i18n("Quanta") );

    int fsize,fimgsize=0;
    int ct=0,imgct=0,position=0;
    KURL u = currentURL();
    if (u.isLocalFile())   //get the file info only for local file. TODO: for non-local ones
    {
       QString nameForInfo = u.path();
       QString path =u.directory(0,0);       //extract path for images
       QString sourcename=u.fileName(0);

       QFile qfile(nameForInfo);
       fsize=qfile.size();                              //html file size

       QString mimetype = KMimeType::findByFileContent(nameForInfo)->name();
       if (mimetype.contains("text"))
       {
        qfile.open(IO_ReadOnly);
        QString imgname,imgpath;
        QTextStream stream(&qfile);
        stream.setEncoding(QTextStream::UnicodeUTF8);
        while (!stream.atEnd())     //open & parse file
        {
          imgname = stream.readLine();
          ct++;
          position=imgname.find("<img",0,false);              //check for images
          if (position!=-1)
          {
            imgname.remove(0,position+4);
            position=imgname.find("src=",0,false);              //extract images names
            imgname.remove(0,position+4);
            if (imgname.startsWith("\"")) imgname.remove(0,1);
            if (imgname.startsWith("'")) imgname.remove(0,1);
            position=imgname.find(" ",0,false);
            if (position!=-1) imgname=imgname.left(position);
            position=imgname.find(">",0,false);
            if (position!=-1) imgname=imgname.left(position);
            position=imgname.find("\"",0,false);
            if (position!=-1) imgname=imgname.left(position);
            position=imgname.find("'",0,false);
            if (position!=-1) imgname=imgname.left(position);
            if (!quantaFileProperties->imageList->findItem(imgname,Qt::ExactMatch))     //check if image was already counted
            {
              KURL v(KURL::fromPathOrURL( path ),imgname);
              imgpath=v.path();
              QFile qimage(imgpath);
              if (qimage.exists() && v.isLocalFile())
              {
               fimgsize+=qimage.size();
               quantaFileProperties->imageList->insertItem(imgname);
               imgct++;
              }
             }
           }
         }
         qfile.close();

         quantaFileProperties->lineNum->setText(i18n("Number of lines: %1").arg(ct));
         quantaFileProperties->imageNum->setText(i18n("Number of images included: %1").arg(imgct));
         quantaFileProperties->imageSize->setText(i18n("Size of the included images: %1 bytes").arg(fimgsize));
         quantaFileProperties->totalSize->setText(i18n("Total size with images: %1 bytes").arg(fsize+fimgsize));
        }
        else if (mimetype.contains("image"))
        {              // assume it's an image file
          QImage imagefile=QImage(nameForInfo);
          quantaFileProperties->lineNum->setText(i18n("Image size: %1 x %2").arg(imagefile.width()).arg(imagefile.height()));
          quantaFileProperties->imageNum->hide();
          quantaFileProperties->imageSize->hide();
          quantaFileProperties->totalSize->hide();
          quantaFileProperties->includedLabel->hide();
          quantaFileProperties->imageList->hide();
        }
        quantaFileProperties->fileDescLbl->setText(i18n("Description:"));
        quantaFileProperties->fileDesc->setText(currentKFileTreeViewItem()->text(1));
        // disable per default
        quantaFileProperties->fileDescLbl->hide();
        quantaFileProperties->fileDesc->hide();
        topLayout->addWidget(quantaFileProperties);
    } //if localfile
  }
  return quantaFileProperties;
}