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.3 2004/12/29 22:15:25 mbuesch 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 #ifndef QT_NO_SQL
00047 #include <qsqlpropertymap.h>
00048 #endif
00049 
00050 #undef QT_NO_TRANSLATION
00051 #include "kapplication.h"
00052 #define QT_NO_TRANSLATION
00053 #include <kglobal.h>
00054 #include <kstandarddirs.h>
00055 #include <kdebug.h>
00056 #include <klocale.h>
00057 #include <kstyle.h>
00058 #include <kiconloader.h>
00059 #include <kclipboard.h>
00060 #include <kconfig.h>
00061 #include <ksimpleconfig.h>
00062 #include <kcmdlineargs.h>
00063 #include <kaboutdata.h>
00064 #include <kglobalsettings.h>
00065 #include <kcrash.h>
00066 #include <kdatastream.h>
00067 #include <klibloader.h>
00068 #include <kmimesourcefactory.h>
00069 #include <kstdaccel.h>
00070 #include <kaccel.h>
00071 #include "kcheckaccelerators.h"
00072 #include <qptrdict.h>
00073 #include <kmacroexpander.h>
00074 #include <kshell.h>
00075 #include <kprotocolinfo.h>
00076 
00077 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00078 #include <kstartupinfo.h>
00079 #endif
00080 
00081 #include <dcopclient.h>
00082 #include <dcopref.h>
00083 
00084 #include <sys/types.h>
00085 #ifdef HAVE_SYS_STAT_H
00086 #include <sys/stat.h>
00087 #endif
00088 #include <sys/wait.h>
00089 
00090 #include "kwin.h"
00091 
00092 #include <fcntl.h>
00093 #include <stdlib.h> // getenv(), srand(), rand()
00094 #include <signal.h>
00095 #include <unistd.h>
00096 #include <time.h>
00097 #include <sys/time.h>
00098 #include <errno.h>
00099 #include <string.h>
00100 #include <netdb.h>
00101 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00102 //#ifndef Q_WS_QWS //FIXME(E): NetWM should talk to QWS...
00103 #include <netwm.h>
00104 #endif
00105 
00106 #include "kprocctrl.h"
00107 
00108 #ifdef HAVE_PATHS_H
00109 #include <paths.h>
00110 #endif
00111 
00112 //#if defined Q_WS_X11 && ! defined K_WS_QTONLY
00113 #ifdef Q_WS_X11
00114 #include <X11/Xlib.h> // schrode
00115 #include <X11/Xutil.h> // schrode
00116 #include <X11/Xatom.h> // schrode
00117 #include <X11/SM/SMlib.h> // schrode
00118 #include <fixx11h.h> // schrode
00119 #endif
00120 #include <KDE-ICE/ICElib.h>
00121 
00122 #ifdef Q_WS_X11
00123 #define DISPLAY "DISPLAY"
00124 #elif defined(Q_WS_QWS)
00125 #define DISPLAY "QWS_DISPLAY"
00126 #endif
00127 
00128 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00129 #include <kipc.h>
00130 #endif
00131 
00132 #include "kappdcopiface.h"
00133 
00134 bool kde_have_kipc = true; // magic hook to disable kipc in kdm
00135 bool kde_kiosk_exception = false; // flag to disable kiosk restrictions
00136 bool kde_kiosk_admin = false;
00137 
00138 KApplication* KApplication::KApp = 0L;
00139 bool KApplication::loadedByKdeinit = false;
00140 DCOPClient *KApplication::s_DCOPClient = 0L;
00141 bool KApplication::s_dcopClientNeedsPostInit = false;
00142 
00143 static Atom atom_DesktopWindow;
00144 static Atom atom_NetSupported;
00145 extern Time qt_x_time;
00146 extern Time qt_x_user_time;
00147 static Atom kde_xdnd_drop;
00148 
00149 // duplicated from patched Qt, so that there won't be unresolved symbols if Qt gets
00150 // replaced by unpatched one
00151 bool qt_qclipboard_bailout_hack = false;
00152 
00153 template class QPtrList<KSessionManaged>;
00154 
00155 #ifdef Q_WS_X11
00156 extern "C" {
00157 static int kde_xio_errhandler( Display * dpy )
00158 {
00159   return kapp->xioErrhandler( dpy );
00160 }
00161 
00162 static int kde_x_errhandler( Display *dpy, XErrorEvent *err )
00163 {
00164   return kapp->xErrhandler( dpy, err );
00165 }
00166 
00167 }
00168 #endif
00169 
00170 extern "C" {
00171 static void kde_ice_ioerrorhandler( IceConn conn )
00172 {
00173     if(kapp)
00174         kapp->iceIOErrorHandler( conn );
00175     // else ignore the error for now
00176 }
00177 }
00178 
00179 /*
00180   Private data to make keeping binary compatibility easier
00181  */
00182 class KApplicationPrivate
00183 {
00184 public:
00185   KApplicationPrivate()
00186     :   actionRestrictions( false ),
00187     refCount( 1 ),
00188     oldIceIOErrorHandler( 0 ),
00189     checkAccelerators( 0 ),
00190     overrideStyle( QString::null ),
00191     startup_id( "0" ),
00192         app_started_timer( NULL ),
00193     m_KAppDCOPInterface( 0L ),
00194     session_save( false ),
00195         oldXErrorHandler( NULL ),
00196         oldXIOErrorHandler( NULL )
00197   {
00198   }
00199 
00200   ~KApplicationPrivate()
00201   {}
00202 
00203 
00204   bool actionRestrictions : 1;
00205   bool guiEnabled : 1;
00212   int refCount;
00213   IceIOErrorHandler oldIceIOErrorHandler;
00214   KCheckAccelerators* checkAccelerators;
00215   QString overrideStyle;
00216   QString geometry_arg;
00217   QCString startup_id;
00218   QTimer* app_started_timer;
00219   KAppDCOPInterface *m_KAppDCOPInterface;
00220   bool session_save;
00221   int (*oldXErrorHandler)(Display*,XErrorEvent*);
00222   int (*oldXIOErrorHandler)(Display*);
00223 
00224   class URLActionRule
00225   {
00226   public:
00227 #define checkExactMatch(s, b) \
00228         if (s.isEmpty()) b = true; \
00229         else if (s[s.length()-1] == '!') \
00230         { b = false; s.truncate(s.length()-1); } \
00231         else b = true;
00232 #define checkStartWildCard(s, b) \
00233         if (s.isEmpty()) b = true; \
00234         else if (s[0] == '*') \
00235         { b = true; s = s.mid(1); } \
00236         else b = false;
00237 #define checkEqual(s, b) \
00238         b = (s == "=");
00239 
00240      URLActionRule(const QString &act,
00241                    const QString &bProt, const QString &bHost, const QString &bPath,
00242                    const QString &dProt, const QString &dHost, const QString &dPath,
00243                    bool perm)
00244                    : action(act),
00245                      baseProt(bProt), baseHost(bHost), basePath(bPath),
00246                      destProt(dProt), destHost(dHost), destPath(dPath),
00247                      permission(perm)
00248                    {
00249                       checkExactMatch(baseProt, baseProtWildCard);
00250                       checkStartWildCard(baseHost, baseHostWildCard);
00251                       checkExactMatch(basePath, basePathWildCard);
00252                       checkExactMatch(destProt, destProtWildCard);
00253                       checkStartWildCard(destHost, destHostWildCard);
00254                       checkExactMatch(destPath, destPathWildCard);
00255                       checkEqual(destProt, destProtEqual);
00256                       checkEqual(destHost, destHostEqual);
00257                    }
00258 
00259      bool baseMatch(const KURL &url, const QString &protClass)
00260      {
00261         if (baseProtWildCard)
00262         {
00263            if ( !baseProt.isEmpty() && !url.protocol().startsWith(baseProt) &&
00264                 (protClass.isEmpty() || (protClass != baseProt)) )
00265               return false;
00266         }
00267         else
00268         {
00269            if ( (url.protocol() != baseProt) &&
00270                 (protClass.isEmpty() || (protClass != baseProt)) )
00271               return false;
00272         }
00273         if (baseHostWildCard)
00274         {
00275            if (!baseHost.isEmpty() && !url.host().endsWith(baseHost))
00276               return false;
00277         }
00278         else
00279         {
00280            if (url.host() != baseHost)
00281               return false;
00282         }
00283         if (basePathWildCard)
00284         {
00285            if (!basePath.isEmpty() && !url.path().startsWith(basePath))
00286               return false;
00287         }
00288         else
00289         {
00290            if (url.path() != basePath)
00291               return false;
00292         }
00293         return true;
00294      }
00295 
00296      bool destMatch(const KURL &url, const QString &protClass, const KURL &base, const QString &baseClass)
00297      {
00298         if (destProtEqual)
00299         {
00300            if ( (url.protocol() != base.protocol()) &&
00301                 (protClass.isEmpty() || baseClass.isEmpty() || protClass != baseClass) )
00302               return false;
00303         }
00304         else if (destProtWildCard)
00305         {
00306            if ( !destProt.isEmpty() && !url.protocol().startsWith(destProt) &&
00307                 (protClass.isEmpty() || (protClass != destProt)) )
00308               return false;
00309         }
00310         else
00311         {
00312            if ( (url.protocol() != destProt) &&
00313                 (protClass.isEmpty() || (protClass != destProt)) )
00314               return false;
00315         }
00316         if (destHostWildCard)
00317         {
00318            if (!destHost.isEmpty() && !url.host().endsWith(destHost))
00319               return false;
00320         }
00321         else if (destHostEqual)
00322         {
00323            if (url.host() != base.host())
00324               return false;
00325         }
00326         else
00327         {
00328            if (url.host() != destHost)
00329               return false;
00330         }
00331         if (destPathWildCard)
00332         {
00333            if (!destPath.isEmpty() && !url.path().startsWith(destPath))
00334               return false;
00335         }
00336         else
00337         {
00338            if (url.path() != destPath)
00339               return false;
00340         }
00341         return true;
00342      }
00343 
00344      QString action;
00345      QString baseProt;
00346      QString baseHost;
00347      QString basePath;
00348      QString destProt;
00349      QString destHost;
00350      QString destPath;
00351      bool baseProtWildCard : 1;
00352      bool baseHostWildCard : 1;
00353      bool basePathWildCard : 1;
00354      bool destProtWildCard : 1;
00355      bool destHostWildCard : 1;
00356      bool destPathWildCard : 1;
00357      bool destProtEqual    : 1;
00358      bool destHostEqual    : 1;
00359      bool permission;
00360   };
00361   QPtrList<URLActionRule> urlActionRestrictions;
00362 
00363     QString sessionKey;
00364     QString pSessionConfigFile;
00365 };
00366 
00367 
00368 static QPtrList<QWidget>*x11Filter = 0;
00369 static bool autoDcopRegistration = true;
00370 
00371 void KApplication::installX11EventFilter( QWidget* filter )
00372 {
00373     if ( !filter )
00374         return;
00375     if (!x11Filter)
00376         x11Filter = new QPtrList<QWidget>;
00377     connect ( filter, SIGNAL( destroyed() ), this, SLOT( x11FilterDestroyed() ) );
00378     x11Filter->append( filter );
00379 }
00380 
00381 void KApplication::x11FilterDestroyed()
00382 {
00383     removeX11EventFilter( static_cast< const QWidget* >( sender()));
00384 }
00385 
00386 void KApplication::removeX11EventFilter( const QWidget* filter )
00387 {
00388     if ( !x11Filter || !filter )
00389         return;
00390     x11Filter->removeRef( filter );
00391     if ( x11Filter->isEmpty() ) {
00392         delete x11Filter;
00393         x11Filter = 0;
00394     }
00395 }
00396 
00397 // FIXME: remove this when we've get a better method of
00398 // customizing accelerator handling -- hopefully in Qt.
00399 // For now, this is set whenever an accelerator is overridden
00400 // in KAccelEventHandler so that the AccelOverride isn't sent twice. -- ellis, 19/10/02
00401 extern bool kde_g_bKillAccelOverride;
00402 
00403 bool KApplication::notify(QObject *receiver, QEvent *event)
00404 {
00405     QEvent::Type t = event->type();
00406     if (kde_g_bKillAccelOverride)
00407     {
00408        kde_g_bKillAccelOverride = false;
00409        // Indicate that the accelerator has been overridden.
00410        if (t == QEvent::AccelOverride)
00411        {
00412           static_cast<QKeyEvent *>(event)->accept();
00413           return true;
00414        }
00415        else
00416           kdWarning(125) << "kde_g_bKillAccelOverride set, but received an event other than AccelOverride." << endl;
00417     }
00418 
00419     if ((t == QEvent::AccelOverride) || (t == QEvent::KeyPress))
00420     {
00421        static const KShortcut& _selectAll = KStdAccel::selectAll();
00422        QLineEdit *edit = ::qt_cast<QLineEdit *>(receiver);
00423        if (edit)
00424        {
00425           // We have a keypress for a lineedit...
00426           QKeyEvent *kevent = static_cast<QKeyEvent *>(event);
00427           KKey key(kevent);
00428           if (_selectAll.contains(key))
00429           {
00430              if (t == QEvent::KeyPress)
00431              {
00432                 edit->selectAll();
00433                 return true;
00434              }
00435              else
00436              {
00437                 kevent->accept();
00438              }
00439           }
00440           // Ctrl-U deletes from start of line.
00441           if (key == KKey(Qt::CTRL + Qt::Key_U))
00442           {
00443              if (t == QEvent::KeyPress)
00444              {
00445                 if (!edit->isReadOnly())
00446                 {
00447                    QString t(edit->text());
00448                    t = t.mid(edit->cursorPosition());
00449                    edit->validateAndSet(t, 0, 0, 0);
00450                 }
00451                 return true;
00452              }
00453              else
00454              {
00455                 kevent->accept();
00456              }
00457 
00458           }
00459        }
00460        QTextEdit *medit = ::qt_cast<QTextEdit *>(receiver);
00461        if (medit)
00462        {
00463           // We have a keypress for a multilineedit...
00464           QKeyEvent *kevent = static_cast<QKeyEvent *>(event);
00465           if (_selectAll.contains(KKey(kevent)))
00466           {
00467              if (t == QEvent::KeyPress)
00468              {
00469                 medit->selectAll();
00470                 return true;
00471              }
00472              else
00473              {
00474                 kevent->accept();
00475              }
00476           }
00477        }
00478     }
00479     if( t == QEvent::Show && receiver->isWidgetType())
00480     {
00481     QWidget* w = static_cast< QWidget* >( receiver );
00482         if( w->isTopLevel() && !startupId().isEmpty()) // TODO better done using window group leader?
00483             KStartupInfo::setWindowStartupId( w->winId(), startupId());
00484         if( w->isTopLevel() && !w->testWFlags( WX11BypassWM ) && !w->isPopup() && !event->spontaneous())
00485         {
00486             if( d->app_started_timer == NULL )
00487             {
00488                 d->app_started_timer = new QTimer( this );
00489                 connect( d->app_started_timer, SIGNAL( timeout()), SLOT( checkAppStartedSlot()));
00490             }
00491             if( !d->app_started_timer->isActive())
00492                 d->app_started_timer->start( 0, true );
00493         }
00494     }
00495     return QApplication::notify(receiver, event);
00496 }
00497 
00498 void KApplication::checkAppStartedSlot()
00499 {
00500     KStartupInfo::handleAutoAppStartedSending();
00501 }
00502 
00503 // the help class for session management communication
00504 static QPtrList<KSessionManaged>* sessionClients()
00505 {
00506     static QPtrList<KSessionManaged>* session_clients = 0L;
00507     if ( !session_clients )
00508         session_clients = new QPtrList<KSessionManaged>;
00509     return session_clients;
00510 }
00511 
00512 /*
00513   Auxiliary function to calculate a a session config name used for the
00514   instance specific config object.
00515   Syntax:  "session/<appname>_<sessionId>"
00516  */
00517 QString KApplication::sessionConfigName() const
00518 {
00519 #if QT_VERSION < 0x030100
00520     return QString("session/%1_%2_%3").arg(name()).arg(sessionId()).arg(d->sessionKey);
00521 #else
00522     QString sessKey = sessionKey();
00523     if ( sessKey.isEmpty() && !d->sessionKey.isEmpty() )
00524         sessKey = d->sessionKey;
00525     return QString("session/%1_%2_%3").arg(name()).arg(sessionId()).arg(sessKey);
00526 #endif
00527 }
00528 
00529 #ifndef Q_WS_QWS
00530 static SmcConn mySmcConnection = 0;
00531 static SmcConn tmpSmcConnection = 0;
00532 #else
00533 // FIXME(E): Implement for Qt Embedded
00534 // Possibly "steal" XFree86's libSM?
00535 #endif
00536 static QTime* smModificationTime = 0;
00537 
00538 KApplication::KApplication( int& argc, char** argv, const QCString& rAppName,
00539                             bool allowStyles, bool GUIenabled ) :
00540   QApplication( argc, argv, GUIenabled ), KInstance(rAppName),
00541 #ifdef Q_WS_X11
00542   display(0L),
00543 #endif
00544   d (new KApplicationPrivate())
00545 {
00546     read_app_startup_id();
00547     if (!GUIenabled)
00548        allowStyles = false;
00549     useStyles = allowStyles;
00550     Q_ASSERT (!rAppName.isEmpty());
00551     setName(rAppName);
00552 
00553     installSigpipeHandler();
00554     KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
00555     parseCommandLine( );
00556     init(GUIenabled);
00557     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00558 }
00559 
00560 KApplication::KApplication( bool allowStyles, bool GUIenabled ) :
00561   QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00562                 GUIenabled ),
00563   KInstance( KCmdLineArgs::about),
00564 #ifdef Q_WS_X11
00565   display(0L),
00566 #endif
00567   d (new KApplicationPrivate)
00568 {
00569     read_app_startup_id();
00570     if (!GUIenabled)
00571        allowStyles = false;
00572     useStyles = allowStyles;
00573     setName( instanceName() );
00574 
00575     installSigpipeHandler();
00576     parseCommandLine( );
00577     init(GUIenabled);
00578     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00579 }
00580 
00581 #ifdef Q_WS_X11
00582 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
00583                     bool allowStyles ) :
00584   QApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00585                 visual, colormap ),
00586   KInstance( KCmdLineArgs::about), display(0L), d (new KApplicationPrivate)
00587 {
00588     read_app_startup_id();
00589     useStyles = allowStyles;
00590     setName( instanceName() );
00591     installSigpipeHandler();
00592     parseCommandLine( );
00593     init( true );
00594     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00595 }
00596 
00597 KApplication::KApplication( Display *dpy, Qt::HANDLE visual, Qt::HANDLE colormap,
00598                     bool allowStyles, KInstance * _instance ) :
00599   QApplication( dpy, *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00600                 visual, colormap ),
00601   KInstance( _instance ), display(0L), d (new KApplicationPrivate)
00602 {
00603     read_app_startup_id();
00604     useStyles = allowStyles;
00605     setName( instanceName() );
00606     installSigpipeHandler();
00607     parseCommandLine( );
00608     init( true );
00609     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00610 }
00611 #endif
00612 
00613 KApplication::KApplication( bool allowStyles, bool GUIenabled, KInstance* _instance ) :
00614   QApplication( *KCmdLineArgs::qt_argc(), *KCmdLineArgs::qt_argv(),
00615                 GUIenabled ),
00616   KInstance( _instance ),
00617 #ifdef Q_WS_X11
00618   display(0L),
00619 #endif
00620   d (new KApplicationPrivate)
00621 {
00622     read_app_startup_id();
00623     if (!GUIenabled)
00624        allowStyles = false;
00625     useStyles = allowStyles;
00626     setName( instanceName() );
00627 
00628     installSigpipeHandler();
00629     parseCommandLine( );
00630     init(GUIenabled);
00631     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00632 }
00633 
00634 #ifdef Q_WS_X11
00635 KApplication::KApplication(Display *display, int& argc, char** argv, const QCString& rAppName,
00636                            bool allowStyles, bool GUIenabled ) :
00637   QApplication( display ), KInstance(rAppName),
00638   display(0L),
00639   d (new KApplicationPrivate())
00640 {
00641     read_app_startup_id();
00642     if (!GUIenabled)
00643        allowStyles = false;
00644     useStyles = allowStyles;
00645 
00646     Q_ASSERT (!rAppName.isEmpty());
00647     setName(rAppName);
00648 
00649     installSigpipeHandler();
00650     KCmdLineArgs::initIgnore(argc, argv, rAppName.data());
00651     parseCommandLine( );
00652     init(GUIenabled);
00653     d->m_KAppDCOPInterface = new KAppDCOPInterface(this);
00654 }
00655 #endif
00656 
00657 int KApplication::xioErrhandler( Display* dpy )
00658 {
00659     if(kapp)
00660     {
00661         emit shutDown();
00662         d->oldXIOErrorHandler( dpy );
00663     }
00664     exit( 1 );
00665     return 0;
00666 }
00667 
00668 int KApplication::xErrhandler( Display* dpy, void* err_ )
00669 { // no idea how to make forward decl. for XErrorEvent
00670     XErrorEvent* err = static_cast< XErrorEvent* >( err_ );
00671     if(kapp)
00672     {
00673         // add KDE specific stuff here
00674         d->oldXErrorHandler( dpy, err );
00675     }
00676     return 0;
00677 }
00678 
00679 void KApplication::iceIOErrorHandler( _IceConn *conn )
00680 {
00681     emit shutDown();
00682 
00683     if ( d->oldIceIOErrorHandler != NULL )
00684       (*d->oldIceIOErrorHandler)( conn );
00685 
00686     exit( 1 );
00687 }
00688 
00689 class KDETranslator : public QTranslator
00690 {
00691 public:
00692   KDETranslator(QObject *parent) : QTranslator(parent, "kdetranslator") {}
00693   virtual QTranslatorMessage findMessage(const char* context,
00694                      const char *sourceText,
00695                      const char* message) const
00696   {
00697     QTranslatorMessage res;
00698     res.setTranslation(KGlobal::locale()->translateQt(context, sourceText, message));
00699     return res;
00700   }
00701 };
00702 
00703 void KApplication::init(bool GUIenabled)
00704 {
00705   d->guiEnabled = GUIenabled;
00706   if ((getuid() != geteuid()) ||
00707       (getgid() != getegid()))
00708   {
00709      fprintf(stderr, "The KDE libraries are not designed to run with suid privileges.\n");
00710      ::exit(127);
00711   }
00712 
00713   KProcessController::ref();
00714 
00715   (void) KClipboardSynchronizer::self();
00716 
00717   QApplication::setDesktopSettingsAware( false );
00718 
00719   KApp = this;
00720 
00721 
00722 #ifdef Q_WS_X11 //FIXME(E)
00723   // create all required atoms in _one_ roundtrip to the X server
00724   if ( GUIenabled ) {
00725       const int max = 20;
00726       Atom* atoms[max];
00727       char* names[max];
00728       Atom atoms_return[max];
00729       int n = 0;
00730 
00731       atoms[n] = &kipcCommAtom;
00732       names[n++] = (char *) "KIPC_COMM_ATOM";
00733 
00734       atoms[n] = &atom_DesktopWindow;
00735       names[n++] = (char *) "KDE_DESKTOP_WINDOW";
00736 
00737       atoms[n] = &atom_NetSupported;
00738       names[n++] = (char *) "_NET_SUPPORTED";
00739 
00740       atoms[n] = &kde_xdnd_drop;
00741       names[n++] = (char *) "XdndDrop";
00742 
00743       XInternAtoms( qt_xdisplay(), names, n, false, atoms_return );
00744 
00745       for (int i = 0; i < n; i++ )
00746       *atoms[i] = atoms_return[i];
00747   }
00748 #endif
00749 
00750   dcopAutoRegistration();
00751   dcopClientPostInit();
00752 
00753   smw = 0;
00754 
00755   // Initial KIPC event mask.
00756 #if defined Q_WS_X11 && ! defined K_WS_QTONLY
00757   kipcEventMask = (1 << KIPC::StyleChanged) | (1 << KIPC::PaletteChanged) |
00758                   (1 << KIPC::FontChanged) | (1 << KIPC::BackgroundChanged) |
00759                   (1 << KIPC::ToolbarStyleChanged) | (1 << KIPC::SettingsChanged) |
00760                   (1 << KIPC::ClipboardConfigChanged);
00761 #endif
00762 
00763   // Trigger creation of locale.
00764   (void) KGlobal::locale();
00765 
00766   KConfig* config = KGlobal::config();
00767   d->actionRestrictions = config->hasGroup("KDE Action Restrictions" ) && !kde_kiosk_exception;
00768   // For brain-dead configurations where the user's local config file is not writable.
00769   // * We use kdialog to warn the user, so we better not generate warnings from
00770   //   kdialog itself.
00771   // * Don't warn if we run with a read-only $HOME
00772   QCString readOnly = getenv("KDE_HOME_READONLY");
00773   if (readOnly.isEmpty() && (qstrcmp(name(), "kdialog") != 0))
00774   {
00775     KConfigGroupSaver saver(config, "KDE Action Restrictions");
00776     if (config->readBoolEntry("warn_unwritable_config",true))
00777        config->checkConfigFilesWritable(true);
00778   }
00779 
00780   if (GUIenabled)
00781   {
00782 #ifdef Q_WS_X11
00783     // this is important since we fork() to launch the help (Matthias)
00784     fcntl(ConnectionNumber(qt_xdisplay()), F_SETFD, FD_CLOEXEC);
00785     // set up the fancy (=robust and error ignoring ) KDE xio error handlers (Matthias)
00786     d->oldXErrorHandler = XSetErrorHandler( kde_x_errhandler );
00787     d->oldXIOErrorHandler = XSetIOErrorHandler( kde_xio_errhandler );
00788 #endif
00789 
00790     connect( this, SIGNAL( aboutToQuit() ), this, SIGNAL( shutDown() ) );
00791 
00792 #ifdef Q_WS_X11 //FIXME(E)
00793     display = desktop()->x11Display();
00794 #endif
00795 
00796     {
00797         QStringList plugins = KGlobal::dirs()->resourceDirs( "qtplugins" );
00798         QStringList::Iterator it = plugins.begin();
00799         while (it != plugins.end()) {
00800             addLibraryPath( *it );
00801             ++it;
00802         }
00803 
00804     }
00805     kdisplaySetStyle();
00806     kdisplaySetFont();
00807 //    kdisplaySetPalette(); done by kdisplaySetStyle
00808     propagateSettings(SETTINGS_QT);
00809 
00810     // Set default mime-source factory
00811     // XXX: This is a hack. Make our factory the default factory, but add the
00812     // previous default factory to the list of factories. Why? When the default
00813     // factory can't resolve something, it iterates in the list of factories.
00814     // But it QWhatsThis only uses the default factory. So if there was already
00815     // a default factory (which happens when using an image library using uic),
00816     // we prefer KDE's factory and so we put that old default factory in the
00817     // list and use KDE as the default. This may speed up things as well.
00818     QMimeSourceFactory* oldDefaultFactory = QMimeSourceFactory::takeDefaultFactory();
00819     QMimeSourceFactory::setDefaultFactory( mimeSourceFactory() );
00820     if ( oldDefaultFactory ) {
00821         QMimeSourceFactory::addFactory( oldDefaultFactory );
00822     }
00823 
00824     KConfigGroupSaver saver( config, "Development" );
00825     if( config->hasKey( "CheckAccelerators" ) || config->hasKey( "AutoCheckAccelerators" ))
00826         d->checkAccelerators = new KCheckAccelerators( this );
00827   }
00828 
00829   // save and restore the RTL setting, as installTranslator calls qt_detectRTLLanguage,
00830   // which makes it impossible to use the -reverse cmdline switch with KDE apps
00831   bool rtl = reverseLayout();
00832   installTranslator(new KDETranslator(this));
00833   setReverseLayout( rtl );
00834   if (i18n( "_: Dear Translator! Translate this string to the string 'LTR' in "
00835      "left-to-right languages (as english) or to 'RTL' in right-to-left "
00836      "languages (such as Hebrew and Arabic) to get proper widget layout." ) == "RTL")
00837     setReverseLayout( !rtl );
00838 
00839   // install appdata resource type
00840   KGlobal::dirs()->addResourceType("appdata", KStandardDirs::kde_default("data")
00841                                    + QString::fromLatin1(name()) + '/');
00842   pSessionConfig = 0L;
00843   bSessionManagement = true;
00844 
00845 #ifdef Q_WS_X11
00846   // register a communication window for desktop changes (Matthias)
00847   if (GUIenabled && kde_have_kipc )
00848   {
00849     smw = new QWidget(0,0);
00850     long data = 1;
00851     XChangeProperty(qt_xdisplay(), smw->winId(),
00852             atom_DesktopWindow, atom_DesktopWindow,
00853             32, PropModeReplace, (unsigned char *)&data, 1);
00854   }
00855 #else
00856   // FIXME(E): Implement for Qt Embedded
00857 #endif
00858 
00859   d->oldIceIOErrorHandler = IceSetIOErrorHandler( kde_ice_ioerrorhandler );
00860 }
00861 
00862 static int my_system (const char *command) {
00863    int pid, status;
00864 
00865    QApplication::flushX();
00866    pid = fork();
00867    if (pid == -1)
00868       return -1;
00869    if (pid == 0) {
00870       const char* shell = "/bin/sh";
00871       execl(shell, shell, "-c", command, (void *)0);
00872       ::exit(127);
00873    }
00874    do {
00875       if (waitpid(pid, &status, 0) == -1) {
00876          if (errno != EINTR)
00877             return -1;
00878        } else
00879             return status;
00880    } while(1);
00881 }
00882 
00883 
00884 DCOPClient *KApplication::dcopClient()
00885 {
00886   if (s_DCOPClient)
00887     return s_DCOPClient;
00888 
00889   s_DCOPClient = new DCOPClient();
00890   KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
00891   if (args && args->isSet("dcopserver"))
00892   {
00893     s_DCOPClient->setServerAddress( args->getOption("dcopserver"));
00894   }
00895   if( kapp ) {
00896     connect(s_DCOPClient, SIGNAL(attachFailed(const QString &)),
00897             kapp, SLOT(dcopFailure(const QString &)));
00898     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
00899             kapp, SLOT(dcopBlockUserInput(bool)) );
00900   }
00901   else
00902     s_dcopClientNeedsPostInit = true;
00903 
00904   DCOPClient::setMainClient( s_DCOPClient );
00905   return s_DCOPClient;
00906 }
00907 
00908 void KApplication::dcopClientPostInit()
00909 {
00910   if( s_dcopClientNeedsPostInit )
00911     {
00912     s_dcopClientNeedsPostInit = false;
00913     connect(s_DCOPClient, SIGNAL(blockUserInput(bool) ),
00914             SLOT(dcopBlockUserInput(bool)) );
00915     s_DCOPClient->bindToApp(); // Make sure we get events from the DCOPClient.
00916     }
00917 }
00918 
00919 void KApplication::dcopAutoRegistration()
00920 {
00921   if (autoDcopRegistration)
00922      {
00923      ( void ) dcopClient();
00924      if( dcopClient()->appId().isEmpty())
00925          dcopClient()->registerAs(name());
00926      }
00927 }
00928 
00929 void KApplication::disableAutoDcopRegistration()
00930 {
00931   autoDcopRegistration = false;
00932 }
00933 
00934 KConfig* KApplication::sessionConfig()
00935 {
00936     if (pSessionConfig)
00937         return pSessionConfig;
00938 
00939     // create an instance specific config object
00940     pSessionConfig = new KConfig( sessionConfigName(), false, false);
00941     return pSessionConfig;
00942 }
00943 
00944 void KApplication::ref()
00945 {
00946     d->refCount++;
00947     //kdDebug() << "KApplication::ref() : refCount = " << d->refCount << endl;
00948 }
00949 
00950 void KApplication::deref()
00951 {
00952     d->refCount--;
00953     //kdDebug() << "KApplication::deref() : refCount = " << d->refCount << endl;
00954     if ( d->refCount <= 0 )
00955         quit();
00956 }
00957 
00958 KSessionManaged::KSessionManaged()
00959 {
00960     sessionClients()->remove( this );
00961     sessionClients()->append( this );
00962 }
00963 
00964 KSessionManaged::~KSessionManaged()
00965 {
00966     sessionClients()->remove( this );
00967 }
00968 
00969 bool KSessionManaged::saveState(QSessionManager&)
00970 {
00971     return true;
00972 }
00973 
00974 bool KSessionManaged::commitData(QSessionManager&)
00975 {
00976     return true;
00977 }
00978 
00979 
00980 void KApplication::disableSessionManagement() {
00981   bSessionManagement = false;
00982 }
00983 
00984 void KApplication::enableSessionManagement() {
00985   bSessionManagement = true;
00986   // Session management support in Qt/KDE is awfully broken.
00987   // If konqueror disables session management right after its startup,
00988   // and enables it later (preloading stuff), it won't be properly
00989   // saved on session shutdown.
00990   // I'm not actually sure why it doesn't work, but saveState()
00991   // doesn't seem to be called on session shutdown, possibly
00992   // because disabling session management after konqueror startup
00993   // disabled it somehow. Forcing saveState() here for this application
00994   // seems to fix it.
00995   if( mySmcConnection ) {
00996         SmcRequestSaveYourself( mySmcConnection, SmSaveLocal, False,
00997                 SmInteractStyleAny,
00998                 False, False );
00999 
01000     // flush the request
01001     IceFlush(SmcGetIceConnection(mySmcConnection));
01002   }
01003 }
01004 
01005 
01006 bool KApplication::requestShutDown(
01007     ShutdownConfirm confirm, ShutdownType sdtype, ShutdownMode sdmode )
01008 {
01009 #ifdef Q_WS_X11
01010     QApplication::syncX();
01011     /*  use ksmserver's dcop interface if necessary  */
01012     if ( confirm == ShutdownConfirmYes ||
01013          sdtype != ShutdownTypeDefault ||
01014          sdmode != ShutdownModeDefault )
01015     {
01016         QByteArray data;
01017         QDataStream arg(data, IO_WriteOnly);
01018         arg << (int)confirm << (int)sdtype << (int)sdmode;
01019     return dcopClient()->send( "ksmserver", "ksmserver",
01020                                    "logout(int,int,int)", data );
01021     }
01022 
01023     if ( mySmcConnection ) {
01024         // we already have a connection to the session manager, use it.
01025         SmcRequestSaveYourself( mySmcConnection, SmSaveBoth, True,
01026                 SmInteractStyleAny,
01027                 confirm == ShutdownConfirmNo, True );
01028 
01029     // flush the request
01030     IceFlush(SmcGetIceConnection(mySmcConnection));
01031         return true;
01032     }
01033 
01034     // open a temporary connection, if possible
01035 
01036     propagateSessionManager();
01037     QCString smEnv = ::getenv("SESSION_MANAGER");
01038     if (smEnv.isEmpty())
01039         return false;
01040 
01041     if (! tmpSmcConnection) {
01042     char cerror[256];
01043     char* myId = 0;
01044     char* prevId = 0;
01045     SmcCallbacks cb;
01046     tmpSmcConnection = SmcOpenConnection( 0, 0, 1, 0,
01047                           0, &cb,
01048                           prevId,
01049                           &myId,
01050                           255,
01051                           cerror );
01052     ::free( myId ); // it was allocated by C
01053     if (!tmpSmcConnection )
01054         return false;
01055     }
01056 
01057     SmcRequestSaveYourself( tmpSmcConnection, SmSaveBoth, True,
01058                 SmInteractStyleAny, False, True );
01059 
01060     // flush the request
01061     IceFlush(SmcGetIceConnection(tmpSmcConnection));
01062     return true;
01063 #else
01064     // FIXME(E): Implement for Qt Embedded
01065     return false;
01066 #endif
01067 }
01068 
01069 void KApplication::propagateSessionManager()
01070 {
01071     QCString fName = QFile::encodeName(locateLocal("socket", "KSMserver"));
01072     QCString display = ::getenv(DISPLAY);
01073     // strip the screen number from the display
01074     display.replace(QRegExp("\\.[0-9]+$"), "");
01075     int i;
01076     while( (i = display.find(':')) >= 0)
01077        display[i] = '_';
01078 
01079     fName += "_"+display;
01080     QCString smEnv = ::getenv("SESSION_MANAGER");
01081     bool check = smEnv.isEmpty();
01082     if ( !check && smModificationTime ) {
01083          QFileInfo info( fName );
01084          QTime current = info.lastModified().time();
01085          check = current > *smModificationTime;
01086     }
01087     if ( check ) {
01088         delete smModificationTime;
01089         QFile f( fName );
01090         if ( !f.open( IO_ReadOnly ) )
01091             return;
01092         QFileInfo info ( f );
01093         smModificationTime = new QTime( info.lastModified().time() );
01094         QTextStream t(&f);
01095         t.setEncoding( QTextStream::Latin1 );
01096         QString s = t.readLine();
01097         f.close();
01098         ::setenv( "SESSION_MANAGER", s.latin1(), true  );
01099     }
01100 }
01101 
01102 void KApplication::commitData( QSessionManager& sm )
01103 {
01104     d->session_save = true;
01105     bool canceled = false;
01106     for (KSessionManaged* it = sessionClients()->first();
01107          it && !canceled;
01108          it = sessionClients()->next() ) {
01109         canceled = !it->commitData( sm );
01110     }
01111     if ( canceled )
01112         sm.cancel();
01113 
01114     if ( sm.allowsInteraction() ) {
01115         QWidgetList done;
01116         QWidgetList *list = QApplication::topLevelWidgets();
01117         bool canceled = false;
01118         QWidget* w = list->first();
01119         while ( !canceled && w ) {
01120             if ( !w->testWState( WState_ForceHide ) && !w->inherits("KMainWindow") ) {
01121                 QCloseEvent e;
01122                 sendEvent( w, &e );
01123                 canceled = !e.isAccepted();
01124                 if ( !canceled )
01125                     done.append( w );
01126                 delete list; // one never knows...
01127                 list = QApplication::topLevelWidgets();
01128                 w = list->first();
01129             } else {
01130                 w = list->next();
01131             }
01132             while ( w && done.containsRef( w ) )
01133                 w = list->next();
01134         }
01135         delete list;
01136     }
01137 
01138 
01139     if ( !bSessionManagement )
01140         sm.setRestartHint( QSessionManager::RestartNever );
01141     else
01142     sm.setRestartHint( QSessionManager::RestartIfRunning );
01143     d->session_save = false;
01144 }
01145 
01146 void KApplication::saveState( QSessionManager& sm )
01147 {
01148     d->session_save = true;
01149 #ifndef Q_WS_QWS
01150     static bool firstTime = true;
01151     mySmcConnection = (SmcConn) sm.handle();
01152 
01153     if ( !bSessionManagement ) {
01154         sm.setRestartHint( QSessionManager::RestartNever );
01155     d->session_save = false;
01156         return;
01157     }
01158     else
01159         sm.setRestartHint( QSessionManager::RestartIfRunning );
01160 
01161 #if QT_VERSION < 0x030100
01162     {
01163         // generate a new session key
01164         timeval tv;
01165         gettimeofday( &tv, 0 );
01166         d->sessionKey  = QString::number( tv.tv_sec ) + "_" + QString::number(tv.tv_usec);
01167     }
01168 #endif
01169 
01170     if ( firstTime ) {
01171         firstTime = false;
01172     d->session_save = false;
01173         return; // no need to save the state.
01174     }
01175 
01176     // remove former session config if still existing, we want a new
01177     // and fresh one. Note that we do not delete the config file here,
01178     // this is done by the session manager when it executes the
01179     // discard commands. In fact it would be harmful to remove the
01180     // file here, as the session might be stored under a different
01181     // name, meaning the user still might need it eventually.
01182     if ( pSessionConfig ) {
01183         delete pSessionConfig;
01184         pSessionConfig = 0;
01185     }
01186 
01187     // tell the session manager about our new lifecycle
01188     QStringList restartCommand = sm.restartCommand();
01189 #if QT_VERSION < 0x030100
01190     restartCommand.clear();
01191     restartCommand  << argv()[0] << "-session" << sm.sessionId() << "-smkey" << d->sessionKey;
01192     sm.setRestartCommand( restartCommand );
01193 #endif
01194 
01195 
01196     QCString multiHead = getenv("KDE_MULTIHEAD");
01197     if (multiHead.lower() == "true") {
01198         // if multihead is enabled, we save our -display argument so that
01199         // we are restored onto the correct head... one problem with this
01200         // is that the display is hard coded, which means we cannot restore
01201         // to a different display (ie. if we are in a university lab and try,
01202         // try to restore a multihead session, our apps could be started on
01203         // someone else's display instead of our own)
01204         QCString displayname = getenv(DISPLAY);
01205         if (! displayname.isNull()) {
01206             // only store the command if we actually have a DISPLAY
01207             // environment variable
01208             restartCommand.append("-display");
01209             restartCommand.append(displayname);
01210         }
01211         sm.setRestartCommand( restartCommand );
01212     }
01213 
01214 
01215     // finally: do session management
01216     emit saveYourself(); // for compatibility
01217     bool canceled = false;
01218     for (KSessionManaged* it = sessionClients()->first();
01219          it && !canceled;
01220          it = sessionClients()->next() ) {
01221         canceled = !it->saveState( sm );
01222     }
01223 
01224     // if we created a new session config object, register a proper discard command
01225     if ( pSessionConfig ) {
01226         pSessionConfig->sync();
01227         QStringList discard;
01228         discard  << "rm" << locateLocal("config", sessionConfigName());
01229         sm.setDiscardCommand( discard );
01230     } else {
01231     sm.setDiscardCommand( "" );
01232     }
01233 
01234     if ( canceled )
01235         sm.cancel();
01236 #else
01237     // FIXME(E): Implement for Qt Embedded
01238 #endif
01239     d->session_save = false;
01240 }
01241 
01242 bool KApplication::sessionSaving() const
01243 {
01244     return d->session_save;
01245 }
01246 
01247 void KApplication::startKdeinit()
01248 {
01249   // Try to launch kdeinit.
01250   QString srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"));
01251   if (srv.isEmpty())
01252      srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"), KDEDIR+QString::fromLatin1("/bin"));
01253   if (srv.isEmpty())
01254      return;
01255   if (kapp && (Tty != kapp->type()))
01256     setOverrideCursor( Qt::waitCursor );
01257   my_system(QFile::encodeName(srv)+" --suicide");
01258   if (kapp && (Tty != kapp->type()))
01259     restoreOverrideCursor();
01260 }
01261 
01262 void KApplication::dcopFailure(const QString &msg)
01263 {
01264   static int failureCount = 0;
01265   failureCount++;
01266   if (failureCount == 1)
01267   {
01268      startKdeinit();
01269      return;
01270   }
01271   if (failureCount == 2)
01272   {
01273      QString msgStr(i18n("There was an error setting up inter-process "
01274                       "communications for KDE. The message returned "
01275                       "by the system was:\n\n"));
01276      msgStr += msg;
01277      msgStr += i18n("\n\nPlease check that the \"dcopserver\" program is running!");
01278 
01279      if (Tty != kapp->type())
01280      {
01281        QMessageBox::critical
01282          (
01283            kapp->mainWidget(),
01284            i18n("DCOP communications error (%1)").arg(kapp->caption()),
01285            msgStr,
01286            i18n("&OK")
01287          );
01288      }
01289      else
01290      {
01291        fprintf(stderr, "%s\n", msgStr.local8Bit().data());
01292      }
01293 
01294      return;
01295   }
01296 }
01297 
01298 static const KCmdLineOptions qt_options[] =
01299 {
01300   //FIXME: Check if other options are specific to Qt/X11
01301 #ifdef Q_WS_X11
01302    { "display <displayname>", I18N_NOOP("Use the X-server display 'displayname'"), 0},
01303 #else
01304    { "display <displayname>", I18N_NOOP("Use the QWS display 'displayname'"), 0},
01305 #endif
01306    { "session <sessionId>", I18N_NOOP("Restore the application for the given 'sessionId'"), 0},
01307    { "cmap", I18N_NOOP("Causes the application to install a private color\nmap on an 8-bit display"), 0},
01308    { "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},
01309    { "nograb", I18N_NOOP("tells Qt to never grab the mouse or the keyboard"), 0},
01310    { "dograb", I18N_NOOP("running under a debugger can cause an implicit\n-nograb, use -dograb to override"), 0},
01311    { "sync", I18N_NOOP("switches to synchronous mode for debugging"), 0},
01312    { "fn", 0, 0},
01313    { "font <fontname>", I18N_NOOP("defines the application font"), 0},
01314    { "bg", 0, 0},
01315    { "background <color>", I18N_NOOP("sets the default background color and an\napplication palette (light and dark shades are\ncalculated)"), 0},
01316    { "fg", 0, 0},
01317    { "foreground <color>", I18N_NOOP("sets the default foreground color"), 0},
01318    { "btn", 0, 0},
01319    { "button <color>", I18N_NOOP("sets the default button color"), 0},
01320    { "name <name>", I18N_NOOP("sets the application name"), 0},
01321    { "title <title>", I18N_NOOP("sets the application title (caption)"), 0},
01322 #ifdef Q_WS_X11
01323    { "visual TrueColor", I18N_NOOP("forces the application to use a TrueColor visual on\nan 8-bit display"), 0},
01324    { "inputstyle <inputstyle>", I18N_NOOP("sets XIM (X Input Method) input style. Possible\nvalues are onthespot, overthespot, offthespot and\nroot"), 0 },
01325    { "im <XIM server>", I18N_NOOP("set XIM server"),0},
01326    { "noxim", I18N_NOOP("disable XIM"), 0 },
01327 #endif
01328 #ifdef Q_WS_QWS
01329    { "qws", I18N_NOOP("forces the application to run as QWS Server"), 0},
01330 #endif
01331    { "reverse", I18N_NOOP("mirrors the whole layout of widgets"), 0},
01332    KCmdLineLastOption
01333 };
01334 
01335 static const KCmdLineOptions kde_options[] =
01336 {
01337    { "caption <caption>",       I18N_NOOP("Use 'caption' as name in the titlebar"), 0},
01338    { "icon <icon>",             I18N_NOOP("Use 'icon' as the application icon"), 0},
01339    { "miniicon <icon>",         I18N_NOOP("Use 'icon' as the icon in the titlebar"), 0},
01340    { "config <filename>",       I18N_NOOP("Use alternative configuration file"), 0},
01341    { "dcopserver <server>",     I18N_NOOP("Use the DCOP Server specified by 'server'"), 0},
01342    { "nocrashhandler",          I18N_NOOP("Disable crash handler, to get core dumps"), 0},
01343    { "waitforwm",          I18N_NOOP("Waits for a WM_NET compatible windowmanager"), 0},
01344    { "style <style>", I18N_NOOP("sets the application GUI style"), 0},
01345    { "geometry <geometry>", I18N_NOOP("sets the client geometry of the main widget"), 0},
01346 #if QT_VERSION < 0x030100
01347    { "smkey <sessionKey>", I18N_NOOP("Define a 'sessionKey' for the session id. Only valid with -session"), 0},
01348 #else
01349    { "smkey <sessionKey>", 0, 0}, // this option is obsolete and exists only to allow smooth upgrades from sessions
01350                                   // saved under Qt 3.0.x -- Qt 3.1.x includes the session key now automatically in
01351                   // the session id (Simon)
01352 #endif
01353    KCmdLineLastOption
01354 };
01355 
01356 void
01357 KApplication::addCmdLineOptions()
01358 {
01359    KCmdLineArgs::addCmdLineOptions(qt_options, "Qt", "qt");
01360    KCmdLineArgs::addCmdLineOptions(kde_options, "KDE", "kde");
01361 }
01362 
01363 void KApplication::parseCommandLine( )
01364 {
01365     KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
01366 
01367     if ( !args ) return;
01368 
01369     if (args->isSet("config"))
01370     {
01371         QString config = QString::fromLocal8Bit(args->getOption("config"));
01372         setConfigName(config);
01373     }
01374 
01375     if (args->isSet("style"))
01376     {
01377 
01378        QStringList styles = QStyleFactory::keys();
01379        QString reqStyle(args->getOption("style").lower());
01380 
01381        for (QStringList::ConstIterator it = styles.begin(); it != styles.end(); ++it)
01382            if ((*it).lower() == reqStyle)
01383            {
01384                d->overrideStyle = *it;
01385                break;
01386            }
01387 
01388        if (d->overrideStyle.isEmpty())
01389           fprintf(stderr, "%s", i18n("The style %1 was not found\n").arg(reqStyle).local8Bit().data());
01390     }
01391 
01392     if (args->isSet("caption"))
01393     {
01394        aCaption = QString::fromLocal8Bit(args->getOption("caption"));
01395     }
01396 
01397     if (args->isSet("miniicon"))
01398     {
01399        const char *tmp = args->getOption("miniicon");
01400        aMiniIconPixmap = SmallIcon(tmp);
01401        aMiniIconName = tmp;
01402     }
01403 
01404     if (args->isSet("icon"))
01405     {
01406        const char *tmp = args->getOption("icon");
01407        aIconPixmap = DesktopIcon( tmp );
01408        aIconName = tmp;
01409        if (aMiniIconPixmap.isNull())
01410        {
01411           aMiniIconPixmap = SmallIcon( tmp );
01412           aMiniIconName = tmp;
01413        }
01414     }
01415 
01416     bool nocrashhandler = (getenv("KDE_DEBUG") != NULL);
01417     if (!nocrashhandler && args->isSet("crashhandler"))
01418     {
01419         // set default crash handler / set emergency save function to nothing
01420         KCrash::setCrashHandler(KCrash::defaultCrashHandler);
01421         KCrash::setEmergencySaveFunction(NULL);
01422 
01423         KCrash::setApplicationName(QString(args->appName()));
01424     }
01425 
01426 #ifdef Q_WS_X11
01427     if ( args->isSet( "waitforwm" ) ) {
01428         Atom type;
01429         (void) desktop(); // trigger desktop creation, we need PropertyNotify events for the root window
01430         int format;
01431         unsigned long length, after;
01432         unsigned char *data;
01433         while ( XGetWindowProperty( qt_xdisplay(), qt_xrootwin(), atom_NetSupported,
01434                     0, 1, false, AnyPropertyType, &type, &format,
01435                                     &length, &after, &data ) != Success || !length ) {
01436             if ( data )
01437                 XFree( data );
01438             XEvent event;
01439             XWindowEvent( qt_xdisplay(), qt_xrootwin(), PropertyChangeMask, &event );
01440         }
01441         if ( data )
01442             XFree( data );
01443     }
01444 #else
01445     // FIXME(E): Implement for Qt Embedded
01446 #endif
01447 
01448     if (args->isSet("geometry"))
01449     {
01450         d->geometry_arg = args->getOption("geometry");
01451     }
01452 
01453     if (args->isSet("smkey"))
01454     {
01455         d->sessionKey = args->getOption("smkey");
01456     }
01457 
01458 }
01459 
01460 QString KApplication::geometryArgument() const
01461 {
01462     return d->geometry_arg;
01463 }
01464 
01465 QPixmap KApplication::icon() const
01466 {
01467   if( aIconPixmap.isNull()) {
01468       KApplication *that = const_cast<KApplication *>(this);
01469       that->aIconPixmap = DesktopIcon( instanceName() );
01470   }
01471   return aIconPixmap;
01472 }
01473 
01474 QString KApplication::iconName() const
01475 {
01476   return aIconName.isNull() ? (QString)instanceName() : aIconName;
01477 }
01478 
01479 QPixmap KApplication::miniIcon() const
01480 {
01481   if (aMiniIconPixmap.isNull()) {
01482       KApplication *that = const_cast<KApplication *>(this);
01483       that->aMiniIconPixmap = SmallIcon( instanceName() );
01484   }
01485   return aMiniIconPixmap;
01486 }
01487 
01488 QString KApplication::miniIconName() const
01489 {
01490   return aMiniIconName.isNull() ? (QString)instanceName() : aMiniIconName;
01491 }
01492 
01493 extern void kDebugCleanup();
01494 
01495 KApplication::~KApplication()
01496 {
01497   delete d->m_KAppDCOPInterface;
01498 
01499   // First call the static deleters and then call KLibLoader::cleanup()
01500   // The static deleters may delete libraries for which they need KLibLoader.
01501   // KLibLoader will take care of the remaining ones.
01502   KGlobal::deleteStaticDeleters();
01503   KLibLoader::cleanUp();
01504 
01505