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