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