kdecore Library API Documentation

kapplication.cpp

00001 /* This file is part of the KDE libraries
00002     Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
00003     Copyright (C) 1998, 1999, 2000 KDE Team
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 as published by the Free Software Foundation; either
00008     version 2 of the License, or (at your option) any later version.
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 // $Id: kapplication.cpp,v 1.670.2.1 2004/08/17 13:44:00 waba Exp $
00022 
00023 #include "config.h"
00024 
00025 #undef QT_NO_TRANSLATION
00026 #include <qtranslator.h>
00027 #define QT_NO_TRANSLATION
00028 #include <qdir.h>
00029 #include <qptrcollection.h>
00030 #include <qwidgetlist.h>
00031 #include <qstrlist.h>
00032 #include <qfile.h>
00033 #include <qmessagebox.h>
00034 #include <qtextstream.h>
00035 #include <qregexp.h>
00036 #include <qlineedit.h>
00037 #include <qtextedit.h>
00038 #include <qsessionmanager.h>
00039 #include <qptrlist.h>
00040 #include <qtimer.h>
00041 #include <qstylesheet.h>
00042 #include <qpixmapcache.h>
00043 #include <qtooltip.h>
00044 #include <qstylefactory.h>
00045 #include <qmetaobject.h>
00046 #include <qimage.h>
00047 #ifndef QT_NO_SQL
00048 #include <qsqlpropertymap.h>
00049 #endif
00050 
00051 #undef QT_NO_TRANSLATION
00052 #include "kapplication.h"
00053 #define QT_NO_TRANSLATION
00054 #include <kglobal.h>
00055 #include <kstandarddirs.h>
00056 #include <kdebug.h>
00057 #include <klocale.h>
00058 #include <kstyle.h>
00059 #include <kiconloader.h>
00060 #include <kclipboard.h>
00061 #include <kconfig.h>
00062 #include <ksimpleconfig.h>
00063 #include <kcmdlineargs.h>
00064 #include <kaboutdata.h>
00065 #include <kglobalsettings.h>
00066 #include <kcrash.h>
00067 #include <kdatastream.h>
00068 #include <klibloader.h>
00069 #include <kmimesourcefactory.h>
00070 #include <kstdaccel.h>
00071 #include <kaccel.h>
00072 #include "kcheckaccelerators.h"
00073 #include <qptrdict.h>
00074 #include <kmacroexpander.h>
00075 #include <kshell.h>
00076 #include <kprotocolinfo.h>
00077 
00078 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00079 #include <kstartupinfo.h>
00080 #endif
00081 
00082 #include <dcopclient.h>
00083 #include <dcopref.h>
00084 
00085 #include <sys/types.h>
00086 #ifdef HAVE_SYS_STAT_H
00087 #include <sys/stat.h>
00088 #endif
00089 #include <sys/wait.h>
00090 
00091 #include "kwin.h"
00092 
00093 #include <fcntl.h>
00094 #include <stdlib.h> // getenv(), srand(), rand()
00095 #include <signal.h>
00096 #include <unistd.h>
00097 #include <time.h>
00098 #include <sys/time.h>
00099 #include <errno.h>
00100 #include <string.h>
00101 #include <netdb.h>
00102 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00103 //#ifndef Q_WS_QWS //FIXME(E): NetWM should talk to QWS...
00104 #include <netwm.h>
00105 #endif
00106 
00107 #include "kprocctrl.h"
00108 
00109 #ifdef HAVE_PATHS_H
00110 #include <paths.h>
00111 #endif
00112 
00113 //#if defined Q_WS_X11 && ! defined K_WS_QTONLY
00114 #ifdef Q_WS_X11
00115 #include <X11/Xlib.h> // schrode
00116 #include <X11/Xutil.h> // schrode
00117 #include <X11/Xatom.h> // schrode
00118 #include <X11/SM/SMlib.h> // schrode
00119 #include <fixx11h.h> // schrode
00120 #endif
00121 #include <KDE-ICE/ICElib.h>
00122 
00123 #ifdef Q_WS_X11
00124 #define DISPLAY "DISPLAY"
00125 #elif defined(Q_WS_QWS)
00126 #define DISPLAY "QWS_DISPLAY"
00127 #endif
00128 
00129 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00130 #include <kipc.h>
00131 #endif
00132 
00133 #include "kappdcopiface.h"
00134 
00135 bool kde_have_kipc = true; // magic hook to disable kipc in kdm
00136 bool kde_kiosk_exception = false; // flag to disable kiosk restrictions
00137 bool kde_kiosk_admin = false;
00138 
00139 KApplication* KApplication::KApp = 0L;
00140 bool KApplication::loadedByKdeinit = false;
00141 DCOPClient *KApplication::s_DCOPClient = 0L;
00142 bool KApplication::s_dcopClientNeedsPostInit = false;
00143 
00144 static Atom atom_DesktopWindow;
00145 static Atom atom_NetSupported;
00146 extern Time qt_x_time;
00147 extern Time qt_x_user_time;
00148 static Atom kde_xdnd_drop;
00149 
00150 // duplicated from patched Qt, so that there won't be unresolved symbols if Qt gets
00151 // replaced by unpatched one
00152 bool qt_qclipboard_bailout_hack = false;
00153 
00154 template class QPtrList<KSessionManaged>;
00155 
00156 #ifdef Q_WS_X11
00157 extern "C" {
00158 static int kde_xio_errhandler( Display * dpy )
00159 {
00160   return kapp->xioErrhandler( dpy );
00161 }
00162 
00163 static int kde_x_errhandler( Display *dpy, XErrorEvent *err )
00164 {
00165   return kapp->xErrhandler( dpy, err );
00166 }
00167 
00168 }
00169 #endif
00170 
00171 extern "C" {
00172 static void kde_ice_ioerrorhandler( IceConn conn )
00173 {
00174     if(kapp)
00175         kapp->iceIOErrorHandler( conn );
00176     // else ignore the error for now
00177 }
00178 }
00179 
00180 /*
00181   Private data to make keeping binary compatibility easier
00182  */
00183 class KApplicationPrivate
00184 {
00185 public:
00186   KApplicationPrivate()
00187     :   actionRestrictions( false ),
00188     refCount( 1 ),
00189     oldIceIOErrorHandler( 0 ),
00190     checkAccelerators( 0 ),
00191     overrideStyle( QString::null ),
00192     startup_id( "0" ),
00193         app_started_timer( NULL ),
00194     m_KAppDCOPInterface( 0L ),
00195     session_save( false ),
00196         oldXErrorHandler( NULL ),
00197         oldXIOErrorHandler( NULL )
00198   {
00199   }
00200 
00201   ~KApplicationPrivate()
00202   {}
00203 
00204 
00205   bool actionRestrictions : 1;
00206   bool guiEnabled : 1;
00213   int refCount;
00214   IceIOErrorHandler oldIceIOErrorHandler;
00215   KCheckAccelerators* checkAccelerators;
00216   QString overrideStyle;
00217   QString geometry_arg;
00218   QCString startup_id;
00219   QTimer* app_started_timer;
00220   KAppDCOPInterface *m_KAppDCOPInterface;
00221   bool session_save;
00222   int (*oldXErrorHandler)(Display*,XErrorEvent*);
00223   int (*oldXIOErrorHandler)(Display*);
00224 
00225   class URLActionRule
00226   {
00227   public:
00228 #define checkExactMatch(s, b) \
00229         if (s.isEmpty()) b = true; \
00230         else if (s[s.length()-1] == '!') \
00231         { b = false; s.truncate(s.length()-1); } \
00232         else b = true;
00233 #define checkStartWildCard(s, b) \
00234         if (s.isEmpty()) b = true; \
00235         else if (s[0] == '*') \
00236         { b = true; s = s.mid(1); } \
00237         else b = false;
00238 #define checkEqual(s, b) \
00239         b = (s == "=");
00240 
00241      URLActionRule(const QString &act,
00242                    const QString &bProt, const QString &bHost, const QString &bPath,
00243                    const QString &dProt, const QString &dHost, const QString &dPath,
00244                    bool perm)
00245                    : action(act),
00246                      baseProt(bProt), baseHost(bHost), basePath(bPath),
00247                      destProt(dProt), destHost(dHost), destPath(dPath),
00248                      permission(perm)
00249                    {
00250                       checkExactMatch(baseProt, baseProtWildCard);
00251                       checkStartWildCard(baseHost, baseHostWildCard);
00252                       checkExactMatch(basePath, basePathWildCard);
00253                       checkExactMatch(destProt, destProtWildCard);
00254                       checkStartWildCard(destHost, destHostWildCard);
00255                       checkExactMatch(destPath, destPathWildCard);
00256                       checkEqual(destProt, destProtEqual);
00257                       checkEqual(destHost, destHostEqual);
00258                    }
00259 
00260      bool baseMatch(const KURL &url, const QString &protClass)
00261      {
00262         if (baseProtWildCard)
00263         {
00264            if ( !baseProt.isEmpty() && !url.protocol().startsWith(baseProt) &&
00265                 (protClass.isEmpty() || (protClass != baseProt)) )
00266               return false;
00267         }
00268         else
00269         {
00270            if ( (url.protocol() != baseProt) &&
00271                 (protClass.isEmpty() || (protClass != baseProt)) )
00272               return false;
00273         }
00274         if (baseHostWildCard)
00275         {
00276            if (!baseHost.isEmpty() && !url.host().endsWith(baseHost))
00277               return false;
00278         }
00279         else
00280         {
00281            if (url.host() != baseHost)
00282               return false;
00283         }
00284         if (basePathWildCard)
00285         {
00286            if (!basePath.isEmpty() && !url.path().startsWith(basePath))
00287               return false;
00288         }
00289         else
00290         {
00291            if (url.path() != basePath)
00292               return false;
00293         }
00294         return true;
00295      }
00296 
00297      bool destMatch(const KURL &url, const QString &protClass, const KURL &base, const QString &baseClass)
00298      {
00299         if (destProtEqual)
00300         {
00301            if ( (url.protocol() != base.protocol()) &&
00302                 (protClass.isEmpty() || baseClass.isEmpty() || protClass != baseClass) )
00303               return false;
00304         }
00305         else if (destProtWildCard)
00306         {
00307            if ( !destProt.isEmpty() && !url.protocol().startsWith(destProt) &&
00308                 (protClass.isEmpty() || (protClass != destProt)) )
00309               return false;
00310         }
00311         else
00312         {
00313            if ( (url.protocol() != destProt) &&
00314                 (protClass.isEmpty() || (protClass != destProt)) )
00315               return false;
00316         }
00317         if (destHostWildCard)
00318         {
00319            if (!destHost.isEmpty() && !url.host().endsWith(destHost))
00320               return false;
00321         }
00322         else if (destHostEqual)
00323         {
00324            if (url.host() != base.host())
00325               return false;
00326         }
00327         else
00328         {
00329            if (url.host() != destHost)
00330               return false;
00331         }
00332         if (destPathWildCard)
00333         {
00334            if (!destPath.isEmpty() && !url.path().startsWith(destPath))
00335               return false;
00336         }
00337         else
00338         {
00339            if (url.path() != destPath)
00340               return false;
00341         }
00342         return true;
00343      }
00344 
00345      QString action;
00346      QString baseProt;
00347      QString baseHost;
00348      QString basePath;
00349      QString destProt;
00350      QString destHost;
00351      QString destPath;
00352      bool baseProtWildCard : 1;
00353      bool baseHostWildCard : 1;
00354      bool basePathWildCard : 1;
00355      bool destProtWildCard : 1;
00356      bool destHostWildCard : 1;
00357      bool destPathWildCard : 1;
00358      bool destProtEqual    : 1;
00359      bool destHostEqual    : 1;
00360      bool permission;
00361   };
00362   QPtrList<URLActionRule> urlActionRestrictions;
00363 
00364     QString sessionKey;
00365     QString pSessionConfigFile;
00366 };
00367 
00368 
00369 static QPtrList<QWidget>*x11Filter = 0;
00370 static bool autoDcopRegistration = true;
00371 
00372 void KApplication::installX11EventFilter( QWidget* filter )
00373 {
00374     if ( !filter )
00375         return;
00376     if (!x11Filter)
00377         x11Filter = new QPtrList<QWidget>;
00378     connect ( filter, SIGNAL( destroyed() ), this, SLOT( x11FilterDestroyed() ) );
00379     x11Filter->append( filter );
00380 }
00381 
00382 void KApplication::x11FilterDestroyed()
00383 {
00384     removeX11EventFilter( static_cast< const QWidget* >( sender()));
00385 }
00386 
00387 void KApplication::removeX11EventFilter( const QWidget* filter )
00388 {
00389     if ( !x11Filter || !filter )
00390         return;
00391     x11Filter->removeRef( filter );
00392     if ( x11Filter->isEmpty() ) {
00393         delete x11Filter;
00394         x11Filter = 0;
00395     }
00396 }
00397 
00398 // FIXME: remove this when we've get a better method of
00399 // customizing accelerator handling -- hopefully in Qt.
00400 // For now, this is set whenever an accelerator is overridden
00401 // in KAccelEventHandler so that the AccelOverride isn't sent twice. -- ellis, 19/10/02
00402 extern bool kde_g_bKillAccelOverride;
00403 
00404 bool KApplication::notify(QObject *receiver, QEvent *event)
00405 {
00406     QEvent::Type t = event->type();
00407     if (kde_g_bKillAccelOverride)
00408     {
00409        kde_g_bKillAccelOverride = false;
00410        // Indicate that the accelerator has been overridden.
00411        if (t == QEvent::AccelOverride)
00412        {
00413           static_cast<QKeyEvent *>(event)->accept();
00414           return true;
00415        }
00416        else
00417           kdWarning(125) << "kde_g_bKillAccelOverride set, but received an event other than AccelOverride." << endl;
00418     }
00419 
00420     if ((t == QEvent::AccelOverride) || (t == QEvent::KeyPress))
00421     {
00422        static const KShortcut& _selectAll = KStdAccel::selectAll();
00423        QLineEdit *edit = ::qt_cast<QLineEdit *>(receiver);
00424        if (edit)
00425        {
00426           // We have a keypress for a lineedit...
00427           QKeyEvent *kevent = static_cast<QKeyEvent *>(event);
00428           KKey key(kevent);
00429           if (_selectAll.contains(key))
00430           {
00431              if (t == QEvent::KeyPress)
00432              {
00433                 edit->selectAll();
00434                 return true;
00435              }
00436              else
00437              {
00438                 kevent->accept();
00439              }
00440           }
00441           // Ctrl-U deletes from start of line.
00442           if (key == KKey(Qt::CTRL + Qt::Key_U))
00443           {
00444              if (t == QEvent::KeyPress)
00445              {
00446                 if (!edit->isReadOnly())
00447                 {
00448                    QString t(edit->text());
00449                    t = t.mid(edit->cursorPosition());
00450                    edit->validateAndSet(t, 0, 0, 0);
00451                 }
00452                 return true;
00453              }
00454              else
00455              {
00456                 kevent->accept();
00457              }
00458 
00459           }
00460        }
00461        QTextEdit *medit = ::qt_cast<QTextEdit *>(receiver);
00462        if (medit)
00463        {
00464           // We have a keypress for a multilineedit...
00465           QKeyEvent *kevent = static_cast<QKeyEvent *>(event);
00466           if (_selectAll.contains(KKey(kevent)))
00467           {
00468              if (t == QEvent::KeyPress)
00469              {
00470                 medit->selectAll();
00471                 return true;
00472              }
00473              else
00474              {
00475                 kevent->accept();
00476              }
00477           }
00478        }
00479     }
00480     if( t == QEvent::Show && receiver->isWidgetType())
00481     {
00482     QWidget* w = static_cast< QWidget* >( receiver );
00483         if( w->isTopLevel() && !startupId().isEmpty()) // TODO better done using window group leader?
00484             KStartupInfo::setWindowStartupId( w->winId(), startupId());
00485         if( w->isTopLevel() && !w->testWFlags( WX11BypassWM ) && !w->isPopup() && !event->spontaneous())
00486         {
00487             if( d->app_started_timer == NULL )
00488             {
00489                 d->app_started_timer = new QTimer( this );
00490                 connect( d->app_started_timer, SIGNAL( timeout()), SLOT( checkAppStartedSlot()));
00491             }
00492             if( !d->app_started_timer->isActive())
00493                 d->app_started_timer->start( 0, true );
00494         }
00495     }
00496     return QApplication::notify(receiver, event);
00497 }
00498 
00499 void KApplication::checkAppStartedSlot()
00500 {
00501     KStartupInfo::handleAutoAppStartedSending();
00502 }
00503 
00504 // the help class for session management communication
00505 static QPtrList<KSessionManaged>* sessionClients()
00506 {
00507     static QPtrList<KSessionManaged>* session_clients = 0L;
00508     if ( !session_clients )
00509         session_clients = new QPtrList<KSessionManaged>;
00510     return session_clients;
00511 }
00512 
00513 /*
00514   Auxiliary function to calculate a a session config name used for the
00515   instance specific config object.
00516   Syntax:  "session/<appname>_<sessionId>"
00517  */
00518 QString KApplication::sessionConfigName() const
00519 {
00520 #if QT_VERSION < 0x030100
00521     return QString("session/%1_%2_%3").arg(name()).arg(sessionId()).arg(d->sessionKey);
00522 #else
00523     QString sessKey = sessionKey();
00524     if ( sessKey.isEmpty() && !d->sessionKey.isEmpty() )
00525         sessKey = d->sessionKey;
00526     return QString("session/%1_%2_%3").arg(name()).arg(sessionId()).arg(sessKey);
00527 #endif
00528 }
00529 
00530 #ifndef Q_WS_QWS
00531 static SmcConn mySmcConnection = 0;
00532 static SmcConn tmpSmcConnection = 0;
00533 #else
00534 // FIXME(E): Implement for Qt Embedded
00535 // Possibly "steal" XFree86's libSM?
00536 #endif
00537 static QTime* smModificationTime = 0;
00538 
00539 KApplication::KApplication( int& argc, char** argv, const QCString& rAppName,
00540                             bool allowStyles, bool GUIenabled ) :
00541   QApplication( argc, argv, GUIenabled ), KInstance(rAppName),
00542 #ifdef Q_WS_X11
00543   display(0L),
00544 #endif
00545   d (new KApplicationPrivate())
00546 {
00547     read_app_startup_id();
00548     if (!GUIenabled)
00549        allowStyles = false;
00550     useStyles = allowStyles;
00551     Q_ASSERT (!rAppName.isEmpty());
00552     setName(rAppName);
00553 
00554     installSigpipeHandler();
00555     KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
00556     parseCommandLine( );
00557     init(GUIenabled);
00558     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00559 }
00560 
00561 KApplication::KApplication( bool allowStyles, bool GUIenabled ) :
00562   QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00563                 GUIenabled ),
00564   KInstance( KCmdLineArgs::about),
00565 #ifdef Q_WS_X11
00566   display(0L),
00567 #endif
00568   d (new KApplicationPrivate)
00569 {
00570     read_app_startup_id();
00571     if (!GUIenabled)
00572        allowStyles = false;
00573     useStyles = allowStyles;
00574     setName( instanceName() );
00575 
00576     installSigpipeHandler();
00577     parseCommandLine( );
00578     init(GUIenabled);
00579     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00580 }
00581 
00582 #ifdef Q_WS_X11
00583 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
00584                     bool allowStyles ) :
00585   QApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00586                 visual, colormap ),
00587   KInstance( KCmdLineArgs::about), display(0L), d (new KApplicationPrivate)
00588 {
00589     read_app_startup_id();
00590     useStyles = allowStyles;
00591     setName( instanceName() );
00592     installSigpipeHandler();
00593     parseCommandLine( );
00594     init( true );
00595     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00596 }
00597 
00598 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
00599                     bool allowStyles, KInstance * _instance ) :
00600   QApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00601                 visual, colormap ),
00602   KInstance( _instance ), display(0L), d (new KApplicationPrivate)
00603 {
00604     read_app_startup_id();
00605     useStyles = allowStyles;
00606     setName( instanceName() );
00607     installSigpipeHandler();
00608     parseCommandLine( );
00609     init( true );
00610     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00611 }
00612 #endif
00613 
00614 KApplication::KApplication( bool allowStyles, bool GUIenabled, KInstance* _instance ) :
00615   QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00616                 GUIenabled ),
00617   KInstance( _instance ),
00618 #ifdef Q_WS_X11
00619   display(0L),
00620 #endif
00621   d (new KApplicationPrivate)
00622 {
00623     read_app_startup_id();
00624     if (!GUIenabled)
00625        allowStyles = false;
00626     useStyles = allowStyles;
00627     setName( instanceName() );
00628 
00629     installSigpipeHandler();
00630     parseCommandLine( );
00631     init(GUIenabled);
00632     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00633 }
00634 
00635 #ifdef Q_WS_X11
00636 KApplication::KApplication(Display *display, int& argc, char** argv, const QCString& rAppName,
00637                            bool allowStyles, bool GUIenabled ) :
00638   QApplication( display ), KInstance(rAppName),
00639   display(0L),
00640   d (new KApplicationPrivate())
00641 {
00642     read_app_startup_id();
00643     if (!GUIenabled)
00644        allowStyles = false;
00645     useStyles = allowStyles;
00646 
00647     Q_ASSERT (!rAppName.isEmpty());
00648     setName(rAppName);
00649 
00650     installSigpipeHandler();
00651     KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
00652     parseCommandLine( );
00653     init(GUIenabled);
00654     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00655 }
00656 #endif
00657 
00658 int KApplication::xioErrhandler( Display* dpy )
00659 {
00660     if(kapp)
00661     {
00662         emit shutDown();
00663         d->oldXIOErrorHandler( dpy );
00664     }
00665     exit( 1 );
00666     return 0;
00667 }
00668 
00669 int KApplication::xErrhandler( Display* dpy, void* err_ )
00670 { // no idea how to make forward decl. for XErrorEvent
00671     XErrorEvent* err = static_cast< XErrorEvent* >( err_ );
00672     if(kapp)
00673     {
00674         // add KDE specific stuff here
00675         d->oldXErrorHandler( dpy, err );
00676     }
00677     return 0;
00678 }
00679 
00680 void KApplication::iceIOErrorHandler( _IceConn *conn )
00681 {
00682     emit shutDown();
00683 
00684     if ( d->oldIceIOErrorHandler != NULL )
00685       (*d->oldIceIOErrorHandler)( conn );
00686 
00687     exit( 1 );
00688 }
00689 
00690 class KDETranslator : public QTranslator
00691 {
00692 public:
00693   KDETranslator(QObject *parent) : QTranslator(parent, "kdetranslator") {}
00694   virtual QTranslatorMessage findMessage(const char* context,
00695                      const char *sourceText,
00696                      const char* message) const
00697   {
00698     QTranslatorMessage res;
00699     res.setTranslation(KGlobal::locale()->translateQt(context, sourceText, message));
00700     return res;
00701   }
00702 };
00703 
00704 void KApplication::init(bool GUIenabled)
00705 {
00706   d->guiEnabled = GUIenabled;
00707   if ((getuid() != geteuid()) ||
00708       (getgid() != getegid()))
00709   {
00710      fprintf(stderr, "The KDE libraries are not designed to run with suid privileges.\n");
00711      ::exit(127);
00712   }
00713 
00714   KProcessController::ref();
00715 
00716   (void) KClipboardSynchronizer::self();
00717 
00718   QApplication::setDesktopSettingsAware( false );
00719 
00720   KApp = this;
00721 
00722 
00723 #ifdef Q_WS_X11 //FIXME(E)
00724   // create all required atoms in _one_ roundtrip to the X server
00725   if ( GUIenabled ) {
00726       const int max = 20;
00727       Atom* atoms[max];
00728       char* names[max];
00729       Atom atoms_return[max];
00730       int n = 0;
00731 
00732       atoms[n] = &kipcCommAtom;
00733       names[n++] = (char *) "KIPC_COMM_ATOM";
00734 
00735       atoms[n] = &atom_DesktopWindow;
00736       names[n++] = (char *) "KDE_DESKTOP_WINDOW";
00737 
00738       atoms[n] = &atom_NetSupported;
00739       names[n++] = (char *) "_NET_SUPPORTED";
00740 
00741       atoms[n] = &kde_xdnd_drop;
00742       names[n++] = (char *) "XdndDrop";
00743 
00744       XInternAtoms( qt_xdisplay(), names, n, false, atoms_return );
00745 
00746       for (int i = 0; i < n; i++ )
00747       *atoms[i] = atoms_return[i];
00748   }
00749 #endif
00750 
00751   dcopAutoRegistration();
00752   dcopClientPostInit();
00753 
00754   smw = 0;
00755 
00756   // Initial KIPC event mask.
00757 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00758   kipcEventMask = (1 << KIPC::StyleChanged) | (1 << KIPC::PaletteChanged) |
00759                   (1 << KIPC::FontChanged) | (1 << KIPC::BackgroundChanged) |
00760                   (1 << KIPC::ToolbarStyleChanged) | (1 << KIPC::SettingsChanged) |
00761                   (1 << KIPC::ClipboardConfigChanged);
00762 #endif
00763 
00764   // Trigger creation of locale.
00765   (void) KGlobal::locale();
00766 
00767   KConfig* config = KGlobal::config();
00768   d->actionRestrictions = config->hasGroup("KDE Action Restrictions" ) && !kde_kiosk_exception;
00769   // For brain-dead configurations where the user's local config file is not writable.
00770   // * We use kdialog to warn the user, so we better not generate warnings from
00771   //   kdialog itself.
00772   // * Don't warn if we run with a read-only $HOME
00773   QCString readOnly = getenv("KDE_HOME_READONLY");
00774   if (readOnly.isEmpty() && (qstrcmp(name(), "kdialog") != 0))
00775   {
00776     KConfigGroupSaver saver(config, "KDE Action Restrictions");
00777     if (config->readBoolEntry("warn_unwritable_config",true))
00778        config->checkConfigFilesWritable(true);
00779   }
00780 
00781   if (GUIenabled)
00782   {
00783 #ifdef Q_WS_X11
00784     // this is important since we fork() to launch the help (Matthias)
00785     fcntl(ConnectionNumber(qt_xdisplay()), F_SETFD, FD_CLOEXEC);
00786     // set up the fancy (=robust and error ignoring ) KDE xio error handlers (Matthias)
00787     d->oldXErrorHandler = XSetErrorHandler( kde_x_errhandler );
00788     d->oldXIOErrorHandler = XSetIOErrorHandler( kde_xio_errhandler );
00789 #endif
00790 
00791     connect( this, SIGNAL( aboutToQuit() ), this, SIGNAL( shutDown() ) );
00792 
00793 #ifdef Q_WS_X11 //FIXME(E)
00794     display = desktop()->x11Display();
00795 #endif
00796 
00797     {
00798         QStringList plugins = KGlobal::dirs()->resourceDirs( "qtplugins" );
00799         QStringList::Iterator it = plugins.begin();
00800         while (it != plugins.end()) {
00801             addLibraryPath( *it );
00802             ++it;
00803         }
00804 
00805     }
00806     kdisplaySetStyle();
00807     kdisplaySetFont();
00808 //    kdisplaySetPalette(); done by kdisplaySetStyle
00809     propagateSettings(SETTINGS_QT);
00810 
00811     // Set default mime-source factory
00812     // XXX: This is a hack. Make our factory the default factory, but add the
00813     // previous default factory to the list of factories. Why? When the default
00814     // factory can't resolve something, it iterates in the list of factories.
00815     // But it QWhatsThis only uses the default factory. So if there was already
00816     // a default factory (which happens when using an image library using uic),
00817     // we prefer KDE's factory and so we put that old default factory in the
00818     // list and use KDE as the default. This may speed up things as well.
00819     QMimeSourceFactory* oldDefaultFactory = QMimeSourceFactory::takeDefaultFactory();
00820     QMimeSourceFactory::setDefaultFactory( mimeSourceFactory() );
00821     if ( oldDefaultFactory ) {
00822         QMimeSourceFactory::addFactory( oldDefaultFactory );
00823     }
00824 
00825     KConfigGroupSaver saver( config, "Development" );
00826     if( config->hasKey( "CheckAccelerators" ) || config->hasKey( "AutoCheckAccelerators" ))
00827         d->checkAccelerators = new KCheckAccelerators( this );
00828   }
00829 
00830   // save and restore the RTL setting, as installTranslator calls qt_detectRTLLanguage,
00831   // which makes it impossible to use the -reverse cmdline switch with KDE apps
00832   bool rtl = reverseLayout();
00833   installTranslator(new KDETranslator(this));
00834   setReverseLayout( rtl );
00835   if (i18n( "_: Dear Translator! Translate this string to the string 'LTR' in "
00836      "left-to-right languages (as english) or to 'RTL' in right-to-left "
00837      "languages (such as Hebrew and Arabic) to get proper widget layout." ) == "RTL")
00838     setReverseLayout( !rtl );
00839 
00840   // install appdata resource type
00841   KGlobal::dirs()->addResourceType("appdata", KStandardDirs::kde_default("data")
00842                                    + QString::fromLatin1(name()) + '/');
00843   pSessionConfig = 0L;
00844   bSessionManagement = true;
00845 
00846 #ifdef Q_WS_X11
00847   // register a communication window for desktop changes (Matthias)
00848   if (GUIenabled && kde_have_kipc )
00849   {
00850     smw = new QWidget(0,0);
00851     long data = 1;
00852     XChangeProperty(qt_xdisplay(), smw->winId(),
00853             atom_DesktopWindow, atom_DesktopWindow,
00854             32, PropModeReplace, (unsigned char *)&data, 1);
00855   }
00856 #else
00857   // FIXME(E): Implement for Qt Embedded
00858 #endif
00859 
00860   d->oldIceIOErrorHandler = IceSetIOErrorHandler( kde_ice_ioerrorhandler );
00861 }
00862 
00863 static int my_system (const char *command) {
00864    int pid, status;
00865 
00866    QApplication::flushX();
00867    pid = fork();
00868    if (pid == -1)
00869       return -1;
00870    if (pid == 0) {
00871       const char* shell = "/bin/sh";
00872       execl(shell, shell, "-c", command, (void *)0);
00873       ::exit(127);
00874    }
00875    do {
00876       if (waitpid(pid, &status, 0) == -1) {
00877          if (errno != EINTR)
00878             return -1;
00879        } else
00880             return status;
00881    } while(1);
00882 }
00883 
00884 
00885 DCOPClient *KApplication::dcopClient()
00886 {
00887   if (s_DCOPClient)
00888     return s_DCOPClient;
00889 
00890   s_DCOPClient = new DCOPClient();
00891   KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
00892   if (args && args->isSet("dcopserver"))
00893   {
00894     s_DCOPClient->setServerAddress( args->getOption("dcopserver"));
00895   }
00896   if( kapp ) {
00897     connect(s_DCOPClient, SIGNAL(attachFailed(const QString &)),
00898             kapp, SLOT(dcopFailure(const QString &)));
00899     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
00900             kapp, SLOT(dcopBlockUserInput(bool)) );
00901   }
00902   else
00903     s_dcopClientNeedsPostInit = true;
00904 
00905   DCOPClient::setMainClient( s_DCOPClient );
00906   return s_DCOPClient;
00907 }
00908 
00909 void KApplication::dcopClientPostInit()
00910 {
00911   if( s_dcopClientNeedsPostInit )
00912     {
00913     s_dcopClientNeedsPostInit = false;
00914     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
00915             SLOT(dcopBlockUserInput(bool)) );
00916     s_DCOPClient->bindToApp(); // Make sure we get events from the DCOPClient.
00917     }
00918 }
00919 
00920 void KApplication::dcopAutoRegistration()
00921 {
00922   if (autoDcopRegistration)
00923      {
00924      ( void ) dcopClient();
00925      if( dcopClient()->appId().isEmpty())
00926          dcopClient()->registerAs(name());
00927      }
00928 }
00929 
00930 void KApplication::disableAutoDcopRegistration()
00931 {
00932   autoDcopRegistration = false;
00933 }
00934 
00935 KConfig* KApplication::sessionConfig()
00936 {
00937     if (pSessionConfig)
00938         return pSessionConfig;
00939 
00940     // create an instance specific config object
00941     pSessionConfig = new KConfig( sessionConfigName(), false, false);
00942     return pSessionConfig;
00943 }
00944 
00945 void KApplication::ref()
00946 {
00947     d->refCount++;
00948     //kdDebug() << "KApplication::ref() : refCount = " << d->refCount << endl;
00949 }
00950 
00951 void KApplication::deref()
00952 {
00953     d->refCount--;
00954     //kdDebug() << "KApplication::deref() : refCount = " << d->refCount << endl;
00955     if ( d->refCount <= 0 )
00956         quit();
00957 }
00958 
00959 KSessionManaged::KSessionManaged()
00960 {
00961     sessionClients()->remove( this );
00962     sessionClients()->append( this );
00963 }
00964 
00965 KSessionManaged::~KSessionManaged()
00966 {
00967     sessionClients()->remove( this );
00968 }
00969 
00970 bool KSessionManaged::saveState(QSessionManager&)
00971 {
00972     return true;
00973 }
00974 
00975 bool KSessionManaged::commitData(QSessionManager&)
00976 {
00977     return true;
00978 }
00979 
00980 
00981 void KApplication::disableSessionManagement() {
00982   bSessionManagement = false;
00983 }
00984 
00985 void KApplication::enableSessionManagement() {
00986   bSessionManagement = true;
00987   // Session management support in Qt/KDE is awfully broken.
00988   // If konqueror disables session management right after its startup,
00989   // and enables it later (preloading stuff), it won't be properly
00990   // saved on session shutdown.
00991   // I'm not actually sure why it doesn't work, but saveState()
00992   // doesn't seem to be called on session shutdown, possibly
00993   // because disabling session management after konqueror startup
00994   // disabled it somehow. Forcing saveState() here for this application
00995   // seems to fix it.
00996   if( mySmcConnection ) {
00997         SmcRequestSaveYourself( mySmcConnection, SmSaveLocal, False,
00998                 SmInteractStyleAny,
00999                 False, False );
01000 
01001     // flush the request
01002     IceFlush(SmcGetIceConnection(mySmcConnection));
01003   }
01004 }
01005 
01006 
01007 bool KApplication::requestShutDown(
01008     ShutdownConfirm confirm, ShutdownType sdtype, ShutdownMode sdmode )
01009 {
01010 #ifdef Q_WS_X11
01011     QApplication::syncX();
01012     /*  use ksmserver's dcop interface if necessary  */
01013     if ( confirm == ShutdownConfirmYes ||
01014          sdtype != ShutdownTypeDefault ||
01015          sdmode != ShutdownModeDefault )
01016     {
01017         QByteArray data;
01018         QDataStream arg(data, IO_WriteOnly);
01019         arg << (int)confirm << (int)sdtype << (int)sdmode;
01020     return dcopClient()->send( "ksmserver", "ksmserver",
01021                                    "logout(int,int,int)", data );
01022     }
01023 
01024     if ( mySmcConnection ) {
01025         // we already have a connection to the session manager, use it.
01026         SmcRequestSaveYourself( mySmcConnection, SmSaveBoth, True,
01027                 SmInteractStyleAny,
01028                 confirm == ShutdownConfirmNo, True );
01029 
01030     // flush the request
01031     IceFlush(SmcGetIceConnection(mySmcConnection));
01032         return true;
01033     }
01034 
01035     // open a temporary connection, if possible
01036 
01037     propagateSessionManager();
01038     QCString smEnv = ::getenv("SESSION_MANAGER");
01039     if (smEnv.isEmpty())
01040         return false;
01041 
01042     if (! tmpSmcConnection) {
01043     char cerror[256];
01044     char* myId = 0;
01045     char* prevId = 0;
01046     SmcCallbacks cb;
01047     tmpSmcConnection = SmcOpenConnection( 0, 0, 1, 0,
01048                           0, &cb,
01049                           prevId,
01050                           &myId,
01051                           255,
01052                           cerror );
01053     ::free( myId ); // it was allocated by C
01054     if (!tmpSmcConnection )
01055         return false;
01056     }
01057 
01058     SmcRequestSaveYourself( tmpSmcConnection, SmSaveBoth, True,
01059                 SmInteractStyleAny, False, True );
01060 
01061     // flush the request
01062     IceFlush(SmcGetIceConnection(tmpSmcConnection));
01063     return true;
01064 #else
01065     // FIXME(E): Implement for Qt Embedded
01066     return false;
01067 #endif
01068 }
01069 
01070 void KApplication::propagateSessionManager()
01071 {
01072     QCString fName = QFile::encodeName(locateLocal("socket", "KSMserver"));
01073     QCString display = ::getenv(DISPLAY);
01074     // strip the screen number from the display
01075     display.replace(QRegExp("\\.[0-9]+$"), "");
01076     int i;
01077     while( (i = display.find(':')) >= 0)
01078        display[i] = '_';
01079 
01080     fName += "_"+display;
01081     QCString smEnv = ::getenv("SESSION_MANAGER");
01082     bool check = smEnv.isEmpty();
01083     if ( !check && smModificationTime ) {
01084          QFileInfo info( fName );
01085          QTime current = info.lastModified().time();
01086          check = current > *smModificationTime;
01087     }
01088     if ( check ) {
01089         delete smModificationTime;
01090         QFile f( fName );
01091         if ( !f.open( IO_ReadOnly ) )
01092             return;
01093         QFileInfo info ( f );
01094         smModificationTime = new QTime( info.lastModified().time() );
01095         QTextStream t(&f);
01096         t.setEncoding( QTextStream::Latin1 );
01097         QString s = t.readLine();
01098         f.close();
01099         ::setenv( "SESSION_MANAGER", s.latin1(), true  );
01100     }
01101 }
01102 
01103 void KApplication::commitData( QSessionManager& sm )
01104 {
01105     d->session_save = true;
01106     bool canceled = false;
01107     for (KSessionManaged* it = sessionClients()->first();
01108          it && !canceled;
01109          it = sessionClients()->next() ) {
01110         canceled = !it->commitData( sm );
01111     }
01112     if ( canceled )
01113         sm.cancel();
01114 
01115     if ( sm.allowsInteraction() ) {
01116         QWidgetList done;
01117         QWidgetList *list = QApplication::topLevelWidgets();
01118         bool canceled = false;
01119         QWidget* w = list->first();
01120         while ( !canceled && w ) {
01121             if ( !w->testWState( WState_ForceHide ) && !w->inherits("KMainWindow") ) {
01122                 QCloseEvent e;
01123                 sendEvent( w, &e );
01124                 canceled = !e.isAccepted();
01125                 if ( !canceled )
01126                     done.append( w );
01127                 delete list; // one never knows...
01128                 list = QApplication::topLevelWidgets();
01129                 w = list->first();
01130             } else {
01131                 w = list->next();
01132             }
01133             while ( w && done.containsRef( w ) )
01134                 w = list->next();
01135         }
01136         delete list;
01137     }
01138 
01139 
01140     if ( !bSessionManagement )
01141         sm.setRestartHint( QSessionManager::RestartNever );
01142     else
01143     sm.setRestartHint( QSessionManager::RestartIfRunning );
01144     d->session_save = false;
01145 }
01146 
01147 void KApplication::saveState( QSessionManager& sm )
01148 {
01149     d->session_save = true;
01150 #ifndef Q_WS_QWS
01151     static bool firstTime = true;
01152     mySmcConnection = (SmcConn) sm.handle();
01153 
01154     if ( !bSessionManagement ) {
01155         sm.setRestartHint( QSessionManager::RestartNever );
01156     d->session_save = false;
01157         return;
01158     }
01159     else
01160         sm.setRestartHint( QSessionManager::RestartIfRunning );
01161 
01162 #if QT_VERSION < 0x030100
01163     {
01164         // generate a new session key
01165         timeval tv;
01166         gettimeofday( &tv, 0 );
01167         d->sessionKey  = QString::number( tv.tv_sec ) + "_" + QString::number(tv.tv_usec);
01168     }
01169 #endif
01170 
01171     if ( firstTime ) {
01172         firstTime = false;
01173     d->session_save = false;
01174         return; // no need to save the state.
01175     }
01176 
01177     // remove former session config if still existing, we want a new
01178     // and fresh one. Note that we do not delete the config file here,
01179     // this is done by the session manager when it executes the
01180     // discard commands. In fact it would be harmful to remove the
01181     // file here, as the session might be stored under a different
01182     // name, meaning the user still might need it eventually.
01183     if ( pSessionConfig ) {
01184         delete pSessionConfig;
01185         pSessionConfig = 0;
01186     }
01187 
01188     // tell the session manager about our new lifecycle
01189     QStringList restartCommand = sm.restartCommand();
01190 #if QT_VERSION < 0x030100
01191     restartCommand.clear();
01192     restartCommand  << argv()[0] << "-session" << sm.sessionId() << "-smkey" << d->sessionKey;
01193     sm.setRestartCommand( restartCommand );
01194 #endif
01195 
01196 
01197     QCString multiHead = getenv("KDE_MULTIHEAD");
01198     if (multiHead.lower() == "true") {
01199         // if multihead is enabled, we save our -display argument so that
01200         // we are restored onto the correct head... one problem with this
01201         // is that the display is hard coded, which means we cannot restore
01202         // to a different display (ie. if we are in a university lab and try,
01203         // try to restore a multihead session, our apps could be started on
01204         // someone else's display instead of our own)
01205         QCString displayname = getenv(DISPLAY);
01206         if (! displayname.isNull()) {
01207             // only store the command if we actually have a DISPLAY
01208             // environment variable
01209             restartCommand.append("-display");
01210             restartCommand.append(displayname);
01211         }
01212         sm.setRestartCommand( restartCommand );
01213     }
01214 
01215 
01216     // finally: do session management
01217     emit saveYourself(); // for compatibility
01218     bool canceled = false;
01219     for (KSessionManaged* it = sessionClients()->first();
01220          it && !canceled;
01221          it = sessionClients()->next() ) {
01222         canceled = !it->saveState( sm );
01223     }
01224 
01225     // if we created a new session config object, register a proper discard command
01226     if ( pSessionConfig ) {
01227         pSessionConfig->sync();
01228         QStringList discard;
01229         discard  << "rm" << locateLocal("config", sessionConfigName());
01230         sm.setDiscardCommand( discard );
01231     } else {
01232     sm.setDiscardCommand( "" );
01233     }
01234 
01235     if ( canceled )
01236         sm.cancel();
01237 #else
01238     // FIXME(E): Implement for Qt Embedded
01239 #endif
01240     d->session_save = false;
01241 }
01242 
01243 bool KApplication::sessionSaving() const
01244 {
01245     return d->session_save;
01246 }
01247 
01248 void KApplication::startKdeinit()
01249 {
01250   // Try to launch kdeinit.
01251   QString srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"));
01252   if (srv.isEmpty())
01253      srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"), KDEDIR+QString::fromLatin1("/bin"));
01254   if (srv.isEmpty())
01255      return;
01256   if (kapp && (Tty != kapp->type()))
01257     setOverrideCursor( Qt::waitCursor );
01258   my_system(QFile::encodeName(srv)+" --suicide");
01259   if (kapp && (Tty != kapp->type()))
01260     restoreOverrideCursor();
01261 }
01262 
01263 void KApplication::dcopFailure(const QString &msg)
01264 {
01265   static int failureCount = 0;
01266   failureCount++;
01267   if (failureCount == 1)
01268   {
01269      startKdeinit();
01270      return;
01271   }
01272   if (failureCount == 2)
01273   {
01274      QString msgStr(i18n("There was an error setting up inter-process "
01275                       "communications for KDE. The message returned "
01276                       "by the system was:\n\n"));
01277      msgStr += msg;
01278      msgStr += i18n("\n\nPlease check that the \"dcopserver\" program is running!");
01279 
01280      if (Tty != kapp->type())
01281      {
01282        QMessageBox::critical
01283          (
01284            kapp->mainWidget(),
01285            i18n("DCOP communications error (%1)").arg(kapp->caption()),
01286            msgStr,
01287            i18n("&OK")
01288          );
01289      }
01290      else
01291      {
01292        fprintf(stderr, "%s\n", msgStr.local8Bit().data());
01293      }
01294 
01295      return;
01296   }
01297 }
01298 
01299 static const KCmdLineOptions qt_options[] =
01300 {
01301   //FIXME: Check if other options are specific to Qt/X11
01302 #ifdef Q_WS_X11
01303    { "display <displayname>", I18N_NOOP("Use the X-server display 'displayname'"), 0},
01304 #else
01305    { "display <displayname>", I18N_NOOP("Use the QWS display 'displayname'"), 0},
01306 #endif
01307    { "session <sessionId>", I18N_NOOP("Restore the application for the given 'sessionId'"), 0},
01308    { "cmap", I18N_NOOP("Causes the application to install a private color\nmap on an 8-bit display"), 0},
01309    { "ncols <count>", I18N_NOOP("Limits the number of colors allocated in the color\ncube on an 8-bit display, if the application is\nusing the QApplication::ManyColor color\nspecification"), 0},
01310    { "nograb", I18N_NOOP("tells Qt to never grab the mouse or the keyboard"), 0},
01311    { "dograb", I18N_NOOP("running under a debugger can cause an implicit\n-nograb, use -dograb to override"), 0},
01312    { "sync", I18N_NOOP("switches to synchronous mode for debugging"), 0},
01313    { "fn", 0, 0},
01314    { "font <fontname>", I18N_NOOP("defines the application font"), 0},
01315    { "bg", 0, 0},
01316    { "background <color>", I18N_NOOP("sets the default background color and an\napplication palette (light and dark shades are\ncalculated)"), 0},
01317    { "fg", 0, 0},
01318    { "foreground <color>", I18N_NOOP("sets the default foreground color"), 0},
01319    { "btn", 0, 0},
01320    { "button <color>", I18N_NOOP("sets the default button color"), 0},
01321    { "name <name>", I18N_NOOP("sets the application name"), 0},
01322    { "title <title>", I18N_NOOP("sets the application title (caption)"), 0},
01323 #ifdef Q_WS_X11
01324    { "visual TrueColor", I18N_NOOP("forces the application to use a TrueColor visual on\nan 8-bit display"), 0},
01325    { "inputstyle <inputstyle>", I18N_NOOP("sets XIM (X Input Method) input style. Possible\nvalues are onthespot, overthespot, offthespot and\nroot"), 0 },
01326    { "im <XIM server>", I18N_NOOP("set XIM server"),0},
01327    { "noxim", I18N_NOOP("disable XIM"), 0 },
01328 #endif
01329 #ifdef Q_WS_QWS
01330    { "qws", I18N_NOOP("forces the application to run as QWS Server"), 0},
01331 #endif
01332    { "reverse", I18N_NOOP("mirrors the whole layout of widgets"), 0},
01333    KCmdLineLastOption
01334 };
01335 
01336 static const KCmdLineOptions kde_options[] =
01337 {
01338    { "caption <caption>",       I18N_NOOP("Use 'caption' as name in the titlebar"), 0},
01339    { "icon <icon>",             I18N_NOOP("Use 'icon' as the application icon"), 0},
01340    { "miniicon <icon>",         I18N_NOOP("Use 'icon' as the icon in the titlebar"), 0},
01341    { "config <filename>",       I18N_NOOP("Use alternative configuration file"), 0},
01342    { "dcopserver <server>",     I18N_NOOP("Use the DCOP Server specified by 'server'"), 0},
01343    { "nocrashhandler",          I18N_NOOP("Disable crash handler, to get core dumps"), 0},
01344    { "waitforwm",          I18N_NOOP("Waits for a WM_NET compatible windowmanager"), 0},
01345    { "style <style>", I18N_NOOP("sets the application GUI style"), 0},
01346    { "geometry <geometry>", I18N_NOOP("sets the client geometry of the main widget"), 0},
01347 #if QT_VERSION < 0x030100
01348    { "smkey <sessionKey>", I18N_NOOP("Define a 'sessionKey' for the session id. Only valid with -session"), 0},
01349 #else
01350    { "smkey <sessionKey>", 0, 0}, // this option is obsolete and exists only to allow smooth upgrades from sessions
01351                                   // saved under Qt 3.0.x -- Qt 3.1.x includes the session key now automatically in
01352                   // the session id (Simon)
01353 #endif
01354    KCmdLineLastOption
01355 };
01356 
01357 void
01358 KApplication::addCmdLineOptions()
01359 {
01360    KCmdLineArgs::addCmdLineOptions(qt_options, "Qt", "qt");
01361    KCmdLineArgs::addCmdLineOptions(kde_options, "KDE", "kde");
01362 }
01363 
01364 void KApplication::parseCommandLine( )
01365 {
01366     KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
01367 
01368     if ( !args ) return;
01369 
01370     if (args->isSet("config"))
01371     {
01372         QString config = QString::fromLocal8Bit(args->getOption("config"));
01373         setConfigName(config);
01374     }
01375 
01376     if (args->isSet("style"))
01377     {
01378 
01379        QStringList styles = QStyleFactory::keys();
01380        QString reqStyle(args->getOption("style").lower());
01381 
01382        for (QStringList::ConstIterator it = styles.begin(); it != styles.end(); ++it)
01383            if ((*it).lower() == reqStyle)
01384            {
01385                d->overrideStyle = *it;
01386                break;
01387            }
01388 
01389        if (d->overrideStyle.isEmpty())
01390           fprintf(stderr, "%s", i18n("The style %1 was not found\n").arg(reqStyle).local8Bit().data());
01391     }
01392 
01393     if (args->isSet("caption"))
01394     {
01395        aCaption = QString::fromLocal8Bit(args->getOption("caption"));
01396     }
01397 
01398     if (args->isSet("miniicon"))
01399     {
01400        const char *tmp = args->getOption("miniicon");
01401        aMiniIconPixmap = SmallIcon(tmp);
01402        aMiniIconName = tmp;
01403     }
01404 
01405     if (args->isSet("icon"))
01406     {
01407        const char *tmp = args->getOption("icon");
01408        aIconPixmap = DesktopIcon( tmp );
01409        aIconName = tmp;
01410        if (aMiniIconPixmap.isNull())
01411        {
01412           aMiniIconPixmap = SmallIcon( tmp );
01413           aMiniIconName = tmp;
01414        }
01415     }
01416 
01417     bool nocrashhandler = (getenv("KDE_DEBUG") != NULL);
01418     if (!nocrashhandler && args->isSet("crashhandler"))
01419     {
01420         // set default crash handler / set emergency save function to nothing
01421         KCrash::setCrashHandler(KCrash::defaultCrashHandler);
01422         KCrash::setEmergencySaveFunction(NULL);
01423 
01424         KCrash::setApplicationName(QString(args->appName()));
01425     }
01426 
01427 #ifdef Q_WS_X11
01428     if ( args->isSet( "waitforwm" ) ) {
01429         Atom type;
01430         (void) desktop(); // trigger desktop creation, we need PropertyNotify events for the root window
01431         int format;
01432         unsigned long length, after;
01433         unsigned char *data;
01434         while ( XGetWindowProperty( qt_xdisplay(), qt_xrootwin(), atom_NetSupported,
01435                     0, 1, false, AnyPropertyType, &type, &format,
01436                                     &length, &after, &data ) != Success || !length ) {
01437             if ( data )
01438                 XFree( data );
01439             XEvent event;
01440             XWindowEvent( qt_xdisplay(), qt_xrootwin(), PropertyChangeMask, &event );
01441         }
01442         if ( data )
01443             XFree( data );
01444     }
01445 #else
01446     // FIXME(E): Implement for Qt Embedded
01447 #endif
01448 
01449     if (args->isSet("geometry"))
01450     {
01451         d->geometry_arg = args->getOption("geometry");
01452     }
01453 
01454     if (args->isSet("smkey"))
01455     {
01456         d->sessionKey = args->getOption("smkey");
01457     }
01458 
01459 }
01460 
01461 QString KApplication::geometryArgument() const
01462 {
01463     return d->geometry_arg;
01464 }
01465 
01466 QPixmap KApplication::icon() const
01467 {
01468   if( aIconPixmap.isNull()) {
01469       KApplication *that = const_cast<KApplication *>(this);
01470       that->aIconPixmap = DesktopIcon( instanceName() );
01471   }
01472   return aIconPixmap;
01473 }
01474 
01475 QString KApplication::iconName() const
01476 {
01477   return aIconName.isNull() ? (QString)instanceName() : aIconName;
01478 }
01479 
01480 QPixmap KApplication::miniIcon() const
01481 {
01482   if (aMiniIconPixmap.isNull()) {
01483       KApplication *that = const_cast<KApplication *>(this);
01484       that->aMiniIconPixmap = SmallIcon( instanceName() );
01485   }
01486   return aMiniIconPixmap;
01487 }
01488 
01489 QString KApplication::miniIconName() const
01490 {
01491   return aMiniIconName.isNull() ? (QString)instanceName() : aMiniIconName;
01492 }
01493 
01494 extern void kDebugCleanup();
01495 
01496 KApplication::~KApplication()
01497 {
01498   delete d->m_KAppDCOPInterface;
01499 
01500   // First call the static deleters and then call KLibLoader::cleanup()
01501   // The static deleters may delete libraries for which they need KLibLoader.
01502   // KLibLoader will take care of the remaining ones.
01503   KGlobal::deleteStaticDeleters();
01504   KLibLoader::cleanUp();
01505 
01506   delete smw;
01507 
01508   // close down IPC
01509   delete s_DCOPClient;
01510   s_DCOPClient = 0L;
01511 
01512   KProcessController::deref();
01513 
01514   if ( d->oldXErrorHandler != NULL )
01515       XSetErrorHandler( d->oldXErrorHandler );
01516   if ( d->oldXIOErrorHandler != NULL )
01517       XSetIOErrorHandler( d->oldXIOErrorHandler );
01518   if ( d->oldIceIOErrorHandler != NULL )
01519       IceSetIOErrorHandler( d->oldIceIOErrorHandler );
01520 
01521   delete d;
01522   KApp = 0;
01523 
01524 #ifndef Q_WS_QWS
01525   mySmcConnection = 0;
01526   delete smModificationTime;
01527   smModificationTime = 0;
01528 
01529   // close the temporary smc connection
01530   if (tmpSmcConnection) {
01531       SmcCloseConnection( tmpSmcConnection, 0, 0 );
01532       tmpSmcConnection = 0;
01533   }
01534 #else
01535   // FIXME(E): Implement for Qt Embedded
01536 #endif
01537 }
01538 
01539 
01540 #ifdef Q_WS_X11
01541 class KAppX11HackWidget: public QWidget
01542 {
01543 public:
01544     bool publicx11Event( XEvent * e) { return x11Event( e ); }
01545 };
01546 #endif
01547 
01548 
01549 
01550 static bool kapp_block_user_input = false;
01551 
01552 void KApplication::dcopBlockUserInput( bool b )
01553 {
01554     kapp_block_user_input = b;
01555 }
01556 
01557 #ifdef Q_WS_X11
01558 bool KApplication::x11EventFilter( XEvent *_event )
01559 {
01560     switch ( _event->type ) {
01561         case ClientMessage:
01562         {
01563 #if KDE_IS_VERSION( 3, 3, 91 )
01564 #warning This should be already in Qt, check.
01565 #endif
01566         // Workaround for focus stealing prevention not working when dragging e.g. text from KWrite
01567         // to KDesktop -> the dialog asking for filename doesn't get activated. This is because
01568         // Qt-3.2.x doesn't have concept of qt_x_user_time at all, and Qt-3.3.0b1 passes the timestamp
01569         // in the XdndDrop message in incorrect field (and doesn't update qt_x_user_time either).
01570         // Patch already sent, future Qt version should have this fixed.
01571             if( _event->xclient.message_type == kde_xdnd_drop )
01572                 { // if the message is XdndDrop
01573                 if( _event->xclient.data.l[ 1 ] == 1 << 24     // and it's broken the way it's in Qt-3.2.x
01574                     && _event->xclient.data.l[ 2 ] == 0
01575                     && _event->xclient.data.l[ 4 ] == 0
01576                     && _event->xclient.data.l[ 3 ] != 0 )
01577                     {
01578                     if( qt_x_user_time == 0
01579                         || ( _event->xclient.data.l[ 3 ] - qt_x_user_time ) < 100000U )
01580                         { // and the timestamp looks reasonable
01581                         qt_x_user_time = _event->xclient.data.l[ 3 ]; // update our qt_x_user_time from it
01582                         }
01583                     }
01584                 else // normal DND, only needed until Qt updates qt_x_user_time from XdndDrop
01585                     {
01586                     if( qt_x_user_time == 0
01587                         || ( _event->xclient.data.l[ 2 ] - qt_x_user_time ) < 100000U )
01588                         { // the timestamp looks reasonable
01589                         qt_x_user_time = _event->xclient.data.l[ 2 ]; // update our qt_x_user_time from it
01590                         }
01591                     }
01592                 }
01593         }
01594     default: break;
01595     }
01596 
01597     if ( kapp_block_user_input ) {
01598         switch ( _event->type  ) {
01599         case ButtonPress:
01600         case ButtonRelease:
01601         case XKeyPress:
01602         case XKeyRelease:
01603         case MotionNotify:
01604             return true;
01605         default:
01606             break;
01607         }
01608     }
01609 
01610     if (x11Filter) {
01611         for (QWidget *w=x11Filter->first(); w; w=x11Filter->next()) {
01612             if (((KAppX11HackWidget*) w)->publicx11Event(_event))
01613                 return true;
01614         }
01615     }
01616 
01617 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
01618     if ((_event->type == ClientMessage) &&
01619             (_event->xclient.message_type == kipcCommAtom))
01620     {
01621         XClientMessageEvent *cme = (XClientMessageEvent *) _event;
01622 
01623         int id = cme->data.l[0];
01624         int arg = cme->data.l[1];
01625         if ((id < 32) && (kipcEventMask & (1 << id)))
01626         {
01627             switch (id)
01628             {
01629             case KIPC::StyleChanged:
01630                 KGlobal::config()->reparseConfiguration();
01631                 kdisplaySetStyle();
01632                 break;
01633 
01634             case KIPC::ToolbarStyleChanged:
01635                 KGlobal::config()->reparseConfiguration();
01636                 if (useStyles)
01637                     emit toolbarAppearanceChanged(arg);
01638                 break;
01639 
01640             case KIPC::PaletteChanged:
01641                 KGlobal::config()->reparseConfiguration();
01642                 kdisplaySetPalette();
01643                 break;
01644 
01645             case KIPC::FontChanged:
01646                 KGlobal::config()->reparseConfiguration();
01647                 KGlobalSettings::rereadFontSettings();
01648                 kdisplaySetFont();
01649                 break;
01650 
01651             case KIPC::BackgroundChanged:
01652                 emit backgroundChanged(arg);
01653                 break;
01654 
01655             case KIPC::SettingsChanged:
01656                 KGlobal::config()->reparseConfiguration();
01657                 if (arg == SETTINGS_PATHS)
01658                     KGlobalSettings::rereadPathSettings();
01659                 else if (arg == SETTINGS_MOUSE)
01660                     KGlobalSettings::rereadMouseSettings();
01661                 propagateSettings((SettingsCategory)arg);
01662                 break;
01663 
01664             case KIPC::IconChanged:
01665                 QPixmapCache::clear();
01666                 KGlobal::config()->reparseConfiguration();
01667                 KGlobal::instance()->newIconLoader();
01668                 emit iconChanged(arg);
01669                 break;
01670 
01671             case KIPC::ClipboardConfigChanged:
01672                 KClipboardSynchronizer::newConfiguration(arg);
01673                 break;
01674             }
01675         }
01676         else if (id >= 32)
01677         {
01678             emit kipcMessage(id, arg);
01679         }
01680         return true;
01681     }
01682 #endif // Q_WS_X11 && ! K_WS_QTONLY
01683     return false;
01684 }
01685 #endif
01686 
01687 void KApplication::updateUserTimestamp( unsigned long time )
01688 {
01689 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
01690     if( time == 0 )
01691     { // get current X timestamp
01692         Window w = XCreateSimpleWindow( qt_xdisplay(), qt_xrootwin(), 0, 0, 1, 1, 0, 0, 0 );
01693         XSelectInput( qt_xdisplay(), w, PropertyChangeMask );
01694         unsigned char data[ 1 ];
01695         XChangeProperty( qt_xdisplay(), w, XA_ATOM, XA_ATOM, 8, PropModeAppend, data, 1 );
01696         XEvent ev;
01697         XWindowEvent( qt_xdisplay(), w, PropertyChangeMask, &ev );
01698         time = ev.xproperty.time;
01699         XDestroyWindow( qt_xdisplay(), w );
01700     }
01701     if( qt_x_user_time == 0
01702         || time - qt_x_user_time < 1000000000U ) // check time > qt_x_user_time, handle wrapping
01703         qt_x_user_time = time;
01704 #endif
01705 }
01706 
01707 unsigned long KApplication::userTimestamp() const
01708 {
01709 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
01710     return qt_x_user_time;
01711 #else
01712     return 0;
01713 #endif
01714 }
01715 
01716 void KApplication::updateRemoteUserTimestamp( const QCString& dcopId, unsigned long time )
01717 {
01718 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
01719     if( time == 0 )
01720         time = qt_x_user_time;
01721     DCOPRef( dcopId, "MainApplication-Interface" ).call( "updateUserTimestamp", time );
01722 #endif
01723 }
01724 
01725 void KApplication::invokeEditSlot( const char *slot )
01726 {
01727   QObject *object = focusWidget();
01728   if( !object )
01729     return;
01730 
01731   QMetaObject *meta = object->metaObject();
01732 
01733   int idx = meta->findSlot( slot + 1, true );
01734   if( idx < 0 )
01735     return;
01736 
01737   object->qt_invoke( idx, 0 );
01738 }
01739 
01740 void KApplication::addKipcEventMask(int id)
01741 {
01742     if (id >= 32)
01743     {
01744         kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01745         return;
01746     }
01747     kipcEventMask |= (1 << id);
01748 }
01749 
01750 void KApplication::removeKipcEventMask(int id)
01751 {
01752     if (id >= 32)
01753     {
01754         kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01755         return;
01756     }
01757     kipcEventMask &= ~(1 << id);
01758 }
01759 
01760 void KApplication::enableStyles()
01761 {
01762     if (!useStyles)
01763     {
01764         useStyles = true;
01765         applyGUIStyle();
01766     }
01767 }
01768 
01769 void KApplication::disableStyles()
01770 {
01771     useStyles = false;
01772 }
01773 
01774 void KApplication::applyGUIStyle()
01775 {
01776     if ( !useStyles ) return;
01777 
01778     KConfigGroup pConfig (KGlobal::config(), "General");
01779     QString defaultStyle = KStyle::defaultStyle();
01780     QString styleStr = pConfig.readEntry("widgetStyle", defaultStyle);
01781 
01782     if (d->overrideStyle.isEmpty()) {
01783       // ### add check wether we already use the correct style to return then
01784       // (workaround for Qt misbehavior to avoid double style initialization)
01785 
01786       QStyle* sp = QStyleFactory::create( styleStr );
01787 
01788       // If there is no default style available, try falling back any available style
01789       if ( !sp && styleStr != defaultStyle)
01790           sp = QStyleFactory::create( defaultStyle );
01791       if ( !sp )
01792           sp = QStyleFactory::create( *(QStyleFactory::keys().begin()) );
01793       setStyle(sp);
01794     }
01795     else
01796         setStyle(d->overrideStyle);
01797     // Reread palette from config file.
01798     kdisplaySetPalette();
01799 }
01800 
01801 QString KApplication::caption() const
01802 {
01803   // Caption set from command line ?
01804   if( !aCaption.isNull() )
01805         return aCaption;
01806   else
01807       // We have some about data ?
01808       if ( KGlobal::instance()->aboutData() )
01809         return KGlobal::instance()->aboutData()->programName();
01810       else
01811         // Last resort : application name
01812         return name();
01813 }
01814 
01815 
01816 //
01817 // 1999-09-20: Espen Sand
01818 // An attempt to simplify consistent captions.
01819 //
01820 QString KApplication::makeStdCaption( const QString &userCaption,
01821                                       bool withAppName, bool modified ) const
01822 {
01823   QString s = userCaption.isEmpty() ? caption() : userCaption;
01824 
01825   // If the document is modified, add '[modified]'.
01826   if (modified)
01827       s += QString::fromUtf8(" [") + i18n("modified") + QString::fromUtf8("]");
01828 
01829   if ( !userCaption.isEmpty() ) {
01830       // Add the application name if:
01831       // User asked for it, it's not a duplication  and the app name (caption()) is not empty
01832       if ( withAppName && !caption().isNull() && !userCaption.endsWith(caption())  )
01833       s += QString::fromUtf8(" - ") + caption();
01834   }
01835 
01836   return s;
01837 }
01838 
01839 QPalette KApplication::createApplicationPalette()
01840 {
01841     KConfig *config = KGlobal::config();
01842     KConfigGroupSaver saver( config, "General" );
01843     return createApplicationPalette( config, KGlobalSettings::contrast() );
01844 }
01845 
01846 QPalette KApplication::createApplicationPalette( KConfig *config, int contrast_ )
01847 {
01848     QColor kde31Background( 238, 238, 230 );
01849     QColor kde31Beige( 255,221,118 );
01850 
01851     QColor kde31Button;
01852     if ( QPixmap::defaultDepth() > 8 )
01853       kde31Button.setRgb( 238, 234, 222 );
01854     else
01855       kde31Button.setRgb( 220, 220, 220 );
01856 
01857     QColor kde31Link( 0, 0, 192 );
01858     QColor kde31VisitedLink( 128, 0,128 );
01859 
01860     QColor background = config->readColorEntry( "background", &kde31Background );
01861     QColor foreground = config->readColorEntry( "foreground", &black );
01862     QColor button = config->readColorEntry( "buttonBackground", &kde31Button );
01863     QColor buttonText = config->readColorEntry( "buttonForeground", &foreground );
01864     QColor highlight = config->readColorEntry( "selectBackground", &kde31Beige );
01865     QColor highlightedText = config->readColorEntry( "selectForeground", &black );
01866     QColor base = config->readColorEntry( "windowBackground", &white );
01867     QColor baseText = config->readColorEntry( "windowForeground", &black );
01868     QColor link = config->readColorEntry( "linkColor", &kde31Link );
01869     QColor visitedLink = config->readColorEntry( "visitedLinkColor", &kde31VisitedLink );
01870 
01871     int highlightVal, lowlightVal;
01872     highlightVal = 100 + (2*contrast_+4)*16/10;
01873     lowlightVal = 100 + (2*contrast_+4)*10;
01874 
01875     QColor disfg = foreground;
01876 
01877     int h, s, v;
01878     disfg.hsv( &h, &s, &v );
01879     if (v > 128)
01880     // dark bg, light fg - need a darker disabled fg
01881     disfg = disfg.dark(lowlightVal);
01882     else if (disfg != black)
01883     // light bg, dark fg - need a lighter disabled fg - but only if !black
01884     disfg = disfg.light(highlightVal);
01885     else
01886     // black fg - use darkgray disabled fg
01887     disfg = Qt::darkGray;
01888 
01889 
01890     QColorGroup disabledgrp(disfg, background,
01891                             background.light(highlightVal),
01892                             background.dark(lowlightVal),
01893                             background.dark(120),
01894                             background.dark(120), base);
01895 
01896     QColorGroup colgrp(foreground, background, background.light(highlightVal),
01897                        background.dark(lowlightVal),
01898                        background.dark(120),
01899                        baseText, base);
01900 
01901     int inlowlightVal = lowlightVal-25;
01902     if(inlowlightVal < 120)
01903         inlowlightVal = 120;
01904 
01905     colgrp.setColor(QColorGroup::Highlight, highlight);
01906     colgrp.setColor(QColorGroup::HighlightedText, highlightedText);
01907     colgrp.setColor(QColorGroup::Button, button);
01908     colgrp.setColor(QColorGroup::ButtonText, buttonText);
01909     colgrp.setColor(QColorGroup::Midlight, background.light(110));
01910     colgrp.setColor(QColorGroup::Link, link);
01911     colgrp.setColor(QColorGroup::LinkVisited, visitedLink);
01912 
01913     disabledgrp.setColor(QColorGroup::Button, button);
01914 
01915     QColor disbtntext = buttonText;
01916     disbtntext.hsv( &h, &s, &v );
01917     if (v > 128)
01918     // dark button, light buttonText - need a darker disabled buttonText
01919     disbtntext = disbtntext.dark(lowlightVal);
01920     else if (disbtntext != black)
01921     // light buttonText, dark button - need a lighter disabled buttonText - but only if !black
01922     disbtntext = disbtntext.light(highlightVal);
01923     else
01924     // black button - use darkgray disabled buttonText
01925     disbtntext = Qt::darkGray;
01926 
01927     disabledgrp.setColor(QColorGroup::ButtonText, disbtntext);
01928     disabledgrp.setColor(QColorGroup::Midlight, background.light(110));
01929     disabledgrp.setColor(QColorGroup::Highlight, highlight.dark(120));
01930     disabledgrp.setColor(QColorGroup::Link, link);
01931     disabledgrp.setColor(QColorGroup::LinkVisited, visitedLink);
01932 
01933     return QPalette(colgrp, disabledgrp, colgrp);
01934 }
01935 
01936 
01937 void KApplication::kdisplaySetPalette()
01938 {
01939     QApplication::setPalette( createApplicationPalette(), true);
01940     emit kdisplayPaletteChanged();
01941     emit appearanceChanged();
01942 }
01943 
01944 
01945 void KApplication::kdisplaySetFont()
01946 {
01947     QApplication::setFont(KGlobalSettings::generalFont(), true);
01948     QApplication::setFont(KGlobalSettings::menuFont(), true, "QMenuBar");
01949     QApplication::setFont(KGlobalSettings::menuFont(), true, "QPopupMenu");
01950     QApplication::setFont(KGlobalSettings::menuFont(), true, "KPopupTitle");
01951 
01952     // "patch" standard QStyleSheet to follow our fonts
01953     QStyleSheet* sheet = QStyleSheet::defaultSheet();
01954     sheet->item ("pre")->setFontFamily (KGlobalSettings::fixedFont().family());
01955     sheet->item ("code")->setFontFamily (KGlobalSettings::fixedFont().family());
01956     sheet->item ("tt")->setFontFamily (KGlobalSettings::fixedFont().family());
01957 
01958     emit kdisplayFontChanged();
01959     emit appearanceChanged();
01960 }
01961 
01962 
01963 void KApplication::kdisplaySetStyle()
01964 {
01965     if (useStyles)
01966     {
01967         applyGUIStyle();
01968         emit kdisplayStyleChanged();
01969         emit appearanceChanged();
01970     }
01971 }
01972 
01973 
01974 void KApplication::propagateSettings(SettingsCategory arg)
01975 {
01976     KConfigBase* config = KGlobal::config();
01977     KConfigGroupSaver saver( config, "KDE" );
01978 
01979 #ifdef QT_HAVE_MAX_IMAGE_SIZE
01980     QSize maxImageSize(4096, 4096);
01981     maxImageSize = config->readSizeEntry("MaxImageSize", &maxImageSize);
01982     QImage::setMaxImageSize(maxImageSize);
01983 #endif
01984 
01985     int num = config->readNumEntry("CursorBlinkRate", QApplication::cursorFlashTime());
01986     if ((num != 0) && (num < 200))
01987         num = 200;
01988     if (num > 2000)
01989         num = 2000;
01990     QApplication::setCursorFlashTime(num);
01991     num = config->readNumEntry("DoubleClickInterval", QApplication::doubleClickInterval());
01992     QApplication::setDoubleClickInterval(num);
01993     num = config->readNumEntry("StartDragTime", QApplication::startDragTime());
01994     QApplication::setStartDragTime(num);
01995     num = config->readNumEntry("StartDragDist", QApplication::startDragDistance());
01996     QApplication::setStartDragDistance(num);
01997     num = config->readNumEntry("WheelScrollLines", QApplication::wheelScrollLines());
01998     QApplication::setWheelScrollLines(num);
01999 
02000     bool b = config->readBoolEntry("EffectAnimateMenu", false);
02001     QApplication::setEffectEnabled( Qt::UI_AnimateMenu, b);
02002     b = config->readBoolEntry("EffectFadeMenu", false);
02003     QApplication::setEffectEnabled( Qt::UI_FadeMenu, b);
02004     b = config->readBoolEntry("EffectAnimateCombo", false);
02005     QApplication::setEffectEnabled( Qt::UI_AnimateCombo, b);
02006     b = config->readBoolEntry("EffectAnimateTooltip", false);
02007     QApplication::setEffectEnabled( Qt::UI_AnimateTooltip, b);
02008     b = config->readBoolEntry("EffectFadeTooltip", false);
02009     QApplication::setEffectEnabled( Qt::UI_FadeTooltip, b);
02010     b = !config->readBoolEntry("EffectNoTooltip", false);
02011     QToolTip::setGloballyEnabled( b );
02012 
02013     emit settingsChanged(arg);
02014 }
02015 
02016 void KApplication::installKDEPropertyMap()
02017 {
02018 #ifndef QT_NO_SQL
02019     static bool installed = false;
02020     if (installed) return;
02021     installed = true;
02028     // QSqlPropertyMap takes ownership of the new default map.
02029     QSqlPropertyMap *kdeMap = new QSqlPropertyMap;
02030     kdeMap->insert( "KColorButton", "color" );
02031     kdeMap->insert( "KComboBox", "currentItem" );
02032     kdeMap->insert( "KDatePicker", "date" );
02033     kdeMap->insert( "KDateWidget", "date" );
02034     kdeMap->insert( "KDateTimeWidget", "dateTime" );
02035     kdeMap->insert( "KEditListBox", "currentItem" );
02036     kdeMap->insert( "KFontCombo", "family" );
02037     kdeMap->insert( "KFontRequester", "font" );
02038     kdeMap->insert( "KFontChooser", "font" );
02039     kdeMap->insert( "KHistoryCombo", "currentItem" );
02040     kdeMap->insert( "KListBox", "currentItem" );
02041     kdeMap->insert( "KLineEdit", "text" );
02042     kdeMap->insert( "KRestrictedLine", "text" );
02043     kdeMap->insert( "KSqueezedTextLabel", "text" );
02044     kdeMap->insert( "KTextBrowser", "source" );
02045     kdeMap->insert( "KTextEdit", "text" );
02046     kdeMap->insert( "KURLRequester", "url" );
02047     kdeMap->insert( "KPasswordEdit", "password" );
02048     kdeMap->insert( "KIntNumInput", "value" );
02049     kdeMap->insert( "KIntSpinBox", "value" );
02050     kdeMap->insert( "KDoubleNumInput", "value" );
02051     #if QT_VERSION < 0x030200
02052       kdeMap->insert( "QRadioButton", "checked" );
02053     #endif
02054     //#if QT_VERSION < 0x030300
02055       // Temp til fixed in QT then enable ifdef with the correct version num
02056       kdeMap->insert( "QGroupBox", "checked" );
02057       kdeMap->insert( "QTabWidget", "currentPage" );
02058     //#endif
02059     QSqlPropertyMap::installDefaultMap( kdeMap );
02060 #endif
02061 }
02062 
02063 void KApplication::invokeHelp( const QString& anchor,
02064                                const QString& _appname) const
02065 {
02066     return invokeHelp( anchor, _appname, "" );
02067 }
02068 
02069 void KApplication::invokeHelp( const QString& anchor,
02070                                const QString& _appname,
02071                                const QCString& startup_id ) const
02072 {
02073    QString url;
02074    QString appname;
02075    if (_appname.isEmpty())
02076      appname = name();
02077    else
02078      appname = _appname;
02079 
02080    if (!anchor.isEmpty())
02081      url = QString("help:/%1?anchor=%2").arg(appname).arg(anchor);
02082    else
02083      url = QString("help:/%1/index.html").arg(appname);
02084 
02085    QString error;
02086    if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02087    {
02088        if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, startup_id, false))
02089        {
02090            if (Tty != kapp->type())
02091                QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02092                i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02093            else
02094                kdWarning() << "Could not launch help:\n" << error << endl;
02095        return;
02096        }
02097    }
02098    else
02099        DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url, startup_id );
02100 }
02101 
02102 void KApplication::invokeHTMLHelp( const QString& _filename, const QString& topic ) const
02103 {
02104    kdWarning() << "invoking HTML help is deprecated! use docbook and invokeHelp!\n";
02105 
02106    QString filename;
02107 
02108    if( _filename.isEmpty() )
02109      filename = QString(name()) + "/index.html";
02110    else
02111      filename = _filename;
02112 
02113    QString url;
02114    if (!topic.isEmpty())
02115      url = QString("help:/%1#%2").arg(filename).arg(topic);
02116    else
02117      url = QString("help:/%1").arg(filename);
02118 
02119    QString error;
02120    if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02121    {
02122        if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, "", false))
02123        {
02124            if (Tty != kapp->type())
02125                QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02126                i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02127            else
02128                kdWarning() << "Could not launch help:\n" << error << endl;
02129            return;
02130        }
02131    }
02132    else
02133        DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url );
02134 }
02135 
02136 
02137 void KApplication::invokeMailer(const QString &address, const QString &subject)
02138 {
02139     return invokeMailer(address,subject,"");
02140 }
02141 
02142 void KApplication::invokeMailer(const QString &address, const QString &subject, const QCString& startup_id)
02143 {
02144    invokeMailer(address, QString::null, QString::null, subject, QString::null, QString::null,
02145        QStringList(), startup_id );
02146 }
02147 
02148 void KApplication::invokeMailer(const KURL &mailtoURL)
02149 {
02150     return invokeMailer( mailtoURL, "" );
02151 }
02152 
02153 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id )
02154 {
02155     return invokeMailer( mailtoURL, startup_id, false);
02156 }
02157 
02158 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id, bool allowAttachments )
02159 {
02160    QString address = KURL::decode_string(mailtoURL.path()), subject, cc, bcc, body;
02161    QStringList queries = QStringList::split('&', mailtoURL.query().mid(1));
02162    QStringList attachURLs;
02163    for (QStringList::Iterator it = queries.begin(); it != queries.end(); ++it)
02164    {
02165      QString q = (*it).lower();
02166      if (q.startsWith("subject="))
02167        subject = KURL::decode_string((*it).mid(8));
02168      else
02169      if (q.startsWith("cc="))
02170        cc = cc.isEmpty()? KURL::decode_string((*it).mid(3)): cc + ',' + KURL::decode_string((*it).mid(3));
02171      else
02172      if (q.startsWith("bcc="))
02173        bcc = bcc.isEmpty()? KURL::decode_string((*it).mid(4)): bcc + ',' + KURL::decode_string((*it).mid(4));
02174      else
02175      if (q.startsWith("body="))
02176        body = KURL::decode_string((*it).mid(5));
02177      else
02178      if (allowAttachments && q.startsWith("attach="))
02179        attachURLs.push_back(KURL::decode_string((*it).mid(7)));
02180      else
02181      if (allowAttachments && q.startsWith("attachment="))
02182        attachURLs.push_back(KURL::decode_string((*it).mid(11)));
02183      else
02184      if (q.startsWith("to="))
02185        address = address.isEmpty()? KURL::decode_string((*it).mid(3)): address + ',' + KURL::decode_string((*it).mid(3));
02186    }
02187 
02188    invokeMailer( address, cc, bcc, subject, body, QString::null, attachURLs, startup_id );
02189 }
02190 
02191 void KApplication::invokeMailer(const QString &to, const QString &cc, const QString &bcc,
02192                                 const QString &subject, const QString &body,
02193                                 const QString & messageFile, const QStringList &attachURLs)
02194 {
02195     return invokeMailer(to,cc,bcc,subject,body,messageFile,attachURLs,"");
02196 }
02197 
02198 void KApplication::invokeMailer(const QString &to, const QString &cc, const QString &bcc,
02199                                 const QString &subject, const QString &body,
02200                                 const QString & /*messageFile TODO*/, const QStringList &attachURLs,
02201                                 const QCString& startup_id )
02202 {
02203    KConfig config("emaildefaults");
02204 
02205    config.setGroup("Defaults");
02206    QString group = config.readEntry("Profile","Default");
02207 
02208    config.setGroup( QString("PROFILE_%1").arg(group) );
02209    QString command = config.readPathEntry("EmailClient");
02210 
02211    if (command.isEmpty() || command == QString::fromLatin1("kmail")
02212        || command.endsWith("/kmail"))
02213      command = QString::fromLatin1("kmail --composer -s %s -c %c -b %b --body %B --attach %A -- %t");
02214 
02215    if (config.readBoolEntry("TerminalClient", false))
02216    {
02217      KConfigGroup confGroup( KGlobal::config(), "General" );
02218      QString preferredTerminal = confGroup.readPathEntry("TerminalApplication", "konsole");
02219      command = preferredTerminal + " -e " + command;
02220    }
02221 
02222    QStringList cmdTokens = KShell::splitArgs(command);
02223    QString cmd = cmdTokens[0];
02224    cmdTokens.remove(cmdTokens.begin());
02225 
02226    QMap<QChar, QString> keyMap;
02227    keyMap.insert('t', to);
02228    keyMap.insert('s', subject);
02229    keyMap.insert('c', cc);
02230    keyMap.insert('b', bcc);
02231    keyMap.insert('B', body);
02232 
02233    for (QStringList::Iterator it = cmdTokens.begin(); it != cmdTokens.end(); )
02234    {
02235      if (*it == "%A")
02236      {
02237          if (it == cmdTokens.begin()) // better safe than sorry ...
02238              continue;
02239          QStringList::ConstIterator urlit = attachURLs.begin();
02240          QStringList::ConstIterator urlend = attachURLs.end();
02241          if ( urlit != urlend )
02242          {
02243              QStringList::Iterator previt = it;
02244              --previt;
02245              *it = *urlit;
02246              ++it;
02247              while ( ++urlit != urlend )
02248              {
02249                  cmdTokens.insert( it, *previt );
02250                  cmdTokens.insert( it, *urlit );
02251              }
02252          } else {
02253              --it;
02254              it = cmdTokens.remove( cmdTokens.remove( it ) );
02255          }
02256      } else {
02257          *it = KMacroExpander::expandMacros(*it, keyMap);
02258          ++it;
02259      }
02260    }
02261 
02262    QString error;
02263    // TODO this should check if cmd has a .desktop file, and use data from it, together
02264    // with sending more ASN data
02265    if (kdeinitExec(cmd, cmdTokens, &error, NULL, startup_id ))
02266      if (Tty != kapp->type())
02267        QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Mail Client"),
02268              i18n("Could not launch the mail client:\n\n%1").arg(error), i18n("&OK"));
02269      else
02270        kdWarning() << "Could not launch mail client:\n" << error << endl;
02271 }
02272 
02273 
02274 void KApplication::invokeBrowser( const QString &url )
02275 {
02276     return invokeBrowser( url, "" );
02277 }
02278 
02279 void KApplication::invokeBrowser( const QString &url, const QCString& startup_id )
02280 {
02281    QString error;
02282 
02283    if (startServiceByDesktopName("kfmclient", url, &error, 0, 0, startup_id, false))
02284    {
02285       if (Tty != kapp->type())
02286           QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Browser"),
02287                i18n("Could not launch the browser:\n\n%1").arg(error), i18n("&OK"));
02288       else
02289           kdWarning() << "Could not launch browser:\n" << error << endl;
02290       return;
02291    }
02292 }
02293 
02294 void KApplication::cut()
02295 {
02296   invokeEditSlot( SLOT( cut() ) );
02297 }
02298 
02299 void KApplication::copy()
02300 {
02301   invokeEditSlot( SLOT( copy() ) );
02302 }
02303 
02304 void KApplication::paste()
02305 {
02306   invokeEditSlot( SLOT( paste() ) );
02307 }
02308 
02309 void KApplication::clear()
02310 {
02311   invokeEditSlot( SLOT( clear() ) );
02312 }
02313 
02314 void KApplication::selectAll()
02315 {
02316   invokeEditSlot( SLOT( selectAll() ) );
02317 }
02318 
02319 QCString
02320 KApplication::launcher()
02321 {
02322    return "klauncher";
02323 }
02324 
02325 static int
02326 startServiceInternal( const QCString &function,
02327               const QString& _name, const QStringList &URLs,
02328               QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02329 {
02330    struct serviceResult
02331    {
02332       int result;
02333       QCString dcopName;
02334       QString error;
02335       pid_t pid;
02336    };
02337 
02338    // Register app as able to send DCOP messages
02339    DCOPClient *dcopClient;
02340    if (kapp)
02341       dcopClient = kapp->dcopClient();
02342    else
02343       dcopClient = new DCOPClient;
02344 
02345    if (!dcopClient->isAttached())
02346    {
02347       if (!dcopClient->attach())
02348       {
02349          if (error)
02350             *error = i18n("Could not register with DCOP.\n");
02351          return -1;
02352       }
02353    }
02354    QByteArray params;
02355    QDataStream stream(params, IO_WriteOnly);
02356    stream << _name << URLs;
02357    QCString replyType;
02358    QByteArray replyData;
02359    QCString _launcher = KApplication::launcher();
02360    QValueList<QCString> envs;
02361 #ifdef Q_WS_X11
02362    if (qt_xdisplay()) {
02363        QCString dpystring(XDisplayString(qt_xdisplay()));
02364        envs.append( QCString("DISPLAY=") + dpystring );
02365    } else if( getenv( "DISPLAY" )) {
02366        QCString dpystring( getenv( "DISPLAY" ));
02367        envs.append( QCString("DISPLAY=") + dpystring );
02368    }
02369 #endif
02370    stream << envs;
02371    // make sure there is id, so that user timestamp exists
02372    stream << ( startup_id.isEmpty() ? KStartupInfo::createNewStartupId() : startup_id );
02373    if( function.left( 12 ) != "kdeinit_exec" )
02374        stream << noWait;
02375 
02376    if (!dcopClient->call(_launcher, _launcher,
02377         function, params, replyType, replyData))
02378    {
02379         if (error)
02380            *error = i18n("KLauncher could not be reached via DCOP.\n");
02381         if (!kapp)
02382            delete dcopClient;
02383         return -1;
02384    }
02385    if (!kapp)
02386       delete dcopClient;
02387 
02388    if (noWait)
02389       return 0;
02390 
02391    QDataStream stream2(replyData, IO_ReadOnly);
02392    serviceResult result;
02393    stream2 >> result.result >> result.dcopName >> result.error >> result.pid;
02394    if (dcopService)
02395       *dcopService = result.dcopName;
02396    if (error)
02397       *error = result.error;
02398    if (pid)
02399       *pid = result.pid;
02400    return result.result;
02401 }
02402 
02403 int
02404 KApplication::startServiceByName( const QString& _name, const QString &URL,
02405                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02406 {
02407    QStringList URLs;
02408    if (!URL.isEmpty())
02409       URLs.append(URL);
02410    return startServiceInternal(
02411                       "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02412                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02413 }
02414 
02415 int
02416 KApplication::startServiceByName( const QString& _name, const QStringList &URLs,
02417                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02418 {
02419    return startServiceInternal(
02420                       "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02421                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02422 }
02423 
02424 int
02425 KApplication::startServiceByDesktopPath( const QString& _name, const QString &URL,
02426                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02427 {
02428    QStringList URLs;
02429    if (!URL.isEmpty())
02430       URLs.append(URL);
02431    return startServiceInternal(
02432                       "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02433                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02434 }
02435 
02436 int
02437 KApplication::startServiceByDesktopPath( const QString& _name, const QStringList &URLs,
02438                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02439 {
02440    return startServiceInternal(
02441                       "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02442                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02443 }
02444 
02445 int
02446 KApplication::startServiceByDesktopName( const QString& _name, const QString &URL,
02447                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02448 {
02449    QStringList URLs;
02450    if (!URL.isEmpty())
02451       URLs.append(URL);
02452    return startServiceInternal(
02453                       "start_service_by_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02454                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02455 }
02456 
02457 int
02458 KApplication::startServiceByDesktopName( const QString& _name, const QStringList &URLs,
02459                   QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02460 {
02461    return startServiceInternal(
02462                       "start_service_by_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02463                       _name, URLs, error, dcopService, pid, startup_id, noWait);
02464 }
02465 
02466 int
02467 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02468                            QString *error, int *pid )
02469 {
02470     return kdeinitExec( name, args, error, pid, "" );
02471 }
02472 
02473 int
02474 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02475                            QString *error, int *pid, const QCString& startup_id )
02476 {
02477    return startServiceInternal("kdeinit_exec(QString,QStringList,QValueList<QCString>,QCString)",
02478         name, args, error, 0, pid, startup_id, false);
02479 }
02480 
02481 int
02482 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02483                            QString *error, int *pid )
02484 {
02485     return kdeinitExecWait( name, args, error, pid, "" );
02486 }
02487 
02488 int
02489 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02490                            QString *error, int *pid, const QCString& startup_id )
02491 {
02492    return startServiceInternal("kdeinit_exec_wait(QString,QStringList,QValueList<QCString>,QCString)",
02493         name, args, error, 0, pid, startup_id, false);
02494 }
02495 
02496 QString KApplication::tempSaveName( const QString& pFilename ) const
02497 {
02498   QString aFilename;
02499 
02500   if( pFilename[0] != '/' )
02501     {
02502       kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02503       aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02504     }
02505   else
02506     aFilename = pFilename;
02507 
02508   QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02509   if( !aAutosaveDir.exists() )
02510     {
02511       if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02512         {
02513           // Last chance: use temp dir
02514           aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02515         }
02516     }
02517 
02518   aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02519 
02520   return aFilename;
02521 }
02522 
02523 
02524 QString KApplication::checkRecoverFile( const QString& pFilename,
02525         bool& bRecover ) const
02526 {
02527   QString aFilename;
02528 
02529   if( pFilename[0] != '/' )
02530     {
02531       kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02532       aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02533     }
02534   else
02535     aFilename = pFilename;
02536 
02537   QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02538   if( !aAutosaveDir.exists() )
02539     {
02540       if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02541         {
02542           // Last chance: use temp dir
02543           aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02544         }
02545     }
02546 
02547   aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02548 
02549   if( QFile( aFilename ).exists() )
02550     {
02551       bRecover = true;
02552       return aFilename;
02553     }
02554   else
02555     {
02556       bRecover = false;
02557       return pFilename;
02558     }
02559 }
02560 
02561 
02562 bool checkAccess(const QString& pathname, int mode)
02563 {
02564   int accessOK = access( QFile::encodeName(pathname), mode );
02565   if ( accessOK == 0 )
02566     return true;  // OK, I can really access the file
02567 
02568   // else
02569   // if we want to write the file would be created. Check, if the
02570   // user may write to the directory to create the file.
02571   if ( (mode & W_OK) == 0 )
02572     return false;   // Check for write access is not part of mode => bail out
02573 
02574 
02575   if (!access( QFile::encodeName(pathname), F_OK)) // if it already exists
02576       return false;
02577 
02578   //strip the filename (everything until '/' from the end
02579   QString dirName(pathname);
02580   int pos = dirName.findRev('/');
02581   if ( pos == -1 )
02582     return false;   // No path in argument. This is evil, we won't allow this
02583   else if ( pos == 0 ) // don't turn e.g. /root into an empty string
02584       pos = 1;
02585 
02586   dirName.truncate(pos); // strip everything starting from the last '/'
02587 
02588   accessOK = access( QFile::encodeName(dirName), W_OK );
02589   // -?- Can I write to the accessed diretory
02590   if ( accessOK == 0 )
02591     return true;  // Yes
02592   else
02593     return false; // No
02594 }
02595 
02596 void KApplication::setTopWidget( QWidget *topWidget )
02597 {
02598   if( !topWidget )
02599       return;
02600 
02601     // set the specified caption
02602     if ( !topWidget->inherits("KMainWindow") ) { // KMainWindow does this already for us
02603         topWidget->setCaption( caption() );
02604     }
02605 
02606     // set the specified icons
02607     topWidget->setIcon( icon() ); //standard X11
02608 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
02609 //#ifdef Q_WS_X11 // FIXME(E): Implement for Qt/Embedded
02610     KWin::setIcons(topWidget->winId(), icon(), miniIcon() ); // NET_WM hints for KWin
02611 
02612     // set the app startup notification window property
02613     KStartupInfo::setWindowStartupId( topWidget->winId(), startupId());
02614 #endif
02615 }
02616 
02617 QCString KApplication::startupId() const
02618 {
02619     return d->startup_id;
02620 }
02621 
02622 void KApplication::setStartupId( const QCString& startup_id )
02623 {
02624     if( startup_id.isEmpty())
02625         d->startup_id = "0";
02626     else
02627         {
02628         d->startup_id = startup_id;
02629         KStartupInfoId id;
02630         id.initId( startup_id );
02631         long timestamp = id.timestamp();
02632         if( timestamp != 0 )
02633             updateUserTimestamp( timestamp );
02634         }
02635 }
02636 
02637 // read the startup notification env variable, save it and unset it in order
02638 // not to propagate it to processes started from this app
02639 void KApplication::read_app_startup_id()
02640 {
02641 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
02642     KStartupInfoId id = KStartupInfo::currentStartupIdEnv();
02643     KStartupInfo::resetStartupEnv();
02644     d->startup_id = id.id();
02645 #endif
02646 }
02647 
02648 int KApplication::random()
02649 {
02650    static int init = false;
02651    if (!init)
02652    {
02653       unsigned int seed;
02654       init = true;
02655       int fd = open("/dev/urandom", O_RDONLY);
02656       if (fd <= 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed))
02657       {
02658             // No /dev/urandom... try something else.
02659             srand(getpid());
02660             seed = rand()+time(0);
02661       }
02662       if (fd >= 0) close(fd);
02663       srand(seed);
02664    }
02665    return rand();
02666 }
02667 
02668 QString KApplication::randomString(int length)
02669 {
02670    if (length <=0 ) return QString::null;
02671 
02672    QString str; str.setLength( length );
02673    int i = 0;
02674    while (length--)
02675    {
02676       int r=random() % 62;
02677       r+=48;
02678       if (r>57) r+=7;
02679       if (r>90) r+=6;
02680       str[i++] =  char(r);
02681       // so what if I work backwards?
02682    }
02683    return str;
02684 }
02685 
02686 bool KApplication::authorize(const QString &genericAction)
02687 {
02688    if (!d->actionRestrictions)
02689       return true;
02690 
02691    KConfig *config = KGlobal::config();
02692    KConfigGroupSaver saver( config, "KDE Action Restrictions" );
02693    return config->readBoolEntry(genericAction, true);
02694 }
02695 
02696 bool KApplication::authorizeKAction(const char *action)
02697 {
02698    if (!d->actionRestrictions || !action)
02699       return true;
02700 
02701    static const QString &action_prefix = KGlobal::staticQString( "action/" );
02702 
02703    return authorize(action_prefix + action);
02704 }
02705 
02706 bool KApplication::authorizeControlModule(const QString &menuId)
02707 {
02708    if (menuId.isEmpty() || kde_kiosk_exception)
02709       return true;
02710    KConfig *config = KGlobal::config();
02711    KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02712    return config->readBoolEntry(menuId, true);
02713 }
02714 
02715 QStringList KApplication::authorizeControlModules(const QStringList &menuIds)
02716 {
02717    KConfig *config = KGlobal::config();
02718    KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02719    QStringList result;
02720    for(QStringList::ConstIterator it = menuIds.begin();
02721        it != menuIds.end(); ++it)
02722    {
02723       if (config->readBoolEntry(*it, true))
02724          result.append(*it);
02725    }
02726    return result;
02727 }
02728 
02729 void KApplication::initUrlActionRestrictions()
02730 {
02731   d->urlActionRestrictions.setAutoDelete(true);
02732   d->urlActionRestrictions.clear();
02733   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02734   ("open", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
02735   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02736   ("list", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
02737 // TEST:
02738 //  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02739 //  ("list", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, false));
02740 //  d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02741 //  ("list", QString::null, QString::null, QString::null, "file", QString::null, QDir::homeDirPath(), true));
02742   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02743   ("link", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
02744   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02745   ("redirect", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
02746 
02747   // We allow redirections to file: but not from internet protocols, redirecting to file:
02748   // is very popular among io-slaves and we don't want to break them
02749   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02750   ("redirect", QString::null, QString::null, QString::null, "file", QString::null, QString::null, true));
02751   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02752   ("redirect", ":internet", QString::null, QString::null, "file", QString::null, QString::null, false));
02753 
02754   // local protocols may redirect everywhere
02755   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02756   ("redirect", ":local", QString::null, QString::null, QString::null, QString::null, QString::null, true));
02757 
02758   // Anyone may redirect to about:
02759   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02760   ("redirect", QString::null, QString::null, QString::null, "about", QString::null, QString::null, true));
02761 
02762   // Anyone may redirect to itself, cq. within it's own group
02763   d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02764   ("redirect", QString::null, QString::null, QString::null, "=", QString::null, QString::null, true));
02765 
02766   KConfig *config = KGlobal::config();
02767   KConfigGroupSaver saver( config, "KDE URL Restrictions" );
02768   int count = config->readNumEntry("rule_count");
02769   QString keyFormat = QString("rule_%1");
02770   for(int i = 1; i <= count; i++)
02771   {
02772     QString key = keyFormat.arg(i);
02773     QStringList rule = config->readListEntry(key);
02774     if (rule.count() != 8)
02775       continue;
02776     QString action = rule[0];
02777     QString refProt = rule[1];
02778     QString refHost = rule[2];
02779     QString refPath = rule[3];
02780     QString urlProt = rule[4];
02781     QString urlHost = rule[5];
02782     QString urlPath = rule[6];
02783     QString strEnabled = rule[7].lower();
02784 
02785     bool bEnabled = (strEnabled == "true");
02786 
02787     if (refPath.startsWith("$HOME"))
02788        refPath.replace(0, 5, QDir::homeDirPath());
02789     else if (refPath.startsWith("~"))
02790        refPath.replace(0, 1, QDir::homeDirPath());
02791     if (urlPath.startsWith("$HOME"))
02792        urlPath.replace(0, 5, QDir::homeDirPath());
02793     else if (urlPath.startsWith("~"))
02794        urlPath.replace(0, 1, QDir::homeDirPath());
02795 
02796     if (refPath.startsWith("$TMP"))
02797        refPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
02798     if (urlPath.startsWith("$TMP"))
02799        urlPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
02800 
02801     d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
02802         ( action, refProt, refHost, refPath, urlProt, urlHost, urlPath, bEnabled));
02803   }
02804 }
02805 
02806 void KApplication::allowURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
02807 {
02808   if (authorizeURLAction(action, _baseURL, _destURL))
02809      return;
02810 
02811   d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
02812         ( action, _baseURL.protocol(), _baseURL.host(), _baseURL.path(-1),
02813                   _destURL.protocol(), _destURL.host(), _destURL.path(-1), true));
02814 }
02815 
02816 bool KApplication::authorizeURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
02817 {
02818   if (_destURL.isEmpty())
02819      return true;
02820 
02821   bool result = false;
02822   if (d->urlActionRestrictions.isEmpty())
02823      initUrlActionRestrictions();
02824 
02825   KURL baseURL(_baseURL);
02826   baseURL.setPath(QDir::cleanDirPath(baseURL.path()));
02827   QString baseClass = KProtocolInfo::protocolClass(baseURL.protocol());
02828   KURL destURL(_destURL);
02829   destURL.setPath(QDir::cleanDirPath(destURL.path()));
02830   QString destClass = KProtocolInfo::protocolClass(destURL.protocol());
02831 
02832   for(KApplicationPrivate::URLActionRule *rule = d->urlActionRestrictions.first();
02833       rule; rule = d->urlActionRestrictions.next())
02834   {
02835      if ((result != rule->permission) && // No need to check if it doesn't make a difference
02836          (action == rule->action) &&
02837          rule->baseMatch(baseURL, baseClass) &&
02838          rule->destMatch(destURL, destClass, baseURL, baseClass))
02839      {
02840         result = rule->permission;
02841      }
02842   }
02843   return result;
02844 }
02845 
02846 
02847 uint KApplication::keyboardModifiers()
02848 {
02849     Window root;
02850     Window child;
02851     int root_x, root_y, win_x, win_y;
02852     uint keybstate;
02853     XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
02854                    &root_x, &root_y, &win_x, &win_y, &keybstate );
02855     return keybstate & 0x00ff;
02856 }
02857 
02858 uint KApplication::mouseState()
02859 {
02860     Window root;
02861     Window child;
02862     int root_x, root_y, win_x, win_y;
02863     uint keybstate;
02864     XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
02865                    &root_x, &root_y, &win_x, &win_y, &keybstate );
02866     return keybstate & 0xff00;
02867 }
02868 
02869 void KApplication::installSigpipeHandler()
02870 {
02871     struct sigaction act;
02872     act.sa_handler = SIG_IGN;
02873     sigemptyset( &act.sa_mask );
02874     act.sa_flags = 0;
02875     sigaction( SIGPIPE, &act, 0 );
02876 }
02877 
02878 void KApplication::sigpipeHandler(int)
02879 {
02880     int saved_errno = errno;
02881     // Using kdDebug from a signal handler is not a good idea.
02882 #ifndef NDEBUG
02883     char msg[1000];
02884     sprintf(msg, "*** SIGPIPE *** (ignored, pid = %ld)\n", (long) getpid());
02885     write(2, msg, strlen(msg));
02886 #endif
02887 
02888     // Do nothing.
02889     errno = saved_errno;
02890 }
02891 
02892 bool KApplication::guiEnabled()
02893 {
02894     return kapp && kapp->d->guiEnabled;
02895 }
02896 
02897 void KApplication::virtual_hook( int id, void* data )
02898 { KInstance::virtual_hook( id, data ); }
02899 
02900 void KSessionManaged::virtual_hook( int, void* )
02901 { /*BASE::virtual_hook( id, data );*/ }
02902 
02903 #include "kapplication.moc"
KDE Logo
This file is part of the documentation for kdecore Library Version 3.3.2.
Documentation copyright © 1996-2004 the KDE developers.
Generated on Fri Jul 22 10:16:15 2005 by doxygen 1.3.6 written by Dimitri van Heesch, © 1997-2003