00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
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>
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
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
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
00152 KDE_EXPORT bool kde_have_kipc = true;
00153 bool kde_kiosk_exception = false;
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
00170
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
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
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
00436
00437
00438
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
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
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
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
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())
00522 KStartupInfo::setWindowStartupId( w->winId(), startupId());
00523 #endif
00524 if( w->isTopLevel() && !w->testWFlags( WX11BypassWM ) && !w->isPopup() && !event->spontaneous())
00525 {
00526 if( d->app_started_timer == NULL )
00527 {
00528 d->app_started_timer = new QTimer( this );
00529 connect( d->app_started_timer, SIGNAL( timeout()), SLOT( checkAppStartedSlot()));
00530 }
00531 if( !d->app_started_timer->isActive())
00532 d->app_started_timer->start( 0, true );
00533 }
00534 if( w->isTopLevel() && ( w->icon() == NULL || w->icon()->isNull()))
00535 {
00536
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
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
00571
00572
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
00587
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 {
00739 #ifdef Q_WS_X11
00740 XErrorEvent* err = static_cast< XErrorEvent* >( err_ );
00741 if(kapp)
00742 {
00743
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
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
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
00836 (void) KGlobal::locale();
00837
00838 KConfig* config = KGlobal::config();
00839 d->actionRestrictions = config->hasGroup("KDE Action Restrictions" ) && !kde_kiosk_exception;
00840
00841
00842
00843
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
00856 fcntl(ConnectionNumber(qt_xdisplay()), F_SETFD, FD_CLOEXEC);
00857
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
00880 propagateSettings(SETTINGS_QT);
00881
00882
00883
00884
00885
00886
00887
00888
00889
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
00917 SetApplicationDockTileImage(ir);
00918 CGImageRelease(ir);
00919 CGColorSpaceRelease(cs);
00920 CGDataProviderRelease(dp);
00921 }
00922 }
00923 #endif
00924
00925
00926
00927
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
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
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
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();
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
01037 pSessionConfig = new KConfig( sessionConfigName(), false, false);
01038 return pSessionConfig;
01039 }
01040
01041 void KApplication::ref()
01042 {
01043 d->refCount++;
01044
01045 }
01046
01047 void KApplication::deref()
01048 {
01049 d->refCount--;
01050
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
01085
01086
01087
01088
01089
01090
01091
01092
01093 if( mySmcConnection ) {
01094 SmcRequestSaveYourself( mySmcConnection, SmSaveLocal, False,
01095 SmInteractStyleAny,
01096 False, False );
01097
01098
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
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
01124 SmcRequestSaveYourself( mySmcConnection, SmSaveBoth, True,
01125 SmInteractStyleAny,
01126 confirm == ShutdownConfirmNo, True );
01127
01128
01129 IceFlush(SmcGetIceConnection(mySmcConnection));
01130 return true;
01131 }
01132
01133
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 );
01152 if (!tmpSmcConnection )
01153 return false;
01154 }
01155
01156 SmcRequestSaveYourself( tmpSmcConnection, SmSaveBoth, True,
01157 SmInteractStyleAny, False, True );
01158
01159
01160 IceFlush(SmcGetIceConnection(tmpSmcConnection));
01161 return true;
01162 #else
01163
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
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;
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 void KApplication::saveState( QSessionManager& sm )
01248 {
01249 d->session_save = true;
01250 #ifdef Q_WS_X11
01251 static bool firstTime = true;
01252 mySmcConnection = (SmcConn) sm.handle();
01253
01254 if ( !bSessionManagement ) {
01255 sm.setRestartHint( QSessionManager::RestartNever );
01256 d->session_save = false;
01257 return;
01258 }
01259 else
01260 sm.setRestartHint( QSessionManager::RestartIfRunning );
01261
01262 if ( firstTime ) {
01263 firstTime = false;
01264 d->session_save = false;
01265 return;
01266 }
01267
01268
01269
01270
01271
01272
01273
01274 if ( pSessionConfig ) {
01275 delete pSessionConfig;
01276 pSessionConfig = 0;
01277 }
01278
01279
01280 QStringList restartCommand = sm.restartCommand();
01281
01282 QCString multiHead = getenv("KDE_MULTIHEAD");
01283 if (multiHead.lower() == "true") {
01284
01285
01286
01287
01288
01289
01290 QCString displayname = getenv(DISPLAY);
01291 if (! displayname.isNull()) {
01292
01293
01294 restartCommand.append("-display");
01295 restartCommand.append(displayname);
01296 }
01297 sm.setRestartCommand( restartCommand );
01298 }
01299
01300
01301
01302 emit saveYourself();
01303 bool canceled = false;
01304 for (KSessionManaged* it = sessionClients()->first();
01305 it && !canceled;
01306 it = sessionClients()->next() ) {
01307 canceled = !it->saveState( sm );
01308 }
01309
01310
01311 if ( pSessionConfig ) {
01312 pSessionConfig->sync();
01313 QStringList discard;
01314 discard << "rm" << locateLocal("config", sessionConfigName());
01315 sm.setDiscardCommand( discard );
01316 } else {
01317 sm.setDiscardCommand( "" );
01318 }
01319
01320 if ( canceled )
01321 sm.cancel();
01322 #else
01323
01324 #endif
01325 d->session_save = false;
01326 }
01327
01328 bool KApplication::sessionSaving() const
01329 {
01330 return d->session_save;
01331 }
01332
01333 void KApplication::startKdeinit()
01334 {
01335 #ifndef Q_WS_WIN //TODO
01336
01337 QString srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"));
01338 if (srv.isEmpty())
01339 srv = KStandardDirs::findExe(QString::fromLatin1("kdeinit"), KGlobal::dirs()->kfsstnd_defaultbindir());
01340 if (srv.isEmpty())
01341 return;
01342 if (kapp && (Tty != kapp->type()))
01343 setOverrideCursor( Qt::waitCursor );
01344 my_system(QFile::encodeName(srv)+" --suicide");
01345 if (kapp && (Tty != kapp->type()))
01346 restoreOverrideCursor();
01347 #endif
01348 }
01349
01350 void KApplication::dcopFailure(const QString &msg)
01351 {
01352 static int failureCount = 0;
01353 failureCount++;
01354 if (failureCount == 1)
01355 {
01356 startKdeinit();
01357 return;
01358 }
01359 if (failureCount == 2)
01360 {
01361 #ifdef Q_WS_WIN
01362 KGlobal::config()->setGroup("General");
01363 if (KGlobal::config()->readBoolEntry("ignoreDCOPFailures", false))
01364 return;
01365 #endif
01366 QString msgStr(i18n("There was an error setting up inter-process "
01367 "communications for KDE. The message returned "
01368 "by the system was:\n\n"));
01369 msgStr += msg;
01370 msgStr += i18n("\n\nPlease check that the \"dcopserver\" program is running!");
01371
01372 if (Tty != kapp->type())
01373 {
01374 QMessageBox::critical
01375 (
01376 kapp->mainWidget(),
01377 i18n("DCOP communications error (%1)").arg(kapp->caption()),
01378 msgStr,
01379 i18n("&OK")
01380 );
01381 }
01382 else
01383 {
01384 fprintf(stderr, "%s\n", msgStr.local8Bit().data());
01385 }
01386
01387 return;
01388 }
01389 }
01390
01391 static const KCmdLineOptions qt_options[] =
01392 {
01393
01394 #ifdef Q_WS_X11
01395 { "display <displayname>", I18N_NOOP("Use the X-server display 'displayname'"), 0},
01396 #else
01397 { "display <displayname>", I18N_NOOP("Use the QWS display 'displayname'"), 0},
01398 #endif
01399 { "session <sessionId>", I18N_NOOP("Restore the application for the given 'sessionId'"), 0},
01400 { "cmap", I18N_NOOP("Causes the application to install a private color\nmap on an 8-bit display"), 0},
01401 { "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},
01402 { "nograb", I18N_NOOP("tells Qt to never grab the mouse or the keyboard"), 0},
01403 { "dograb", I18N_NOOP("running under a debugger can cause an implicit\n-nograb, use -dograb to override"), 0},
01404 { "sync", I18N_NOOP("switches to synchronous mode for debugging"), 0},
01405 { "fn", 0, 0},
01406 { "font <fontname>", I18N_NOOP("defines the application font"), 0},
01407 { "bg", 0, 0},
01408 { "background <color>", I18N_NOOP("sets the default background color and an\napplication palette (light and dark shades are\ncalculated)"), 0},
01409 { "fg", 0, 0},
01410 { "foreground <color>", I18N_NOOP("sets the default foreground color"), 0},
01411 { "btn", 0, 0},
01412 { "button <color>", I18N_NOOP("sets the default button color"), 0},
01413 { "name <name>", I18N_NOOP("sets the application name"), 0},
01414 { "title <title>", I18N_NOOP("sets the application title (caption)"), 0},
01415 #ifdef Q_WS_X11
01416 { "visual TrueColor", I18N_NOOP("forces the application to use a TrueColor visual on\nan 8-bit display"), 0},
01417 { "inputstyle <inputstyle>", I18N_NOOP("sets XIM (X Input Method) input style. Possible\nvalues are onthespot, overthespot, offthespot and\nroot"), 0 },
01418 { "im <XIM server>", I18N_NOOP("set XIM server"),0},
01419 { "noxim", I18N_NOOP("disable XIM"), 0 },
01420 #endif
01421 #ifdef Q_WS_QWS
01422 { "qws", I18N_NOOP("forces the application to run as QWS Server"), 0},
01423 #endif
01424 { "reverse", I18N_NOOP("mirrors the whole layout of widgets"), 0},
01425 KCmdLineLastOption
01426 };
01427
01428 static const KCmdLineOptions kde_options[] =
01429 {
01430 { "caption <caption>", I18N_NOOP("Use 'caption' as name in the titlebar"), 0},
01431 { "icon <icon>", I18N_NOOP("Use 'icon' as the application icon"), 0},
01432 { "miniicon <icon>", I18N_NOOP("Use 'icon' as the icon in the titlebar"), 0},
01433 { "config <filename>", I18N_NOOP("Use alternative configuration file"), 0},
01434 { "dcopserver <server>", I18N_NOOP("Use the DCOP Server specified by 'server'"), 0},
01435 { "nocrashhandler", I18N_NOOP("Disable crash handler, to get core dumps"), 0},
01436 { "waitforwm", I18N_NOOP("Waits for a WM_NET compatible windowmanager"), 0},
01437 { "style <style>", I18N_NOOP("sets the application GUI style"), 0},
01438 { "geometry <geometry>", I18N_NOOP("sets the client geometry of the main widget - see man X for the argument format"), 0},
01439 { "smkey <sessionKey>", 0, 0},
01440
01441
01442 KCmdLineLastOption
01443 };
01444
01445 void
01446 KApplication::addCmdLineOptions()
01447 {
01448 KCmdLineArgs::addCmdLineOptions(qt_options, "Qt", "qt");
01449 KCmdLineArgs::addCmdLineOptions(kde_options, "KDE", "kde");
01450 }
01451
01452 void KApplication::parseCommandLine( )
01453 {
01454 KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde");
01455
01456 if ( !args ) return;
01457
01458 if (args->isSet("config"))
01459 {
01460 QString config = QString::fromLocal8Bit(args->getOption("config"));
01461 setConfigName(config);
01462 }
01463
01464 if (args->isSet("style"))
01465 {
01466
01467 QStringList styles = QStyleFactory::keys();
01468 QString reqStyle(args->getOption("style").lower());
01469
01470 for (QStringList::ConstIterator it = styles.begin(); it != styles.end(); ++it)
01471 if ((*it).lower() == reqStyle)
01472 {
01473 d->overrideStyle = *it;
01474 break;
01475 }
01476
01477 if (d->overrideStyle.isEmpty())
01478 fprintf(stderr, "%s", i18n("The style %1 was not found\n").arg(reqStyle).local8Bit().data());
01479 }
01480
01481 if (args->isSet("caption"))
01482 {
01483 aCaption = QString::fromLocal8Bit(args->getOption("caption"));
01484 }
01485
01486 if (args->isSet("miniicon"))
01487 {
01488 const char *tmp = args->getOption("miniicon");
01489 if (!aIconPixmap.pm.miniIcon) {
01490 aIconPixmap.pm.miniIcon = new QPixmap;
01491 }
01492 *aIconPixmap.pm.miniIcon = SmallIcon(tmp);
01493 aMiniIconName = tmp;
01494 }
01495
01496 if (args->isSet("icon"))
01497 {
01498 const char *tmp = args->getOption("icon");
01499 if (!aIconPixmap.pm.icon) {
01500 aIconPixmap.pm.icon = new QPixmap;
01501 }
01502 *aIconPixmap.pm.icon = DesktopIcon( tmp );
01503 aIconName = tmp;
01504 if (!aIconPixmap.pm.miniIcon) {
01505 aIconPixmap.pm.miniIcon = new QPixmap;
01506 }
01507 if (aIconPixmap.pm.miniIcon->isNull())
01508 {
01509 *aIconPixmap.pm.miniIcon = SmallIcon( tmp );
01510 aMiniIconName = tmp;
01511 }
01512 }
01513
01514 bool nocrashhandler = (getenv("KDE_DEBUG") != NULL);
01515 if (!nocrashhandler && args->isSet("crashhandler"))
01516 {
01517
01518 KCrash::setCrashHandler(KCrash::defaultCrashHandler);
01519 KCrash::setEmergencySaveFunction(NULL);
01520
01521 KCrash::setApplicationName(QString(args->appName()));
01522 }
01523
01524 #ifdef Q_WS_X11
01525 if ( args->isSet( "waitforwm" ) ) {
01526 Atom type;
01527 (void) desktop();
01528 int format;
01529 unsigned long length, after;
01530 unsigned char *data;
01531 while ( XGetWindowProperty( qt_xdisplay(), qt_xrootwin(), atom_NetSupported,
01532 0, 1, false, AnyPropertyType, &type, &format,
01533 &length, &after, &data ) != Success || !length ) {
01534 if ( data )
01535 XFree( data );
01536 XEvent event;
01537 XWindowEvent( qt_xdisplay(), qt_xrootwin(), PropertyChangeMask, &event );
01538 }
01539 if ( data )
01540 XFree( data );
01541 }
01542 #else
01543
01544 #endif
01545
01546 if (args->isSet("geometry"))
01547 {
01548 d->geometry_arg = args->getOption("geometry");
01549 }
01550
01551 if (args->isSet("smkey"))
01552 {
01553 d->sessionKey = args->getOption("smkey");
01554 }
01555
01556 }
01557
01558 QString KApplication::geometryArgument() const
01559 {
01560 return d->geometry_arg;
01561 }
01562
01563 QPixmap KApplication::icon() const
01564 {
01565 if( !aIconPixmap.pm.icon) {
01566 aIconPixmap.pm.icon = new QPixmap;
01567 }
01568 if( aIconPixmap.pm.icon->isNull()) {
01569 *aIconPixmap.pm.icon = DesktopIcon( instanceName() );
01570 }
01571 return *aIconPixmap.pm.icon;
01572 }
01573
01574 QString KApplication::iconName() const
01575 {
01576 return aIconName.isNull() ? (QString)instanceName() : aIconName;
01577 }
01578
01579 QPixmap KApplication::miniIcon() const
01580 {
01581 if (!aIconPixmap.pm.miniIcon) {
01582 aIconPixmap.pm.miniIcon = new QPixmap;
01583 }
01584 if (aIconPixmap.pm.miniIcon->isNull()) {
01585 *aIconPixmap.pm.miniIcon = SmallIcon( instanceName() );
01586 }
01587 return *aIconPixmap.pm.miniIcon;
01588 }
01589
01590 QString KApplication::miniIconName() const
01591 {
01592 return aMiniIconName.isNull() ? (QString)instanceName() : aMiniIconName;
01593 }
01594
01595 extern void kDebugCleanup();
01596
01597 KApplication::~KApplication()
01598 {
01599 delete aIconPixmap.pm.miniIcon;
01600 aIconPixmap.pm.miniIcon = 0L;
01601 delete aIconPixmap.pm.icon;
01602 aIconPixmap.pm.icon = 0L;
01603 delete d->m_KAppDCOPInterface;
01604
01605
01606
01607
01608 KGlobal::deleteStaticDeleters();
01609 KLibLoader::cleanUp();
01610
01611 delete smw;
01612
01613
01614 delete s_DCOPClient;
01615 s_DCOPClient = 0L;
01616
01617 KProcessController::deref();
01618
01619 #ifdef Q_WS_X11
01620 if ( d->oldXErrorHandler != NULL )
01621 XSetErrorHandler( d->oldXErrorHandler );
01622 if ( d->oldXIOErrorHandler != NULL )
01623 XSetIOErrorHandler( d->oldXIOErrorHandler );
01624 if ( d->oldIceIOErrorHandler != NULL )
01625 IceSetIOErrorHandler( d->oldIceIOErrorHandler );
01626 #endif
01627
01628 delete d;
01629 KApp = 0;
01630
01631 #ifdef Q_WS_X11
01632 mySmcConnection = 0;
01633 delete smModificationTime;
01634 smModificationTime = 0;
01635
01636
01637 if (tmpSmcConnection) {
01638 SmcCloseConnection( tmpSmcConnection, 0, 0 );
01639 tmpSmcConnection = 0;
01640 }
01641 #else
01642
01643 #endif
01644 }
01645
01646
01647 #ifdef Q_WS_X11
01648 class KAppX11HackWidget: public QWidget
01649 {
01650 public:
01651 bool publicx11Event( XEvent * e) { return x11Event( e ); }
01652 };
01653 #endif
01654
01655
01656
01657 static bool kapp_block_user_input = false;
01658
01659 void KApplication::dcopBlockUserInput( bool b )
01660 {
01661 kapp_block_user_input = b;
01662 }
01663
01664 #ifdef Q_WS_X11
01665 bool KApplication::x11EventFilter( XEvent *_event )
01666 {
01667 switch ( _event->type ) {
01668 case ClientMessage:
01669 {
01670 #if KDE_IS_VERSION( 3, 90, 90 )
01671 #warning This should be already in Qt, check.
01672 #endif
01673
01674
01675
01676
01677
01678 if( _event->xclient.message_type == kde_xdnd_drop )
01679 {
01680 if( _event->xclient.data.l[ 1 ] == 1 << 24
01681 && _event->xclient.data.l[ 2 ] == 0
01682 && _event->xclient.data.l[ 4 ] == 0
01683 && _event->xclient.data.l[ 3 ] != 0 )
01684 {
01685 if( qt_x_user_time == 0
01686 || NET::timestampCompare( _event->xclient.data.l[ 3 ], qt_x_user_time ) > 0 )
01687 {
01688 qt_x_user_time = _event->xclient.data.l[ 3 ];
01689 }
01690 }
01691 else
01692 {
01693 if( qt_x_user_time == 0
01694 || NET::timestampCompare( _event->xclient.data.l[ 2 ], qt_x_user_time ) > 0 )
01695 {
01696 qt_x_user_time = _event->xclient.data.l[ 2 ];
01697 }
01698 }
01699 }
01700 }
01701 default: break;
01702 }
01703
01704 if ( kapp_block_user_input ) {
01705 switch ( _event->type ) {
01706 case ButtonPress:
01707 case ButtonRelease:
01708 case XKeyPress:
01709 case XKeyRelease:
01710 case MotionNotify:
01711 case EnterNotify:
01712 case LeaveNotify:
01713 return true;
01714 default:
01715 break;
01716 }
01717 }
01718
01719 if (x11Filter) {
01720 for (QWidget *w=x11Filter->first(); w; w=x11Filter->next()) {
01721 if (((KAppX11HackWidget*) w)->publicx11Event(_event))
01722 return true;
01723 }
01724 }
01725
01726 if ((_event->type == ClientMessage) &&
01727 (_event->xclient.message_type == kipcCommAtom))
01728 {
01729 XClientMessageEvent *cme = (XClientMessageEvent *) _event;
01730
01731 int id = cme->data.l[0];
01732 int arg = cme->data.l[1];
01733 if ((id < 32) && (kipcEventMask & (1 << id)))
01734 {
01735 switch (id)
01736 {
01737 case KIPC::StyleChanged:
01738 KGlobal::config()->reparseConfiguration();
01739 kdisplaySetStyle();
01740 break;
01741
01742 case KIPC::ToolbarStyleChanged:
01743 KGlobal::config()->reparseConfiguration();
01744 if (useStyles)
01745 emit toolbarAppearanceChanged(arg);
01746 break;
01747
01748 case KIPC::PaletteChanged:
01749 KGlobal::config()->reparseConfiguration();
01750 kdisplaySetPalette();
01751 break;
01752
01753 case KIPC::FontChanged:
01754 KGlobal::config()->reparseConfiguration();
01755 KGlobalSettings::rereadFontSettings();
01756 kdisplaySetFont();
01757 break;
01758
01759 case KIPC::BackgroundChanged:
01760 emit backgroundChanged(arg);
01761 break;
01762
01763 case KIPC::SettingsChanged:
01764 KGlobal::config()->reparseConfiguration();
01765 if (arg == SETTINGS_PATHS)
01766 KGlobalSettings::rereadPathSettings();
01767 else if (arg == SETTINGS_MOUSE)
01768 KGlobalSettings::rereadMouseSettings();
01769 propagateSettings((SettingsCategory)arg);
01770 break;
01771
01772 case KIPC::IconChanged:
01773 QPixmapCache::clear();
01774 KGlobal::config()->reparseConfiguration();
01775 KGlobal::instance()->newIconLoader();
01776 emit iconChanged(arg);
01777 break;
01778
01779 case KIPC::ClipboardConfigChanged:
01780 KClipboardSynchronizer::newConfiguration(arg);
01781 break;
01782
01783 case KIPC::BlockShortcuts:
01784 KGlobalAccel::blockShortcuts(arg);
01785 emit kipcMessage(id, arg);
01786 break;
01787 }
01788 }
01789 else if (id >= 32)
01790 {
01791 emit kipcMessage(id, arg);
01792 }
01793 return true;
01794 }
01795 return false;
01796 }
01797 #endif // Q_WS_X11
01798
01799 void KApplication::updateUserTimestamp( unsigned long time )
01800 {
01801 #if defined Q_WS_X11
01802 if( time == 0 )
01803 {
01804 Window w = XCreateSimpleWindow( qt_xdisplay(), qt_xrootwin(), 0, 0, 1, 1, 0, 0, 0 );
01805 XSelectInput( qt_xdisplay(), w, PropertyChangeMask );
01806 unsigned char data[ 1 ];
01807 XChangeProperty( qt_xdisplay(), w, XA_ATOM, XA_ATOM, 8, PropModeAppend, data, 1 );
01808 XEvent ev;
01809 XWindowEvent( qt_xdisplay(), w, PropertyChangeMask, &ev );
01810 time = ev.xproperty.time;
01811 XDestroyWindow( qt_xdisplay(), w );
01812 }
01813 if( qt_x_user_time == 0
01814 || NET::timestampCompare( time, qt_x_user_time ) > 0 )
01815 qt_x_user_time = time;
01816 #endif
01817 }
01818
01819 unsigned long KApplication::userTimestamp() const
01820 {
01821 #if defined Q_WS_X11
01822 return qt_x_user_time;
01823 #else
01824 return 0;
01825 #endif
01826 }
01827
01828 void KApplication::updateRemoteUserTimestamp( const QCString& dcopId, unsigned long time )
01829 {
01830 #if defined Q_WS_X11
01831 if( time == 0 )
01832 time = qt_x_user_time;
01833 DCOPRef( dcopId, "MainApplication-Interface" ).call( "updateUserTimestamp", time );
01834 #endif
01835 }
01836
01837 void KApplication::invokeEditSlot( const char *slot )
01838 {
01839 QObject *object = focusWidget();
01840 if( !object )
01841 return;
01842
01843 QMetaObject *meta = object->metaObject();
01844
01845 int idx = meta->findSlot( slot + 1, true );
01846 if( idx < 0 )
01847 return;
01848
01849 object->qt_invoke( idx, 0 );
01850 }
01851
01852 void KApplication::addKipcEventMask(int id)
01853 {
01854 if (id >= 32)
01855 {
01856 kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01857 return;
01858 }
01859 kipcEventMask |= (1 << id);
01860 }
01861
01862 void KApplication::removeKipcEventMask(int id)
01863 {
01864 if (id >= 32)
01865 {
01866 kdDebug(101) << "Cannot use KIPC event mask for message IDs >= 32\n";
01867 return;
01868 }
01869 kipcEventMask &= ~(1 << id);
01870 }
01871
01872 void KApplication::enableStyles()
01873 {
01874 if (!useStyles)
01875 {
01876 useStyles = true;
01877 applyGUIStyle();
01878 }
01879 }
01880
01881 void KApplication::disableStyles()
01882 {
01883 useStyles = false;
01884 }
01885
01886 void KApplication::applyGUIStyle()
01887 {
01888 if ( !useStyles ) return;
01889
01890 KConfigGroup pConfig (KGlobal::config(), "General");
01891 QString defaultStyle = KStyle::defaultStyle();
01892 QString styleStr = pConfig.readEntry("widgetStyle", defaultStyle);
01893
01894 if (d->overrideStyle.isEmpty()) {
01895
01896
01897
01898 QStyle* sp = QStyleFactory::create( styleStr );
01899
01900
01901 if ( !sp && styleStr != defaultStyle)
01902 sp = QStyleFactory::create( defaultStyle );
01903 if ( !sp )
01904 sp = QStyleFactory::create( *(QStyleFactory::keys().begin()) );
01905 setStyle(sp);
01906 }
01907 else
01908 setStyle(d->overrideStyle);
01909
01910 kdisplaySetPalette();
01911
01912 QApplication::x11_apply_settings();
01913 }
01914
01915 QString KApplication::caption() const
01916 {
01917
01918 if( !aCaption.isNull() )
01919 return aCaption;
01920 else
01921
01922 if ( KGlobal::instance()->aboutData() )
01923 return KGlobal::instance()->aboutData()->programName();
01924 else
01925
01926 return name();
01927 }
01928
01929
01930
01931
01932
01933
01934 QString KApplication::makeStdCaption( const QString &userCaption,
01935 bool withAppName, bool modified ) const
01936 {
01937 QString s = userCaption.isEmpty() ? caption() : userCaption;
01938
01939
01940 if (modified)
01941 s += QString::fromUtf8(" [") + i18n("modified") + QString::fromUtf8("]");
01942
01943 if ( !userCaption.isEmpty() ) {
01944
01945
01946 if ( withAppName && !caption().isNull() && !userCaption.endsWith(caption()) )
01947 s += QString::fromUtf8(" - ") + caption();
01948 }
01949
01950 return s;
01951 }
01952
01953 QPalette KApplication::createApplicationPalette()
01954 {
01955 KConfig *config = KGlobal::config();
01956 KConfigGroupSaver saver( config, "General" );
01957 return createApplicationPalette( config, KGlobalSettings::contrast() );
01958 }
01959
01960 QPalette KApplication::createApplicationPalette( KConfig *config, int contrast_ )
01961 {
01962 QColor kde34Background( 239, 239, 239 );
01963 QColor kde34Blue( 103,141,178 );
01964
01965 QColor kde34Button;
01966 if ( QPixmap::defaultDepth() > 8 )
01967 kde34Button.setRgb( 221, 223, 228 );
01968 else
01969 kde34Button.setRgb( 220, 220, 220 );
01970
01971 QColor kde34Link( 0, 0, 238 );
01972 QColor kde34VisitedLink( 82, 24, 139 );
01973
01974 QColor background = config->readColorEntry( "background", &kde34Background );
01975 QColor foreground = config->readColorEntry( "foreground", &black );
01976 QColor button = config->readColorEntry( "buttonBackground", &kde34Button );
01977 QColor buttonText = config->readColorEntry( "buttonForeground", &black );
01978 QColor highlight = config->readColorEntry( "selectBackground", &kde34Blue );
01979 QColor highlightedText = config->readColorEntry( "selectForeground", &white );
01980 QColor base = config->readColorEntry( "windowBackground", &white );
01981 QColor baseText = config->readColorEntry( "windowForeground", &black );
01982 QColor link = config->readColorEntry( "linkColor", &kde34Link );
01983 QColor visitedLink = config->readColorEntry( "visitedLinkColor", &kde34VisitedLink );
01984
01985 int highlightVal, lowlightVal;
01986 highlightVal = 100 + (2*contrast_+4)*16/10;
01987 lowlightVal = 100 + (2*contrast_+4)*10;
01988
01989 QColor disfg = foreground;
01990
01991 int h, s, v;
01992 disfg.hsv( &h, &s, &v );
01993 if (v > 128)
01994
01995 disfg = disfg.dark(lowlightVal);
01996 else if (disfg != black)
01997
01998 disfg = disfg.light(highlightVal);
01999 else
02000
02001 disfg = Qt::darkGray;
02002
02003
02004 QColorGroup disabledgrp(disfg, background,
02005 background.light(highlightVal),
02006 background.dark(lowlightVal),
02007 background.dark(120),
02008 background.dark(120), base);
02009
02010 QColorGroup colgrp(foreground, background, background.light(highlightVal),
02011 background.dark(lowlightVal),
02012 background.dark(120),
02013 baseText, base);
02014
02015 int inlowlightVal = lowlightVal-25;
02016 if(inlowlightVal < 120)
02017 inlowlightVal = 120;
02018
02019 colgrp.setColor(QColorGroup::Highlight, highlight);
02020 colgrp.setColor(QColorGroup::HighlightedText, highlightedText);
02021 colgrp.setColor(QColorGroup::Button, button);
02022 colgrp.setColor(QColorGroup::ButtonText, buttonText);
02023 colgrp.setColor(QColorGroup::Midlight, background.light(110));
02024 colgrp.setColor(QColorGroup::Link, link);
02025 colgrp.setColor(QColorGroup::LinkVisited, visitedLink);
02026
02027 disabledgrp.setColor(QColorGroup::Button, button);
02028
02029 QColor disbtntext = buttonText;
02030 disbtntext.hsv( &h, &s, &v );
02031 if (v > 128)
02032
02033 disbtntext = disbtntext.dark(lowlightVal);
02034 else if (disbtntext != black)
02035
02036 disbtntext = disbtntext.light(highlightVal);
02037 else
02038
02039 disbtntext = Qt::darkGray;
02040
02041 disabledgrp.setColor(QColorGroup::ButtonText, disbtntext);
02042 disabledgrp.setColor(QColorGroup::Midlight, background.light(110));
02043 disabledgrp.setColor(QColorGroup::Highlight, highlight.dark(120));
02044 disabledgrp.setColor(QColorGroup::Link, link);
02045 disabledgrp.setColor(QColorGroup::LinkVisited, visitedLink);
02046
02047 return QPalette(colgrp, disabledgrp, colgrp);
02048 }
02049
02050
02051 void KApplication::kdisplaySetPalette()
02052 {
02053 #ifdef Q_WS_MACX
02054
02055 {
02056 KConfig *config = KGlobal::config();
02057 KConfigGroupSaver saver( config, "General" );
02058 bool do_not_set_palette = FALSE;
02059 if(config->readBoolEntry("nopaletteChange", &do_not_set_palette))
02060 return;
02061 }
02062 #endif
02063 QApplication::setPalette( createApplicationPalette(), true);
02064 emit kdisplayPaletteChanged();
02065 emit appearanceChanged();
02066 }
02067
02068
02069 void KApplication::kdisplaySetFont()
02070 {
02071 QApplication::setFont(KGlobalSettings::generalFont(), true);
02072 QApplication::setFont(KGlobalSettings::menuFont(), true, "QMenuBar");
02073 QApplication::setFont(KGlobalSettings::menuFont(), true, "QPopupMenu");
02074 QApplication::setFont(KGlobalSettings::menuFont(), true, "KPopupTitle");
02075
02076
02077 QStyleSheet* sheet = QStyleSheet::defaultSheet();
02078 sheet->item ("pre")->setFontFamily (KGlobalSettings::fixedFont().family());
02079 sheet->item ("code")->setFontFamily (KGlobalSettings::fixedFont().family());
02080 sheet->item ("tt")->setFontFamily (KGlobalSettings::fixedFont().family());
02081
02082 emit kdisplayFontChanged();
02083 emit appearanceChanged();
02084 }
02085
02086
02087 void KApplication::kdisplaySetStyle()
02088 {
02089 if (useStyles)
02090 {
02091 applyGUIStyle();
02092 emit kdisplayStyleChanged();
02093 emit appearanceChanged();
02094 }
02095 }
02096
02097
02098 void KApplication::propagateSettings(SettingsCategory arg)
02099 {
02100 KConfigBase* config = KGlobal::config();
02101 KConfigGroupSaver saver( config, "KDE" );
02102
02103 int num = config->readNumEntry("CursorBlinkRate", QApplication::cursorFlashTime());
02104 if ((num != 0) && (num < 200))
02105 num = 200;
02106 if (num > 2000)
02107 num = 2000;
02108 QApplication::setCursorFlashTime(num);
02109 num = config->readNumEntry("DoubleClickInterval", QApplication::doubleClickInterval());
02110 QApplication::setDoubleClickInterval(num);
02111 num = config->readNumEntry("StartDragTime", QApplication::startDragTime());
02112 QApplication::setStartDragTime(num);
02113 num = config->readNumEntry("StartDragDist", QApplication::startDragDistance());
02114 QApplication::setStartDragDistance(num);
02115 num = config->readNumEntry("WheelScrollLines", QApplication::wheelScrollLines());
02116 QApplication::setWheelScrollLines(num);
02117
02118 bool b = config->readBoolEntry("EffectAnimateMenu", false);
02119 QApplication::setEffectEnabled( Qt::UI_AnimateMenu, b);
02120 b = config->readBoolEntry("EffectFadeMenu", false);
02121 QApplication::setEffectEnabled( Qt::UI_FadeMenu, b);
02122 b = config->readBoolEntry("EffectAnimateCombo", false);
02123 QApplication::setEffectEnabled( Qt::UI_AnimateCombo, b);
02124 b = config->readBoolEntry("EffectAnimateTooltip", false);
02125 QApplication::setEffectEnabled( Qt::UI_AnimateTooltip, b);
02126 b = config->readBoolEntry("EffectFadeTooltip", false);
02127 QApplication::setEffectEnabled( Qt::UI_FadeTooltip, b);
02128 b = !config->readBoolEntry("EffectNoTooltip", false);
02129 QToolTip::setGloballyEnabled( b );
02130
02131 emit settingsChanged(arg);
02132 }
02133
02134 void KApplication::installKDEPropertyMap()
02135 {
02136 #ifndef QT_NO_SQL
02137 static bool installed = false;
02138 if (installed) return;
02139 installed = true;
02146
02147 QSqlPropertyMap *kdeMap = new QSqlPropertyMap;
02148 kdeMap->insert( "KColorButton", "color" );
02149 kdeMap->insert( "KComboBox", "currentItem" );
02150 kdeMap->insert( "KDatePicker", "date" );
02151 kdeMap->insert( "KDateWidget", "date" );
02152 kdeMap->insert( "KDateTimeWidget", "dateTime" );
02153 kdeMap->insert( "KEditListBox", "items" );
02154 kdeMap->insert( "KFontCombo", "family" );
02155 kdeMap->insert( "KFontRequester", "font" );
02156 kdeMap->insert( "KFontChooser", "font" );
02157 kdeMap->insert( "KHistoryCombo", "currentItem" );
02158 kdeMap->insert( "KListBox", "currentItem" );
02159 kdeMap->insert( "KLineEdit", "text" );
02160 kdeMap->insert( "KRestrictedLine", "text" );
02161 kdeMap->insert( "KSqueezedTextLabel", "text" );
02162 kdeMap->insert( "KTextBrowser", "source" );
02163 kdeMap->insert( "KTextEdit", "text" );
02164 kdeMap->insert( "KURLRequester", "url" );
02165 kdeMap->insert( "KPasswordEdit", "password" );
02166 kdeMap->insert( "KIntNumInput", "value" );
02167 kdeMap->insert( "KIntSpinBox", "value" );
02168 kdeMap->insert( "KDoubleNumInput", "value" );
02169
02170 kdeMap->insert( "QGroupBox", "checked" );
02171 kdeMap->insert( "QTabWidget", "currentPage" );
02172 QSqlPropertyMap::installDefaultMap( kdeMap );
02173 #endif
02174 }
02175
02176 void KApplication::invokeHelp( const QString& anchor,
02177 const QString& _appname) const
02178 {
02179 return invokeHelp( anchor, _appname, "" );
02180 }
02181
02182 #ifndef Q_WS_WIN
02183
02184
02185 void KApplication::invokeHelp( const QString& anchor,
02186 const QString& _appname,
02187 const QCString& startup_id ) const
02188 {
02189 QString url;
02190 QString appname;
02191 if (_appname.isEmpty())
02192 appname = name();
02193 else
02194 appname = _appname;
02195
02196 if (!anchor.isEmpty())
02197 url = QString("help:/%1?anchor=%2").arg(appname).arg(anchor);
02198 else
02199 url = QString("help:/%1/index.html").arg(appname);
02200
02201 QString error;
02202 if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02203 {
02204 if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, startup_id, false))
02205 {
02206 if (Tty != kapp->type())
02207 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02208 i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02209 else
02210 kdWarning() << "Could not launch help:\n" << error << endl;
02211 return;
02212 }
02213 }
02214 else
02215 DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url, startup_id );
02216 }
02217 #endif
02218
02219 void KApplication::invokeHTMLHelp( const QString& _filename, const QString& topic ) const
02220 {
02221 kdWarning() << "invoking HTML help is deprecated! use docbook and invokeHelp!\n";
02222
02223 QString filename;
02224
02225 if( _filename.isEmpty() )
02226 filename = QString(name()) + "/index.html";
02227 else
02228 filename = _filename;
02229
02230 QString url;
02231 if (!topic.isEmpty())
02232 url = QString("help:/%1#%2").arg(filename).arg(topic);
02233 else
02234 url = QString("help:/%1").arg(filename);
02235
02236 QString error;
02237 if ( !dcopClient()->isApplicationRegistered("khelpcenter") )
02238 {
02239 if (startServiceByDesktopName("khelpcenter", url, &error, 0, 0, "", false))
02240 {
02241 if (Tty != kapp->type())
02242 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Help Center"),
02243 i18n("Could not launch the KDE Help Center:\n\n%1").arg(error), i18n("&OK"));
02244 else
02245 kdWarning() << "Could not launch help:\n" << error << endl;
02246 return;
02247 }
02248 }
02249 else
02250 DCOPRef( "khelpcenter", "KHelpCenterIface" ).send( "openUrl", url );
02251 }
02252
02253
02254 void KApplication::invokeMailer(const QString &address, const QString &subject)
02255 {
02256 return invokeMailer(address,subject,"");
02257 }
02258
02259 void KApplication::invokeMailer(const QString &address, const QString &subject, const QCString& startup_id)
02260 {
02261 invokeMailer(address, QString::null, QString::null, subject, QString::null, QString::null,
02262 QStringList(), startup_id );
02263 }
02264
02265 void KApplication::invokeMailer(const KURL &mailtoURL)
02266 {
02267 return invokeMailer( mailtoURL, "" );
02268 }
02269
02270 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id )
02271 {
02272 return invokeMailer( mailtoURL, startup_id, false);
02273 }
02274
02275 void KApplication::invokeMailer(const KURL &mailtoURL, const QCString& startup_id, bool allowAttachments )
02276 {
02277 QString address = KURL::decode_string(mailtoURL.path()), subject, cc, bcc, body;
02278 QStringList queries = QStringList::split('&', mailtoURL.query().mid(1));
02279 QStringList attachURLs;
02280 for (QStringList::Iterator it = queries.begin(); it != queries.end(); ++it)
02281 {
02282 QString q = (*it).lower();
02283 if (q.startsWith("subject="))
02284 subject = KURL::decode_string((*it).mid(8));
02285 else
02286 if (q.startsWith("cc="))
02287 cc = cc.isEmpty()? KURL::decode_string((*it).mid(3)): cc + ',' + KURL::decode_string((*it).mid(3));
02288 else
02289 if (q.startsWith("bcc="))
02290 bcc = bcc.isEmpty()? KURL::decode_string((*it).mid(4)): bcc + ',' + KURL::decode_string((*it).mid(4));
02291 else
02292 if (q.startsWith("body="))
02293 body = KURL::decode_string((*it).mid(5));
02294 else
02295 if (allowAttachments && q.startsWith("attach="))
02296 attachURLs.push_back(KURL::decode_string((*it).mid(7)));
02297 else
02298 if (allowAttachments && q.startsWith("attachment="))
02299 attachURLs.push_back(KURL::decode_string((*it).mid(11)));
02300 else
02301 if (q.startsWith("to="))
02302 address = address.isEmpty()? KURL::decode_string((*it).mid(3)): address + ',' + KURL::decode_string((*it).mid(3));
02303 }
02304
02305 invokeMailer( address, cc, bcc, subject, body, QString::null, attachURLs, startup_id );
02306 }
02307
02308 void KApplication::invokeMailer(const QString &to, const QString &cc, const QString &bcc,
02309 const QString &subject, const QString &body,
02310 const QString & messageFile, const QStringList &attachURLs)
02311 {
02312 return invokeMailer(to,cc,bcc,subject,body,messageFile,attachURLs,"");
02313 }
02314
02315 #ifndef Q_WS_WIN
02316
02317
02318
02319 static QStringList splitEmailAddressList( const QString & aStr )
02320 {
02321
02322
02323
02324
02325
02326
02327
02328
02329
02330 QStringList list;
02331
02332 if (aStr.isEmpty())
02333 return list;
02334
02335 QString addr;
02336 uint addrstart = 0;
02337 int commentlevel = 0;
02338 bool insidequote = false;
02339
02340 for (uint index=0; index<aStr.length(); index++) {
02341
02342
02343 switch (aStr[index].latin1()) {
02344 case '"' :
02345 if (commentlevel == 0)
02346 insidequote = !insidequote;
02347 break;
02348 case '(' :
02349 if (!insidequote)
02350 commentlevel++;
02351 break;
02352 case ')' :
02353 if (!insidequote) {
02354 if (commentlevel > 0)
02355 commentlevel--;
02356 else {
02357
02358
02359 return list;
02360 }
02361 }
02362 break;
02363 case '\\' :
02364 index++;
02365 break;
02366 case ',' :
02367 if (!insidequote && (commentlevel == 0)) {
02368 addr = aStr.mid(addrstart, index-addrstart);
02369 if (!addr.isEmpty())
02370 list += addr.simplifyWhiteSpace();
02371 addrstart = index+1;
02372 }
02373 break;
02374 }
02375 }
02376
02377 if (!insidequote && (commentlevel == 0)) {
02378 addr = aStr.mid(addrstart, aStr.length()-addrstart);
02379 if (!addr.isEmpty())
02380 list += addr.simplifyWhiteSpace();
02381 }
02382
02383
02384
02385
02386
02387 return list;
02388 }
02389
02390 void KApplication::invokeMailer(const QString &_to, const QString &_cc, const QString &_bcc,
02391 const QString &subject, const QString &body,
02392 const QString & , const QStringList &attachURLs,
02393 const QCString& startup_id )
02394 {
02395 KConfig config("emaildefaults");
02396
02397 config.setGroup("Defaults");
02398 QString group = config.readEntry("Profile","Default");
02399
02400 config.setGroup( QString("PROFILE_%1").arg(group) );
02401 QString command = config.readPathEntry("EmailClient");
02402
02403 QString to, cc, bcc;
02404 if (command.isEmpty() || command == QString::fromLatin1("kmail")
02405 || command.endsWith("/kmail"))
02406 {
02407 command = QString::fromLatin1("kmail --composer -s %s -c %c -b %b --body %B --attach %A -- %t");
02408 if ( !_to.isEmpty() )
02409 {
02410
02411
02412 to = QString( "=?utf8?b?%1?=" )
02413 .arg( KCodecs::base64Encode( _to.utf8(), false ) );
02414 }
02415 if ( !_cc.isEmpty() )
02416 cc = QString( "=?utf8?b?%1?=" )
02417 .arg( KCodecs::base64Encode( _cc.utf8(), false ) );
02418 if ( !_bcc.isEmpty() )
02419 bcc = QString( "=?utf8?b?%1?=" )
02420 .arg( KCodecs::base64Encode( _bcc.utf8(), false ) );
02421 } else {
02422 to = _to;
02423 cc = _cc;
02424 bcc = _bcc;
02425 if( !command.contains( '%' ))
02426 command += " %u";
02427 }
02428
02429 if (config.readBoolEntry("TerminalClient", false))
02430 {
02431 KConfigGroup confGroup( KGlobal::config(), "General" );
02432 QString preferredTerminal = confGroup.readPathEntry("TerminalApplication", "konsole");
02433 command = preferredTerminal + " -e " + command;
02434 }
02435
02436 QStringList cmdTokens = KShell::splitArgs(command);
02437 QString cmd = cmdTokens[0];
02438 cmdTokens.remove(cmdTokens.begin());
02439
02440 KURL url;
02441 QStringList qry;
02442 if (!to.isEmpty())
02443 {
02444 QStringList tos = splitEmailAddressList( to );
02445 url.setPath( tos.first() );
02446 tos.remove( tos.begin() );
02447 for (QStringList::ConstIterator it = tos.begin(); it != tos.end(); ++it)
02448 qry.append( "to=" + KURL::encode_string( *it ) );
02449 }
02450 const QStringList ccs = splitEmailAddressList( cc );
02451 for (QStringList::ConstIterator it = ccs.begin(); it != ccs.end(); ++it)
02452 qry.append( "cc=" + KURL::encode_string( *it ) );
02453 const QStringList bccs = splitEmailAddressList( bcc );
02454 for (QStringList::ConstIterator it = bccs.begin(); it != bccs.end(); ++it)
02455 qry.append( "bcc=" + KURL::encode_string( *it ) );
02456 for (QStringList::ConstIterator it = attachURLs.begin(); it != attachURLs.end(); ++it)
02457 qry.append( "attach=" + KURL::encode_string( *it ) );
02458 if (!subject.isEmpty())
02459 qry.append( "subject=" + KURL::encode_string( subject ) );
02460 if (!body.isEmpty())
02461 qry.append( "body=" + KURL::encode_string( body ) );
02462 url.setQuery( qry.join( "&" ) );
02463 if ( ! (to.isEmpty() && qry.isEmpty()) )
02464 url.setProtocol("mailto");
02465
02466 QMap<QChar, QString> keyMap;
02467 keyMap.insert('t', to);
02468 keyMap.insert('s', subject);
02469 keyMap.insert('c', cc);
02470 keyMap.insert('b', bcc);
02471 keyMap.insert('B', body);
02472 keyMap.insert('u', url.url());
02473
02474 QString attachlist = attachURLs.join(",");
02475 attachlist.prepend('\'');
02476 attachlist.append('\'');
02477 keyMap.insert('A', attachlist);
02478
02479 for (QStringList::Iterator it = cmdTokens.begin(); it != cmdTokens.end(); )
02480 {
02481 if (*it == "%A")
02482 {
02483 if (it == cmdTokens.begin())
02484 continue;
02485 QStringList::ConstIterator urlit = attachURLs.begin();
02486 QStringList::ConstIterator urlend = attachURLs.end();
02487 if ( urlit != urlend )
02488 {
02489 QStringList::Iterator previt = it;
02490 --previt;
02491 *it = *urlit;
02492 ++it;
02493 while ( ++urlit != urlend )
02494 {
02495 cmdTokens.insert( it, *previt );
02496 cmdTokens.insert( it, *urlit );
02497 }
02498 } else {
02499 --it;
02500 it = cmdTokens.remove( cmdTokens.remove( it ) );
02501 }
02502 } else {
02503 *it = KMacroExpander::expandMacros(*it, keyMap);
02504 ++it;
02505 }
02506 }
02507
02508 QString error;
02509
02510
02511 if (kdeinitExec(cmd, cmdTokens, &error, NULL, startup_id ))
02512 if (Tty != kapp->type())
02513 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Mail Client"),
02514 i18n("Could not launch the mail client:\n\n%1").arg(error), i18n("&OK"));
02515 else
02516 kdWarning() << "Could not launch mail client:\n" << error << endl;
02517 }
02518 #endif
02519
02520 void KApplication::invokeBrowser( const QString &url )
02521 {
02522 return invokeBrowser( url, "" );
02523 }
02524
02525 #ifndef Q_WS_WIN
02526
02527
02528 void KApplication::invokeBrowser( const QString &url, const QCString& startup_id )
02529 {
02530 QString error;
02531
02532 if (startServiceByDesktopName("kfmclient", url, &error, 0, 0, startup_id, false))
02533 {
02534 if (Tty != kapp->type())
02535 QMessageBox::critical(kapp->mainWidget(), i18n("Could not Launch Browser"),
02536 i18n("Could not launch the browser:\n\n%1").arg(error), i18n("&OK"));
02537 else
02538 kdWarning() << "Could not launch browser:\n" << error << endl;
02539 return;
02540 }
02541 }
02542 #endif
02543
02544 void KApplication::cut()
02545 {
02546 invokeEditSlot( SLOT( cut() ) );
02547 }
02548
02549 void KApplication::copy()
02550 {
02551 invokeEditSlot( SLOT( copy() ) );
02552 }
02553
02554 void KApplication::paste()
02555 {
02556 invokeEditSlot( SLOT( paste() ) );
02557 }
02558
02559 void KApplication::clear()
02560 {
02561 invokeEditSlot( SLOT( clear() ) );
02562 }
02563
02564 void KApplication::selectAll()
02565 {
02566 invokeEditSlot( SLOT( selectAll() ) );
02567 }
02568
02569 QCString
02570 KApplication::launcher()
02571 {
02572 return "klauncher";
02573 }
02574
02575 static int
02576 startServiceInternal( const QCString &function,
02577 const QString& _name, const QStringList &URLs,
02578 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02579 {
02580 struct serviceResult
02581 {
02582 int result;
02583 QCString dcopName;
02584 QString error;
02585 pid_t pid;
02586 };
02587
02588
02589 DCOPClient *dcopClient;
02590 if (kapp)
02591 dcopClient = kapp->dcopClient();
02592 else
02593 dcopClient = new DCOPClient;
02594
02595 if (!dcopClient->isAttached())
02596 {
02597 if (!dcopClient->attach())
02598 {
02599 if (error)
02600 *error = i18n("Could not register with DCOP.\n");
02601 return -1;
02602 }
02603 }
02604 QByteArray params;
02605 QDataStream stream(params, IO_WriteOnly);
02606 stream << _name << URLs;
02607 QCString replyType;
02608 QByteArray replyData;
02609 QCString _launcher = KApplication::launcher();
02610 QValueList<QCString> envs;
02611 #ifdef Q_WS_X11
02612 if (qt_xdisplay()) {
02613 QCString dpystring(XDisplayString(qt_xdisplay()));
02614 envs.append( QCString("DISPLAY=") + dpystring );
02615 } else if( getenv( "DISPLAY" )) {
02616 QCString dpystring( getenv( "DISPLAY" ));
02617 envs.append( QCString("DISPLAY=") + dpystring );
02618 }
02619 #endif
02620 stream << envs;
02621 #if defined Q_WS_X11
02622
02623 stream << ( startup_id.isEmpty() ? KStartupInfo::createNewStartupId() : startup_id );
02624 #endif
02625 if( function.left( 12 ) != "kdeinit_exec" )
02626 stream << noWait;
02627
02628 if (!dcopClient->call(_launcher, _launcher,
02629 function, params, replyType, replyData))
02630 {
02631 if (error)
02632 *error = i18n("KLauncher could not be reached via DCOP.\n");
02633 if (!kapp)
02634 delete dcopClient;
02635 return -1;
02636 }
02637 if (!kapp)
02638 delete dcopClient;
02639
02640 if (noWait)
02641 return 0;
02642
02643 QDataStream stream2(replyData, IO_ReadOnly);
02644 serviceResult result;
02645 stream2 >> result.result >> result.dcopName >> result.error >> result.pid;
02646 if (dcopService)
02647 *dcopService = result.dcopName;
02648 if (error)
02649 *error = result.error;
02650 if (pid)
02651 *pid = result.pid;
02652 return result.result;
02653 }
02654
02655 int
02656 KApplication::startServiceByName( const QString& _name, const QString &URL,
02657 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02658 {
02659 QStringList URLs;
02660 if (!URL.isEmpty())
02661 URLs.append(URL);
02662 return startServiceInternal(
02663 "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02664 _name, URLs, error, dcopService, pid, startup_id, noWait);
02665 }
02666
02667 int
02668 KApplication::startServiceByName( const QString& _name, const QStringList &URLs,
02669 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02670 {
02671 return startServiceInternal(
02672 "start_service_by_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02673 _name, URLs, error, dcopService, pid, startup_id, noWait);
02674 }
02675
02676 int
02677 KApplication::startServiceByDesktopPath( const QString& _name, const QString &URL,
02678 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02679 {
02680 QStringList URLs;
02681 if (!URL.isEmpty())
02682 URLs.append(URL);
02683 return startServiceInternal(
02684 "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02685 _name, URLs, error, dcopService, pid, startup_id, noWait);
02686 }
02687
02688 int
02689 KApplication::startServiceByDesktopPath( const QString& _name, const QStringList &URLs,
02690 QString *error, QCString *dcopService, int *pid, const QCString& startup_id, bool noWait )
02691 {
02692 return startServiceInternal(
02693 "start_service_by_desktop_path(QString,QStringList,QValueList<QCString>,QCString,bool)",
02694 _name, URLs, error, dcopService, pid, startup_id, noWait);
02695 }
02696
02697 int
02698 KApplication::startServiceByDesktopName( 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_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02706 _name, URLs, error, dcopService, pid, startup_id, noWait);
02707 }
02708
02709 int
02710 KApplication::startServiceByDesktopName( 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_desktop_name(QString,QStringList,QValueList<QCString>,QCString,bool)",
02715 _name, URLs, error, dcopService, pid, startup_id, noWait);
02716 }
02717
02718 int
02719 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02720 QString *error, int *pid )
02721 {
02722 return kdeinitExec( name, args, error, pid, "" );
02723 }
02724
02725 int
02726 KApplication::kdeinitExec( const QString& name, const QStringList &args,
02727 QString *error, int *pid, const QCString& startup_id )
02728 {
02729 return startServiceInternal("kdeinit_exec(QString,QStringList,QValueList<QCString>,QCString)",
02730 name, args, error, 0, pid, startup_id, false);
02731 }
02732
02733 int
02734 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02735 QString *error, int *pid )
02736 {
02737 return kdeinitExecWait( name, args, error, pid, "" );
02738 }
02739
02740 int
02741 KApplication::kdeinitExecWait( const QString& name, const QStringList &args,
02742 QString *error, int *pid, const QCString& startup_id )
02743 {
02744 return startServiceInternal("kdeinit_exec_wait(QString,QStringList,QValueList<QCString>,QCString)",
02745 name, args, error, 0, pid, startup_id, false);
02746 }
02747
02748 QString KApplication::tempSaveName( const QString& pFilename ) const
02749 {
02750 QString aFilename;
02751
02752 if( QDir::isRelativePath(pFilename) )
02753 {
02754 kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02755 aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02756 }
02757 else
02758 aFilename = pFilename;
02759
02760 QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02761 if( !aAutosaveDir.exists() )
02762 {
02763 if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02764 {
02765
02766 aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02767 }
02768 }
02769
02770 aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02771
02772 return aFilename;
02773 }
02774
02775
02776 QString KApplication::checkRecoverFile( const QString& pFilename,
02777 bool& bRecover ) const
02778 {
02779 QString aFilename;
02780
02781 if( QDir::isRelativePath(pFilename) )
02782 {
02783 kdWarning(101) << "Relative filename passed to KApplication::tempSaveName" << endl;
02784 aFilename = QFileInfo( QDir( "." ), pFilename ).absFilePath();
02785 }
02786 else
02787 aFilename = pFilename;
02788
02789 QDir aAutosaveDir( QDir::homeDirPath() + "/autosave/" );
02790 if( !aAutosaveDir.exists() )
02791 {
02792 if( !aAutosaveDir.mkdir( aAutosaveDir.absPath() ) )
02793 {
02794
02795 aAutosaveDir.setPath( KGlobal::dirs()->saveLocation("tmp") );
02796 }
02797 }
02798
02799 aFilename.replace( "/", "\\!" ).prepend( "#" ).append( "#" ).prepend( "/" ).prepend( aAutosaveDir.absPath() );
02800
02801 if( QFile( aFilename ).exists() )
02802 {
02803 bRecover = true;
02804 return aFilename;
02805 }
02806 else
02807 {
02808 bRecover = false;
02809 return pFilename;
02810 }
02811 }
02812
02813
02814 bool checkAccess(const QString& pathname, int mode)
02815 {
02816 int accessOK = access( QFile::encodeName(pathname), mode );
02817 if ( accessOK == 0 )
02818 return true;
02819
02820
02821
02822
02823 if ( (mode & W_OK) == 0 )
02824 return false;
02825
02826
02827 if (!access( QFile::encodeName(pathname), F_OK))
02828 return false;
02829
02830
02831 QString dirName(pathname);
02832 int pos = dirName.findRev('/');
02833 if ( pos == -1 )
02834 return false;
02835 else if ( pos == 0 )
02836 pos = 1;
02837
02838 dirName.truncate(pos);
02839
02840 accessOK = access( QFile::encodeName(dirName), W_OK );
02841
02842 if ( accessOK == 0 )
02843 return true;
02844 else
02845 return false;
02846 }
02847
02848 void KApplication::setTopWidget( QWidget *topWidget )
02849 {
02850 if( !topWidget )
02851 return;
02852
02853
02854 if ( !topWidget->inherits("KMainWindow") ) {
02855 topWidget->setCaption( caption() );
02856 }
02857
02858
02859 topWidget->setIcon( icon() );
02860 #if defined Q_WS_X11
02861
02862 KWin::setIcons(topWidget->winId(), icon(), miniIcon() );
02863
02864
02865 KStartupInfo::setWindowStartupId( topWidget->winId(), startupId());
02866 #endif
02867 }
02868
02869 QCString KApplication::startupId() const
02870 {
02871 return d->startup_id;
02872 }
02873
02874 void KApplication::setStartupId( const QCString& startup_id )
02875 {
02876 if( startup_id == d->startup_id )
02877 return;
02878 #if defined Q_WS_X11
02879 KStartupInfo::handleAutoAppStartedSending();
02880 #endif
02881 if( startup_id.isEmpty())
02882 d->startup_id = "0";
02883 else
02884 {
02885 d->startup_id = startup_id;
02886 #if defined Q_WS_X11
02887 KStartupInfoId id;
02888 id.initId( startup_id );
02889 long timestamp = id.timestamp();
02890 if( timestamp != 0 )
02891 updateUserTimestamp( timestamp );
02892 #endif
02893 }
02894 }
02895
02896
02897
02898 void KApplication::read_app_startup_id()
02899 {
02900 #if defined Q_WS_X11
02901 KStartupInfoId id = KStartupInfo::currentStartupIdEnv();
02902 KStartupInfo::resetStartupEnv();
02903 d->startup_id = id.id();
02904 #endif
02905 }
02906
02907 int KApplication::random()
02908 {
02909 static bool init = false;
02910 if (!init)
02911 {
02912 unsigned int seed;
02913 init = true;
02914 int fd = open("/dev/urandom", O_RDONLY);
02915 if (fd < 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed))
02916 {
02917
02918 srand(getpid());
02919 seed = rand()+time(0);
02920 }
02921 if (fd >= 0) close(fd);
02922 srand(seed);
02923 }
02924 return rand();
02925 }
02926
02927 QString KApplication::randomString(int length)
02928 {
02929 if (length <=0 ) return QString::null;
02930
02931 QString str; str.setLength( length );
02932 int i = 0;
02933 while (length--)
02934 {
02935 int r=random() % 62;
02936 r+=48;
02937 if (r>57) r+=7;
02938 if (r>90) r+=6;
02939 str[i++] = char(r);
02940
02941 }
02942 return str;
02943 }
02944
02945 bool KApplication::authorize(const QString &genericAction)
02946 {
02947 if (!d->actionRestrictions)
02948 return true;
02949
02950 KConfig *config = KGlobal::config();
02951 KConfigGroupSaver saver( config, "KDE Action Restrictions" );
02952 return config->readBoolEntry(genericAction, true);
02953 }
02954
02955 bool KApplication::authorizeKAction(const char *action)
02956 {
02957 if (!d->actionRestrictions || !action)
02958 return true;
02959
02960 static const QString &action_prefix = KGlobal::staticQString( "action/" );
02961
02962 return authorize(action_prefix + action);
02963 }
02964
02965 bool KApplication::authorizeControlModule(const QString &menuId)
02966 {
02967 if (menuId.isEmpty() || kde_kiosk_exception)
02968 return true;
02969 KConfig *config = KGlobal::config();
02970 KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02971 return config->readBoolEntry(menuId, true);
02972 }
02973
02974 QStringList KApplication::authorizeControlModules(const QStringList &menuIds)
02975 {
02976 KConfig *config = KGlobal::config();
02977 KConfigGroupSaver saver( config, "KDE Control Module Restrictions" );
02978 QStringList result;
02979 for(QStringList::ConstIterator it = menuIds.begin();
02980 it != menuIds.end(); ++it)
02981 {
02982 if (config->readBoolEntry(*it, true))
02983 result.append(*it);
02984 }
02985 return result;
02986 }
02987
02988 void KApplication::initUrlActionRestrictions()
02989 {
02990 d->urlActionRestrictions.setAutoDelete(true);
02991 d->urlActionRestrictions.clear();
02992 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02993 ("open", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
02994 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
02995 ("list", QString::null, QString::null, QString::null, QString::null, QString::null, QString::null, true));
02996
02997
02998
02999
03000
03001 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03002 ("link", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
03003 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03004 ("redirect", QString::null, QString::null, QString::null, ":internet", QString::null, QString::null, true));
03005
03006
03007
03008 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03009 ("redirect", QString::null, QString::null, QString::null, "file", QString::null, QString::null, true));
03010 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03011 ("redirect", ":internet", QString::null, QString::null, "file", QString::null, QString::null, false));
03012
03013
03014 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03015 ("redirect", ":local", QString::null, QString::null, QString::null, QString::null, QString::null, true));
03016
03017
03018 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03019 ("redirect", QString::null, QString::null, QString::null, "about", QString::null, QString::null, true));
03020
03021
03022 d->urlActionRestrictions.append( new KApplicationPrivate::URLActionRule
03023 ("redirect", QString::null, QString::null, QString::null, "=", QString::null, QString::null, true));
03024
03025 KConfig *config = KGlobal::config();
03026 KConfigGroupSaver saver( config, "KDE URL Restrictions" );
03027 int count = config->readNumEntry("rule_count");
03028 QString keyFormat = QString("rule_%1");
03029 for(int i = 1; i <= count; i++)
03030 {
03031 QString key = keyFormat.arg(i);
03032 QStringList rule = config->readListEntry(key);
03033 if (rule.count() != 8)
03034 continue;
03035 QString action = rule[0];
03036 QString refProt = rule[1];
03037 QString refHost = rule[2];
03038 QString refPath = rule[3];
03039 QString urlProt = rule[4];
03040 QString urlHost = rule[5];
03041 QString urlPath = rule[6];
03042 QString strEnabled = rule[7].lower();
03043
03044 bool bEnabled = (strEnabled == "true");
03045
03046 if (refPath.startsWith("$HOME"))
03047 refPath.replace(0, 5, QDir::homeDirPath());
03048 else if (refPath.startsWith("~"))
03049 refPath.replace(0, 1, QDir::homeDirPath());
03050 if (urlPath.startsWith("$HOME"))
03051 urlPath.replace(0, 5, QDir::homeDirPath());
03052 else if (urlPath.startsWith("~"))
03053 urlPath.replace(0, 1, QDir::homeDirPath());
03054
03055 if (refPath.startsWith("$TMP"))
03056 refPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
03057 if (urlPath.startsWith("$TMP"))
03058 urlPath.replace(0, 4, KGlobal::dirs()->saveLocation("tmp"));
03059
03060 d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
03061 ( action, refProt, refHost, refPath, urlProt, urlHost, urlPath, bEnabled));
03062 }
03063 }
03064
03065 void KApplication::allowURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
03066 {
03067 if (authorizeURLAction(action, _baseURL, _destURL))
03068 return;
03069
03070 d->urlActionRestrictions.append(new KApplicationPrivate::URLActionRule
03071 ( action, _baseURL.protocol(), _baseURL.host(), _baseURL.path(-1),
03072 _destURL.protocol(), _destURL.host(), _destURL.path(-1), true));
03073 }
03074
03075 bool KApplication::authorizeURLAction(const QString &action, const KURL &_baseURL, const KURL &_destURL)
03076 {
03077 if (_destURL.isEmpty())
03078 return true;
03079
03080 bool result = false;
03081 if (d->urlActionRestrictions.isEmpty())
03082 initUrlActionRestrictions();
03083
03084 KURL baseURL(_baseURL);
03085 baseURL.setPath(QDir::cleanDirPath(baseURL.path()));
03086 QString baseClass = KProtocolInfo::protocolClass(baseURL.protocol());
03087 KURL destURL(_destURL);
03088 destURL.setPath(QDir::cleanDirPath(destURL.path()));
03089 QString destClass = KProtocolInfo::protocolClass(destURL.protocol());
03090
03091 for(KApplicationPrivate::URLActionRule *rule = d->urlActionRestrictions.first();
03092 rule; rule = d->urlActionRestrictions.next())
03093 {
03094 if ((result != rule->permission) &&
03095 (action == rule->action) &&
03096 rule->baseMatch(baseURL, baseClass) &&
03097 rule->destMatch(destURL, destClass, baseURL, baseClass))
03098 {
03099 result = rule->permission;
03100 }
03101 }
03102 return result;
03103 }
03104
03105
03106 uint KApplication::keyboardModifiers()
03107 {
03108 #ifdef Q_WS_X11
03109 Window root;
03110 Window child;
03111 int root_x, root_y, win_x, win_y;
03112 uint keybstate;
03113 XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03114 &root_x, &root_y, &win_x, &win_y, &keybstate );
03115 return keybstate & 0x00ff;
03116 #elif defined W_WS_MACX
03117 return GetCurrentEventKeyModifiers() & 0x00ff;
03118 #else
03119
03120 return 0;
03121 #endif
03122 }
03123
03124 uint KApplication::mouseState()
03125 {
03126 uint mousestate;
03127 #ifdef Q_WS_X11
03128 Window root;
03129 Window child;
03130 int root_x, root_y, win_x, win_y;
03131 XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03132 &root_x, &root_y, &win_x, &win_y, &mousestate );
03133 #elif defined(Q_WS_WIN)
03134 const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
03135 if (GetAsyncKeyState(VK_LBUTTON))
03136 mousestate |= (mousebtn_swapped ? Button3Mask : Button1Mask);
03137 if (GetAsyncKeyState(VK_MBUTTON))
03138 mousestate |= Button2Mask;
03139 if (GetAsyncKeyState(VK_RBUTTON))
03140 mousestate |= (mousebtn_swapped ? Button1Mask : Button3Mask);
03141 #elif defined(Q_WS_MACX)
03142 mousestate = GetCurrentEventButtonState();
03143 #else
03144
03145 #endif
03146 return mousestate & 0xff00;
03147 }
03148
03149 Qt::ButtonState KApplication::keyboardMouseState()
03150 {
03151 int ret = 0;
03152 #ifdef Q_WS_X11
03153 Window root;
03154 Window child;
03155 int root_x, root_y, win_x, win_y;
03156 uint state;
03157 XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
03158 &root_x, &root_y, &win_x, &win_y, &state );
03159
03160 if( state & Button1Mask )
03161 ret |= LeftButton;
03162 if( state & Button2Mask )
03163 ret |= MidButton;
03164 if( state & Button3Mask )
03165 ret |= RightButton;
03166 if( state & ShiftMask )
03167 ret |= ShiftButton;
03168 if( state & ControlMask )
03169 ret |= ControlButton;
03170 if( state & KKeyNative::modX( KKey::ALT ))
03171 ret |= AltButton;
03172 if( state & KKeyNative::modX( KKey::WIN ))
03173 ret |= MetaButton;
03174 #elif defined(Q_WS_WIN)
03175 const bool mousebtn_swapped = GetSystemMetrics(SM_SWAPBUTTON);
03176 if (GetAsyncKeyState(VK_LBUTTON))
03177 ret |= (mousebtn_swapped ? RightButton : LeftButton);
03178 if (GetAsyncKeyState(VK_MBUTTON))
03179 ret |= MidButton;
03180 if (GetAsyncKeyState(VK_RBUTTON))
03181 ret |= (mousebtn_swapped ? LeftButton : RightButton);
03182 if (GetAsyncKeyState(VK_SHIFT))
03183 ret |= ShiftButton;
03184 if (GetAsyncKeyState(VK_CONTROL))
03185 ret |= ControlButton;
03186 if (GetAsyncKeyState(VK_MENU))
03187 ret |= AltButton;
03188 if (GetAsyncKeyState(VK_LWIN) || GetAsyncKeyState(VK_RWIN))
03189 ret |= MetaButton;
03190 #else
03191
03192 #endif
03193 return static_cast< ButtonState >( ret );
03194 }
03195
03196 void KApplication::installSigpipeHandler()
03197 {
03198 #ifdef Q_OS_UNIX
03199 struct sigaction act;
03200 act.sa_handler = SIG_IGN;
03201 sigemptyset( &act.sa_mask );
03202 act.sa_flags = 0;
03203 sigaction( SIGPIPE, &act, 0 );
03204 #endif
03205 }
03206
03207 void KApplication::sigpipeHandler(int)
03208 {
03209 int saved_errno = errno;
03210
03211 #ifndef NDEBUG
03212 char msg[1000];
03213 sprintf(msg, "*** SIGPIPE *** (ignored, pid = %ld)\n", (long) getpid());
03214 write(2, msg, strlen(msg));
03215 #endif
03216
03217
03218 errno = saved_errno;
03219 }
03220
03221 bool KApplication::guiEnabled()
03222 {
03223 return kapp && kapp->d->guiEnabled;
03224 }
03225
03226 void KApplication::virtual_hook( int id, void* data )
03227 { KInstance::virtual_hook( id, data ); }
03228
03229 void KSessionManaged::virtual_hook( int, void* )
03230 { }
03231
03232 #include "kapplication.moc"