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