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