]> icculus.org git repositories - duncan/yast2-qt4.git/blob - src/YQUI_core.cc
moving classes where they are used
[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 #include <ycp/YCPTerm.h>
32 #include <ycp/YCPCode.h>
33
34 #define y2log_component "qt-ui"
35 #include <ycp/y2log.h>
36
37 #include "YQUI.h"
38 #include "YQApplication.h"
39 #include "YQWidgetFactory.h"
40 #include "YQOptionalWidgetFactory.h"
41 #include "YEvent.h"
42 #include "YUISymbols.h"
43 #include "YQEBunny.h"
44 #include "utf8.h"
45
46 #include "YQDialog.h"
47 #include "QY2Settings.h"
48
49
50 #define BUSY_CURSOR_TIMEOUT     200     // milliseconds
51
52 YQUI * YQUI::_ui = 0;
53
54 static void qMessageHandler( QtMsgType type, const char * msg );
55
56 YQUI::YQUI( int argc, char **argv, bool with_threads, const char * macro_file )
57     : QObject()
58     , YUI( with_threads )
59     , _main_win( NULL )
60     , _eventLoop( 0 )
61     , _wm_close_blocked( false )
62     , _auto_activate_dialogs( true )
63 {
64     y2milestone( "YQUI constructor start" );
65
66     _ui                         = this;
67     _fatal_error                = false;
68     _have_wm                    = true;
69     _fullscreen                 = false;
70     _decorate_toplevel_window   = true;
71     _usingVisionImpairedPalette = false;
72     _leftHandedMouse            = false;
73     _askedForLeftHandedMouse    = false;
74     screenShotNameTemplate      = "";
75     blocked_level               = 0;
76
77     qInstallMsgHandler( qMessageHandler );
78
79     // Copy command line arguments for QApplication
80
81     _ui_argv = (char **) malloc( (argc+1) * sizeof( const char * ) );
82     _ui_argc = argc + 1;
83
84     for ( int i=0; i < argc; i++ )
85       _ui_argv[i+1] = strdup( argv[i] );
86
87     _ui_argv[0] = strdup( "YaST2" );
88     _ui_inited = false;
89
90     topmostConstructorHasFinished();
91 }
92
93 void YQUI::init_ui()
94 {
95     if (_ui_inited)
96         return;
97
98     /*
99       Qt thinks the first QObject defines the main thread, but
100       the main thread in this case is the ycp thread, not UI
101     */
102     //extern void qt_set_current_thread_to_main_thread();
103     //qt_set_current_thread_to_main_thread();
104
105     _ui_inited = true;
106
107     new QApplication( _ui_argc, _ui_argv);
108     _busy_cursor_timer = new QTimer( qApp );
109     _busy_cursor_timer->setSingleShot( true );
110
111     _user_input_timer.setSingleShot( true );
112
113     _normalPalette = qApp->palette();
114
115     // Qt keeps track to a global QApplication in qApp.
116     Q_CHECK_PTR( qApp );
117
118     qApp->installEventFilter( this );
119     processCommandLineArgs( _ui_argc, _ui_argv );
120     calcDefaultSize();
121
122     // Event loop object. Required since a YaST2 UI needs to react to commands
123     // from the YCP command stream as well as to X11 / Qt events.
124     _eventLoop = new QEventLoop( qApp );
125     _do_exit_loop = false;
126
127     // Create main window for `opt(`defaultsize) dialogs.
128     //
129     // We have to use something else than QWidgetStack since QWidgetStack
130     // doesn't accept a WFlags arg which we badly need here.
131
132     Qt::WFlags wflags = Qt::Window;
133
134     if ( ! _decorate_toplevel_window )
135     {
136         y2debug( "Suppressing WM decorations for toplevel window" );
137         wflags |= Qt::FramelessWindowHint;
138     }
139
140     _main_win = new QWidget( 0, wflags ); // parent, wflags
141     _main_win->setFocusPolicy( Qt::StrongFocus );
142     _main_win->setObjectName( "main_window" );
143
144     // Create widget stack for `opt(`defaultsize) dialogs
145     QVBoxLayout *vbox = new QVBoxLayout( _main_win );
146     vbox->setSpacing( 0 );
147     vbox->setMargin( 0 );
148
149     _widget_stack = new QStackedWidget( _main_win );
150     _widget_stack->setFocusPolicy( Qt::StrongFocus );
151     vbox->addWidget( _widget_stack );
152 #if 0
153     _main_win->installEventFilter( this );
154 #endif
155
156     _main_win->resize( _default_size );
157
158     if ( _fullscreen || ! _have_wm )
159         _main_win->move( 0, 0 );
160
161
162     // Set window title
163
164     QString title( "YaST2" );
165     char hostname[ MAXHOSTNAMELEN+1 ];
166
167     if ( gethostname( hostname, sizeof( hostname )-1 ) == 0 )
168     {
169         hostname[ sizeof( hostname ) -1 ] = '\0'; // make sure it's terminated
170
171         if ( strlen( hostname ) > 0 )
172         {
173             if ( ( strcmp( hostname, "(none)" ) != 0 &&
174                    strcmp( hostname, "linux"  ) != 0 ) )
175             {
176                 title += "@";
177                 title += hostname;
178             }
179         }
180     }
181
182     _main_win->setWindowTitle( title );
183
184
185     // Hide the main window for now. The first call to UI::OpenDialog() on an
186     // `opt(`defaultSize) dialog will trigger a showDialog() call that shows
187     // the main window - there is nothing to display yet.
188
189     _main_win->hide();
190
191
192     // Ugly hack as a workaround of bug #121872 (Segfault at program exit
193     // if no Qt style defined):
194     //
195     // Qt does not seem to be designed for use in plugin libs. It loads some
196     // add-on libs dynamically with dlopen() and unloads them at program exit
197     // (QGPluginManager). Unfortunately, since they all depend on the Qt master
198     // lib (libqt-mt) themselves, when they are unloading the last call to
199     // dlclose() for them causes the last reference to libqt-mt to vanish as
200     // well. Since libqt-mt is already in the process of destruction there is
201     // no more reference from the caller of libqt-mt, and the GLIBC decides
202     // that libqt-mt is not needed any more (zero references) and unmaps
203     // libqt-mt. When the static destructor of libqt-mt that triggered the
204     // cleanup in QGPluginManager returns, the code it is to return to is
205     // already unmapped, causing a segfault.
206     //
207     // Workaround: Keep one more reference to libqt-mt open - dlopen() it here
208     // and make sure there is no corresponding dlclose().
209
210     QString qt_lib_name = QString( QTLIBDIR "/libQtGui.so.%1" ).arg( QT_VERSION >> 16 );;
211     void * qt_lib = dlopen( qt_lib_name.toUtf8().constData(), RTLD_GLOBAL );
212     y2milestone( "Forcing %s open %s", qt_lib_name.toUtf8().constData(),
213                  qt_lib ? "successful" : "failed" );
214
215     //  Init other stuff
216
217     qApp->setFont( yqApp()->currentFont() );
218     busyCursor();
219
220     connect( & _user_input_timer,       SIGNAL( timeout()          ),
221              this,                      SLOT  ( userInputTimeout() ) );
222
223     connect(  _busy_cursor_timer,       SIGNAL( timeout()       ),
224              this,                      SLOT  ( busyCursor()    ) );
225
226 #warning macro_file
227     //    if ( macro_file )
228     // playMacro( macro_file );
229
230     y2milestone( "YQUI constructor end %ld", QThread::currentThreadId () );
231     qApp->processEvents();
232 }
233
234
235 YQApplication *
236 YQUI::yqApp()
237 {
238     return static_cast<YQApplication *>( app() );
239 }
240
241
242 void YQUI::processCommandLineArgs( int argc, char **argv )
243 {
244     if ( argv )
245     {
246         for( int i=0; i < argc; i++ )
247         {
248             QString opt = argv[i];
249
250             y2milestone ("Qt argument: %s", argv[i]);
251
252             // Normalize command line option - accept "--xy" as well as "-xy"
253
254             if ( opt.startsWith( "--" ) )
255                 opt.remove(0, 1);
256
257             if      ( opt == QString( "-no-wm"          ) )     _have_wm                        = false;
258             else if ( opt == QString( "-fullscreen"     ) )     _fullscreen                     = true;
259             else if ( opt == QString( "-noborder"       ) )     _decorate_toplevel_window       = false;
260             else if ( opt == QString( "-auto-font"      ) )     yqApp()->setAutoFonts( true );
261             else if ( opt == QString( "-auto-fonts"     ) )     yqApp()->setAutoFonts( true );
262             // --macro is handled by YUI_component
263             else if ( opt == QString( "-help"  ) )
264             {
265                 fprintf( stderr,
266                          "Command line options for the YaST2 Qt UI:\n"
267                          "\n"
268                          "--nothreads   run without additional UI threads\n"
269                          "--no-wm       assume no window manager is running\n"
270                          "--fullscreen  use full screen for `opt(`defaultsize) dialogs\n"
271                          "--noborder    no window manager border for `opt(`defaultsize) dialogs\n"
272                          "--auto-fonts  automatically pick fonts, disregard Qt standard settings\n"
273                          "--help        this help text\n"
274                          "\n"
275                          "--macro <macro-file>        play a macro right on startup\n"
276                          "\n"
277                          "-no-wm, -noborder etc. are accepted as well as --no-wm, --noborder\n"
278                          "to maintain backwards compatibility.\n"
279                          "\n"
280                          );
281
282                 raiseFatalError();
283             }
284         }
285     }
286
287     // Qt handles command line option "-reverse" for Arabic / Hebrew
288 }
289
290
291
292 YQUI::~YQUI()
293 {
294     y2debug("Closing down Qt UI.");
295
296     normalCursor();
297
298     // Intentionally NOT calling dlclose() to libqt-mt
299     // (see constructor for explanation)
300 }
301
302
303
304 YWidgetFactory *
305 YQUI::createWidgetFactory()
306 {
307     YQWidgetFactory * factory = new YQWidgetFactory();
308     YUI_CHECK_NEW( factory );
309
310     return factory;
311 }
312
313
314
315 YOptionalWidgetFactory *
316 YQUI::createOptionalWidgetFactory()
317 {
318     YQOptionalWidgetFactory * factory = new YQOptionalWidgetFactory();
319     YUI_CHECK_NEW( factory );
320
321     return factory;
322 }
323
324
325 YApplication *
326 YQUI::createApplication()
327 {
328     YQApplication * app = new YQApplication();
329     YUI_CHECK_NEW( app );
330
331     return app;
332 }
333
334
335 void YQUI::calcDefaultSize()
336 {
337     QSize primaryScreenSize     = qApp->desktop()->screenGeometry( qApp->desktop()->primaryScreen() ).size();
338     QSize availableSize         = qApp->desktop()->availableGeometry().size();
339
340     if ( _fullscreen )
341     {
342         _default_size = availableSize;
343
344         y2milestone( "-fullscreen: using %dx%d for `opt(`defaultsize)",
345                      _default_size.width(), _default_size.height() );
346     }
347     else if ( _have_wm )
348     {
349         // Get _default_size via -geometry command line option (if set)
350
351 // NOTE not needed in qt4
352 //      QWidget * dummy = new QWidget();
353 //      dummy->hide();
354 //      qApp->setMainWidget( dummy );
355 //      _default_size = dummy->size();
356
357
358         // Set min defaultsize or figure one out if -geometry was not used
359
360         if ( _default_size.width()  < 800 ||
361              _default_size.height() < 600   )
362         {
363             if ( primaryScreenSize.width() >= 1024 && primaryScreenSize.height() >= 768  )
364             {
365                 // Scale down to 70% of screen size
366
367                 _default_size.setWidth ( max( (int) (availableSize.width()  * 0.7), 800 ) );
368                 _default_size.setHeight( max( (int) (availableSize.height() * 0.7), 600 ) );
369             }
370             else
371             {
372                 _default_size = availableSize;
373             }
374         }
375         else
376         {
377             y2milestone( "Forced size (via -geometry): %dx%d",
378                          _default_size.width(), _default_size.height() );
379         }
380     }
381     else        // ! _have_wm
382     {
383         _default_size = primaryScreenSize;
384     }
385
386
387     y2milestone( "Default size: %dx%d", _default_size.width(), _default_size.height() );
388 }
389
390
391
392 void YQUI::internalError( const char * msg )
393 {
394     normalCursor();
395     int button = QMessageBox::critical( 0, "YaST2 Internal Error", msg,
396                                         QMessageBox::Abort | QMessageBox::Default,
397                                         0 ); // button1
398     busyCursor();
399
400     if ( button == QMessageBox::Abort )
401     {
402         raiseFatalError();
403         abort();
404
405         // exit() leaves a process running (WFM?), so this really seems to be
406         // the only way to make sure we are really going down.
407     }
408 }
409
410 void YQUI::idleLoop( int fd_ycp )
411 {
412     init_ui();
413
414     // runs in main thread
415     _eventLoop->wakeUp();
416
417     fd_set rfds;
418
419     FD_ZERO(&rfds);
420     FD_SET(fd_ycp, &rfds);
421
422     while (true)
423     {
424         int retval = select(fd_ycp+1, &rfds, NULL, NULL, NULL);
425         if (retval)
426             break;
427     }
428     _eventLoop->exit();
429 }
430
431 void YQUI::sendEvent( YEvent * event )
432 {
433     if ( event )
434     {
435         _event_handler.sendEvent( event );
436
437         if ( _do_exit_loop )
438             _eventLoop->exit( 1 );
439     }
440 }
441
442
443 YEvent * YQUI::userInput( unsigned long timeout_millisec )
444 {
445     init_ui();
446
447     _event_handler.blockEvents( false );
448     _eventLoop->wakeUp();
449     blocked_level = 0;
450
451     //y2milestone( "userInput %ld", timeout_millisec );
452
453     YEvent *    event  = 0;
454     YQDialog *  dialog = dynamic_cast<YQDialog *> ( YDialog::currentDialog( false ) );
455
456     if ( _user_input_timer.isActive() )
457         _user_input_timer.stop();
458
459     if ( dialog )
460     {
461         if ( timeout_millisec > 0 )
462             _user_input_timer.start( timeout_millisec ); // single shot
463
464         dialog->activate( true );
465
466         if ( qApp->focusWidget() )
467             qApp->focusWidget()->setFocus();
468
469         normalCursor();
470         _do_exit_loop = true; // should exit_loop() be called in sendEvent()?
471         _eventLoop->exec();
472         _do_exit_loop = false;
473
474         event = _event_handler.consumePendingEvent();
475         dialog->activate( false );
476
477         // Display a busy cursor, but only if there is no other activity within
478         // BUSY_CURSOR_TIMEOUT milliseconds (avoid cursor flicker)
479
480         _busy_cursor_timer->start( BUSY_CURSOR_TIMEOUT ); // single shot
481     }
482
483     if ( _user_input_timer.isActive() )
484         _user_input_timer.stop();
485
486     return event;
487 }
488
489
490 YEvent * YQUI::pollInput()
491 {
492     YEvent * event = 0;
493
494     if ( _user_input_timer.isActive() )
495         _user_input_timer.stop();
496
497     if ( ! pendingEvent() )
498     {
499         YQDialog * dialog = dynamic_cast<YQDialog *> ( YDialog::currentDialog( false ) );
500
501         if ( dialog )
502         {
503             dialog->activate( true );
504             //qApp->processEvents();
505             event = _event_handler.consumePendingEvent();
506             dialog->activate( false );
507         }
508     }
509
510     if ( pendingEvent() )
511         event = _event_handler.consumePendingEvent();
512
513     return event;
514 }
515
516
517 void YQUI::userInputTimeout()
518 {
519     if ( ! pendingEvent() )
520         sendEvent( new YTimeoutEvent() );
521 }
522
523
524 #warning obsolete
525 #if 0
526 YDialog * YQUI::createDialog( YWidgetOpt & opt )
527 {
528     init_ui();
529
530     y2milestone( "createDialog %ld", QThread::currentThreadId () );
531     bool has_defaultsize = opt.hasDefaultSize.value();
532     QWidget * qt_parent =
533       has_defaultsize ? _widget_stack : _main_win;
534
535     // FIXME: Probably obsolete
536     if ( ! has_defaultsize && ! _popup_stack.empty() )
537         qt_parent = _popup_stack.back();
538
539     YQDialog * dialog = new YQDialog( opt, qt_parent, has_defaultsize );
540     Q_CHECK_PTR( dialog );
541
542     if ( ! has_defaultsize )
543         _popup_stack.push_back( (QWidget *) dialog->widgetRep() );
544
545     return dialog;
546 }
547 #endif
548
549
550 void YQUI::showDialog( YDialog * dialog )
551 {
552     QWidget * qw = (QWidget *) dialog->widgetRep();
553
554     if ( ! qw )
555     {
556         y2error( "No widgetRep() for dialog" );
557         return;
558     }
559
560     if ( dialog->dialogType() == YMainDialog )
561     {
562         _widget_stack->addWidget  ( qw );
563         _widget_stack->setCurrentWidget( qw );
564
565         if ( ! _main_win->isVisible() )
566         {
567             // y2milestone( "Showing main window" );
568             _main_win->resize( _default_size );
569
570             if ( ! _have_wm )
571                 _main_win->move( 0, 0 );
572
573             _main_win->show();
574             qw->setFocus();
575         }
576     }
577     else        // non-defaultsize dialog
578     {
579         qw->show();
580     }
581
582     ( (YQDialog *) dialog)->ensureOnlyOneDefaultButton();
583
584     //qApp->processEvents();
585 }
586
587
588 void YQUI::closeDialog( YDialog * dialog )
589 {
590     QWidget * qw = (QWidget *) dialog->widgetRep();
591
592     if ( ! qw )
593     {
594         y2error( "No widgetRep() for dialog" );
595         return;
596     }
597
598     if ( dialog->dialogType() == YMainDialog )
599     {
600         _widget_stack->removeWidget( qw );
601     }
602     else        // non-defaultsize dialog
603     {
604         qw->hide();
605
606 #warning FIXME
607 #if 0
608         // Clean up the popup stack. libyui guarantees that a dialog will be
609         // deleted after closeDialog() so it is safe to pop that dialog from
610         // the popup stack here.
611
612         if ( ! _popup_stack.empty() && _popup_stack.back() == qw )
613             _popup_stack.pop_back();
614         else
615             y2error( "Popup dialog stack corrupted!" );
616 #endif
617     }
618 }
619
620
621 void YQUI::easterEgg()
622 {
623     y2milestone( "Starting easter egg..." );
624
625
626     YQEasterBunny::layEgg();
627     y2milestone( "Done." );
628
629 #if 0
630     // desktop()->repaint() has no effect - we need to do it the hard way.
631     system( "/usr/X11R6/bin/xrefresh" );
632 #endif
633 }
634
635
636 QString YQUI::productName() const
637 {
638     return fromUTF8( YUI::productName() );
639 }
640
641
642 void
643 YQUI::setTextdomain( const char * domain )
644 {
645     bindtextdomain( domain, LOCALEDIR );
646     bind_textdomain_codeset( domain, "utf8" );
647     textdomain( domain );
648
649     // Make change known.
650     {
651         extern int _nl_msg_cat_cntr;
652         ++_nl_msg_cat_cntr;
653     }
654 }
655
656
657 void YQUI::blockEvents( bool block )
658 {
659     if ( block )
660     {
661         if ( ++blocked_level == 1 )
662         {
663             _event_handler.blockEvents( true );
664             _eventLoop->exit();
665         }
666     }
667     else
668     {
669         if ( --blocked_level == 0 )
670         {
671             _event_handler.blockEvents( false );
672             _eventLoop->wakeUp();
673         }
674     }
675 }
676
677
678 bool YQUI::eventsBlocked() const
679 {
680     return _event_handler.eventsBlocked();
681 }
682
683 static void
684 qMessageHandler( QtMsgType type, const char * msg )
685 {
686     switch (type)
687     {
688         case QtDebugMsg:
689             y2milestone ("qt-debug: %s\n", msg);
690             break;
691         case QtWarningMsg:
692             y2warning ("qt-warning: %s\n", msg);
693             //abort();
694             break;
695         case QtCriticalMsg:
696             y2warning ("qt-critical: %s\n", msg);
697             break;
698         case QtFatalMsg:
699             y2internal ("qt-fatal: %s\n", msg);
700             exit (1);           // qt does the same
701     }
702 }
703
704
705
706 #include "YQUI.moc"