kapplication.cpp

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