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