]> icculus.org git repositories - duncan/yast2-qt4.git/blob - src/YQUI_core.cc
one less warning
[duncan/yast2-qt4.git] / src / YQUI_core.cc
1 /*---------------------------------------------------------------------\
2 |                                                                      |
3 |                      __   __    ____ _____ ____                      |
4 |                      \ \ / /_ _/ ___|_   _|___ \                     |
5 |                       \ V / _` \___ \ | |   __) |                    |
6 |                        | | (_| |___) || |  / __/                     |
7 |                        |_|\__,_|____/ |_| |_____|                    |
8 |                                                                      |
9 |                               core system                            |
10 |                                                        (C) SuSE GmbH |
11 \----------------------------------------------------------------------/
12
13   File:         YQUI_core.cc
14
15   Author:       Stefan Hundhammer <sh@suse.de>
16
17 /-*/
18
19 #include <rpc/types.h>          // MAXHOSTNAMELEN
20 #include <dlfcn.h>
21 #include <libintl.h>
22
23 #include <QCursor>
24 #include <QMessageBox>
25 #include <QSocketNotifier>
26 #include <QStackedWidget>
27 #include <QDesktopWidget>
28 #include <QThread>
29 #include <QVBoxLayout>
30
31 #define y2log_component "qt-ui"
32 #include <ycp/y2log.h>
33
34 #include "YQUI.h"
35 #include "QY2Styler.h"
36 #include "YQApplication.h"
37 #include "YQWidgetFactory.h"
38 #include "YQOptionalWidgetFactory.h"
39 #include "YEvent.h"
40 #include "YUISymbols.h"
41 #include "utf8.h"
42
43 #include "YQDialog.h"
44 #include "QY2Settings.h"
45
46 #define BUSY_CURSOR_TIMEOUT     200     // milliseconds
47
48 YQUI * YQUI::_ui = 0;
49
50 static void qMessageHandler( QtMsgType type, const char * msg );
51
52 YQUI::YQUI( int argc, char **argv, bool with_threads, const char * macro_file )
53     : YUI( with_threads )
54     , _main_win( NULL )
55     , _do_exit_loop( false )
56     , _eventLoop( 0 )
57 {
58     y2milestone( "YQUI constructor start" );
59
60     _ui                         = this;
61     _fatal_error                = false;
62     _fullscreen                 = false;
63     _usingVisionImpairedPalette = false;
64     _leftHandedMouse            = false;
65     _askedForLeftHandedMouse    = false;
66     _noborder                   = false;
67     screenShotNameTemplate      = "";
68     blocked_level               = 0;
69
70     qInstallMsgHandler( qMessageHandler );
71
72     // Copy command line arguments for QApplication
73
74     _ui_argv = (char **) malloc( (argc+1) * sizeof( const char * ) );
75     _ui_argc = argc + 1;
76
77     for ( int i=0; i < argc; i++ )
78       _ui_argv[i+1] = strdup( argv[i] );
79
80     _ui_argv[0] = strdup( "YaST2" );
81     _ui_inited = false;
82
83     topmostConstructorHasFinished();
84 }
85
86 YQUI_Ui::YQUI_Ui()
87     : QObject()
88 {
89 }
90
91 void YQUI::init_ui()
92 {
93     if (_ui_inited)
94         return;
95
96     _ui_inited = true;
97
98     new QApplication( _ui_argc, _ui_argv);
99
100     _qobject = new YQUI_Ui();
101     _busy_cursor_timer = new QTimer( _qobject );
102     _busy_cursor_timer->setSingleShot( true );
103
104     _user_input_timer = new QTimer( _qobject );
105     _user_input_timer->setSingleShot( true );
106
107     _normalPalette = qApp->palette();
108
109     // Qt keeps track to a global QApplication in qApp.
110     Q_CHECK_PTR( qApp );
111
112     processCommandLineArgs( _ui_argc, _ui_argv );
113     calcDefaultSize();
114
115     _styler = new QY2Styler( qApp );
116     QString style = getenv("Y2STYLE");
117     if ( !style.isNull() )
118         _styler->setStyleSheet( style );
119
120     // Event loop object. Required since a YaST2 UI needs to react to commands
121     // from the YCP command stream as well as to X11 / Qt events.
122     _eventLoop = new QEventLoop( qApp );
123     _do_exit_loop = false;
124
125     // Create main window for `opt(`defaultsize) dialogs.
126     //
127     // We have to use something else than QWidgetStack since QWidgetStack
128     // doesn't accept a WFlags arg which we badly need here.
129
130     _main_win = new QWidget( 0, Qt::Window ); // parent, wflags
131     _main_win->setFocusPolicy( Qt::StrongFocus );
132     _main_win->setObjectName( "main_window" );
133
134     _main_win->resize( _default_size );
135
136     if ( _fullscreen )
137         _main_win->move( 0, 0 );
138
139
140     // Set window title
141
142     QString title( "YaST2" );
143     char hostname[ MAXHOSTNAMELEN+1 ];
144
145     if ( gethostname( hostname, sizeof( hostname )-1 ) == 0 )
146     {
147         hostname[ sizeof( hostname ) -1 ] = '\0'; // make sure it's terminated
148
149         if ( strlen( hostname ) > 0 )
150         {
151             if ( ( strcmp( hostname, "(none)" ) != 0 &&
152                    strcmp( hostname, "linux"  ) != 0 ) )
153             {
154                 title += "@";
155                 title += hostname;
156             }
157         }
158     }
159
160     _main_win->setWindowTitle( title );
161
162
163     // Hide the main window for now. The first call to UI::OpenDialog() on an
164     // `opt(`defaultSize) dialog will trigger a showDialog() call that shows
165     // the main window - there is nothing to display yet.
166
167     _main_win->hide();
168
169
170     // Ugly hack as a workaround of bug #121872 (Segfault at program exit
171     // if no Qt style defined):
172     //
173     // Qt does not seem to be designed for use in plugin libs. It loads some
174     // add-on libs dynamically with dlopen() and unloads them at program exit
175     // (QGPluginManager). Unfortunately, since they all depend on the Qt master
176     // lib (libqt-mt) themselves, when they are unloading the last call to
177     // dlclose() for them causes the last reference to libqt-mt to vanish as
178     // well. Since libqt-mt is already in the process of destruction there is
179     // no more reference from the caller of libqt-mt, and the GLIBC decides
180     // that libqt-mt is not needed any more (zero references) and unmaps
181     // libqt-mt. When the static destructor of libqt-mt that triggered the
182     // cleanup in QGPluginManager returns, the code it is to return to is
183     // already unmapped, causing a segfault.
184     //
185     // Workaround: Keep one more reference to libqt-mt open - dlopen() it here
186     // and make sure there is no corresponding dlclose().
187
188     QString qt_lib_name = QString( QTLIBDIR "/libQtGui.so.%1" ).arg( QT_VERSION >> 16 );;
189     void * qt_lib = dlopen( qt_lib_name.toUtf8().constData(), RTLD_GLOBAL );
190     y2milestone( "Forcing %s open %s", qt_lib_name.toUtf8().constData(),
191                  qt_lib ? "successful" : "failed" );
192
193     //  Init other stuff
194
195     qApp->setFont( yqApp()->currentFont() );
196     busyCursor();
197
198     QObject::connect(  _user_input_timer,       SIGNAL( timeout()          ),
199                        _qobject,                SLOT  ( slotUserInputTimeout() ) );
200
201     QObject::connect(  _busy_cursor_timer,      SIGNAL( timeout()       ),
202                        _qobject,                SLOT  ( slotBusyCursor() ) );
203
204 #warning macro_file
205     //    if ( macro_file )
206     // playMacro( macro_file );
207
208     y2milestone( "YQUI constructor end %ld", QThread::currentThreadId () );
209     qApp->processEvents();
210 }
211
212
213 YQApplication *
214 YQUI::yqApp()
215 {
216     return static_cast<YQApplication *>( app() );
217 }
218
219
220 void YQUI::processCommandLineArgs( int argc, char **argv )
221 {
222     if ( argv )
223     {
224         for( int i=0; i < argc; i++ )
225         {
226             QString opt = argv[i];
227
228             y2milestone ("Qt argument: %s", argv[i]);
229
230             // Normalize command line option - accept "--xy" as well as "-xy"
231
232             if ( opt.startsWith( "--" ) )
233                 opt.remove(0, 1);
234
235             if      ( opt == QString( "-fullscreen"     ) )     _fullscreen     = true;
236             else if ( opt == QString( "-noborder"       ) )     _noborder       = true;
237             else if ( opt == QString( "-auto-font"      ) )     yqApp()->setAutoFonts( true );
238             else if ( opt == QString( "-auto-fonts"     ) )     yqApp()->setAutoFonts( true );
239             // --macro is handled by YUI_component
240             else if ( opt == QString( "-help"  ) )
241             {
242                 fprintf( stderr,
243                          "Command line options for the YaST2 Qt UI:\n"
244                          "\n"
245                          "--nothreads   run without additional UI threads\n"
246                          "--fullscreen  use full screen for `opt(`defaultsize) dialogs\n"
247                          "--noborder    no window manager border for `opt(`defaultsize) dialogs\n"
248                          "--auto-fonts  automatically pick fonts, disregard Qt standard settings\n"
249                          "--help        this help text\n"
250                          "\n"
251                          "--macro <macro-file>        play a macro right on startup\n"
252                          "\n"
253                          "-no-wm, -noborder etc. are accepted as well as --no-wm, --noborder\n"
254                          "to maintain backwards compatibility.\n"
255                          "\n"
256                          );
257
258                 raiseFatalError();
259             }
260         }
261     }
262
263     // Qt handles command line option "-reverse" for Arabic / Hebrew
264 }
265
266
267
268 YQUI::~YQUI()
269 {
270     y2debug("Closing down Qt UI.");
271
272     normalCursor();
273
274     // Intentionally NOT calling dlclose() to libqt-mt
275     // (see constructor for explanation)
276 }
277
278
279
280 YWidgetFactory *
281 YQUI::createWidgetFactory()
282 {
283     YQWidgetFactory * factory = new YQWidgetFactory();
284     YUI_CHECK_NEW( factory );
285
286     return factory;
287 }
288
289
290
291 YOptionalWidgetFactory *
292 YQUI::createOptionalWidgetFactory()
293 {
294     YQOptionalWidgetFactory * factory = new YQOptionalWidgetFactory();
295     YUI_CHECK_NEW( factory );
296
297     return factory;
298 }
299
300
301 YApplication *
302 YQUI::createApplication()
303 {
304     YQApplication * app = new YQApplication();
305     YUI_CHECK_NEW( app );
306
307     return app;
308 }
309
310
311 void YQUI::calcDefaultSize()
312 {
313     QSize primaryScreenSize     = qApp->desktop()->screenGeometry( qApp->desktop()->primaryScreen() ).size();
314     QSize availableSize         = qApp->desktop()->availableGeometry().size();
315
316     if ( _fullscreen )
317     {
318         _default_size = availableSize;
319
320         y2milestone( "-fullscreen: using %dx%d for `opt(`defaultsize)",
321                      _default_size.width(), _default_size.height() );
322     }
323     else
324     {
325         // Get _default_size via -geometry command line option (if set)
326
327 // NOTE not needed in qt4
328 //      QWidget * dummy = new QWidget();
329 //      dummy->hide();
330 //      qApp->setMainWidget( dummy );
331 //      _default_size = dummy->size();
332
333         // Set min defaultsize or figure one out if -geometry was not used
334
335         if ( _default_size.width()  < 800 ||
336              _default_size.height() < 600   )
337         {
338             if ( primaryScreenSize.width() >= 1024 && primaryScreenSize.height() >= 768  )
339             {
340                 // Scale down to 70% of screen size
341
342                 _default_size.setWidth ( max( (int) (availableSize.width()  * 0.7), 800 ) );
343                 _default_size.setHeight( max( (int) (availableSize.height() * 0.7), 600 ) );
344             }
345             else
346             {
347                 _default_size = availableSize;
348             }
349         }
350         else
351         {
352             y2milestone( "Forced size (via -geometry): %dx%d",
353                          _default_size.width(), _default_size.height() );
354         }
355     }
356
357     y2milestone( "Default size: %dx%d", _default_size.width(), _default_size.height() );
358 }
359
360
361
362 void YQUI::internalError( const char * msg )
363 {
364     normalCursor();
365     int button = QMessageBox::critical( 0, "YaST2 Internal Error", msg,
366                                         QMessageBox::Abort | QMessageBox::Default,
367                                         0 ); // button1
368     busyCursor();
369
370     if ( button == QMessageBox::Abort )
371     {
372         raiseFatalError();
373         abort();
374
375         // exit() leaves a process running (WFM?), so this really seems to be
376         // the only way to make sure we are really going down.
377     }
378 }
379
380 void YQUI::idleLoop( int fd_ycp )
381 {
382     init_ui();
383
384     _leave_idle_loop = false;
385
386     // process Qt events until fd_ycp is readable.
387     QSocketNotifier * notifier = new QSocketNotifier( fd_ycp, QSocketNotifier::Read );
388     QObject::connect( notifier, SIGNAL( activated    ( int ) ),
389                       _qobject, SLOT( slotLeaveIdleLoop() ) );
390
391     notifier->setEnabled( true );
392
393     while ( !_leave_idle_loop )
394         _eventLoop->processEvents( QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents );
395
396     delete notifier;
397 }
398
399 void YQUI::leaveIdleLoop()
400 {
401     _leave_idle_loop = true;
402 }
403
404 void YQUI_Ui::slotLeaveIdleLoop()
405 {
406     YQUI::ui()->leaveIdleLoop();
407 }
408
409 void YQUI::sendEvent( YEvent * event )
410 {
411     if ( event )
412     {
413         _event_handler.sendEvent( event );
414
415         if ( _do_exit_loop )
416             _eventLoop->exit( 1 );
417     }
418 }
419
420
421 YEvent * YQUI::userInput( unsigned long timeout_millisec )
422 {
423     init_ui();
424
425     _event_handler.blockEvents( false );
426     _eventLoop->wakeUp();
427     blocked_level = 0;
428
429     //y2milestone( "userInput %ld %ld", timeout_millisec, QThread::currentThreadId() );
430
431     YEvent *    event  = 0;
432     YQDialog *  dialog = dynamic_cast<YQDialog *> ( YDialog::currentDialog( false ) );
433
434     _user_input_timer->stop();
435
436     if ( dialog )
437     {
438         if ( timeout_millisec > 0 )
439             _user_input_timer->start( timeout_millisec ); // single shot
440
441         if ( qApp->focusWidget() )
442             qApp->focusWidget()->setFocus();
443
444         normalCursor();
445         _do_exit_loop = true; // should exit_loop() be called in sendEvent()?
446         _eventLoop->exec();
447         _do_exit_loop = false;
448
449         event = _event_handler.consumePendingEvent();
450
451         // Display a busy cursor, but only if there is no other activity within
452         // BUSY_CURSOR_TIMEOUT milliseconds (avoid cursor flicker)
453
454         _busy_cursor_timer->start( BUSY_CURSOR_TIMEOUT ); // single shot
455     }
456
457     _user_input_timer->stop();
458
459     return event;
460 }
461
462
463 YEvent * YQUI::pollInput()
464 {
465     YEvent * event = 0;
466
467     _user_input_timer->stop();
468
469     if ( ! pendingEvent() )
470     {
471         YQDialog * dialog = dynamic_cast<YQDialog *> ( YDialog::currentDialog( false ) );
472
473         if ( dialog )
474         {
475             _eventLoop->processEvents( QEventLoop::AllEvents, 10 );
476             event = _event_handler.consumePendingEvent();
477         }
478     }
479
480     if ( pendingEvent() )
481         event = _event_handler.consumePendingEvent();
482
483     return event;
484 }
485
486
487 void YQUI_Ui::slotUserInputTimeout()
488 {
489     YQUI::ui()->userInputTimeout();
490 }
491
492 void YQUI::userInputTimeout()
493 {
494     if ( ! pendingEvent() )
495         sendEvent( new YTimeoutEvent() );
496 }
497
498
499 #warning FIXME Move this to Y(Q)Dialog (and rename it to ::finalize()?)
500 void YQUI::showDialog( YDialog * dialog )
501 {
502     QWidget * qw = (QWidget *) dialog->widgetRep();
503
504     if ( qw )
505     {
506         qw->show();
507         qw->raise();
508         qw->update();
509     }
510
511     ( (YQDialog *) dialog)->ensureOnlyOneDefaultButton();
512
513     //qApp->processEvents();
514 }
515
516
517 void YQUI::closeDialog( YDialog * dialog )
518 {
519 }
520
521
522 QString YQUI::productName() const
523 {
524     return fromUTF8( YUI::productName() );
525 }
526
527
528 void
529 YQUI::setTextdomain( const char * domain )
530 {
531     bindtextdomain( domain, LOCALEDIR );
532     bind_textdomain_codeset( domain, "utf8" );
533     textdomain( domain );
534
535     // Make change known.
536     {
537         extern int _nl_msg_cat_cntr;
538         ++_nl_msg_cat_cntr;
539     }
540 }
541
542
543 void YQUI::blockEvents( bool block )
544 {
545     init_ui();
546
547     if ( block )
548     {
549         if ( ++blocked_level == 1 )
550         {
551             _event_handler.blockEvents( true );
552             _eventLoop->exit();
553         }
554     }
555     else
556     {
557         if ( --blocked_level == 0 )
558         {
559             _event_handler.blockEvents( false );
560             _eventLoop->wakeUp();
561         }
562     }
563 }
564
565
566 bool YQUI::eventsBlocked() const
567 {
568     return _event_handler.eventsBlocked();
569 }
570
571 static void
572 qMessageHandler( QtMsgType type, const char * msg )
573 {
574     switch (type)
575     {
576         case QtDebugMsg:
577             y2milestone ("qt-debug: %s\n", msg);
578             break;
579         case QtWarningMsg:
580             y2warning ("qt-warning: %s\n", msg);
581             abort();
582             break;
583         case QtCriticalMsg:
584             y2warning ("qt-critical: %s\n", msg);
585             break;
586         case QtFatalMsg:
587             y2internal ("qt-fatal: %s\n", msg);
588             exit (1);           // qt does the same
589     }
590 }
591
592
593
594 #include "YQUI.moc"