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