1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/gtk/app.cpp
3 // Purpose:
4 // Author:      Robert Roebling
5 // Copyright:   (c) 1998 Robert Roebling, Julian Smart
6 // Licence:     wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
8 
9 // For compilers that support precompilation, includes "wx.h".
10 #include "wx/wxprec.h"
11 
12 #include "wx/app.h"
13 
14 #ifndef WX_PRECOMP
15     #include "wx/intl.h"
16     #include "wx/log.h"
17     #include "wx/utils.h"
18     #include "wx/memory.h"
19     #include "wx/font.h"
20 #endif
21 
22 #include "wx/thread.h"
23 
24 #ifdef __WXGPE__
25     #include <gpe/init.h>
26 #endif
27 
28 #include "wx/apptrait.h"
29 #include "wx/fontmap.h"
30 
31 #if wxUSE_LIBHILDON
32     #include <hildon-widgets/hildon-program.h>
33 #endif // wxUSE_LIBHILDON
34 
35 #if wxUSE_LIBHILDON2
36     #include <hildon/hildon.h>
37 #endif // wxUSE_LIBHILDON2
38 
39 #include <gtk/gtk.h>
40 #include "wx/gtk/private.h"
41 
42 //-----------------------------------------------------------------------------
43 // link GnomeVFS
44 //-----------------------------------------------------------------------------
45 
46 #if wxUSE_MIMETYPE && wxUSE_LIBGNOMEVFS
47     #include "wx/link.h"
wxFORCE_LINK_MODULE(gnome_vfs)48     wxFORCE_LINK_MODULE(gnome_vfs)
49 #endif
50 
51 //-----------------------------------------------------------------------------
52 // local functions
53 //-----------------------------------------------------------------------------
54 
55 // One-shot signal emission hook, to install idle handler.
56 extern "C" {
57 static gboolean
58 wx_emission_hook(GSignalInvocationHint*, guint, const GValue*, gpointer data)
59 {
60     wxApp* app = wxTheApp;
61     if (app != NULL)
62         app->WakeUpIdle();
63     bool* hook_installed = (bool*)data;
64     // record that hook is not installed
65     *hook_installed = false;
66     // remove hook
67     return false;
68 }
69 }
70 
71 // Add signal emission hooks, to re-install idle handler when needed.
wx_add_idle_hooks()72 static void wx_add_idle_hooks()
73 {
74     // "event" hook
75     {
76         static bool hook_installed;
77         if (!hook_installed)
78         {
79             static guint sig_id;
80             if (sig_id == 0)
81                 sig_id = g_signal_lookup("event", GTK_TYPE_WIDGET);
82             hook_installed = true;
83             g_signal_add_emission_hook(
84                 sig_id, 0, wx_emission_hook, &hook_installed, NULL);
85         }
86     }
87     // "size_allocate" hook
88     // Needed to match the behaviour of the old idle system,
89     // but probably not necessary.
90     {
91         static bool hook_installed;
92         if (!hook_installed)
93         {
94             static guint sig_id;
95             if (sig_id == 0)
96                 sig_id = g_signal_lookup("size_allocate", GTK_TYPE_WIDGET);
97             hook_installed = true;
98             g_signal_add_emission_hook(
99                 sig_id, 0, wx_emission_hook, &hook_installed, NULL);
100         }
101     }
102 }
103 
104 extern "C" {
wxapp_idle_callback(gpointer)105 static gboolean wxapp_idle_callback(gpointer)
106 {
107     return wxTheApp->DoIdle();
108 }
109 }
110 
111 // 0: no change, 1: focus in, 2: focus out
112 static int gs_focusChange;
113 
114 extern "C" {
115 static gboolean
wx_focus_event_hook(GSignalInvocationHint *,unsigned,const GValue * param_values,void * data)116 wx_focus_event_hook(GSignalInvocationHint*, unsigned, const GValue* param_values, void* data)
117 {
118     // If focus change on TLW
119     if (GTK_IS_WINDOW(g_value_peek_pointer(param_values)))
120         gs_focusChange = GPOINTER_TO_INT(data);
121 
122     return true;
123 }
124 }
125 
DoIdle()126 bool wxApp::DoIdle()
127 {
128     guint id_save;
129     {
130         // Allow another idle source to be added while this one is busy.
131         // Needed if an idle event handler runs a new event loop,
132         // for example by showing a dialog.
133 #if wxUSE_THREADS
134         wxMutexLocker lock(m_idleMutex);
135 #endif
136         id_save = m_idleSourceId;
137         m_idleSourceId = 0;
138         wx_add_idle_hooks();
139 
140 #if wxDEBUG_LEVEL
141         // don't generate the idle events while the assert modal dialog is shown,
142         // this matches the behaviour of wxMSW
143         if (m_isInAssert)
144             return false;
145 #endif
146     }
147 
148     gdk_threads_enter();
149 
150     if (gs_focusChange) {
151         SetActive(gs_focusChange == 1, NULL);
152         gs_focusChange = 0;
153     }
154 
155     bool needMore;
156     do {
157         ProcessPendingEvents();
158 
159         needMore = ProcessIdle();
160     } while (needMore && gtk_events_pending() == 0);
161     gdk_threads_leave();
162 
163 #if wxUSE_THREADS
164     wxMutexLocker lock(m_idleMutex);
165 #endif
166 
167     bool keepSource = false;
168     // if a new idle source has not been added, either as a result of idle
169     // processing above or by another thread calling WakeUpIdle()
170     if (m_idleSourceId == 0)
171     {
172         // if more idle processing was requested or pending events have appeared
173         if (needMore || HasPendingEvents())
174         {
175             // keep this source installed
176             m_idleSourceId = id_save;
177             keepSource = true;
178         }
179         else // add hooks and remove this source
180             wx_add_idle_hooks();
181     }
182     // else remove this source, leave new one installed
183     // we must keep an idle source, otherwise a wakeup could be lost
184 
185     return keepSource;
186 }
187 
188 //-----------------------------------------------------------------------------
189 // Access to the root window global
190 //-----------------------------------------------------------------------------
191 
wxGetRootWindow()192 GtkWidget* wxGetRootWindow()
193 {
194     static GtkWidget *s_RootWindow = NULL;
195 
196     if (s_RootWindow == NULL)
197     {
198         s_RootWindow = gtk_window_new( GTK_WINDOW_TOPLEVEL );
199         gtk_widget_realize( s_RootWindow );
200     }
201     return s_RootWindow;
202 }
203 
204 //-----------------------------------------------------------------------------
205 // wxApp
206 //-----------------------------------------------------------------------------
207 
IMPLEMENT_DYNAMIC_CLASS(wxApp,wxEvtHandler)208 IMPLEMENT_DYNAMIC_CLASS(wxApp,wxEvtHandler)
209 
210 wxApp::wxApp()
211 {
212     m_isInAssert = false;
213     m_idleSourceId = 0;
214 }
215 
~wxApp()216 wxApp::~wxApp()
217 {
218 }
219 
SetNativeTheme(const wxString & theme)220 bool wxApp::SetNativeTheme(const wxString& theme)
221 {
222 #ifdef __WXGTK3__
223     wxUnusedVar(theme);
224     return false;
225 #else
226     wxString path;
227     path = gtk_rc_get_theme_dir();
228     path += "/";
229     path += theme.utf8_str();
230     path += "/gtk-2.0/gtkrc";
231 
232     if ( wxFileExists(path.utf8_str()) )
233         gtk_rc_add_default_file(path.utf8_str());
234     else if ( wxFileExists(theme.utf8_str()) )
235         gtk_rc_add_default_file(theme.utf8_str());
236     else
237     {
238         wxLogWarning("Theme \"%s\" not available.", theme);
239 
240         return false;
241     }
242 
243     gtk_rc_reparse_all_for_settings(gtk_settings_get_default(), TRUE);
244 
245     return true;
246 #endif
247 }
248 
OnInitGui()249 bool wxApp::OnInitGui()
250 {
251     if ( !wxAppBase::OnInitGui() )
252         return false;
253 
254 #ifndef __WXGTK3__
255     // if this is a wxGLApp (derived from wxApp), and we've already
256     // chosen a specific visual, then derive the GdkVisual from that
257     if ( GetXVisualInfo() )
258     {
259         GdkVisual* vis = gtk_widget_get_default_visual();
260 
261         GdkColormap *colormap = gdk_colormap_new( vis, FALSE );
262         gtk_widget_set_default_colormap( colormap );
263     }
264     else
265     {
266         // On some machines, the default visual is just 256 colours, so
267         // we make sure we get the best. This can sometimes be wasteful.
268         if (m_useBestVisual)
269         {
270             if (m_forceTrueColour)
271             {
272                 GdkVisual* visual = gdk_visual_get_best_with_both( 24, GDK_VISUAL_TRUE_COLOR );
273                 if (!visual)
274                 {
275                     wxLogError(wxT("Unable to initialize TrueColor visual."));
276                     return false;
277                 }
278                 GdkColormap *colormap = gdk_colormap_new( visual, FALSE );
279                 gtk_widget_set_default_colormap( colormap );
280             }
281             else
282             {
283                 if (gdk_visual_get_best() != gdk_visual_get_system())
284                 {
285                     GdkVisual* visual = gdk_visual_get_best();
286                     GdkColormap *colormap = gdk_colormap_new( visual, FALSE );
287                     gtk_widget_set_default_colormap( colormap );
288                 }
289             }
290         }
291     }
292 #endif
293 
294 #if wxUSE_LIBHILDON || wxUSE_LIBHILDON2
295     if ( !GetHildonProgram() )
296     {
297         wxLogError(_("Unable to initialize Hildon program"));
298         return false;
299     }
300 #endif // wxUSE_LIBHILDON || wxUSE_LIBHILDON2
301 
302     return true;
303 }
304 
305 // use unusual names for the parameters to avoid conflict with wxApp::arg[cv]
Initialize(int & argc_,wxChar ** argv_)306 bool wxApp::Initialize(int& argc_, wxChar **argv_)
307 {
308     if ( !wxAppBase::Initialize(argc_, argv_) )
309         return false;
310 
311 #if wxUSE_THREADS
312     if (!g_thread_supported())
313     {
314         g_thread_init(NULL);
315         gdk_threads_init();
316     }
317 #endif // wxUSE_THREADS
318 
319     // gtk+ 2.0 supports Unicode through UTF-8 strings
320     wxConvCurrent = &wxConvUTF8;
321 
322 #ifdef __UNIX__
323     // decide which conversion to use for the file names
324 
325     // (1) this variable exists for the sole purpose of specifying the encoding
326     //     of the filenames for GTK+ programs, so use it if it is set
327     wxString encName(wxGetenv(wxT("G_FILENAME_ENCODING")));
328     encName = encName.BeforeFirst(wxT(','));
329     if (encName.CmpNoCase(wxT("@locale")) == 0)
330         encName.clear();
331     encName.MakeUpper();
332     if (encName.empty())
333     {
334 #if wxUSE_INTL
335         // (2) if a non default locale is set, assume that the user wants his
336         //     filenames in this locale too
337         encName = wxLocale::GetSystemEncodingName().Upper();
338 
339         // But don't consider ASCII in this case.
340         if ( !encName.empty() )
341         {
342 #if wxUSE_FONTMAP
343             wxFontEncoding enc = wxFontMapperBase::GetEncodingFromName(encName);
344             if ( enc == wxFONTENCODING_DEFAULT )
345 #else // !wxUSE_FONTMAP
346             if ( encName == wxT("US-ASCII") )
347 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
348             {
349                 // This means US-ASCII when returned from GetEncodingFromName().
350                 encName.clear();
351             }
352         }
353 #endif // wxUSE_INTL
354 
355         // (3) finally use UTF-8 by default
356         if ( encName.empty() )
357             encName = wxT("UTF-8");
358         wxSetEnv(wxT("G_FILENAME_ENCODING"), encName);
359     }
360 
361     static wxConvBrokenFileNames fileconv(encName);
362     wxConvFileName = &fileconv;
363 #endif // __UNIX__
364 
365 
366     bool init_result;
367     int i;
368 
369 #if wxUSE_UNICODE
370     // gtk_init() wants UTF-8, not wchar_t, so convert
371     char **argvGTK = new char *[argc_ + 1];
372     for ( i = 0; i < argc_; i++ )
373     {
374         argvGTK[i] = wxStrdupA(wxConvUTF8.cWX2MB(argv_[i]));
375     }
376 
377     argvGTK[argc_] = NULL;
378 
379     int argcGTK = argc_;
380 
381     // Prevent gtk_init_check() from changing the locale automatically for
382     // consistency with the other ports that don't do it. If necessary,
383     // wxApp::SetCLocale() may be explicitly called.
384     gtk_disable_setlocale();
385 
386 #ifdef __WXGPE__
387     init_result = true;  // is there a _check() version of this?
388     gpe_application_init( &argcGTK, &argvGTK );
389 #else
390     init_result = gtk_init_check( &argcGTK, &argvGTK ) != 0;
391 #endif
392 
393     if ( argcGTK != argc_ )
394     {
395         // we have to drop the parameters which were consumed by GTK+
396         for ( i = 0; i < argcGTK; i++ )
397         {
398             while ( strcmp(wxConvUTF8.cWX2MB(argv_[i]), argvGTK[i]) != 0 )
399             {
400                 memmove(argv_ + i, argv_ + i + 1, (argc_ - i)*sizeof(*argv_));
401             }
402         }
403 
404         argc_ = argcGTK;
405         argv_[argc_] = NULL;
406     }
407     //else: gtk_init() didn't modify our parameters
408 
409     // free our copy
410     for ( i = 0; i < argcGTK; i++ )
411     {
412         free(argvGTK[i]);
413     }
414 
415     delete [] argvGTK;
416 #else // !wxUSE_UNICODE
417     // gtk_init() shouldn't actually change argv_ itself (just its contents) so
418     // it's ok to pass pointer to it
419     init_result = gtk_init_check( &argc_, &argv_ );
420 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
421 
422     // update internal arg[cv] as GTK+ may have removed processed options:
423     this->argc = argc_;
424     this->argv = argv_;
425 
426     if ( m_traits )
427     {
428         // if there are still GTK+ standard options unparsed in the command
429         // line, it means that they were not syntactically correct and GTK+
430         // already printed a warning on the command line and we should now
431         // exit:
432         wxArrayString opt, desc;
433         m_traits->GetStandardCmdLineOptions(opt, desc);
434 
435         for ( i = 0; i < argc_; i++ )
436         {
437             // leave just the names of the options with values
438             const wxString str = wxString(argv_[i]).BeforeFirst('=');
439 
440             for ( size_t j = 0; j < opt.size(); j++ )
441             {
442                 // remove the leading spaces from the option string as it does
443                 // have them
444                 if ( opt[j].Trim(false).BeforeFirst('=') == str )
445                 {
446                     // a GTK+ option can be left on the command line only if
447                     // there was an error in (or before, in another standard
448                     // options) it, so abort, just as we do if incorrect
449                     // program option is given
450                     wxLogError(_("Invalid GTK+ command line option, use \"%s --help\""),
451                                argv_[0]);
452                     return false;
453                 }
454             }
455         }
456     }
457 
458     if ( !init_result )
459     {
460         wxLogError(_("Unable to initialize GTK+, is DISPLAY set properly?"));
461         return false;
462     }
463 
464     // we cannot enter threads before gtk_init is done
465     gdk_threads_enter();
466 
467 #if wxUSE_INTL
468     wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
469 #endif
470 
471     // make sure GtkWidget type is loaded, signal emission hooks need it
472     const GType widgetType = GTK_TYPE_WIDGET;
473     g_type_class_ref(widgetType);
474 
475     // focus in/out hooks used for generating wxEVT_ACTIVATE_APP
476     g_signal_add_emission_hook(
477         g_signal_lookup("focus_in_event", widgetType),
478         0, wx_focus_event_hook, GINT_TO_POINTER(1), NULL);
479     g_signal_add_emission_hook(
480         g_signal_lookup("focus_out_event", widgetType),
481         0, wx_focus_event_hook, GINT_TO_POINTER(2), NULL);
482 
483     WakeUpIdle();
484 
485     return true;
486 }
487 
CleanUp()488 void wxApp::CleanUp()
489 {
490     if (m_idleSourceId != 0)
491         g_source_remove(m_idleSourceId);
492 
493     // release reference acquired by Initialize()
494     gpointer gt = g_type_class_peek(GTK_TYPE_WIDGET);
495     if (gt != NULL)
496         g_type_class_unref(gt);
497 
498     gdk_threads_leave();
499 
500     wxAppBase::CleanUp();
501 }
502 
WakeUpIdle()503 void wxApp::WakeUpIdle()
504 {
505 #if wxUSE_THREADS
506     wxMutexLocker lock(m_idleMutex);
507 #endif
508     if (m_idleSourceId == 0)
509         m_idleSourceId = g_idle_add_full(G_PRIORITY_LOW, wxapp_idle_callback, NULL, NULL);
510 }
511 
512 // Checking for pending events requires first removing our idle source,
513 // otherwise it will cause the check to always return true.
EventsPending()514 bool wxApp::EventsPending()
515 {
516 #if wxUSE_THREADS
517     wxMutexLocker lock(m_idleMutex);
518 #endif
519     if (m_idleSourceId != 0)
520     {
521         g_source_remove(m_idleSourceId);
522         m_idleSourceId = 0;
523         wx_add_idle_hooks();
524     }
525     return gtk_events_pending() != 0;
526 }
527 
OnAssertFailure(const wxChar * file,int line,const wxChar * func,const wxChar * cond,const wxChar * msg)528 void wxApp::OnAssertFailure(const wxChar *file,
529                             int line,
530                             const wxChar* func,
531                             const wxChar* cond,
532                             const wxChar *msg)
533 {
534     // there is no need to do anything if asserts are disabled in this build
535     // anyhow
536 #if wxDEBUG_LEVEL
537     // block wx idle events while assert dialog is showing
538     m_isInAssert = true;
539 
540     wxAppBase::OnAssertFailure(file, line, func, cond, msg);
541 
542     m_isInAssert = false;
543 #else // !wxDEBUG_LEVEL
544     wxUnusedVar(file);
545     wxUnusedVar(line);
546     wxUnusedVar(func);
547     wxUnusedVar(cond);
548     wxUnusedVar(msg);
549 #endif // wxDEBUG_LEVEL/!wxDEBUG_LEVEL
550 }
551 
552 #if wxUSE_THREADS
MutexGuiEnter()553 void wxGUIAppTraits::MutexGuiEnter()
554 {
555     gdk_threads_enter();
556 }
557 
MutexGuiLeave()558 void wxGUIAppTraits::MutexGuiLeave()
559 {
560     gdk_threads_leave();
561 }
562 #endif // wxUSE_THREADS
563 
564 /* static */
GTKIsUsingGlobalMenu()565 bool wxApp::GTKIsUsingGlobalMenu()
566 {
567     static int s_isUsingGlobalMenu = -1;
568     if ( s_isUsingGlobalMenu == -1 )
569     {
570         // Currently we just check for this environment variable because this
571         // is how support for the global menu is implemented under Ubuntu.
572         //
573         // If we ever get false positives, we could also check for
574         // XDG_CURRENT_DESKTOP env var being set to "Unity".
575         wxString proxy;
576         s_isUsingGlobalMenu = wxGetEnv("UBUNTU_MENUPROXY", &proxy) &&
577                                 !proxy.empty() && proxy != "0";
578     }
579 
580     return s_isUsingGlobalMenu == 1;
581 }
582 
583 #if wxUSE_LIBHILDON || wxUSE_LIBHILDON2
584 // Maemo-specific method: get the main program object
GetHildonProgram()585 HildonProgram *wxApp::GetHildonProgram()
586 {
587     return hildon_program_get_instance();
588 }
589 
590 #endif // wxUSE_LIBHILDON || wxUSE_LIBHILDON2
591