kdecore Library API Documentation

kstandarddirs.cpp

00001 /* This file is part of the KDE libraries
00002    Copyright (C) 1999 Sirtaj Singh Kang <taj@kde.org>
00003    Copyright (C) 1999 Stephan Kulow <coolo@kde.org>
00004    Copyright (C) 1999 Waldo Bastian <bastian@kde.org>
00005 
00006    This library is free software; you can redistribute it and/or
00007    modify it under the terms of the GNU Library General Public
00008    License version 2 as published by the Free Software Foundation.
00009 
00010    This library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Library General Public License for more details.
00014 
00015    You should have received a copy of the GNU Library General Public License
00016    along with this library; see the file COPYING.LIB.  If not, write to
00017    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00018    Boston, MA 02111-1307, USA.
00019 */
00020 
00021 /*
00022  * Author: Stephan Kulow <coolo@kde.org> and Sirtaj Singh Kang <taj@kde.org>
00023  * Version: $Id: kstandarddirs.cpp,v 1.168.2.1 2004/01/20 11:18:33 ossi Exp $
00024  * Generated:   Thu Mar  5 16:05:28 EST 1998
00025  */
00026 
00027 #include "config.h"
00028 
00029 #include <stdlib.h>
00030 #include <assert.h>
00031 #include <errno.h>
00032 #ifdef HAVE_SYS_STAT_H
00033 #include <sys/stat.h>
00034 #endif
00035 #include <sys/types.h>
00036 #include <dirent.h>
00037 #include <pwd.h>
00038 
00039 #include <qregexp.h>
00040 #include <qasciidict.h>
00041 #include <qdict.h>
00042 #include <qdir.h>
00043 #include <qfileinfo.h>
00044 #include <qstring.h>
00045 #include <qstringlist.h>
00046 
00047 #include "kstandarddirs.h"
00048 #include "kconfig.h"
00049 #include "kdebug.h"
00050 #include "kinstance.h"
00051 #include "kshell.h"
00052 #include <sys/param.h>
00053 #include <unistd.h>
00054 
00055 template class QDict<QStringList>;
00056 
00057 class KStandardDirs::KStandardDirsPrivate
00058 {
00059 public:
00060    KStandardDirsPrivate()
00061     : restrictionsActive(false),
00062       dataRestrictionActive(false)
00063    { }
00064 
00065    bool restrictionsActive;
00066    bool dataRestrictionActive;
00067    QAsciiDict<bool> restrictions;
00068    QStringList xdgdata_prefixes;
00069    QStringList xdgconf_prefixes;
00070 };
00071 
00072 static const char* const types[] = {"html", "icon", "apps", "sound",
00073                   "data", "locale", "services", "mime",
00074                   "servicetypes", "config", "exe",
00075                   "wallpaper", "lib", "pixmap", "templates",
00076                   "module", "qtplugins",
00077                   "xdgdata-apps", "xdgdata-dirs", "xdgconf-menu",
00078                               "kcfg", 0 };
00079 
00080 #if defined(__x86_64__) || defined(__s390x__) || defined(__powerpc64__) || defined(__sparc64__)
00081 #  define LIBDIR_NAME "lib64"
00082 #else
00083 #  define LIBDIR_NAME "lib"
00084 #endif
00085 
00086 static int tokenize( QStringList& token, const QString& str,
00087         const QString& delim );
00088 
00089 KStandardDirs::KStandardDirs( ) : addedCustoms(false)
00090 {
00091     d = new KStandardDirsPrivate;
00092     dircache.setAutoDelete(true);
00093     relatives.setAutoDelete(true);
00094     absolutes.setAutoDelete(true);
00095     savelocations.setAutoDelete(true);
00096     addKDEDefaults();
00097 }
00098 
00099 KStandardDirs::~KStandardDirs()
00100 {
00101     delete d;
00102 }
00103 
00104 bool KStandardDirs::isRestrictedResource(const char *type, const QString& relPath) const
00105 {
00106    if (!d || !d->restrictionsActive)
00107       return false;
00108 
00109    if (d->restrictions[type])
00110       return true;
00111 
00112    if (strcmp(type, "data")==0)
00113    {
00114       applyDataRestrictions(relPath);
00115       if (d->dataRestrictionActive)
00116       {
00117          d->dataRestrictionActive = false;
00118          return true;
00119       }
00120    }
00121    return false;
00122 }
00123 
00124 void KStandardDirs::applyDataRestrictions(const QString &relPath) const
00125 {
00126    QString key;
00127    int i = relPath.find('/');
00128    if (i != -1)
00129       key = "data_"+relPath.left(i);
00130    else
00131       key = "data_"+relPath;
00132 
00133    if (d && d->restrictions[key.latin1()])
00134       d->dataRestrictionActive = true;
00135 }
00136 
00137 
00138 QStringList KStandardDirs::allTypes() const
00139 {
00140     QStringList list;
00141     for (int i = 0; types[i] != 0; ++i)
00142         list.append(QString::fromLatin1(types[i]));
00143     return list;
00144 }
00145 
00146 void KStandardDirs::addPrefix( const QString& _dir )
00147 {
00148     if (_dir.isNull())
00149     return;
00150 
00151     QString dir = _dir;
00152     if (dir.at(dir.length() - 1) != '/')
00153     dir += '/';
00154 
00155     if (!prefixes.contains(dir)) {
00156     prefixes.append(dir);
00157     dircache.clear();
00158     }
00159 }
00160 
00161 void KStandardDirs::addXdgConfigPrefix( const QString& _dir )
00162 {
00163     if (_dir.isNull())
00164     return;
00165 
00166     QString dir = _dir;
00167     if (dir.at(dir.length() - 1) != '/')
00168     dir += '/';
00169 
00170     if (!d->xdgconf_prefixes.contains(dir)) {
00171     d->xdgconf_prefixes.append(dir);
00172     dircache.clear();
00173     }
00174 }
00175 
00176 void KStandardDirs::addXdgDataPrefix( const QString& _dir )
00177 {
00178     if (_dir.isNull())
00179     return;
00180 
00181     QString dir = _dir;
00182     if (dir.at(dir.length() - 1) != '/')
00183     dir += '/';
00184 
00185     if (!d->xdgdata_prefixes.contains(dir)) {
00186     d->xdgdata_prefixes.append(dir);
00187     dircache.clear();
00188     }
00189 }
00190 
00191 
00192 QString KStandardDirs::kfsstnd_prefixes()
00193 {
00194    return prefixes.join(":");
00195 }
00196 
00197 bool KStandardDirs::addResourceType( const char *type,
00198                      const QString& relativename )
00199 {
00200     if (relativename.isNull())
00201        return false;
00202 
00203     QStringList *rels = relatives.find(type);
00204     if (!rels) {
00205     rels = new QStringList();
00206     relatives.insert(type, rels);
00207     }
00208     QString copy = relativename;
00209     if (copy.at(copy.length() - 1) != '/')
00210     copy += '/';
00211     if (!rels->contains(copy)) {
00212     rels->prepend(copy);
00213     dircache.remove(type); // clean the cache
00214     return true;
00215     }
00216     return false;
00217 }
00218 
00219 bool KStandardDirs::addResourceDir( const char *type,
00220                     const QString& absdir)
00221 {
00222     QStringList *paths = absolutes.find(type);
00223     if (!paths) {
00224     paths = new QStringList();
00225     absolutes.insert(type, paths);
00226     }
00227     QString copy = absdir;
00228     if (copy.at(copy.length() - 1) != '/')
00229       copy += '/';
00230 
00231     if (!paths->contains(copy)) {
00232     paths->append(copy);
00233     dircache.remove(type); // clean the cache
00234     return true;
00235     }
00236     return false;
00237 }
00238 
00239 QString KStandardDirs::findResource( const char *type,
00240                      const QString& filename ) const
00241 {
00242     if (filename.at(0) == '/')
00243     return filename; // absolute dirs are absolute dirs, right? :-/
00244 
00245 #if 0
00246 kdDebug() << "Find resource: " << type << endl;
00247 for (QStringList::ConstIterator pit = prefixes.begin();
00248      pit != prefixes.end();
00249      pit++)
00250 {
00251   kdDebug() << "Prefix: " << *pit << endl;
00252 }
00253 #endif
00254 
00255     QString dir = findResourceDir(type, filename);
00256     if (dir.isNull())
00257     return dir;
00258     else return dir + filename;
00259 }
00260 
00261 static Q_UINT32 updateHash(const QString &file, Q_UINT32 hash)
00262 {
00263     QCString cFile = QFile::encodeName(file);
00264     struct stat buff;
00265     if ((access(cFile, R_OK) == 0) &&
00266         (stat( cFile, &buff ) == 0) &&
00267         (S_ISREG( buff.st_mode )))
00268     {
00269        hash = hash + (Q_UINT32) buff.st_ctime;
00270     }
00271     return hash;
00272 }
00273 
00274 Q_UINT32 KStandardDirs::calcResourceHash( const char *type,
00275                   const QString& filename, bool deep) const
00276 {
00277     Q_UINT32 hash = 0;
00278 
00279     if (filename.at(0) == '/')
00280     {
00281         // absolute dirs are absolute dirs, right? :-/
00282     return updateHash(filename, hash);
00283     }
00284     if (d && d->restrictionsActive && (strcmp(type, "data")==0))
00285        applyDataRestrictions(filename);
00286     QStringList candidates = resourceDirs(type);
00287     QString fullPath;
00288 
00289     for (QStringList::ConstIterator it = candidates.begin();
00290      it != candidates.end(); it++)
00291     {
00292         hash = updateHash(*it + filename, hash);
00293         if (!deep && hash)
00294            return hash;
00295     }
00296     return hash;
00297 }
00298 
00299 
00300 QStringList KStandardDirs::findDirs( const char *type,
00301                                      const QString& reldir ) const
00302 {
00303     QDir testdir;
00304     QStringList list;
00305     if (reldir.startsWith("/"))
00306     {
00307         testdir.setPath(reldir);
00308         if (testdir.exists())
00309         {
00310             if (reldir.endsWith("/"))
00311                list.append(reldir);
00312             else
00313                list.append(reldir+'/');
00314         }
00315         return list;
00316     }
00317 
00318     checkConfig();
00319 
00320     if (d && d->restrictionsActive && (strcmp(type, "data")==0))
00321        applyDataRestrictions(reldir);
00322     QStringList candidates = resourceDirs(type);
00323 
00324     for (QStringList::ConstIterator it = candidates.begin();
00325          it != candidates.end(); it++) {
00326         testdir.setPath(*it + reldir);
00327         if (testdir.exists())
00328             list.append(testdir.absPath() + '/');
00329     }
00330 
00331     return list;
00332 }
00333 
00334 QString KStandardDirs::findResourceDir( const char *type,
00335                     const QString& filename) const
00336 {
00337 #ifndef NDEBUG
00338     if (filename.isEmpty()) {
00339       kdWarning() << "filename for type " << type << " in KStandardDirs::findResourceDir is not supposed to be empty!!" << endl;
00340       return QString::null;
00341     }
00342 #endif
00343 
00344     if (d && d->restrictionsActive && (strcmp(type, "data")==0))
00345        applyDataRestrictions(filename);
00346     QStringList candidates = resourceDirs(type);
00347     QString fullPath;
00348 
00349     for (QStringList::ConstIterator it = candidates.begin();
00350      it != candidates.end(); it++)
00351       if (exists(*it + filename))
00352     return *it;
00353 
00354 #ifndef NDEBUG
00355     if(false && type != "locale")
00356       kdDebug() << "KStdDirs::findResDir(): can't find \"" << filename << "\" in type \"" << type << "\"." << endl;
00357 #endif
00358 
00359     return QString::null;
00360 }
00361 
00362 bool KStandardDirs::exists(const QString &fullPath)
00363 {
00364     struct stat buff;
00365     if (access(QFile::encodeName(fullPath), R_OK) == 0 && stat( QFile::encodeName(fullPath), &buff ) == 0)
00366     if (fullPath.at(fullPath.length() - 1) != '/') {
00367         if (S_ISREG( buff.st_mode ))
00368         return true;
00369     } else
00370         if (S_ISDIR( buff.st_mode ))
00371         return true;
00372     return false;
00373 }
00374 
00375 static void lookupDirectory(const QString& path, const QString &relPart,
00376                 const QRegExp &regexp,
00377                 QStringList& list,
00378                 QStringList& relList,
00379                 bool recursive, bool unique)
00380 {
00381   QString pattern = regexp.pattern();
00382   if (recursive || pattern.contains('?') || pattern.contains('*'))
00383   {
00384     // We look for a set of files.
00385     DIR *dp = opendir( QFile::encodeName(path));
00386     if (!dp)
00387       return;
00388 
00389     assert(path.at(path.length() - 1) == '/');
00390 
00391     struct dirent *ep;
00392     struct stat buff;
00393 
00394     QString _dot(".");
00395     QString _dotdot("..");
00396 
00397     while( ( ep = readdir( dp ) ) != 0L )
00398     {
00399       QString fn( QFile::decodeName(ep->d_name));
00400       if (fn == _dot || fn == _dotdot || fn.at(fn.length() - 1).latin1() == '~')
00401     continue;
00402 
00403       if (!recursive && !regexp.exactMatch(fn))
00404     continue; // No match
00405 
00406       QString pathfn = path + fn;
00407       if ( stat( QFile::encodeName(pathfn), &buff ) != 0 ) {
00408     kdDebug() << "Error stat'ing " << pathfn << " : " << perror << endl;
00409     continue; // Couldn't stat (e.g. no read permissions)
00410       }
00411       if ( recursive ) {
00412     if ( S_ISDIR( buff.st_mode )) {
00413       lookupDirectory(pathfn + '/', relPart + fn + '/', regexp, list, relList, recursive, unique);
00414     }
00415         if (!regexp.exactMatch(fn))
00416       continue; // No match
00417       }
00418       if ( S_ISREG( buff.st_mode))
00419       {
00420         if (!unique || !relList.contains(relPart + fn))
00421         {
00422         list.append( pathfn );
00423         relList.append( relPart + fn );
00424         }
00425       }
00426     }
00427     closedir( dp );
00428   }
00429   else
00430   {
00431      // We look for a single file.
00432      QString fn = pattern;
00433      QString pathfn = path + fn;
00434      struct stat buff;
00435      if ( stat( QFile::encodeName(pathfn), &buff ) != 0 )
00436         return; // File not found
00437      if ( S_ISREG( buff.st_mode))
00438      {
00439        if (!unique || !relList.contains(relPart + fn))
00440        {
00441          list.append( pathfn );
00442          relList.append( relPart + fn );
00443        }
00444      }
00445   }
00446 }
00447 
00448 static void lookupPrefix(const QString& prefix, const QString& relpath,
00449                          const QString& relPart,
00450              const QRegExp &regexp,
00451              QStringList& list,
00452              QStringList& relList,
00453              bool recursive, bool unique)
00454 {
00455     if (relpath.isNull()) {
00456        lookupDirectory(prefix, relPart, regexp, list,
00457                relList, recursive, unique);
00458        return;
00459     }
00460     QString path;
00461     QString rest;
00462 
00463     if (relpath.length())
00464     {
00465        int slash = relpath.find('/');
00466        if (slash < 0)
00467        rest = relpath.left(relpath.length() - 1);
00468        else {
00469        path = relpath.left(slash);
00470        rest = relpath.mid(slash + 1);
00471        }
00472     }
00473 
00474     assert(prefix.at(prefix.length() - 1) == '/');
00475 
00476     struct stat buff;
00477 
00478     if (path.contains('*') || path.contains('?')) {
00479 
00480     QRegExp pathExp(path, true, true);
00481     DIR *dp = opendir( QFile::encodeName(prefix) );
00482     if (!dp) {
00483         return;
00484     }
00485 
00486     struct dirent *ep;
00487 
00488         QString _dot(".");
00489         QString _dotdot("..");
00490 
00491     while( ( ep = readdir( dp ) ) != 0L )
00492         {
00493         QString fn( QFile::decodeName(ep->d_name));
00494         if (fn == _dot || fn == _dotdot || fn.at(fn.length() - 1) == '~')
00495             continue;
00496 
00497         if (pathExp.search(fn) == -1)
00498             continue; // No match
00499         QString rfn = relPart+fn;
00500         fn = prefix + fn;
00501         if ( stat( QFile::encodeName(fn), &buff ) != 0 ) {
00502             kdDebug() << "Error statting " << fn << " : " << perror << endl;
00503             continue; // Couldn't stat (e.g. no permissions)
00504         }
00505         if ( S_ISDIR( buff.st_mode ))
00506             lookupPrefix(fn + '/', rest, rfn + '/', regexp, list, relList, recursive, unique);
00507         }
00508 
00509     closedir( dp );
00510     } else {
00511         // Don't stat, if the dir doesn't exist we will find out
00512         // when we try to open it.
00513         lookupPrefix(prefix + path + '/', rest,
00514                      relPart + path + '/', regexp, list,
00515                      relList, recursive, unique);
00516     }
00517 }
00518 
00519 QStringList
00520 KStandardDirs::findAllResources( const char *type,
00521                      const QString& filter,
00522                  bool recursive,
00523                      bool unique,
00524                                  QStringList &relList) const
00525 {
00526     QStringList list;
00527     QString filterPath;
00528     QString filterFile;
00529 
00530     if (filter.length())
00531     {
00532        int slash = filter.findRev('/');
00533        if (slash < 0)
00534        filterFile = filter;
00535        else {
00536        filterPath = filter.left(slash + 1);
00537        filterFile = filter.mid(slash + 1);
00538        }
00539     }
00540 
00541     checkConfig();
00542 
00543     QStringList candidates;
00544     if (filterPath.startsWith("/")) // absolute path
00545     {
00546         filterPath = filterPath.mid(1);
00547         candidates << "/";
00548     }
00549     else
00550     {
00551         if (d && d->restrictionsActive && (strcmp(type, "data")==0))
00552             applyDataRestrictions(filter);
00553         candidates = resourceDirs(type);
00554     }
00555     if (filterFile.isEmpty())
00556     filterFile = "*";
00557 
00558     QRegExp regExp(filterFile, true, true);
00559 
00560     for (QStringList::ConstIterator it = candidates.begin();
00561          it != candidates.end(); it++)
00562     {
00563         lookupPrefix(*it, filterPath, "", regExp, list,
00564                      relList, recursive, unique);
00565     }
00566 
00567     return list;
00568 }
00569 
00570 QStringList
00571 KStandardDirs::findAllResources( const char *type,
00572                      const QString& filter,
00573                  bool recursive,
00574                      bool unique) const
00575 {
00576     QStringList relList;
00577     return findAllResources(type, filter, recursive, unique, relList);
00578 }
00579 
00580 QString
00581 KStandardDirs::realPath(const QString &dirname)
00582 {
00583     char realpath_buffer[MAXPATHLEN + 1];
00584     memset(realpath_buffer, 0, MAXPATHLEN + 1);
00585 
00586     /* If the path contains symlinks, get the real name */
00587     if (realpath( QFile::encodeName(dirname).data(), realpath_buffer) != 0) {
00588         // succes, use result from realpath
00589         int len = strlen(realpath_buffer);
00590         realpath_buffer[len] = '/';
00591         realpath_buffer[len+1] = 0;
00592         return QFile::decodeName(realpath_buffer);
00593     }
00594 
00595     return dirname;
00596 }
00597 
00598 void KStandardDirs::createSpecialResource(const char *type)
00599 {
00600    char hostname[256];
00601    hostname[0] = 0;
00602    gethostname(hostname, 255);
00603    QString dir = QString("%1%2-%3").arg(localkdedir()).arg(type).arg(hostname);
00604    char link[1024];
00605    link[1023] = 0;
00606    int result = readlink(QFile::encodeName(dir).data(), link, 1023);
00607    if ((result == -1) && (errno == ENOENT))
00608    {
00609       QString srv = findExe(QString::fromLatin1("lnusertemp"), KDEDIR+QString::fromLatin1("/bin"));
00610       if (srv.isEmpty())
00611          srv = findExe(QString::fromLatin1("lnusertemp"));
00612       if (!srv.isEmpty())
00613       {
00614          system(QFile::encodeName(srv)+" "+type);
00615          result = readlink(QFile::encodeName(dir).data(), link, 1023);
00616       }
00617    }
00618    if (result > 0)
00619    {
00620       link[result] = 0;
00621       if (link[0] == '/')
00622          dir = QFile::decodeName(link);
00623       else
00624          dir = QDir::cleanDirPath(dir+QFile::decodeName(link));
00625    }
00626    addResourceDir(type, dir+'/');
00627 }
00628 
00629 QStringList KStandardDirs::resourceDirs(const char *type) const
00630 {
00631     QStringList *candidates = dircache.find(type);
00632 
00633     if (!candidates) { // filling cache
00634         if (strcmp(type, "socket") == 0)
00635            const_cast<KStandardDirs *>(this)->createSpecialResource(type);
00636         else if (strcmp(type, "tmp") == 0)
00637            const_cast<KStandardDirs *>(this)->createSpecialResource(type);
00638         else if (strcmp(type, "cache") == 0)
00639            const_cast<KStandardDirs *>(this)->createSpecialResource(type);
00640 
00641         QDir testdir;
00642 
00643         candidates = new QStringList();
00644         QStringList *dirs;
00645 
00646         bool restrictionActive = false;
00647         if (d && d->restrictionsActive)
00648         {
00649            if (d->dataRestrictionActive)
00650               restrictionActive = true;
00651            else if (d->restrictions["all"])
00652               restrictionActive = true;
00653            else if (d->restrictions[type])
00654               restrictionActive = true;
00655            d->dataRestrictionActive = false; // Reset
00656         }
00657 
00658         dirs = relatives.find(type);
00659         if (dirs)
00660         {
00661             bool local = true;
00662             const QStringList *prefixList = 0;
00663             if (strncmp(type, "xdgdata-", 8) == 0)
00664                 prefixList = &(d->xdgdata_prefixes);
00665             else if (strncmp(type, "xdgconf-", 8) == 0)
00666                 prefixList = &(d->xdgconf_prefixes);
00667             else
00668                 prefixList = &prefixes;
00669 
00670             for (QStringList::ConstIterator pit = prefixList->begin();
00671                  pit != prefixList->end();
00672                  pit++)
00673             {
00674                 for (QStringList::ConstIterator it = dirs->begin();
00675                      it != dirs->end(); ++it) {
00676                     QString path = realPath(*pit + *it);
00677                     testdir.setPath(path);
00678                     if (local && restrictionActive)
00679                        continue;
00680                     if ((local || testdir.exists()) && !candidates->contains(path))
00681                         candidates->append(path);
00682                 }
00683                 local = false;
00684             }
00685         }
00686         dirs = absolutes.find(type);
00687         if (dirs)
00688             for (QStringList::ConstIterator it = dirs->begin();
00689                  it != dirs->end(); ++it)
00690             {
00691                 testdir.setPath(*it);
00692                 if (testdir.exists())
00693                 {
00694                     QString filename = realPath(*it);
00695                     if (!candidates->contains(filename))
00696                         candidates->append(filename);
00697                 }
00698             }
00699         dircache.insert(type, candidates);
00700     }
00701 
00702 #if 0
00703     kdDebug() << "found dirs for resource " << type << ":" << endl;
00704     for (QStringList::ConstIterator pit = candidates->begin();
00705      pit != candidates->end();
00706      pit++)
00707     {
00708     fprintf(stderr, "%s\n", (*pit).latin1());
00709     }
00710 #endif
00711 
00712 
00713   return *candidates;
00714 }
00715 
00716 QStringList KStandardDirs::systemPaths( const QString& pstr )
00717 {
00718     QStringList tokens;
00719     QString p = pstr;
00720 
00721     if( p.isNull() ) 
00722     {
00723     p = getenv( "PATH" );
00724     }
00725 
00726     tokenize( tokens, p, ":\b" );
00727 
00728     QStringList exePaths;
00729 
00730     // split path using : or \b as delimiters
00731     for( unsigned i = 0; i < tokens.count(); i++ )
00732     {
00733     p = tokens[ i ];
00734 
00735         if ( p[ 0 ] == '~' )
00736         {
00737             int len = p.find( '/' );
00738             if ( len == -1 )
00739                 len = p.length();
00740             if ( len == 1 )
00741             {
00742                 p.replace( 0, 1, QDir::homeDirPath() );
00743             }
00744             else
00745             {
00746                 QString user = p.mid( 1, len - 1 );
00747                 struct passwd *dir = getpwnam( user.local8Bit().data() );
00748                 if ( dir && strlen( dir->pw_dir ) )
00749                     p.replace( 0, len, QString::fromLocal8Bit( dir->pw_dir ) );
00750             }
00751         }
00752 
00753     exePaths << p;
00754     }
00755 
00756     return exePaths;
00757 }
00758 
00759 
00760 QString KStandardDirs::findExe( const QString& appname,
00761                 const QString& pstr, bool ignore)
00762 {
00763     QFileInfo info;
00764 
00765     // absolute path ?
00766     if (appname.startsWith(QString::fromLatin1("/")))
00767     {
00768         info.setFile( appname );
00769         if( info.exists() && ( ignore || info.isExecutable() )
00770             && info.isFile() ) {
00771             return appname;
00772         }
00773         return QString::null;
00774     }
00775 
00776     QString p = QString("%1/%2").arg(__KDE_BINDIR).arg(appname);
00777     info.setFile( p );
00778     if( info.exists() && ( ignore || info.isExecutable() )
00779          && ( info.isFile() || info.isSymLink() )  ) {
00780          return p;
00781     }
00782 
00783     QStringList exePaths = systemPaths( pstr );
00784     for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); it++)
00785     {
00786     p = (*it) + "/";
00787     p += appname;
00788 
00789     // Check for executable in this tokenized path
00790     info.setFile( p );
00791 
00792     if( info.exists() && ( ignore || info.isExecutable() )
00793            && ( info.isFile() || info.isSymLink() )  ) {
00794         return p;
00795     }
00796     }
00797 
00798     // If we reach here, the executable wasn't found.
00799     // So return empty string.
00800 
00801     return QString::null;
00802 }
00803 
00804 int KStandardDirs::findAllExe( QStringList& list, const QString& appname,
00805             const QString& pstr, bool ignore )
00806 {
00807     QFileInfo info;
00808     QString p;
00809     list.clear();
00810 
00811     QStringList exePaths = systemPaths( pstr );
00812     for (QStringList::ConstIterator it = exePaths.begin(); it != exePaths.end(); it++)
00813     {
00814     p = (*it) + "/";
00815     p += appname;
00816 
00817     info.setFile( p );
00818 
00819     if( info.exists() && (ignore || info.isExecutable())
00820         && info.isFile() ) {
00821         list.append( p );
00822     }
00823     }
00824 
00825     return list.count();
00826 }
00827 
00828 static int tokenize( QStringList& tokens, const QString& str,
00829              const QString& delim )
00830 {
00831     int len = str.length();
00832     QString token = "";
00833 
00834     for( int index = 0; index < len; index++)
00835     {
00836     if ( delim.find( str[ index ] ) >= 0 )
00837     {
00838         tokens.append( token );
00839         token = "";
00840     }
00841     else
00842     {
00843         token += str[ index ];
00844     }
00845     }
00846     if ( token.length() > 0 )
00847     {
00848     tokens.append( token );
00849     }
00850 
00851     return tokens.count();
00852 }
00853 
00854 QString KStandardDirs::kde_default(const char *type) {
00855     if (!strcmp(type, "data"))
00856     return "share/apps/";
00857     if (!strcmp(type, "html"))
00858     return "share/doc/HTML/";
00859     if (!strcmp(type, "icon"))
00860     return "share/icons/";
00861     if (!strcmp(type, "config"))
00862     return "share/config/";
00863     if (!strcmp(type, "pixmap"))
00864     return "share/pixmaps/";
00865     if (!strcmp(type, "apps"))
00866     return "share/applnk/";
00867     if (!strcmp(type, "sound"))
00868     return "share/sounds/";
00869     if (!strcmp(type, "locale"))
00870     return "share/locale/";
00871     if (!strcmp(type, "services"))
00872     return "share/services/";
00873     if (!strcmp(type, "servicetypes"))
00874     return "share/servicetypes/";
00875     if (!strcmp(type, "mime"))
00876     return "share/mimelnk/";
00877     if (!strcmp(type, "cgi"))
00878     return "cgi-bin/";
00879     if (!strcmp(type, "wallpaper"))
00880     return "share/wallpapers/";
00881     if (!strcmp(type, "templates"))
00882     return "share/templates/";
00883     if (!strcmp(type, "exe"))
00884     return "bin/";
00885     if (!strcmp(type, "lib"))
00886     return LIBDIR_NAME "/";
00887     if (!strcmp(type, "module"))
00888     return LIBDIR_NAME "/kde3/";
00889     if (!strcmp(type, "qtplugins"))
00890         return LIBDIR_NAME "/kde3/plugins/";
00891     if (!strcmp(type, "xdgdata-apps"))
00892         return "applications/";
00893     if (!strcmp(type, "xdgdata-dirs"))
00894         return "desktop-directories/";
00895     if (!strcmp(type, "xdgconf-menu"))
00896         return "menus/";
00897     if (!strcmp(type, "kcfg"))
00898     return "share/config.kcfg";
00899     qFatal("unknown resource type %s", type);
00900     return QString::null;
00901 }
00902 
00903 QString KStandardDirs::saveLocation(const char *type,
00904                     const QString& suffix,
00905                     bool create) const
00906 {
00907     checkConfig();
00908 
00909     QString *pPath = savelocations.find(type);
00910     if (!pPath)
00911     {
00912        QStringList *dirs = relatives.find(type);
00913        if (!dirs && (
00914                      (strcmp(type, "socket") == 0) ||
00915                      (strcmp(type, "tmp") == 0) ||
00916                      (strcmp(type, "cache") == 0) ))
00917        {
00918           (void) resourceDirs(type); // Generate socket|tmp|cache resource.
00919           dirs = relatives.find(type); // Search again.
00920        }
00921        if (dirs)
00922        {
00923           // Check for existence of typed directory + suffix
00924           if (strncmp(type, "xdgdata-", 8) == 0)
00925              pPath = new QString(realPath(localxdgdatadir() + dirs->last()));
00926           else if (strncmp(type, "xdgconf-", 8) == 0)
00927              pPath = new QString(realPath(localxdgconfdir() + dirs->last()));
00928           else
00929              pPath = new QString(realPath(localkdedir() + dirs->last()));
00930        }
00931        else {
00932           dirs = absolutes.find(type);
00933           if (!dirs)
00934              qFatal("KStandardDirs: The resource type %s is not registered", type);
00935           pPath = new QString(realPath(dirs->last()));
00936        }
00937 
00938        savelocations.insert(type, pPath);
00939     }
00940     QString fullPath = *pPath + suffix;
00941 
00942     struct stat st;
00943     if (stat(QFile::encodeName(fullPath), &st) != 0 || !(S_ISDIR(st.st_mode))) {
00944     if(!create) {
00945 #ifndef NDEBUG
00946         qDebug("save location %s doesn't exist", fullPath.latin1());
00947 #endif
00948         return fullPath;
00949     }
00950     if(!makeDir(fullPath, 0700)) {
00951             qWarning("failed to create %s", fullPath.latin1());
00952         return fullPath;
00953     }
00954         dircache.remove(type);
00955     }
00956     return fullPath;
00957 }
00958 
00959 QString KStandardDirs::relativeLocation(const char *type, const QString &absPath)
00960 {
00961     QString fullPath = absPath;
00962     int i = absPath.findRev('/');
00963     if (i != -1)
00964     {
00965        fullPath = realPath(absPath.left(i+1))+absPath.mid(i+1); // Normalize
00966     }
00967 
00968     QStringList candidates = resourceDirs(type);
00969 
00970     for (QStringList::ConstIterator it = candidates.begin();
00971      it != candidates.end(); it++)
00972       if (fullPath.startsWith(*it))
00973       {
00974     return fullPath.mid((*it).length());
00975       }
00976 
00977     return absPath;
00978 }
00979 
00980 
00981 bool KStandardDirs::makeDir(const QString& dir, int mode)
00982 {
00983     // we want an absolute path
00984     if (dir.at(0) != '/')
00985         return false;
00986 
00987     QString target = dir;
00988     uint len = target.length();
00989 
00990     // append trailing slash if missing
00991     if (dir.at(len - 1) != '/')
00992         target += '/';
00993 
00994     QString base("");
00995     uint i = 1;
00996 
00997     while( i < len )
00998     {
00999         struct stat st;
01000         int pos = target.find('/', i);
01001         base += target.mid(i - 1, pos - i + 1);
01002         QCString baseEncoded = QFile::encodeName(base);
01003         // bail out if we encountered a problem
01004         if (stat(baseEncoded, &st) != 0)
01005         {
01006           // Directory does not exist....
01007           // Or maybe a dangling symlink ?
01008           if (lstat(baseEncoded, &st) == 0)
01009               (void)unlink(baseEncoded); // try removing
01010 
01011       if ( mkdir(baseEncoded, (mode_t) mode) != 0) {
01012         perror("trying to create local folder");
01013         return false; // Couldn't create it :-(
01014       }
01015         }
01016         i = pos + 1;
01017     }
01018     return true;
01019 }
01020 
01021 static QString readEnvPath(const char *env)
01022 {
01023    QCString c_path = getenv(env);
01024    if (c_path.isEmpty())
01025       return QString::null;
01026    return QFile::decodeName(c_path);
01027 }
01028 
01029 void KStandardDirs::addKDEDefaults()
01030 {
01031     QStringList kdedirList;
01032 
01033     // begin KDEDIRS
01034     QString kdedirs = readEnvPath("KDEDIRS");
01035     if (!kdedirs.isEmpty())
01036     {
01037     tokenize(kdedirList, kdedirs, ":");
01038     }
01039     else
01040     {
01041     QString kdedir = readEnvPath("KDEDIR");
01042     if (!kdedir.isEmpty())
01043         {
01044            kdedir = KShell::tildeExpand(kdedir);
01045        kdedirList.append(kdedir);
01046         }
01047     }
01048     kdedirList.append(KDEDIR);
01049 
01050 #ifdef __KDE_EXECPREFIX
01051     QString execPrefix(__KDE_EXECPREFIX);
01052     if (execPrefix!="NONE")
01053        kdedirList.append(execPrefix);
01054 #endif
01055 
01056     // We treat root differently to prevent a "su" shell messing up the
01057     // file permissions in the user's home directory.
01058     QString localKdeDir = readEnvPath(getuid() ? "KDEHOME" : "KDEROOTHOME");
01059     if (!localKdeDir.isEmpty())
01060     {
01061        if (localKdeDir[localKdeDir.length()-1] != '/')
01062           localKdeDir += '/';
01063     }
01064     else
01065     {
01066        localKdeDir =  QDir::homeDirPath() + "/.kde/";
01067     }
01068 
01069     if (localKdeDir != "-/")
01070     {
01071         localKdeDir = KShell::tildeExpand(localKdeDir);
01072         addPrefix(localKdeDir);
01073     }
01074 
01075     for (QStringList::ConstIterator it = kdedirList.begin();
01076      it != kdedirList.end(); it++)
01077     {
01078         QString dir = KShell::tildeExpand(*it);
01079     addPrefix(dir);
01080     }
01081     // end KDEDIRS
01082 
01083     // begin XDG_CONFIG_XXX
01084     QStringList xdgdirList;
01085     QString xdgdirs = readEnvPath("XDG_CONFIG_DIRS");
01086     if (!xdgdirs.isEmpty())
01087     {
01088     tokenize(xdgdirList, xdgdirs, ":");
01089     }
01090     else
01091     {
01092     xdgdirList.clear();
01093         xdgdirList.append("/etc/xdg");
01094         xdgdirList.append(KDESYSCONFDIR "/xdg");
01095     }
01096 
01097     QString localXdgDir = readEnvPath("XDG_CONFIG_HOME");
01098     if (!localXdgDir.isEmpty())
01099     {
01100        if (localXdgDir[localXdgDir.length()-1] != '/')
01101           localXdgDir += '/';
01102     }
01103     else
01104     {
01105        localXdgDir =  QDir::homeDirPath() + "/.config/";
01106     }
01107 
01108     localXdgDir = KShell::tildeExpand(localXdgDir);
01109     addXdgConfigPrefix(localXdgDir);
01110 
01111     for (QStringList::ConstIterator it = xdgdirList.begin();
01112      it != xdgdirList.end(); it++)
01113     {
01114         QString dir = KShell::tildeExpand(*it);
01115     addXdgConfigPrefix(dir);
01116     }
01117     // end XDG_CONFIG_XXX
01118 
01119     // begin XDG_DATA_XXX
01120     xdgdirs = readEnvPath("XDG_DATA_DIRS");
01121     if (!xdgdirs.isEmpty())
01122     {
01123     tokenize(xdgdirList, xdgdirs, ":");
01124     }
01125     else
01126     {
01127     xdgdirList.clear();
01128         for (QStringList::ConstIterator it = kdedirList.begin();
01129            it != kdedirList.end(); it++)
01130         {
01131            QString dir = *it;
01132            if (dir[dir.length()-1] != '/')
01133              dir += '/';
01134            xdgdirList.append(dir+"share/");
01135         }
01136 
01137         xdgdirList.append("/usr/local/share/");
01138         xdgdirList.append("/usr/share/");
01139     }
01140 
01141     localXdgDir = readEnvPath("XDG_DATA_HOME");
01142     if (!localXdgDir.isEmpty())
01143     {
01144        if (localXdgDir[localXdgDir.length()-1] != '/')
01145           localXdgDir += '/';
01146     }
01147     else
01148     {
01149        localXdgDir = QDir::homeDirPath() + "/.local/share/";
01150     }
01151 
01152     localXdgDir = KShell::tildeExpand(localXdgDir);
01153     addXdgDataPrefix(localXdgDir);
01154 
01155     for (QStringList::ConstIterator it = xdgdirList.begin();
01156      it != xdgdirList.end(); it++)
01157     {
01158         QString dir = KShell::tildeExpand(*it);
01159     addXdgDataPrefix(dir);
01160     }
01161     // end XDG_DATA_XXX
01162 
01163 
01164     uint index = 0;
01165     while (types[index] != 0) {
01166     addResourceType(types[index], kde_default(types[index]));
01167     index++;
01168     }
01169 
01170     addResourceDir("home", QDir::homeDirPath());
01171 }
01172 
01173 void KStandardDirs::checkConfig() const
01174 {
01175     if (!addedCustoms && KGlobal::_instance && KGlobal::_instance->_config)
01176         const_cast<KStandardDirs*>(this)->addCustomized(KGlobal::_instance->_config);
01177 }
01178 
01179 bool KStandardDirs::addCustomized(KConfig *config)
01180 {
01181     if (addedCustoms) // there are already customized entries
01182         return false; // we just quite and hope they are the right ones
01183 
01184     // save the numbers of config directories. If this changes,
01185     // we will return true to give KConfig a chance to reparse
01186     uint configdirs = resourceDirs("config").count();
01187 
01188     // reading the prefixes in
01189     QString oldGroup = config->group();
01190     config->setGroup("Directories");
01191 
01192     QStringList list;
01193     QStringList::ConstIterator it;
01194     list = config->readListEntry("prefixes");
01195     for (it = list.begin(); it != list.end(); it++)
01196     addPrefix(*it);
01197 
01198     // iterating over all entries in the group Directories
01199     // to find entries that start with dir_$type
01200     QMap<QString, QString> entries = config->entryMap("Directories");
01201 
01202     QMap<QString, QString>::ConstIterator it2;
01203     for (it2 = entries.begin(); it2 != entries.end(); it2++)
01204     {
01205     QString key = it2.key();
01206     if (key.left(4) == "dir_") {
01207         // generate directory list, there may be more than 1.
01208         QStringList dirs = QStringList::split(',',
01209                           *it2);
01210         QStringList::Iterator sIt(dirs.begin());
01211         QString resType = key.mid(4, key.length());
01212         for (; sIt != dirs.end(); ++sIt) {
01213         addResourceDir(resType.latin1(), *sIt);
01214         }
01215     }
01216     }
01217 
01218     // Process KIOSK restrictions.
01219     config->setGroup("KDE Resource Restrictions");
01220     entries = config->entryMap("KDE Resource Restrictions");
01221     for (it2 = entries.begin(); it2 != entries.end(); it2++)
01222     {
01223     QString key = it2.key();
01224         if (!config->readBoolEntry(key, true))
01225         {
01226            d->restrictionsActive = true;
01227            d->restrictions.insert(key.latin1(), &d->restrictionsActive); // Anything will do
01228            dircache.remove(key.latin1());
01229         }
01230     }
01231 
01232     // save it for future calls - that will return
01233     addedCustoms = true;
01234     config->setGroup(oldGroup);
01235 
01236     // return true if the number of config dirs changed
01237     return (resourceDirs("config").count() != configdirs);
01238 }
01239 
01240 QString KStandardDirs::localkdedir() const
01241 {
01242     // Return the prefix to use for saving
01243     return prefixes.first();
01244 }
01245 
01246 QString KStandardDirs::localxdgdatadir() const
01247 {
01248     // Return the prefix to use for saving
01249     return d->xdgdata_prefixes.first();
01250 }
01251 
01252 QString KStandardDirs::localxdgconfdir() const
01253 {
01254     // Return the prefix to use for saving
01255     return d->xdgconf_prefixes.first();
01256 }
01257 
01258 // just to make code more readable without macros
01259 QString locate( const char *type,
01260         const QString& filename, const KInstance* inst )
01261 {
01262     return inst->dirs()->findResource(type, filename);
01263 }
01264 
01265 QString locateLocal( const char *type,
01266                  const QString& filename, const KInstance* inst )
01267 {
01268     return locateLocal(type, filename, true, inst);
01269 }
01270 
01271 QString locateLocal( const char *type,
01272                  const QString& filename, bool createDir, const KInstance* inst )
01273 {
01274     // try to find slashes. If there are some, we have to
01275     // create the subdir first
01276     int slash = filename.findRev('/')+1;
01277     if (!slash) // only one filename
01278     return inst->dirs()->saveLocation(type, QString::null, createDir) + filename;
01279 
01280     // split path from filename
01281     QString dir = filename.left(slash);
01282     QString file = filename.mid(slash);
01283     return inst->dirs()->saveLocation(type, dir, createDir) + file;
01284 }
KDE Logo
This file is part of the documentation for kdecore Library Version 3.2.0.
Documentation copyright © 1996-2004 the KDE developers.
Generated on Wed Feb 4 12:33:51 2004 by doxygen 1.2.18 written by Dimitri van Heesch, © 1997-2003