don't use annoying and unneeded in C++ casts of NULL to "T *" in all other files...
[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
53 //-----------------------------------------------------------------------------
54 // wxYield
55 //-----------------------------------------------------------------------------
56
57 bool wxApp::Yield(bool onlyIfNeeded)
58 {
59 if ( m_isInsideYield )
60 {
61 if ( !onlyIfNeeded )
62 {
63 wxFAIL_MSG( wxT("wxYield called recursively" ) );
64 }
65
66 return false;
67 }
68
69 #if wxUSE_THREADS
70 if ( !wxThread::IsMain() )
71 {
72 // can't call gtk_main_iteration() from other threads like this
73 return true;
74 }
75 #endif // wxUSE_THREADS
76
77 m_isInsideYield = true;
78
79 #if wxUSE_LOG
80 // disable log flushing from here because a call to wxYield() shouldn't
81 // normally result in message boxes popping up &c
82 wxLog::Suspend();
83 #endif
84
85 while (EventsPending())
86 gtk_main_iteration();
87
88 // It's necessary to call ProcessIdle() to update the frames sizes which
89 // might have been changed (it also will update other things set from
90 // OnUpdateUI() which is a nice (and desired) side effect). But we
91 // call ProcessIdle() only once since this is not meant for longish
92 // background jobs (controlled by wxIdleEvent::RequestMore() and the
93 // return value of Processidle().
94 ProcessIdle();
95
96 #if wxUSE_LOG
97 // let the logs be flashed again
98 wxLog::Resume();
99 #endif
100
101 m_isInsideYield = false;
102
103 return true;
104 }
105
106 //-----------------------------------------------------------------------------
107 // local functions
108 //-----------------------------------------------------------------------------
109
110 // One-shot signal emission hook, to install idle handler.
111 extern "C" {
112 static gboolean
113 wx_emission_hook(GSignalInvocationHint*, guint, const GValue*, gpointer data)
114 {
115 wxApp* app = wxTheApp;
116 if (app != NULL)
117 app->WakeUpIdle();
118 gulong* hook_id = (gulong*)data;
119 // record that hook is not installed
120 *hook_id = 0;
121 // remove hook
122 return false;
123 }
124 }
125
126 // Add signal emission hooks, to re-install idle handler when needed.
127 static void wx_add_idle_hooks()
128 {
129 // "event" hook
130 {
131 static gulong hook_id = 0;
132 if (hook_id == 0)
133 {
134 static guint sig_id = 0;
135 if (sig_id == 0)
136 sig_id = g_signal_lookup("event", GTK_TYPE_WIDGET);
137 hook_id = g_signal_add_emission_hook(
138 sig_id, 0, wx_emission_hook, &hook_id, NULL);
139 }
140 }
141 // "size_allocate" hook
142 // Needed to match the behavior of the old idle system,
143 // but probably not necessary.
144 {
145 static gulong hook_id = 0;
146 if (hook_id == 0)
147 {
148 static guint sig_id = 0;
149 if (sig_id == 0)
150 sig_id = g_signal_lookup("size_allocate", GTK_TYPE_WIDGET);
151 hook_id = g_signal_add_emission_hook(
152 sig_id, 0, wx_emission_hook, &hook_id, NULL);
153 }
154 }
155 }
156
157 extern "C" {
158 static gboolean wxapp_idle_callback(gpointer)
159 {
160 return wxTheApp->DoIdle();
161 }
162 }
163
164 bool wxApp::DoIdle()
165 {
166 guint id_save;
167 {
168 // Allow another idle source to be added while this one is busy.
169 // Needed if an idle event handler runs a new event loop,
170 // for example by showing a dialog.
171 #if wxUSE_THREADS
172 wxMutexLocker lock(*m_idleMutex);
173 #endif
174 id_save = m_idleSourceId;
175 m_idleSourceId = 0;
176 wx_add_idle_hooks();
177 #ifdef __WXDEBUG__
178 // don't generate the idle events while the assert modal dialog is shown,
179 // this matches the behavior of wxMSW
180 if (m_isInAssert)
181 return false;
182 #endif
183 }
184
185 gdk_threads_enter();
186 bool needMore;
187 do {
188 needMore = ProcessIdle();
189 } while (needMore && gtk_events_pending() == 0);
190 gdk_threads_leave();
191
192 #if wxUSE_THREADS
193 wxMutexLocker lock(*m_idleMutex);
194 #endif
195 // if a new idle source was added during ProcessIdle
196 if (m_idleSourceId != 0)
197 {
198 // remove it
199 g_source_remove(m_idleSourceId);
200 m_idleSourceId = 0;
201 }
202
203 // Pending events can be added asynchronously,
204 // need to keep idle source if any have appeared
205 needMore = needMore || HasPendingEvents();
206
207 // if more idle processing requested
208 if (needMore)
209 {
210 // keep this source installed
211 m_idleSourceId = id_save;
212 return true;
213 }
214 // add hooks and remove this source
215 wx_add_idle_hooks();
216 return false;
217 }
218
219 //-----------------------------------------------------------------------------
220 // Access to the root window global
221 //-----------------------------------------------------------------------------
222
223 GtkWidget* wxGetRootWindow()
224 {
225 if (gs_RootWindow == NULL)
226 {
227 gs_RootWindow = gtk_window_new( GTK_WINDOW_TOPLEVEL );
228 gtk_widget_realize( gs_RootWindow );
229 }
230 return gs_RootWindow;
231 }
232
233 //-----------------------------------------------------------------------------
234 // wxApp
235 //-----------------------------------------------------------------------------
236
237 IMPLEMENT_DYNAMIC_CLASS(wxApp,wxEvtHandler)
238
239 wxApp::wxApp()
240 {
241 #ifdef __WXDEBUG__
242 m_isInAssert = false;
243 #endif // __WXDEBUG__
244 #if wxUSE_THREADS
245 m_idleMutex = NULL;
246 #endif
247 m_idleSourceId = 0;
248 }
249
250 wxApp::~wxApp()
251 {
252 }
253
254 bool wxApp::SetNativeTheme(const wxString& theme)
255 {
256 wxString path;
257 path = gtk_rc_get_theme_dir();
258 path += "/";
259 path += theme.utf8_str();
260 path += "/gtk-2.0/gtkrc";
261
262 if ( wxFileExists(path.utf8_str()) )
263 gtk_rc_add_default_file(path.utf8_str());
264 else if ( wxFileExists(theme.utf8_str()) )
265 gtk_rc_add_default_file(theme.utf8_str());
266 else
267 {
268 wxLogWarning("Theme \"%s\" not available.", theme);
269
270 return false;
271 }
272
273 gtk_rc_reparse_all_for_settings(gtk_settings_get_default(), TRUE);
274
275 return true;
276 }
277
278 bool wxApp::OnInitGui()
279 {
280 if ( !wxAppBase::OnInitGui() )
281 return false;
282
283 // if this is a wxGLApp (derived from wxApp), and we've already
284 // chosen a specific visual, then derive the GdkVisual from that
285 if ( GetXVisualInfo() )
286 {
287 GdkVisual* vis = gtk_widget_get_default_visual();
288
289 GdkColormap *colormap = gdk_colormap_new( vis, FALSE );
290 gtk_widget_set_default_colormap( colormap );
291 }
292 else
293 {
294 // On some machines, the default visual is just 256 colours, so
295 // we make sure we get the best. This can sometimes be wasteful.
296 if (m_useBestVisual)
297 {
298 if (m_forceTrueColour)
299 {
300 GdkVisual* visual = gdk_visual_get_best_with_both( 24, GDK_VISUAL_TRUE_COLOR );
301 if (!visual)
302 {
303 wxLogError(wxT("Unable to initialize TrueColor visual."));
304 return false;
305 }
306 GdkColormap *colormap = gdk_colormap_new( visual, FALSE );
307 gtk_widget_set_default_colormap( colormap );
308 }
309 else
310 {
311 if (gdk_visual_get_best() != gdk_visual_get_system())
312 {
313 GdkVisual* visual = gdk_visual_get_best();
314 GdkColormap *colormap = gdk_colormap_new( visual, FALSE );
315 gtk_widget_set_default_colormap( colormap );
316 }
317 }
318 }
319 }
320
321 #if wxUSE_LIBHILDON
322 m_hildonProgram = hildon_program_get_instance();
323 if ( !m_hildonProgram )
324 {
325 wxLogError(_("Unable to initialize Hildon program"));
326 return false;
327 }
328 #endif // wxUSE_LIBHILDON
329
330 return true;
331 }
332
333 GdkVisual *wxApp::GetGdkVisual()
334 {
335 GdkVisual *visual = NULL;
336
337 XVisualInfo *xvi = (XVisualInfo *)GetXVisualInfo();
338 if ( xvi )
339 visual = gdkx_visual_get( xvi->visualid );
340 else
341 visual = gdk_drawable_get_visual( wxGetRootWindow()->window );
342
343 wxASSERT( visual );
344
345 return visual;
346 }
347
348 // use unusual names for the parameters to avoid conflict with wxApp::arg[cv]
349 bool wxApp::Initialize(int& argc_, wxChar **argv_)
350 {
351 if ( !wxAppBase::Initialize(argc_, argv_) )
352 return false;
353
354 #if wxUSE_THREADS
355 if (!g_thread_supported())
356 {
357 g_thread_init(NULL);
358 gdk_threads_init();
359 }
360 #endif // wxUSE_THREADS
361
362 // gtk+ 2.0 supports Unicode through UTF-8 strings
363 wxConvCurrent = &wxConvUTF8;
364
365 // decide which conversion to use for the file names
366
367 // (1) this variable exists for the sole purpose of specifying the encoding
368 // of the filenames for GTK+ programs, so use it if it is set
369 wxString encName(wxGetenv(_T("G_FILENAME_ENCODING")));
370 encName = encName.BeforeFirst(_T(','));
371 if (encName.CmpNoCase(_T("@locale")) == 0)
372 encName.clear();
373 encName.MakeUpper();
374 #if wxUSE_INTL
375 if (encName.empty())
376 {
377 // (2) if a non default locale is set, assume that the user wants his
378 // filenames in this locale too
379 encName = wxLocale::GetSystemEncodingName().Upper();
380 // (3) finally use UTF-8 by default
381 if (encName.empty() || encName == _T("US-ASCII"))
382 encName = _T("UTF-8");
383 wxSetEnv(_T("G_FILENAME_ENCODING"), encName);
384 }
385 #else
386 if (encName.empty())
387 encName = _T("UTF-8");
388
389 // if wxUSE_INTL==0 it probably indicates that only "C" locale is supported
390 // by the program anyhow so prevent GTK+ from calling setlocale(LC_ALL, "")
391 // from gtk_init_check() as it does by default
392 gtk_disable_setlocale();
393
394 #endif // wxUSE_INTL
395 static wxConvBrokenFileNames fileconv(encName);
396 wxConvFileName = &fileconv;
397
398
399 bool init_result;
400 int i;
401
402 #if wxUSE_UNICODE
403 // gtk_init() wants UTF-8, not wchar_t, so convert
404 char **argvGTK = new char *[argc_ + 1];
405 for ( i = 0; i < argc_; i++ )
406 {
407 argvGTK[i] = wxStrdupA(wxConvUTF8.cWX2MB(argv_[i]));
408 }
409
410 argvGTK[argc_] = NULL;
411
412 int argcGTK = argc_;
413
414 #ifdef __WXGPE__
415 init_result = true; // is there a _check() version of this?
416 gpe_application_init( &argcGTK, &argvGTK );
417 #else
418 init_result = gtk_init_check( &argcGTK, &argvGTK );
419 #endif
420 wxUpdateLocaleIsUtf8();
421
422 if ( argcGTK != argc_ )
423 {
424 // we have to drop the parameters which were consumed by GTK+
425 for ( i = 0; i < argcGTK; i++ )
426 {
427 while ( strcmp(wxConvUTF8.cWX2MB(argv_[i]), argvGTK[i]) != 0 )
428 {
429 memmove(argv_ + i, argv_ + i + 1, (argc_ - i)*sizeof(*argv_));
430 }
431 }
432
433 argc_ = argcGTK;
434 argv_[argc_] = NULL;
435 }
436 //else: gtk_init() didn't modify our parameters
437
438 // free our copy
439 for ( i = 0; i < argcGTK; i++ )
440 {
441 free(argvGTK[i]);
442 }
443
444 delete [] argvGTK;
445 #else // !wxUSE_UNICODE
446 // gtk_init() shouldn't actually change argv_ itself (just its contents) so
447 // it's ok to pass pointer to it
448 init_result = gtk_init_check( &argc_, &argv_ );
449 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
450
451 // update internal arg[cv] as GTK+ may have removed processed options:
452 this->argc = argc_;
453 this->argv = argv_;
454
455 if ( m_traits )
456 {
457 // if there are still GTK+ standard options unparsed in the command
458 // line, it means that they were not syntactically correct and GTK+
459 // already printed a warning on the command line and we should now
460 // exit:
461 wxArrayString opt, desc;
462 m_traits->GetStandardCmdLineOptions(opt, desc);
463
464 for ( i = 0; i < argc_; i++ )
465 {
466 // leave just the names of the options with values
467 const wxString str = wxString(argv_[i]).BeforeFirst('=');
468
469 for ( size_t j = 0; j < opt.size(); j++ )
470 {
471 // remove the leading spaces from the option string as it does
472 // have them
473 if ( opt[j].Trim(false).BeforeFirst('=') == str )
474 {
475 // a GTK+ option can be left on the command line only if
476 // there was an error in (or before, in another standard
477 // options) it, so abort, just as we do if incorrect
478 // program option is given
479 wxLogError(_("Invalid GTK+ command line option, use \"%s --help\""),
480 argv_[0]);
481 return false;
482 }
483 }
484 }
485 }
486
487 if ( !init_result )
488 {
489 wxLogError(_("Unable to initialize GTK+, is DISPLAY set properly?"));
490 return false;
491 }
492
493 // we can not enter threads before gtk_init is done
494 gdk_threads_enter();
495
496 wxSetDetectableAutoRepeat( true );
497
498 #if wxUSE_INTL
499 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
500 #endif
501
502 #if wxUSE_THREADS
503 m_idleMutex = new wxMutex;
504 #endif
505 // make sure GtkWidget type is loaded, idle hooks need it
506 g_type_class_ref(GTK_TYPE_WIDGET);
507 WakeUpIdle();
508
509 return true;
510 }
511
512 void wxApp::CleanUp()
513 {
514 if (m_idleSourceId != 0)
515 g_source_remove(m_idleSourceId);
516
517 // release reference acquired by Initialize()
518 g_type_class_unref(g_type_class_peek(GTK_TYPE_WIDGET));
519
520 gdk_threads_leave();
521
522 wxAppBase::CleanUp();
523
524 // delete this mutex as late as possible as it's used from WakeUpIdle(), in
525 // particular do it after calling the base class CleanUp() which can result
526 // in it being called
527 #if wxUSE_THREADS
528 delete m_idleMutex;
529 m_idleMutex = NULL;
530 #endif
531 }
532
533 void wxApp::WakeUpIdle()
534 {
535 #if wxUSE_THREADS
536 wxMutexLocker lock(*m_idleMutex);
537 #endif
538 if (m_idleSourceId == 0)
539 m_idleSourceId = g_idle_add_full(G_PRIORITY_LOW, wxapp_idle_callback, NULL, NULL);
540 }
541
542 // Checking for pending events requires first removing our idle source,
543 // otherwise it will cause the check to always return true.
544 bool wxApp::EventsPending()
545 {
546 #if wxUSE_THREADS
547 wxMutexLocker lock(*m_idleMutex);
548 #endif
549 if (m_idleSourceId != 0)
550 {
551 g_source_remove(m_idleSourceId);
552 m_idleSourceId = 0;
553 wx_add_idle_hooks();
554 }
555 return gtk_events_pending() != 0;
556 }
557
558 #ifdef __WXDEBUG__
559
560 void wxApp::OnAssertFailure(const wxChar *file,
561 int line,
562 const wxChar* func,
563 const wxChar* cond,
564 const wxChar *msg)
565 {
566
567 // block wx idle events while assert dialog is showing
568 m_isInAssert = true;
569
570 wxAppBase::OnAssertFailure(file, line, func, cond, msg);
571
572 m_isInAssert = false;
573 }
574
575 #endif // __WXDEBUG__
576
577 #if wxUSE_THREADS
578 void wxGUIAppTraits::MutexGuiEnter()
579 {
580 gdk_threads_enter();
581 }
582
583 void wxGUIAppTraits::MutexGuiLeave()
584 {
585 gdk_threads_leave();
586 }
587 #endif // wxUSE_THREADS