check in the 'selective yield' patch (see ticket #10320):
[wxWidgets.git] / src / gtk / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/gtk/app.cpp
3 // Purpose:
4 // Author: Robert Roebling
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling, Julian Smart
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #include "wx/app.h"
14
15 #ifndef WX_PRECOMP
16 #include "wx/intl.h"
17 #include "wx/log.h"
18 #include "wx/utils.h"
19 #include "wx/memory.h"
20 #include "wx/font.h"
21 #endif
22
23 #include "wx/thread.h"
24
25 #ifdef __WXGPE__
26 #include <gpe/init.h>
27 #endif
28
29 #include "wx/gtk/private.h"
30 #include "wx/apptrait.h"
31
32 #if wxUSE_LIBHILDON
33 #include <hildon-widgets/hildon-program.h>
34 #endif // wxUSE_LIBHILDON
35
36 #include <gdk/gdkx.h>
37
38 //-----------------------------------------------------------------------------
39 // link GnomeVFS
40 //-----------------------------------------------------------------------------
41
42 #if wxUSE_MIMETYPE && wxUSE_LIBGNOMEVFS
43 #include "wx/link.h"
44 wxFORCE_LINK_MODULE(gnome_vfs)
45 #endif
46
47 //-----------------------------------------------------------------------------
48 // global data
49 //-----------------------------------------------------------------------------
50
51 static GtkWidget *gs_RootWindow = NULL;
52 static wxArrayPtrVoid g_arrGdkEvents;
53
54 //-----------------------------------------------------------------------------
55 // wxYield
56 //-----------------------------------------------------------------------------
57
58 bool wxApp::DoYield(bool onlyIfNeeded, long eventsToProcess)
59 {
60 if ( m_isInsideYield )
61 {
62 if ( !onlyIfNeeded )
63 {
64 wxFAIL_MSG( wxT("wxYield called recursively" ) );
65 }
66
67 return false;
68 }
69
70 #if wxUSE_THREADS
71 if ( !wxThread::IsMain() )
72 {
73 // can't call gtk_main_iteration() from other threads like this
74 return true;
75 }
76 #endif // wxUSE_THREADS
77
78 m_isInsideYield = true;
79 m_eventsToProcessInsideYield = eventsToProcess;
80
81 #if wxUSE_LOG
82 // disable log flushing from here because a call to wxYield() shouldn't
83 // normally result in message boxes popping up &c
84 wxLog::Suspend();
85 #endif
86
87 // NOTE: gtk_main_iteration() doesn't allow us to filter events, so we
88 // rather use gtk_main_do_event() after filtering the events at
89 // GDK level
90
91 GdkDisplay* disp = gtk_widget_get_display(gs_RootWindow);
92
93 // gdk_display_get_event() will transform X11 events into GDK events
94 // and will queue all of them in the display (private) structure;
95 // finally it will "unqueue" the last one and return it to us
96 GdkEvent* event = gdk_display_get_event(disp);
97 while (event)
98 {
99 // categorize the GDK event according to wxEventCategory.
100 // See http://library.gnome.org/devel/gdk/unstable/gdk-Events.html#GdkEventType
101 // for more info.
102
103 wxEventCategory cat = wxEVT_CATEGORY_UNKNOWN;
104 switch (event->type)
105 {
106 case GDK_SELECTION_REQUEST:
107 case GDK_SELECTION_NOTIFY:
108 case GDK_SELECTION_CLEAR:
109 case GDK_OWNER_CHANGE:
110 cat = wxEVT_CATEGORY_CLIPBOARD;
111 break;
112
113
114 case GDK_KEY_PRESS:
115 case GDK_KEY_RELEASE:
116 case GDK_BUTTON_PRESS:
117 case GDK_2BUTTON_PRESS:
118 case GDK_3BUTTON_PRESS:
119 case GDK_BUTTON_RELEASE:
120 case GDK_SCROLL: // generated from mouse buttons
121 case GDK_CLIENT_EVENT:
122 cat = wxEVT_CATEGORY_USER_INPUT;
123 break;
124
125
126 case GDK_PROXIMITY_IN:
127 case GDK_PROXIMITY_OUT:
128
129 case GDK_MOTION_NOTIFY:
130 case GDK_ENTER_NOTIFY:
131 case GDK_LEAVE_NOTIFY:
132 case GDK_VISIBILITY_NOTIFY:
133 case GDK_PROPERTY_NOTIFY:
134
135 case GDK_FOCUS_CHANGE:
136 case GDK_CONFIGURE:
137 case GDK_WINDOW_STATE:
138 case GDK_SETTING:
139 case GDK_DELETE:
140 case GDK_DESTROY:
141
142 case GDK_EXPOSE:
143 case GDK_NO_EXPOSE:
144 case GDK_MAP:
145 case GDK_UNMAP:
146 //case GDK_DAMAGE:
147
148 case GDK_DRAG_ENTER:
149 case GDK_DRAG_LEAVE:
150 case GDK_DRAG_MOTION:
151 case GDK_DRAG_STATUS:
152 case GDK_DROP_START:
153 case GDK_DROP_FINISHED:
154 case GDK_GRAB_BROKEN:
155 cat = wxEVT_CATEGORY_UI;
156 break;
157
158 default:
159 cat = wxEVT_CATEGORY_UNKNOWN;
160 break;
161 }
162
163 if (eventsToProcess & cat)
164 gtk_main_do_event(event); // process it now
165 else
166 g_arrGdkEvents.Add(event); // process it later
167
168 // get next event
169 event = gdk_display_get_event(disp);
170 }
171
172 if (eventsToProcess != wxEVT_CATEGORY_CLIPBOARD)
173 {
174 // It's necessary to call ProcessIdle() to update the frames sizes which
175 // might have been changed (it also will update other things set from
176 // OnUpdateUI() which is a nice (and desired) side effect). But we
177 // call ProcessIdle() only once since this is not meant for longish
178 // background jobs (controlled by wxIdleEvent::RequestMore() and the
179 // return value of Processidle().
180 ProcessIdle(); // ProcessIdle() also calls ProcessPendingEvents()
181 }
182 //else: if we are inside ~wxClipboardSync() and we call ProcessIdle() and
183 // the user app contains an UI update handler which calls wxClipboard::IsSupported,
184 // then we fall into a never-ending loop...
185
186 // put all unprocessed GDK events back in the queue
187 for (size_t i=0; i<g_arrGdkEvents.GetCount(); i++)
188 {
189 GdkEvent* ev = (GdkEvent*)g_arrGdkEvents[i];
190
191 // NOTE: gdk_display_put_event makes a copy of the event passed to it
192 gdk_display_put_event(disp, ev);
193 gdk_event_free(ev);
194 }
195
196 g_arrGdkEvents.Clear();
197
198 #if wxUSE_LOG
199 // let the logs be flashed again
200 wxLog::Resume();
201 #endif
202
203 m_isInsideYield = false;
204
205 return true;
206 }
207
208 //-----------------------------------------------------------------------------
209 // local functions
210 //-----------------------------------------------------------------------------
211
212 // One-shot signal emission hook, to install idle handler.
213 extern "C" {
214 static gboolean
215 wx_emission_hook(GSignalInvocationHint*, guint, const GValue*, gpointer data)
216 {
217 wxApp* app = wxTheApp;
218 if (app != NULL)
219 app->WakeUpIdle();
220 gulong* hook_id = (gulong*)data;
221 // record that hook is not installed
222 *hook_id = 0;
223 // remove hook
224 return false;
225 }
226 }
227
228 // Add signal emission hooks, to re-install idle handler when needed.
229 static void wx_add_idle_hooks()
230 {
231 // "event" hook
232 {
233 static gulong hook_id = 0;
234 if (hook_id == 0)
235 {
236 static guint sig_id = 0;
237 if (sig_id == 0)
238 sig_id = g_signal_lookup("event", GTK_TYPE_WIDGET);
239 hook_id = g_signal_add_emission_hook(
240 sig_id, 0, wx_emission_hook, &hook_id, NULL);
241 }
242 }
243 // "size_allocate" hook
244 // Needed to match the behavior of the old idle system,
245 // but probably not necessary.
246 {
247 static gulong hook_id = 0;
248 if (hook_id == 0)
249 {
250 static guint sig_id = 0;
251 if (sig_id == 0)
252 sig_id = g_signal_lookup("size_allocate", GTK_TYPE_WIDGET);
253 hook_id = g_signal_add_emission_hook(
254 sig_id, 0, wx_emission_hook, &hook_id, NULL);
255 }
256 }
257 }
258
259 extern "C" {
260 static gboolean wxapp_idle_callback(gpointer)
261 {
262 return wxTheApp->DoIdle();
263 }
264 }
265
266 bool wxApp::DoIdle()
267 {
268 guint id_save;
269 {
270 // Allow another idle source to be added while this one is busy.
271 // Needed if an idle event handler runs a new event loop,
272 // for example by showing a dialog.
273 #if wxUSE_THREADS
274 wxMutexLocker lock(*m_idleMutex);
275 #endif
276 id_save = m_idleSourceId;
277 m_idleSourceId = 0;
278 wx_add_idle_hooks();
279 #ifdef __WXDEBUG__
280 // don't generate the idle events while the assert modal dialog is shown,
281 // this matches the behavior of wxMSW
282 if (m_isInAssert)
283 return false;
284 #endif
285 }
286
287 gdk_threads_enter();
288 bool needMore;
289 do {
290 needMore = ProcessIdle();
291 } while (needMore && gtk_events_pending() == 0);
292 gdk_threads_leave();
293
294 #if wxUSE_THREADS
295 wxMutexLocker lock(*m_idleMutex);
296 #endif
297 // if a new idle source was added during ProcessIdle
298 if (m_idleSourceId != 0)
299 {
300 // remove it
301 g_source_remove(m_idleSourceId);
302 m_idleSourceId = 0;
303 }
304
305 // Pending events can be added asynchronously,
306 // need to keep idle source if any have appeared
307 needMore = needMore || HasPendingEvents();
308
309 // if more idle processing requested
310 if (needMore)
311 {
312 // keep this source installed
313 m_idleSourceId = id_save;
314 return true;
315 }
316 // add hooks and remove this source
317 wx_add_idle_hooks();
318 return false;
319 }
320
321 //-----------------------------------------------------------------------------
322 // Access to the root window global
323 //-----------------------------------------------------------------------------
324
325 GtkWidget* wxGetRootWindow()
326 {
327 if (gs_RootWindow == NULL)
328 {
329 gs_RootWindow = gtk_window_new( GTK_WINDOW_TOPLEVEL );
330 gtk_widget_realize( gs_RootWindow );
331 }
332 return gs_RootWindow;
333 }
334
335 //-----------------------------------------------------------------------------
336 // wxApp
337 //-----------------------------------------------------------------------------
338
339 IMPLEMENT_DYNAMIC_CLASS(wxApp,wxEvtHandler)
340
341 wxApp::wxApp()
342 {
343 #ifdef __WXDEBUG__
344 m_isInAssert = false;
345 #endif // __WXDEBUG__
346 #if wxUSE_THREADS
347 m_idleMutex = NULL;
348 #endif
349 m_idleSourceId = 0;
350 }
351
352 wxApp::~wxApp()
353 {
354 }
355
356 bool wxApp::SetNativeTheme(const wxString& theme)
357 {
358 wxString path;
359 path = gtk_rc_get_theme_dir();
360 path += "/";
361 path += theme.utf8_str();
362 path += "/gtk-2.0/gtkrc";
363
364 if ( wxFileExists(path.utf8_str()) )
365 gtk_rc_add_default_file(path.utf8_str());
366 else if ( wxFileExists(theme.utf8_str()) )
367 gtk_rc_add_default_file(theme.utf8_str());
368 else
369 {
370 wxLogWarning("Theme \"%s\" not available.", theme);
371
372 return false;
373 }
374
375 gtk_rc_reparse_all_for_settings(gtk_settings_get_default(), TRUE);
376
377 return true;
378 }
379
380 bool wxApp::OnInitGui()
381 {
382 if ( !wxAppBase::OnInitGui() )
383 return false;
384
385 // if this is a wxGLApp (derived from wxApp), and we've already
386 // chosen a specific visual, then derive the GdkVisual from that
387 if ( GetXVisualInfo() )
388 {
389 GdkVisual* vis = gtk_widget_get_default_visual();
390
391 GdkColormap *colormap = gdk_colormap_new( vis, FALSE );
392 gtk_widget_set_default_colormap( colormap );
393 }
394 else
395 {
396 // On some machines, the default visual is just 256 colours, so
397 // we make sure we get the best. This can sometimes be wasteful.
398 if (m_useBestVisual)
399 {
400 if (m_forceTrueColour)
401 {
402 GdkVisual* visual = gdk_visual_get_best_with_both( 24, GDK_VISUAL_TRUE_COLOR );
403 if (!visual)
404 {
405 wxLogError(wxT("Unable to initialize TrueColor visual."));
406 return false;
407 }
408 GdkColormap *colormap = gdk_colormap_new( visual, FALSE );
409 gtk_widget_set_default_colormap( colormap );
410 }
411 else
412 {
413 if (gdk_visual_get_best() != gdk_visual_get_system())
414 {
415 GdkVisual* visual = gdk_visual_get_best();
416 GdkColormap *colormap = gdk_colormap_new( visual, FALSE );
417 gtk_widget_set_default_colormap( colormap );
418 }
419 }
420 }
421 }
422
423 #if wxUSE_LIBHILDON
424 m_hildonProgram = hildon_program_get_instance();
425 if ( !m_hildonProgram )
426 {
427 wxLogError(_("Unable to initialize Hildon program"));
428 return false;
429 }
430 #endif // wxUSE_LIBHILDON
431
432 return true;
433 }
434
435 GdkVisual *wxApp::GetGdkVisual()
436 {
437 GdkVisual *visual = NULL;
438
439 XVisualInfo *xvi = (XVisualInfo *)GetXVisualInfo();
440 if ( xvi )
441 visual = gdkx_visual_get( xvi->visualid );
442 else
443 visual = gdk_drawable_get_visual( wxGetRootWindow()->window );
444
445 wxASSERT( visual );
446
447 return visual;
448 }
449
450 // use unusual names for the parameters to avoid conflict with wxApp::arg[cv]
451 bool wxApp::Initialize(int& argc_, wxChar **argv_)
452 {
453 if ( !wxAppBase::Initialize(argc_, argv_) )
454 return false;
455
456 #if wxUSE_THREADS
457 if (!g_thread_supported())
458 {
459 g_thread_init(NULL);
460 gdk_threads_init();
461 }
462 #endif // wxUSE_THREADS
463
464 // gtk+ 2.0 supports Unicode through UTF-8 strings
465 wxConvCurrent = &wxConvUTF8;
466
467 // decide which conversion to use for the file names
468
469 // (1) this variable exists for the sole purpose of specifying the encoding
470 // of the filenames for GTK+ programs, so use it if it is set
471 wxString encName(wxGetenv(_T("G_FILENAME_ENCODING")));
472 encName = encName.BeforeFirst(_T(','));
473 if (encName.CmpNoCase(_T("@locale")) == 0)
474 encName.clear();
475 encName.MakeUpper();
476 #if wxUSE_INTL
477 if (encName.empty())
478 {
479 // (2) if a non default locale is set, assume that the user wants his
480 // filenames in this locale too
481 encName = wxLocale::GetSystemEncodingName().Upper();
482 // (3) finally use UTF-8 by default
483 if (encName.empty() || encName == _T("US-ASCII"))
484 encName = _T("UTF-8");
485 wxSetEnv(_T("G_FILENAME_ENCODING"), encName);
486 }
487 #else
488 if (encName.empty())
489 encName = _T("UTF-8");
490
491 // if wxUSE_INTL==0 it probably indicates that only "C" locale is supported
492 // by the program anyhow so prevent GTK+ from calling setlocale(LC_ALL, "")
493 // from gtk_init_check() as it does by default
494 gtk_disable_setlocale();
495
496 #endif // wxUSE_INTL
497 static wxConvBrokenFileNames fileconv(encName);
498 wxConvFileName = &fileconv;
499
500
501 bool init_result;
502 int i;
503
504 #if wxUSE_UNICODE
505 // gtk_init() wants UTF-8, not wchar_t, so convert
506 char **argvGTK = new char *[argc_ + 1];
507 for ( i = 0; i < argc_; i++ )
508 {
509 argvGTK[i] = wxStrdupA(wxConvUTF8.cWX2MB(argv_[i]));
510 }
511
512 argvGTK[argc_] = NULL;
513
514 int argcGTK = argc_;
515
516 #ifdef __WXGPE__
517 init_result = true; // is there a _check() version of this?
518 gpe_application_init( &argcGTK, &argvGTK );
519 #else
520 init_result = gtk_init_check( &argcGTK, &argvGTK );
521 #endif
522 wxUpdateLocaleIsUtf8();
523
524 if ( argcGTK != argc_ )
525 {
526 // we have to drop the parameters which were consumed by GTK+
527 for ( i = 0; i < argcGTK; i++ )
528 {
529 while ( strcmp(wxConvUTF8.cWX2MB(argv_[i]), argvGTK[i]) != 0 )
530 {
531 memmove(argv_ + i, argv_ + i + 1, (argc_ - i)*sizeof(*argv_));
532 }
533 }
534
535 argc_ = argcGTK;
536 argv_[argc_] = NULL;
537 }
538 //else: gtk_init() didn't modify our parameters
539
540 // free our copy
541 for ( i = 0; i < argcGTK; i++ )
542 {
543 free(argvGTK[i]);
544 }
545
546 delete [] argvGTK;
547 #else // !wxUSE_UNICODE
548 // gtk_init() shouldn't actually change argv_ itself (just its contents) so
549 // it's ok to pass pointer to it
550 init_result = gtk_init_check( &argc_, &argv_ );
551 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
552
553 // update internal arg[cv] as GTK+ may have removed processed options:
554 this->argc = argc_;
555 this->argv = argv_;
556
557 if ( m_traits )
558 {
559 // if there are still GTK+ standard options unparsed in the command
560 // line, it means that they were not syntactically correct and GTK+
561 // already printed a warning on the command line and we should now
562 // exit:
563 wxArrayString opt, desc;
564 m_traits->GetStandardCmdLineOptions(opt, desc);
565
566 for ( i = 0; i < argc_; i++ )
567 {
568 // leave just the names of the options with values
569 const wxString str = wxString(argv_[i]).BeforeFirst('=');
570
571 for ( size_t j = 0; j < opt.size(); j++ )
572 {
573 // remove the leading spaces from the option string as it does
574 // have them
575 if ( opt[j].Trim(false).BeforeFirst('=') == str )
576 {
577 // a GTK+ option can be left on the command line only if
578 // there was an error in (or before, in another standard
579 // options) it, so abort, just as we do if incorrect
580 // program option is given
581 wxLogError(_("Invalid GTK+ command line option, use \"%s --help\""),
582 argv_[0]);
583 return false;
584 }
585 }
586 }
587 }
588
589 if ( !init_result )
590 {
591 wxLogError(_("Unable to initialize GTK+, is DISPLAY set properly?"));
592 return false;
593 }
594
595 // we can not enter threads before gtk_init is done
596 gdk_threads_enter();
597
598 wxSetDetectableAutoRepeat( true );
599
600 #if wxUSE_INTL
601 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
602 #endif
603
604 #if wxUSE_THREADS
605 m_idleMutex = new wxMutex;
606 #endif
607 // make sure GtkWidget type is loaded, idle hooks need it
608 g_type_class_ref(GTK_TYPE_WIDGET);
609 WakeUpIdle();
610
611 return true;
612 }
613
614 void wxApp::CleanUp()
615 {
616 if (m_idleSourceId != 0)
617 g_source_remove(m_idleSourceId);
618
619 // release reference acquired by Initialize()
620 g_type_class_unref(g_type_class_peek(GTK_TYPE_WIDGET));
621
622 gdk_threads_leave();
623
624 wxAppBase::CleanUp();
625
626 // delete this mutex as late as possible as it's used from WakeUpIdle(), in
627 // particular do it after calling the base class CleanUp() which can result
628 // in it being called
629 #if wxUSE_THREADS
630 delete m_idleMutex;
631 m_idleMutex = NULL;
632 #endif
633 }
634
635 void wxApp::WakeUpIdle()
636 {
637 #if wxUSE_THREADS
638 wxMutexLocker lock(*m_idleMutex);
639 #endif
640 if (m_idleSourceId == 0)
641 m_idleSourceId = g_idle_add_full(G_PRIORITY_LOW, wxapp_idle_callback, NULL, NULL);
642 }
643
644 // Checking for pending events requires first removing our idle source,
645 // otherwise it will cause the check to always return true.
646 bool wxApp::EventsPending()
647 {
648 #if wxUSE_THREADS
649 wxMutexLocker lock(*m_idleMutex);
650 #endif
651 if (m_idleSourceId != 0)
652 {
653 g_source_remove(m_idleSourceId);
654 m_idleSourceId = 0;
655 wx_add_idle_hooks();
656 }
657 return gtk_events_pending() != 0;
658 }
659
660 #ifdef __WXDEBUG__
661
662 void wxApp::OnAssertFailure(const wxChar *file,
663 int line,
664 const wxChar* func,
665 const wxChar* cond,
666 const wxChar *msg)
667 {
668
669 // block wx idle events while assert dialog is showing
670 m_isInAssert = true;
671
672 wxAppBase::OnAssertFailure(file, line, func, cond, msg);
673
674 m_isInAssert = false;
675 }
676
677 #endif // __WXDEBUG__
678
679 #if wxUSE_THREADS
680 void wxGUIAppTraits::MutexGuiEnter()
681 {
682 gdk_threads_enter();
683 }
684
685 void wxGUIAppTraits::MutexGuiLeave()
686 {
687 gdk_threads_leave();
688 }
689 #endif // wxUSE_THREADS