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