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