kmimetype.cpp

00001 /*  This file is part of the KDE libraries
00002  *  Copyright (C) 1999 Waldo Bastian <bastian@kde.org>
00003  *                     David Faure   <faure@kde.org>
00004  *
00005  *  This library is free software; you can redistribute it and/or
00006  *  modify it under the terms of the GNU Library General Public
00007  *  License version 2 as published by the Free Software Foundation;
00008  *
00009  *  This library is distributed in the hope that it will be useful,
00010  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  *  Library General Public License for more details.
00013  *
00014  *  You should have received a copy of the GNU Library General Public License
00015  *  along with this library; see the file COPYING.LIB.  If not, write to
00016  *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00017  *  Boston, MA 02110-1301, USA.
00018  **/
00019 // $Id$
00020 
00021 #include <config.h>
00022 
00023 #include <sys/types.h>
00024 #include <sys/stat.h>
00025 
00026 #include <assert.h>
00027 #include <dirent.h>
00028 #include <errno.h>
00029 #include <stddef.h>
00030 #include <unistd.h>
00031 #include <stdlib.h>
00032 
00033 #include <kprotocolinfo.h>
00034 #include <kio/global.h>
00035 #include "kmimetype.h"
00036 #include "kservicetypefactory.h"
00037 #include "kmimemagic.h"
00038 #include "kservice.h"
00039 #include "krun.h"
00040 #include "kautomount.h"
00041 #include <kdirnotify_stub.h>
00042 
00043 #include <qstring.h>
00044 #include <qfile.h>
00045 #include <kmessageboxwrapper.h>
00046 
00047 #include <dcopclient.h>
00048 #include <dcopref.h>
00049 #include <kapplication.h>
00050 #include <kprocess.h>
00051 #include <kdebug.h>
00052 #include <kdesktopfile.h>
00053 #include <kdirwatch.h>
00054 #include <kiconloader.h>
00055 #include <klocale.h>
00056 #include <ksimpleconfig.h>
00057 #include <kstandarddirs.h>
00058 #include <kurl.h>
00059 #include <ksycoca.h>
00060 #include <kde_file.h>
00061 
00062 template class KSharedPtr<KMimeType>;
00063 template class QValueList<KMimeType::Ptr>;
00064 
00065 KMimeType::Ptr KMimeType::s_pDefaultType = 0L;
00066 bool KMimeType::s_bChecked = false;
00067 
00068 void KMimeType::buildDefaultType()
00069 {
00070   assert ( !s_pDefaultType );
00071   // Try to find the default type
00072   KServiceType * mime = KServiceTypeFactory::self()->
00073         findServiceTypeByName( defaultMimeType() );
00074 
00075   if (mime && mime->isType( KST_KMimeType ))
00076   {
00077       s_pDefaultType = KMimeType::Ptr((KMimeType *) mime);
00078   }
00079   else
00080   {
00081      errorMissingMimeType( defaultMimeType() );
00082      KStandardDirs stdDirs;
00083      QString sDefaultMimeType = stdDirs.resourceDirs("mime").first()+defaultMimeType()+".desktop";
00084      s_pDefaultType = new KMimeType( sDefaultMimeType, defaultMimeType(),
00085                                      "unknown", "mime", QStringList() );
00086   }
00087 }
00088 
00089 KMimeType::Ptr KMimeType::defaultMimeTypePtr()
00090 {
00091   if ( !s_pDefaultType ) // we need a default type first
00092     buildDefaultType();
00093   return s_pDefaultType;
00094 }
00095 
00096 // Check for essential mimetypes
00097 void KMimeType::checkEssentialMimeTypes()
00098 {
00099   if ( s_bChecked ) // already done
00100     return;
00101   if ( !s_pDefaultType ) // we need a default type first
00102     buildDefaultType();
00103 
00104   s_bChecked = true; // must be done before building mimetypes
00105 
00106   // No Mime-Types installed ?
00107   // Lets do some rescue here.
00108   if ( !KServiceTypeFactory::self()->checkMimeTypes() )
00109   {
00110     KMessageBoxWrapper::error( 0L, i18n( "No mime types installed." ) );
00111     return; // no point in going any further
00112   }
00113 
00114   if ( KMimeType::mimeType( "inode/directory" ) == s_pDefaultType )
00115     errorMissingMimeType( "inode/directory" );
00116   if ( KMimeType::mimeType( "inode/directory-locked" ) == s_pDefaultType )
00117     errorMissingMimeType( "inode/directory-locked" );
00118   if ( KMimeType::mimeType( "inode/blockdevice" ) == s_pDefaultType )
00119     errorMissingMimeType( "inode/blockdevice" );
00120   if ( KMimeType::mimeType( "inode/chardevice" ) == s_pDefaultType )
00121     errorMissingMimeType( "inode/chardevice" );
00122   if ( KMimeType::mimeType( "inode/socket" ) == s_pDefaultType )
00123     errorMissingMimeType( "inode/socket" );
00124   if ( KMimeType::mimeType( "inode/fifo" ) == s_pDefaultType )
00125     errorMissingMimeType( "inode/fifo" );
00126   if ( KMimeType::mimeType( "application/x-shellscript" ) == s_pDefaultType )
00127     errorMissingMimeType( "application/x-shellscript" );
00128   if ( KMimeType::mimeType( "application/x-executable" ) == s_pDefaultType )
00129     errorMissingMimeType( "application/x-executable" );
00130   if ( KMimeType::mimeType( "application/x-desktop" ) == s_pDefaultType )
00131     errorMissingMimeType( "application/x-desktop" );
00132 }
00133 
00134 void KMimeType::errorMissingMimeType( const QString& _type )
00135 {
00136   QString tmp = i18n( "Could not find mime type\n%1" ).arg( _type );
00137 
00138   KMessageBoxWrapper::sorry( 0, tmp );
00139 }
00140 
00141 KMimeType::Ptr KMimeType::mimeType( const QString& _name )
00142 {
00143   KServiceType * mime = KServiceTypeFactory::self()->findServiceTypeByName( _name );
00144 
00145   if ( !mime || !mime->isType( KST_KMimeType ) )
00146   {
00147     // When building ksycoca, findServiceTypeByName doesn't create an object
00148     // but returns one from a dict.
00149     if ( !KSycoca::self()->isBuilding() )
00150         delete mime;
00151     if ( !s_pDefaultType )
00152       buildDefaultType();
00153     return s_pDefaultType;
00154   }
00155 
00156   // We got a mimetype
00157   return KMimeType::Ptr((KMimeType *) mime);
00158 }
00159 
00160 KMimeType::List KMimeType::allMimeTypes()
00161 {
00162   return KServiceTypeFactory::self()->allMimeTypes();
00163 }
00164 
00165 KMimeType::Ptr KMimeType::findByURL( const KURL& _url, mode_t _mode,
00166                                      bool _is_local_file, bool _fast_mode )
00167 {
00168   checkEssentialMimeTypes();
00169   QString path = _url.path();
00170 
00171   if ( !_fast_mode && !_is_local_file && _url.isLocalFile() )
00172     _is_local_file = true;
00173 
00174   if ( !_fast_mode && _is_local_file && (_mode == 0 || _mode == (mode_t)-1) )
00175   {
00176     KDE_struct_stat buff;
00177     if ( KDE_stat( QFile::encodeName(path), &buff ) != -1 )
00178       _mode = buff.st_mode;
00179   }
00180 
00181   // Look at mode_t first
00182   if ( S_ISDIR( _mode ) )
00183   {
00184     // Special hack for local files. We want to see whether we
00185     // are allowed to enter the directory
00186     if ( _is_local_file )
00187     {
00188       if ( access( QFile::encodeName(path), R_OK ) == -1 )
00189         return mimeType( "inode/directory-locked" );
00190     }
00191     return mimeType( "inode/directory" );
00192   }
00193   if ( S_ISCHR( _mode ) )
00194     return mimeType( "inode/chardevice" );
00195   if ( S_ISBLK( _mode ) )
00196     return mimeType( "inode/blockdevice" );
00197   if ( S_ISFIFO( _mode ) )
00198     return mimeType( "inode/fifo" );
00199   if ( S_ISSOCK( _mode ) )
00200     return mimeType( "inode/socket" );
00201   // KMimeMagic can do that better for local files
00202   if ( !_is_local_file && S_ISREG( _mode ) && ( _mode & ( S_IXUSR | S_IXGRP | S_IXOTH ) ) )
00203     return mimeType( "application/x-executable" );
00204 
00205   QString fileName ( _url.fileName() );
00206 
00207   static const QString& slash = KGlobal::staticQString("/");
00208   if ( ! fileName.isNull() && !path.endsWith( slash ) )
00209   {
00210       // Try to find it out by looking at the filename
00211       KMimeType::Ptr mime = KServiceTypeFactory::self()->findFromPattern( fileName );
00212       if ( mime )
00213       {
00214         // Found something - can we trust it ? (e.g. don't trust *.pl over HTTP, could be anything)
00215         if ( _is_local_file || _url.hasSubURL() || // Explicitly trust suburls
00216              KProtocolInfo::determineMimetypeFromExtension( _url.protocol() ) )
00217         {
00218             if ( _is_local_file && !_fast_mode ) {
00219                 if ( mime->patternsAccuracy()<100 )
00220                 {
00221                     KMimeMagicResult* result =
00222                             KMimeMagic::self()->findFileType( path );
00223 
00224                     if ( result && result->isValid() )
00225                         return mimeType( result->mimeType() );
00226                 }
00227             }
00228 
00229             return mime;
00230         }
00231       }
00232 
00233       static const QString& dotdesktop = KGlobal::staticQString(".desktop");
00234       static const QString& dotkdelnk = KGlobal::staticQString(".kdelnk");
00235       static const QString& dotdirectory = KGlobal::staticQString(".directory");
00236 
00237       // Another filename binding, hardcoded, is .desktop:
00238       if ( fileName.endsWith( dotdesktop ) )
00239         return mimeType( "application/x-desktop" );
00240       // Another filename binding, hardcoded, is .kdelnk;
00241       // this is preserved for backwards compatibility
00242       if ( fileName.endsWith( dotkdelnk ) )
00243         return mimeType( "application/x-desktop" );
00244       // .directory files are detected as x-desktop by mimemagic
00245       // but don't have a Type= entry. Better cheat and say they are text files
00246       if ( fileName == dotdirectory )
00247         return mimeType( "text/plain" );
00248     }
00249 
00250   if ( !_is_local_file || _fast_mode )
00251   {
00252     QString def = KProtocolInfo::defaultMimetype( _url );
00253     if ( !def.isEmpty() && def != defaultMimeType() )
00254     {
00255        // The protocol says it always returns a given mimetype (e.g. text/html for "man:")
00256        return mimeType( def );
00257     }
00258     if ( path.endsWith( slash ) || path.isEmpty() )
00259     {
00260       // We have no filename at all. Maybe the protocol has a setting for
00261       // which mimetype this means (e.g. directory).
00262       // For HTTP (def==defaultMimeType()) we don't assume anything,
00263       // because of redirections (e.g. freshmeat downloads).
00264       if ( def.isEmpty() )
00265       {
00266           // Assume inode/directory, if the protocol supports listing.
00267           if ( KProtocolInfo::supportsListing( _url ) )
00268               return mimeType( QString::fromLatin1("inode/directory") );
00269           else
00270               return defaultMimeTypePtr(); // == 'no idea', e.g. for "data:,foo/"
00271       }
00272     }
00273 
00274     // No more chances for non local URLs
00275     return defaultMimeTypePtr();
00276   }
00277 
00278   // Do some magic for local files
00279   //kdDebug(7009) << QString("Mime Type finding for '%1'").arg(path) << endl;
00280   KMimeMagicResult* result = KMimeMagic::self()->findFileType( path );
00281 
00282   // If we still did not find it, we must assume the default mime type
00283   if ( !result || !result->isValid() )
00284     return defaultMimeTypePtr();
00285 
00286   // The mimemagic stuff was successful
00287   return mimeType( result->mimeType() );
00288 }
00289 
00290 KMimeType::Ptr KMimeType::findByURL( const KURL& _url, mode_t _mode,
00291                                      bool _is_local_file, bool _fast_mode,
00292                                      bool *accurate)
00293 {
00294     KMimeType::Ptr mime = findByURL(_url, _mode, _is_local_file, _fast_mode);
00295     if (accurate) *accurate = !(_fast_mode) || ((mime->patternsAccuracy() == 100) && mime != defaultMimeTypePtr());
00296     return mime;
00297 }
00298 
00299 KMimeType::Ptr KMimeType::diagnoseFileName(const QString &fileName, QString &pattern)
00300 {
00301   return KServiceTypeFactory::self()->findFromPattern( fileName, &pattern );
00302 }
00303 
00304 KMimeType::Ptr KMimeType::findByPath( const QString& path, mode_t mode, bool fast_mode )
00305 {
00306     KURL u;
00307     u.setPath(path);
00308     return findByURL( u, mode, true, fast_mode );
00309 }
00310 
00311 KMimeType::Ptr KMimeType::findByContent( const QByteArray &data, int *accuracy )
00312 {
00313   KMimeMagicResult *result = KMimeMagic::self()->findBufferType(data);
00314   if (accuracy)
00315       *accuracy = result->accuracy();
00316   return mimeType( result->mimeType() );
00317 }
00318 
00319 KMimeType::Ptr KMimeType::findByFileContent( const QString &fileName, int *accuracy )
00320 {
00321   KMimeMagicResult *result = KMimeMagic::self()->findFileType(fileName);
00322   if (accuracy)
00323       *accuracy = result->accuracy();
00324   return mimeType( result->mimeType() );
00325 }
00326 
00327 #define GZIP_MAGIC1 0x1f
00328 #define GZIP_MAGIC2 0x8b
00329 
00330 KMimeType::Format KMimeType::findFormatByFileContent( const QString &fileName )
00331 {
00332   KMimeType::Format result;
00333   result.compression = Format::NoCompression;
00334   KMimeType::Ptr mime = findByPath(fileName);
00335   if (mime->name() == defaultMimeType())
00336      mime = findByFileContent(fileName);
00337 
00338   result.text = mime->name().startsWith("text/");
00339   QVariant v = mime->property("X-KDE-text");
00340   if (v.isValid())
00341      result.text = v.toBool();
00342 
00343   if (mime->name().startsWith("inode/"))
00344      return result;
00345 
00346   QFile f(fileName);
00347   if (f.open(IO_ReadOnly))
00348   {
00349      unsigned char buf[10+1];
00350      int l = f.readBlock((char *)buf, 10);
00351      if ((l > 2) && (buf[0] == GZIP_MAGIC1) && (buf[1] == GZIP_MAGIC2))
00352         result.compression = Format::GZipCompression;
00353   }
00354   return result;
00355 }
00356 
00357 KMimeType::KMimeType( const QString & _fullpath, const QString& _type, const QString& _icon,
00358                       const QString& _comment, const QStringList& _patterns )
00359   : KServiceType( _fullpath, _type, _icon, _comment )
00360 {
00361   m_lstPatterns = _patterns;
00362 }
00363 
00364 KMimeType::KMimeType( const QString & _fullpath ) : KServiceType( _fullpath )
00365 {
00366   KDesktopFile _cfg( _fullpath, true );
00367   init ( &_cfg );
00368 
00369   if ( !isValid() )
00370     kdWarning(7009) << "mimetype not valid '" << m_strName << "' (missing entry in the file ?)" << endl;
00371 }
00372 
00373 KMimeType::KMimeType( KDesktopFile *config ) : KServiceType( config )
00374 {
00375   init( config );
00376 
00377   if ( !isValid() )
00378     kdWarning(7009) << "mimetype not valid '" << m_strName << "' (missing entry in the file ?)" << endl;
00379 }
00380 
00381 void KMimeType::init( KDesktopFile * config )
00382 {
00383   config->setDesktopGroup();
00384   m_lstPatterns = config->readListEntry( "Patterns", ';' );
00385 
00386   // Read the X-KDE-AutoEmbed setting and store it in the properties map
00387   QString XKDEAutoEmbed = QString::fromLatin1("X-KDE-AutoEmbed");
00388   if ( config->hasKey( XKDEAutoEmbed ) )
00389     m_mapProps.insert( XKDEAutoEmbed, QVariant( config->readBoolEntry( XKDEAutoEmbed ), 0 ) );
00390 
00391   QString XKDEText = QString::fromLatin1("X-KDE-text");
00392   if ( config->hasKey( XKDEText ) )
00393     m_mapProps.insert( XKDEText, config->readBoolEntry( XKDEText ) );
00394 
00395   QString XKDEIsAlso = QString::fromLatin1("X-KDE-IsAlso");
00396   if ( config->hasKey( XKDEIsAlso ) ) {
00397     QString inherits = config->readEntry( XKDEIsAlso );
00398     if ( inherits != name() )
00399         m_mapProps.insert( XKDEIsAlso, inherits );
00400     else
00401         kdWarning(7009) << "Error: " << inherits << " inherits from itself!!!!" << endl;
00402   }
00403 
00404   QString XKDEPatternsAccuracy = QString::fromLatin1("X-KDE-PatternsAccuracy");
00405   if ( config->hasKey( XKDEPatternsAccuracy ) )
00406     m_mapProps.insert( XKDEPatternsAccuracy, config->readEntry( XKDEPatternsAccuracy ) );
00407 
00408 }
00409 
00410 KMimeType::KMimeType( QDataStream& _str, int offset ) : KServiceType( _str, offset )
00411 {
00412   loadInternal( _str ); // load our specific stuff
00413 }
00414 
00415 void KMimeType::load( QDataStream& _str )
00416 {
00417   KServiceType::load( _str );
00418   loadInternal( _str );
00419 }
00420 
00421 void KMimeType::loadInternal( QDataStream& _str )
00422 {
00423   // kdDebug(7009) << "KMimeType::load( QDataStream& ) : loading list of patterns" << endl;
00424   _str >> m_lstPatterns;
00425 }
00426 
00427 void KMimeType::save( QDataStream& _str )
00428 {
00429   KServiceType::save( _str );
00430   // Warning adding/removing fields here involves a binary incompatible change - update version
00431   // number in ksycoca.h
00432   _str << m_lstPatterns;
00433 }
00434 
00435 QVariant KMimeType::property( const QString& _name ) const
00436 {
00437   if ( _name == "Patterns" )
00438     return QVariant( m_lstPatterns );
00439 
00440   return KServiceType::property( _name );
00441 }
00442 
00443 QStringList KMimeType::propertyNames() const
00444 {
00445   QStringList res = KServiceType::propertyNames();
00446   res.append( "Patterns" );
00447 
00448   return res;
00449 }
00450 
00451 KMimeType::~KMimeType()
00452 {
00453 }
00454 
00455 QPixmap KMimeType::pixmap( KIcon::Group _group, int _force_size, int _state,
00456                            QString * _path ) const
00457 {
00458   KIconLoader *iconLoader=KGlobal::iconLoader();
00459   QString iconName=icon( QString::null, false );
00460   if (!iconLoader->extraDesktopThemesAdded())
00461   {
00462     QPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
00463     if (!pixmap.isNull() ) return pixmap;
00464 
00465     iconLoader->addExtraDesktopThemes();
00466   }
00467 
00468   return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
00469 }
00470 
00471 QPixmap KMimeType::pixmap( const KURL& _url, KIcon::Group _group, int _force_size,
00472                            int _state, QString * _path ) const
00473 {
00474   KIconLoader *iconLoader=KGlobal::iconLoader();
00475   QString iconName=icon( _url, _url.isLocalFile() );
00476   if (!iconLoader->extraDesktopThemesAdded())
00477   {
00478     QPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
00479     if (!pixmap.isNull() ) return pixmap;
00480 
00481     iconLoader->addExtraDesktopThemes();
00482   }
00483 
00484   return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
00485 }
00486 
00487 QPixmap KMimeType::pixmapForURL( const KURL & _url, mode_t _mode, KIcon::Group _group,
00488                                  int _force_size, int _state, QString * _path )
00489 {
00490   KIconLoader *iconLoader=KGlobal::iconLoader();
00491   QString iconName = iconForURL( _url, _mode );
00492 
00493   if (!iconLoader->extraDesktopThemesAdded())
00494   {
00495     QPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
00496     if (!pixmap.isNull() ) return pixmap;
00497 
00498     iconLoader->addExtraDesktopThemes();
00499   }
00500 
00501   return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
00502 
00503 }
00504 
00505 QString KMimeType::iconForURL( const KURL & _url, mode_t _mode )
00506 {
00507     const KMimeType::Ptr mt = findByURL( _url, _mode, _url.isLocalFile(),
00508                                          false /*HACK*/);
00509     static const QString& unknown = KGlobal::staticQString("unknown");
00510     const QString mimeTypeIcon = mt->icon( _url, _url.isLocalFile() );
00511     QString i = mimeTypeIcon;
00512 
00513     // if we don't find an icon, maybe we can use the one for the protocol
00514     if ( i == unknown || i.isEmpty() || mt == defaultMimeTypePtr()
00515         // and for the root of the protocol (e.g. trash:/) the protocol icon has priority over the mimetype icon
00516         || _url.path().length() <= 1 )
00517     {
00518         i = favIconForURL( _url ); // maybe there is a favicon?
00519 
00520         if ( i.isEmpty() )
00521             i = KProtocolInfo::icon( _url.protocol() );
00522 
00523         // root of protocol: if we found nothing, revert to mimeTypeIcon (which is usually "folder")
00524         if ( _url.path().length() <= 1 && ( i == unknown || i.isEmpty() ) )
00525             i = mimeTypeIcon;
00526     }
00527     return i;
00528 }
00529 
00530 QString KMimeType::favIconForURL( const KURL& url )
00531 {
00532     // this method will be called quite often, so better not read the config
00533     // again and again.
00534     static bool useFavIcons = true;
00535     static bool check = true;
00536     if ( check ) {
00537         check = false;
00538         KConfig *config = KGlobal::config();
00539         KConfigGroupSaver cs( config, "HTML Settings" );
00540         useFavIcons = config->readBoolEntry( "EnableFavicon", true );
00541     }
00542 
00543     if ( url.isLocalFile() || !url.protocol().startsWith("http")
00544          || !useFavIcons )
00545         return QString::null;
00546 
00547     DCOPRef kded( "kded", "favicons" );
00548     DCOPReply result = kded.call( "iconForURL(KURL)", url );
00549     if ( result.isValid() )
00550         return result;
00551 
00552     return QString::null;
00553 }
00554 
00555 QString KMimeType::parentMimeType() const
00556 {
00557   QVariant v = property("X-KDE-IsAlso");
00558   return v.toString();
00559 }
00560 
00561 bool KMimeType::is( const QString& mimeTypeName ) const
00562 {
00563   if ( name() == mimeTypeName )
00564       return true;
00565   QString st = parentMimeType();
00566   //if (st.isEmpty()) kdDebug(7009)<<"Parent mimetype is empty"<<endl;
00567   while ( !st.isEmpty() )
00568   {
00569       //kdDebug(7009)<<"Checking parent mime type: "<<st<<endl;
00570       KMimeType::Ptr ptr = KMimeType::mimeType( st );
00571       if (!ptr) return false; //error
00572       if ( ptr->name() == mimeTypeName )
00573           return true;
00574       st = ptr->parentMimeType();
00575   }
00576   return false;
00577 }
00578 
00579 int KMimeType::patternsAccuracy() const {
00580   QVariant v = property("X-KDE-PatternsAccuracy");
00581   if (!v.isValid()) return 100;
00582   else
00583       return v.toInt();
00584 }
00585 
00586 
00587 /*******************************************************
00588  *
00589  * KFolderType
00590  *
00591  ******************************************************/
00592 
00593 QString KFolderType::icon( const QString& _url, bool _is_local ) const
00594 {
00595   if ( !_is_local || _url.isEmpty() )
00596     return KMimeType::icon( _url, _is_local );
00597 
00598   return KFolderType::icon( KURL(_url), _is_local );
00599 }
00600 
00601 QString KFolderType::icon( const KURL& _url, bool _is_local ) const
00602 {
00603   if ( !_is_local )
00604     return KMimeType::icon( _url, _is_local );
00605 
00606   KURL u( _url );
00607   u.addPath( ".directory" );
00608 
00609   QString icon;
00610   // using KStandardDirs as this one checks for path being
00611   // a file instead of a directory
00612   if ( KStandardDirs::exists( u.path() ) )
00613   {
00614     KSimpleConfig cfg( u.path(), true );
00615     cfg.setDesktopGroup();
00616     icon = cfg.readEntry( "Icon" );
00617     QString empty_icon = cfg.readEntry( "EmptyIcon" );
00618 
00619     if ( !empty_icon.isEmpty() )
00620     {
00621       bool isempty = false;
00622       DIR *dp = 0L;
00623       struct dirent *ep;
00624       dp = opendir( QFile::encodeName(_url.path()) );
00625       if ( dp )
00626       {
00627         QValueList<QCString> entries;
00628         // Note that readdir isn't guaranteed to return "." and ".." first (#79826)
00629         ep=readdir( dp ); if ( ep ) entries.append( ep->d_name );
00630         ep=readdir( dp ); if ( ep ) entries.append( ep->d_name );
00631         if ( (ep=readdir( dp )) == 0L ) // third file is NULL entry -> empty directory
00632           isempty = true;
00633         else {
00634           entries.append( ep->d_name );
00635           if ( readdir( dp ) == 0 ) { // only three
00636             // check if we got "." ".." and ".directory"
00637             isempty = entries.find( "." ) != entries.end() &&
00638                       entries.find( ".." ) != entries.end() &&
00639                       entries.find( ".directory" ) != entries.end();
00640           }
00641         }
00642         if (!isempty && !strcmp(ep->d_name, ".directory"))
00643           isempty = (readdir(dp) == 0L);
00644         closedir( dp );
00645       }
00646 
00647       if ( isempty )
00648         return empty_icon;
00649     }
00650   }
00651 
00652   if ( icon.isEmpty() )
00653     return KMimeType::icon( _url, _is_local );
00654 
00655   if ( icon.startsWith( "./" ) ) {
00656     // path is relative with respect to the location
00657     // of the .directory file (#73463)
00658     KURL v( _url );
00659     v.addPath( icon.mid( 2 ) );
00660     icon = v.path();
00661   }
00662 
00663   return icon;
00664 }
00665 
00666 QString KFolderType::comment( const QString& _url, bool _is_local ) const
00667 {
00668   if ( !_is_local || _url.isEmpty() )
00669     return KMimeType::comment( _url, _is_local );
00670 
00671   return KFolderType::comment( KURL(_url), _is_local );
00672 }
00673 
00674 QString KFolderType::comment( const KURL& _url, bool _is_local ) const
00675 {
00676   if ( !_is_local )
00677     return KMimeType::comment( _url, _is_local );
00678 
00679   KURL u( _url );
00680   u.addPath( ".directory" );
00681 
00682   KSimpleConfig cfg( u.path(), true );
00683   cfg.setDesktopGroup();
00684   QString comment = cfg.readEntry( "Comment" );
00685   if ( comment.isEmpty() )
00686     return KMimeType::comment( _url, _is_local );
00687 
00688   return comment;
00689 }
00690 
00691 /*******************************************************
00692  *
00693  * KDEDesktopMimeType
00694  *
00695  ******************************************************/
00696 
00697 QString KDEDesktopMimeType::icon( const QString& _url, bool _is_local ) const
00698 {
00699   if ( !_is_local || _url.isEmpty() )
00700     return KMimeType::icon( _url, _is_local );
00701 
00702   KURL u( _url );
00703   return icon( u, _is_local );
00704 }
00705 
00706 QString KDEDesktopMimeType::icon( const KURL& _url, bool _is_local ) const
00707 {
00708   if ( !_is_local )
00709     return KMimeType::icon( _url, _is_local );
00710 
00711   KSimpleConfig cfg( _url.path(), true );
00712   cfg.setDesktopGroup();
00713   QString icon = cfg.readEntry( "Icon" );
00714   QString type = cfg.readEntry( "Type" );
00715 
00716   if ( type == "FSDevice" || type == "FSDev") // need to provide FSDev for
00717                                               // backwards compatibility
00718   {
00719     QString unmount_icon = cfg.readEntry( "UnmountIcon" );
00720     QString dev = cfg.readEntry( "Dev" );
00721     if ( !icon.isEmpty() && !unmount_icon.isEmpty() && !dev.isEmpty() )
00722     {
00723       QString mp = KIO::findDeviceMountPoint( dev );
00724       // Is the device not mounted ?
00725       if ( mp.isNull() )
00726         return unmount_icon;
00727     }
00728   } else if ( type == "Link" ) {
00729       const QString emptyIcon = cfg.readEntry( "EmptyIcon" );
00730       if ( !emptyIcon.isEmpty() ) {
00731           const QString u = cfg.readPathEntry( "URL" );
00732           const KURL url( u );
00733           if ( url.protocol() == "trash" ) {
00734               // We need to find if the trash is empty, preferrably without using a KIO job.
00735               // So instead kio_trash leaves an entry in its config file for us.
00736               KSimpleConfig trashConfig( "trashrc", true );
00737               trashConfig.setGroup( "Status" );
00738               if ( trashConfig.readBoolEntry( "Empty", true ) ) {
00739                   return emptyIcon;
00740               }
00741           }
00742       }
00743   }
00744 
00745   if ( icon.isEmpty() )
00746     return KMimeType::icon( _url, _is_local );
00747 
00748   return icon;
00749 }
00750 
00751 QPixmap KDEDesktopMimeType::pixmap( const KURL& _url, KIcon::Group _group, int _force_size,
00752                                     int _state, QString * _path ) const
00753 {
00754   QString _icon = icon( _url, _url.isLocalFile() );
00755   QPixmap pix = KGlobal::iconLoader()->loadIcon( _icon, _group,
00756         _force_size, _state, _path, false );
00757   if ( pix.isNull() )
00758       pix = KGlobal::iconLoader()->loadIcon( "unknown", _group,
00759         _force_size, _state, _path, false );
00760   return pix;
00761 }
00762 
00763 QString KDEDesktopMimeType::comment( const QString& _url, bool _is_local ) const
00764 {
00765   if ( !_is_local || _url.isEmpty() )
00766     return KMimeType::comment( _url, _is_local );
00767 
00768   KURL u( _url );
00769   return comment( u, _is_local );
00770 }
00771 
00772 QString KDEDesktopMimeType::comment( const KURL& _url, bool _is_local ) const
00773 {
00774   if ( !_is_local )
00775     return KMimeType::comment( _url, _is_local );
00776 
00777   KSimpleConfig cfg( _url.path(), true );
00778   cfg.setDesktopGroup();
00779   QString comment = cfg.readEntry( "Comment" );
00780   if ( comment.isEmpty() )
00781     return KMimeType::comment( _url, _is_local );
00782 
00783   return comment;
00784 }
00785 
00786 pid_t KDEDesktopMimeType::run( const KURL& u, bool _is_local )
00787 {
00788   // It might be a security problem to run external untrusted desktop
00789   // entry files
00790   if ( !_is_local )
00791     return 0;
00792 
00793   KSimpleConfig cfg( u.path(), true );
00794   cfg.setDesktopGroup();
00795   QString type = cfg.readEntry( "Type" );
00796   if ( type.isEmpty() )
00797   {
00798     QString tmp = i18n("The desktop entry file %1 "
00799                        "has no Type=... entry.").arg(u.path() );
00800     KMessageBoxWrapper::error( 0, tmp);
00801     return 0;
00802   }
00803 
00804   //kdDebug(7009) << "TYPE = " << type.data() << endl;
00805 
00806   if ( type == "FSDevice" )
00807     return runFSDevice( u, cfg );
00808   else if ( type == "Application" )
00809     return runApplication( u, u.path() );
00810   else if ( type == "Link" )
00811   {
00812     cfg.setDollarExpansion( true ); // for URL=file:$HOME (Simon)
00813     return runLink( u, cfg );
00814   }
00815   else if ( type == "MimeType" )
00816     return runMimeType( u, cfg );
00817 
00818 
00819   QString tmp = i18n("The desktop entry of type\n%1\nis unknown.").arg( type );
00820   KMessageBoxWrapper::error( 0, tmp);
00821 
00822   return 0;
00823 }
00824 
00825 pid_t KDEDesktopMimeType::runFSDevice( const KURL& _url, const KSimpleConfig &cfg )
00826 {
00827   pid_t retval = 0;
00828 
00829   QString dev = cfg.readEntry( "Dev" );
00830 
00831   if ( dev.isEmpty() )
00832   {
00833     QString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( _url.path() );
00834     KMessageBoxWrapper::error( 0, tmp);
00835     return retval;
00836   }
00837 
00838   QString mp = KIO::findDeviceMountPoint( dev );
00839   // Is the device already mounted ?
00840   if ( !mp.isNull() )
00841   {
00842     KURL mpURL;
00843     mpURL.setPath( mp );
00844     // Open a new window
00845     retval = KRun::runURL( mpURL, QString::fromLatin1("inode/directory") );
00846   }
00847   else
00848   {
00849     bool ro = cfg.readBoolEntry( "ReadOnly", false );
00850     QString fstype = cfg.readEntry( "FSType" );
00851     if ( fstype == "Default" ) // KDE-1 thing
00852       fstype = QString::null;
00853     QString point = cfg.readEntry( "MountPoint" );
00854 #ifndef Q_WS_WIN
00855     (void) new KAutoMount( ro, fstype, dev, point, _url.path() );
00856 #endif
00857     retval = -1; // we don't want to return 0, but we don't want to return a pid
00858   }
00859 
00860   return retval;
00861 }
00862 
00863 pid_t KDEDesktopMimeType::runApplication( const KURL& , const QString & _serviceFile )
00864 {
00865   KService s( _serviceFile );
00866   if ( !s.isValid() )
00867     // The error message was already displayed, so we can just quit here
00868     return 0;
00869 
00870   KURL::List lst;
00871   return KRun::run( s, lst );
00872 }
00873 
00874 pid_t KDEDesktopMimeType::runLink( const KURL& _url, const KSimpleConfig &cfg )
00875 {
00876   QString u = cfg.readPathEntry( "URL" );
00877   if ( u.isEmpty() )
00878   {
00879     QString tmp = i18n("The desktop entry file\n%1\nis of type Link but has no URL=... entry.").arg( _url.prettyURL() );
00880     KMessageBoxWrapper::error( 0, tmp );
00881     return 0;
00882   }
00883 
00884   KURL url ( u );
00885   KRun* run = new KRun(url);
00886 
00887   // X-KDE-LastOpenedWith holds the service desktop entry name that
00888   // was should be preferred for opening this URL if possible.
00889   // This is used by the Recent Documents menu for instance.
00890   QString lastOpenedWidth = cfg.readEntry( "X-KDE-LastOpenedWith" );
00891   if ( !lastOpenedWidth.isEmpty() )
00892       run->setPreferredService( lastOpenedWidth );
00893 
00894   return -1; // we don't want to return 0, but we don't want to return a pid
00895 }
00896 
00897 pid_t KDEDesktopMimeType::runMimeType( const KURL& url , const KSimpleConfig & )
00898 {
00899   // Hmm, can't really use keditfiletype since we might be looking
00900   // at the global file, or at a file not in share/mimelnk...
00901 
00902   QStringList args;
00903   args << "openProperties";
00904   args << url.path();
00905 
00906   int pid;
00907   if ( !KApplication::kdeinitExec("kfmclient", args, 0, &pid) )
00908       return pid;
00909 
00910   KProcess p;
00911   p << "kfmclient" << args;
00912   p.start(KProcess::DontCare);
00913   return p.pid();
00914 }
00915 
00916 QValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::builtinServices( const KURL& _url )
00917 {
00918   QValueList<Service> result;
00919 
00920   if ( !_url.isLocalFile() )
00921     return result;
00922 
00923   KSimpleConfig cfg( _url.path(), true );
00924   cfg.setDesktopGroup();
00925   QString type = cfg.readEntry( "Type" );
00926 
00927   if ( type.isEmpty() )
00928     return result;
00929 
00930   if ( type == "FSDevice" )
00931   {
00932     QString dev = cfg.readEntry( "Dev" );
00933     if ( dev.isEmpty() )
00934     {
00935       QString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( _url.path() );
00936       KMessageBoxWrapper::error( 0, tmp);
00937     }
00938     else
00939     {
00940       QString mp = KIO::findDeviceMountPoint( dev );
00941       // not mounted ?
00942       if ( mp.isEmpty() )
00943       {
00944         Service mount;
00945         mount.m_strName = i18n("Mount");
00946         mount.m_type = ST_MOUNT;
00947         result.append( mount );
00948       }
00949       else
00950       {
00951         Service unmount;
00952 #ifdef HAVE_VOLMGT
00953         /*
00954          *  Solaris' volume management can only umount+eject
00955          */
00956         unmount.m_strName = i18n("Eject");
00957 #else
00958         unmount.m_strName = i18n("Unmount");
00959 #endif
00960         unmount.m_type = ST_UNMOUNT;
00961         result.append( unmount );
00962       }
00963     }
00964   }
00965 
00966   return result;
00967 }
00968 
00969 QValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const QString& path, bool bLocalFiles )
00970 {
00971   KSimpleConfig cfg( path, true );
00972   return userDefinedServices( path, cfg, bLocalFiles );
00973 }
00974 
00975 QValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const QString& path, KConfig& cfg, bool bLocalFiles )
00976 {
00977  return userDefinedServices( path, cfg, bLocalFiles, KURL::List() );
00978 }
00979 
00980 QValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const QString& path, KConfig& cfg, bool bLocalFiles, const KURL::List & file_list )
00981 {
00982   QValueList<Service> result;
00983 
00984   cfg.setDesktopGroup();
00985 
00986   if ( !cfg.hasKey( "Actions" ) && !cfg.hasKey( "X-KDE-GetActionMenu") )
00987     return result;
00988 
00989   if ( cfg.hasKey( "TryExec" ) )
00990   {
00991       QString tryexec = cfg.readPathEntry( "TryExec" );
00992       QString exe =  KStandardDirs::findExe( tryexec );
00993       if (exe.isEmpty()) {
00994           return result;
00995       }
00996   }
00997 
00998   QStringList keys;
00999 
01000   if( cfg.hasKey( "X-KDE-GetActionMenu" )) {
01001     QString dcopcall = cfg.readEntry( "X-KDE-GetActionMenu" );
01002     const QCString app = dcopcall.section(' ', 0,0).utf8();
01003 
01004     QByteArray dataToSend;
01005     QDataStream dataStream(dataToSend, IO_WriteOnly);
01006     dataStream << file_list;
01007     QCString replyType;
01008     QByteArray replyData;
01009     QCString object =    dcopcall.section(' ', 1,-2).utf8();
01010     QString function =  dcopcall.section(' ', -1);
01011     if(!function.endsWith("(KURL::List)")) {
01012       kdWarning() << "Desktop file " << path << " contains an invalid X-KDE-ShowIfDcopCall - the function must take the exact parameter (KURL::List) and must be specified." << endl;
01013     } else {
01014       if(kapp->dcopClient()->call( app, object,
01015                    function.utf8(),
01016                    dataToSend, replyType, replyData, true, 100)
01017         && replyType == "QStringList" ) {
01018 
01019         QDataStream dataStreamIn(replyData, IO_ReadOnly);
01020         dataStreamIn >> keys;
01021       }
01022     }
01023   }
01024 
01025   keys += cfg.readListEntry( "Actions", ';' ); //the desktop standard defines ";" as separator!
01026 
01027   if ( keys.count() == 0 )
01028     return result;
01029 
01030   QStringList::ConstIterator it = keys.begin();
01031   QStringList::ConstIterator end = keys.end();
01032   for ( ; it != end; ++it )
01033   {
01034     //kdDebug(7009) << "CURRENT KEY = " << (*it) << endl;
01035 
01036     QString group = *it;
01037 
01038     if (group == "_SEPARATOR_")
01039     {
01040         Service s;
01041         result.append(s);
01042         continue;
01043     }
01044 
01045     group.prepend( "Desktop Action " );
01046 
01047     bool bInvalidMenu = false;
01048 
01049     if ( cfg.hasGroup( group ) )
01050     {
01051       cfg.setGroup( group );
01052 
01053       if ( !cfg.hasKey( "Name" ) || !cfg.hasKey( "Exec" ) )
01054         bInvalidMenu = true;
01055       else
01056       {
01057         QString exec = cfg.readPathEntry( "Exec" );
01058         if ( bLocalFiles || exec.contains("%U") || exec.contains("%u") )
01059         {
01060           Service s;
01061           s.m_strName = cfg.readEntry( "Name" );
01062           s.m_strIcon = cfg.readEntry( "Icon" );
01063           s.m_strExec = exec;
01064           s.m_type = ST_USER_DEFINED;
01065           s.m_display = !cfg.readBoolEntry( "NoDisplay" );
01066           result.append( s );
01067         }
01068       }
01069     }
01070     else
01071       bInvalidMenu = true;
01072 
01073     if ( bInvalidMenu )
01074     {
01075       QString tmp = i18n("The desktop entry file\n%1\n has an invalid menu entry\n%2.").arg( path ).arg( *it );
01076       KMessageBoxWrapper::error( 0, tmp );
01077     }
01078   }
01079 
01080   return result;
01081 }
01082 
01083 void KDEDesktopMimeType::executeService( const QString& _url, KDEDesktopMimeType::Service& _service )
01084 {
01085     KURL u;
01086     u.setPath(_url);
01087     KURL::List lst;
01088     lst.append( u );
01089     executeService( lst, _service );
01090 }
01091 
01092 void KDEDesktopMimeType::executeService( const KURL::List& urls, KDEDesktopMimeType::Service& _service )
01093 {
01094   //kdDebug(7009) << "EXECUTING Service " << _service.m_strName << endl;
01095 
01096   if ( _service.m_type == ST_USER_DEFINED )
01097   {
01098     kdDebug() << "KDEDesktopMimeType::executeService " << _service.m_strName
01099               << " first url's path=" << urls.first().path() << " exec=" << _service.m_strExec << endl;
01100     KRun::run( _service.m_strExec, urls, _service.m_strName, _service.m_strIcon, _service.m_strIcon );
01101     // The action may update the desktop file. Example: eject unmounts (#5129).
01102     KDirNotify_stub allDirNotify("*", "KDirNotify*");
01103     allDirNotify.FilesChanged( urls );
01104     return;
01105   }
01106   else if ( _service.m_type == ST_MOUNT || _service.m_type == ST_UNMOUNT )
01107   {
01108     Q_ASSERT( urls.count() == 1 );
01109     QString path = urls.first().path();
01110     //kdDebug(7009) << "MOUNT&UNMOUNT" << endl;
01111 
01112     KSimpleConfig cfg( path, true );
01113     cfg.setDesktopGroup();
01114     QString dev = cfg.readEntry( "Dev" );
01115     if ( dev.isEmpty() )
01116     {
01117       QString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( path );
01118       KMessageBoxWrapper::error( 0, tmp );
01119       return;
01120     }
01121     QString mp = KIO::findDeviceMountPoint( dev );
01122 
01123     if ( _service.m_type == ST_MOUNT )
01124     {
01125       // Already mounted? Strange, but who knows ...
01126       if ( !mp.isEmpty() )
01127       {
01128         kdDebug(7009) << "ALREADY Mounted" << endl;
01129         return;
01130       }
01131 
01132       bool ro = cfg.readBoolEntry( "ReadOnly", false );
01133       QString fstype = cfg.readEntry( "FSType" );
01134       if ( fstype == "Default" ) // KDE-1 thing
01135           fstype = QString::null;
01136       QString point = cfg.readEntry( "MountPoint" );
01137 #ifndef Q_WS_WIN
01138       (void)new KAutoMount( ro, fstype, dev, point, path, false );
01139 #endif
01140     }
01141     else if ( _service.m_type == ST_UNMOUNT )
01142     {
01143       // Not mounted? Strange, but who knows ...
01144       if ( mp.isEmpty() )
01145         return;
01146 
01147 #ifndef Q_WS_WIN
01148       (void)new KAutoUnmount( mp, path );
01149 #endif
01150     }
01151   }
01152   else
01153     assert( 0 );
01154 }
01155 
01156 const QString & KMimeType::defaultMimeType()
01157 {
01158     static const QString & s_strDefaultMimeType =
01159         KGlobal::staticQString( "application/octet-stream" );
01160     return s_strDefaultMimeType;
01161 }
01162 
01163 void KMimeType::virtual_hook( int id, void* data )
01164 { KServiceType::virtual_hook( id, data ); }
01165 
01166 void KFolderType::virtual_hook( int id, void* data )
01167 { KMimeType::virtual_hook( id, data ); }
01168 
01169 void KDEDesktopMimeType::virtual_hook( int id, void* data )
01170 { KMimeType::virtual_hook( id, data ); }
01171 
01172 void KExecMimeType::virtual_hook( int id, void* data )
01173 { KMimeType::virtual_hook( id, data ); }
01174 
01175 #include "kmimetyperesolver.moc"
01176 
KDE Home | KDE Accessibility Home | Description of Access Keys