1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/gtk/utilsgtk.cpp
3 // Purpose:
4 // Author:      Robert Roebling
5 // Copyright:   (c) 1998 Robert Roebling
6 // Licence:     wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
8 
9 // For compilers that support precompilation, includes "wx.h".
10 #include "wx/wxprec.h"
11 
12 #include "wx/utils.h"
13 
14 #ifndef WX_PRECOMP
15     #include "wx/string.h"
16     #include "wx/intl.h"
17     #include "wx/log.h"
18 #endif
19 
20 #include "wx/apptrait.h"
21 #include "wx/process.h"
22 #include "wx/sysopt.h"
23 
24 #include "wx/gtk/private/timer.h"
25 #include "wx/evtloop.h"
26 
27 #include <gtk/gtk.h>
28 #ifdef GDK_WINDOWING_WIN32
29 #include <gdk/gdkwin32.h>
30 #endif
31 #ifdef GDK_WINDOWING_X11
32 #include <gdk/gdkx.h>
33 #endif
34 
35 #if wxDEBUG_LEVEL
36     #include "wx/gtk/assertdlg_gtk.h"
37     #if wxUSE_STACKWALKER
38         #include "wx/stackwalk.h"
39     #endif // wxUSE_STACKWALKER
40 #endif // wxDEBUG_LEVEL
41 
42 #include <stdarg.h>
43 #include <string.h>
44 #include <sys/stat.h>
45 #include <sys/types.h>
46 #ifdef __UNIX__
47 #include <unistd.h>
48 #endif
49 
50 #if wxUSE_DETECT_SM
51     #include <X11/SM/SMlib.h>
52 
53     #include "wx/unix/utilsx11.h"
54 #endif
55 
56 #include "wx/gtk/private/gtk2-compat.h"
57 
58 //-----------------------------------------------------------------------------
59 // data
60 //-----------------------------------------------------------------------------
61 
62 extern GtkWidget *wxGetRootWindow();
63 
64 //----------------------------------------------------------------------------
65 // misc.
66 //----------------------------------------------------------------------------
67 
wxBell()68 void wxBell()
69 {
70     gdk_beep();
71 }
72 
73 // ----------------------------------------------------------------------------
74 // display characteristics
75 // ----------------------------------------------------------------------------
76 
77 #ifdef GDK_WINDOWING_X11
wxGetDisplay()78 void *wxGetDisplay()
79 {
80     return GDK_DISPLAY_XDISPLAY(gtk_widget_get_display(wxGetRootWindow()));
81 }
82 #endif
83 
wxDisplaySize(int * width,int * height)84 void wxDisplaySize( int *width, int *height )
85 {
86     if (width) *width = gdk_screen_width();
87     if (height) *height = gdk_screen_height();
88 }
89 
wxDisplaySizeMM(int * width,int * height)90 void wxDisplaySizeMM( int *width, int *height )
91 {
92     if (width) *width = gdk_screen_width_mm();
93     if (height) *height = gdk_screen_height_mm();
94 }
95 
wxColourDisplay()96 bool wxColourDisplay()
97 {
98     return true;
99 }
100 
wxDisplayDepth()101 int wxDisplayDepth()
102 {
103     return gdk_visual_get_depth(gtk_widget_get_visual(wxGetRootWindow()));
104 }
105 
wxFindWindowAtPoint(const wxPoint & pt)106 wxWindow* wxFindWindowAtPoint(const wxPoint& pt)
107 {
108     return wxGenericFindWindowAtPoint(pt);
109 }
110 
111 #if !wxUSE_UNICODE
112 
113 WXDLLIMPEXP_CORE wxCharBuffer
wxConvertToGTK(const wxString & s,wxFontEncoding enc)114 wxConvertToGTK(const wxString& s, wxFontEncoding enc)
115 {
116     wxWCharBuffer wbuf;
117     if ( enc == wxFONTENCODING_SYSTEM || enc == wxFONTENCODING_DEFAULT )
118     {
119         wbuf = wxConvUI->cMB2WC(s.c_str());
120     }
121     else // another encoding, use generic conversion class
122     {
123         wbuf = wxCSConv(enc).cMB2WC(s.c_str());
124     }
125 
126     if ( !wbuf && !s.empty() )
127     {
128         // conversion failed, but we still want to show something to the user
129         // even if it's going to be wrong it is better than nothing
130         //
131         // we choose ISO8859-1 here arbitrarily, it's just the most common
132         // encoding probably and, also importantly here, conversion from it
133         // never fails as it's done internally by wxCSConv
134         wbuf = wxCSConv(wxFONTENCODING_ISO8859_1).cMB2WC(s.c_str());
135     }
136 
137     return wxConvUTF8.cWC2MB(wbuf);
138 }
139 
140 WXDLLIMPEXP_CORE wxCharBuffer
wxConvertFromGTK(const wxString & s,wxFontEncoding enc)141 wxConvertFromGTK(const wxString& s, wxFontEncoding enc)
142 {
143     // this conversion should never fail as GTK+ always uses UTF-8 internally
144     // so there are no complications here
145     const wxWCharBuffer wbuf(wxConvUTF8.cMB2WC(s.c_str()));
146     if ( enc == wxFONTENCODING_SYSTEM )
147         return wxConvUI->cWC2MB(wbuf);
148 
149     return wxCSConv(enc).cWC2MB(wbuf);
150 }
151 
152 #endif // !wxUSE_UNICODE
153 
154 // Returns NULL if version is certainly greater or equal than major.minor.micro
155 // Returns string describing the error if version is lower than
156 // major.minor.micro OR it cannot be determined and one should not rely on the
157 // availability of pango version major.minor.micro, nor the non-availability
wx_pango_version_check(int major,int minor,int micro)158 const gchar *wx_pango_version_check (int major, int minor, int micro)
159 {
160     // NOTE: you don't need to use this macro to check for Pango features
161     //       added in pango-1.4 or earlier since GTK 2.4 (our minimum requirement
162     //       for GTK lib) required pango 1.4...
163 
164 #ifdef __WXGTK3__
165     return pango_version_check(major, minor, micro);
166 #elif defined(PANGO_VERSION_MAJOR)
167     if (!gtk_check_version (2,11,0))
168     {
169         // GTK+ 2.11 requires Pango >= 1.15.3 and pango_version_check
170         // was added in Pango 1.15.2 thus we know for sure the pango lib we're
171         // using has the pango_version_check function:
172         return pango_version_check (major, minor, micro);
173     }
174 
175     return "can't check";
176 #else // !PANGO_VERSION_MAJOR
177     wxUnusedVar(major);
178     wxUnusedVar(minor);
179     wxUnusedVar(micro);
180 
181     return "too old headers";
182 #endif
183 }
184 
185 // ----------------------------------------------------------------------------
186 // wxPlatformInfo-related
187 // ----------------------------------------------------------------------------
188 
GetToolkitVersion(int * verMaj,int * verMin) const189 wxPortId wxGUIAppTraits::GetToolkitVersion(int *verMaj, int *verMin) const
190 {
191     if ( verMaj )
192         *verMaj = gtk_major_version;
193     if ( verMin )
194         *verMin = gtk_minor_version;
195 
196     return wxPORT_GTK;
197 }
198 
199 #if wxUSE_TIMER
200 
CreateTimerImpl(wxTimer * timer)201 wxTimerImpl *wxGUIAppTraits::CreateTimerImpl(wxTimer *timer)
202 {
203     return new wxGTKTimerImpl(timer);
204 }
205 
206 #endif // wxUSE_TIMER
207 
208 #if wxUSE_DETECT_SM
GetSM()209 static wxString GetSM()
210 {
211     wxX11Display dpy;
212     if ( !dpy )
213         return wxEmptyString;
214 
215     char smerr[256];
216     char *client_id;
217     SmcConn smc_conn = SmcOpenConnection(NULL, NULL,
218                                          999, 999,
219                                          0 /* mask */, NULL /* callbacks */,
220                                          NULL, &client_id,
221                                          WXSIZEOF(smerr), smerr);
222 
223     if ( !smc_conn )
224     {
225         // Don't report error if there is no session manager at all
226         if (getenv("SESSION_MANAGER"))
227         {
228             wxLogDebug("Failed to connect to session manager: %s", smerr);
229         }
230         return wxEmptyString;
231     }
232 
233     char *vendor = SmcVendor(smc_conn);
234     wxString ret = wxString::FromAscii( vendor );
235     free(vendor);
236 
237     SmcCloseConnection(smc_conn, 0, NULL);
238     free(client_id);
239 
240     return ret;
241 }
242 #endif // wxUSE_DETECT_SM
243 
244 
245 //-----------------------------------------------------------------------------
246 // wxGUIAppTraits
247 //-----------------------------------------------------------------------------
248 
CreateEventLoop()249 wxEventLoopBase *wxGUIAppTraits::CreateEventLoop()
250 {
251     return new wxEventLoop();
252 }
253 
254 
255 #ifdef __UNIX__
256 
257 #if wxDEBUG_LEVEL && wxUSE_STACKWALKER
258 
259 // private helper class
260 class StackDump : public wxStackWalker
261 {
262 public:
StackDump(GtkAssertDialog * dlg)263     StackDump(GtkAssertDialog *dlg) { m_dlg=dlg; }
264 
265 protected:
OnStackFrame(const wxStackFrame & frame)266     virtual void OnStackFrame(const wxStackFrame& frame)
267     {
268         wxString fncname = frame.GetName();
269 
270         // append this stack frame's info in the dialog
271         if (!frame.GetFileName().empty() || !fncname.empty())
272         {
273             gtk_assert_dialog_append_stack_frame(m_dlg,
274                                                 fncname.utf8_str(),
275                                                 frame.GetFileName().utf8_str(),
276                                                 frame.GetLine());
277         }
278     }
279 
280 private:
281     GtkAssertDialog *m_dlg;
282 };
283 
get_stackframe_callback(void * p)284 static void get_stackframe_callback(void* p)
285 {
286     StackDump* dump = static_cast<StackDump*>(p);
287     // skip over frames up to including wxOnAssert()
288     dump->ProcessFrames(6);
289 }
290 
291 #endif // wxDEBUG_LEVEL && wxUSE_STACKWALKER
292 
ShowAssertDialog(const wxString & msg)293 bool wxGUIAppTraits::ShowAssertDialog(const wxString& msg)
294 {
295 #if wxDEBUG_LEVEL
296     // we can't show the dialog from another thread
297     if ( wxIsMainThread() )
298     {
299         // under GTK2 we prefer to use a dialog widget written using directly
300         // in GTK+ as use a dialog written using wxWidgets would need the
301         // wxWidgets idle processing to work correctly which might not be the
302         // case when assert happens
303         GtkWidget *dialog = gtk_assert_dialog_new();
304         gtk_assert_dialog_set_message(GTK_ASSERT_DIALOG(dialog), msg.mb_str());
305 
306         GdkDisplay* display = gtk_widget_get_display(dialog);
307 #ifdef __WXGTK3__
308         GdkDeviceManager* manager = gdk_display_get_device_manager(display);
309         GdkDevice* device = gdk_device_manager_get_client_pointer(manager);
310         gdk_device_ungrab(device, unsigned(GDK_CURRENT_TIME));
311 #else
312         gdk_display_pointer_ungrab(display, unsigned(GDK_CURRENT_TIME));
313 #endif
314 
315 #if wxUSE_STACKWALKER
316         // save the current stack ow...
317         StackDump dump(GTK_ASSERT_DIALOG(dialog));
318         dump.SaveStack(100); // showing more than 100 frames is not very useful
319 
320         // ...but process it only if the user needs it
321         gtk_assert_dialog_set_backtrace_callback
322         (
323             GTK_ASSERT_DIALOG(dialog),
324             get_stackframe_callback,
325             &dump
326         );
327 #endif // wxUSE_STACKWALKER
328 
329         gint result = gtk_dialog_run(GTK_DIALOG (dialog));
330         bool returnCode = false;
331         switch (result)
332         {
333             case GTK_ASSERT_DIALOG_STOP:
334                 wxTrap();
335                 break;
336             case GTK_ASSERT_DIALOG_CONTINUE:
337                 // nothing to do
338                 break;
339             case GTK_ASSERT_DIALOG_CONTINUE_SUPPRESSING:
340                 // no more asserts
341                 returnCode = true;
342                 break;
343 
344             default:
345                 wxFAIL_MSG( wxT("unexpected return code from GtkAssertDialog") );
346         }
347 
348         gtk_widget_destroy(dialog);
349         return returnCode;
350     }
351 #endif // wxDEBUG_LEVEL
352 
353     return wxAppTraitsBase::ShowAssertDialog(msg);
354 }
355 
356 #endif // __UNIX__
357 
358 #if defined(__UNIX__) || defined(__OS2__)
359 
GetDesktopEnvironment() const360 wxString wxGUIAppTraits::GetDesktopEnvironment() const
361 {
362     wxString de = wxSystemOptions::GetOption(wxT("gtk.desktop"));
363 #if wxUSE_DETECT_SM
364     if ( de.empty() )
365     {
366         static const wxString s_SM = GetSM();
367 
368         if (s_SM == wxT("GnomeSM"))
369             de = wxT("GNOME");
370         else if (s_SM == wxT("KDE"))
371             de = wxT("KDE");
372     }
373 #endif // wxUSE_DETECT_SM
374 
375     return de;
376 }
377 
378 #endif // __UNIX__ || __OS2__
379 
380 #ifdef __UNIX__
381 
382 // see the hack below in wxCmdLineParser::GetUsageString().
383 // TODO: replace this hack with a g_option_group_get_entries()
384 //       call as soon as such function exists;
385 //       see http://bugzilla.gnome.org/show_bug.cgi?id=431021 for the relative
386 //       feature request
387 struct _GOptionGroup
388 {
389   gchar           *name;
390   gchar           *description;
391   gchar           *help_description;
392 
393   GDestroyNotify   destroy_notify;
394   gpointer         user_data;
395 
396   GTranslateFunc   translate_func;
397   GDestroyNotify   translate_notify;
398   gpointer     translate_data;
399 
400   GOptionEntry    *entries;
401   gint             n_entries;
402 
403   GOptionParseFunc pre_parse_func;
404   GOptionParseFunc post_parse_func;
405   GOptionErrorFunc error_func;
406 };
407 
408 static
wxGetNameFromGtkOptionEntry(const GOptionEntry * opt)409 wxString wxGetNameFromGtkOptionEntry(const GOptionEntry *opt)
410 {
411     wxString ret;
412 
413     if (opt->short_name)
414         ret << wxT("-") << opt->short_name;
415     if (opt->long_name)
416     {
417         if (!ret.empty())
418             ret << wxT(", ");
419         ret << wxT("--") << opt->long_name;
420 
421         if (opt->arg_description)
422             ret << wxT("=") << opt->arg_description;
423     }
424 
425     return wxT("  ") + ret;
426 }
427 
428 wxString
GetStandardCmdLineOptions(wxArrayString & names,wxArrayString & desc) const429 wxGUIAppTraits::GetStandardCmdLineOptions(wxArrayString& names,
430                                           wxArrayString& desc) const
431 {
432     wxString usage;
433 
434     // Check whether GLib version is lower than the last tested version for
435     // which the code below works because, as we use the undocumented
436     // _GOptionGroup struct, we don't want to run this code with future
437     // versions which might change it and result in run-time crashes.
438     if (glib_check_version(2,44,0))
439     {
440         usage << _("The following standard GTK+ options are also supported:\n");
441 
442         // passing true here means that the function can open the default
443         // display while parsing (not really used here anyhow)
444         GOptionGroup *gtkOpts = gtk_get_option_group(true);
445 
446         // WARNING: here we access the internals of GOptionGroup:
447         GOptionEntry *entries = ((_GOptionGroup*)gtkOpts)->entries;
448         unsigned int n_entries = ((_GOptionGroup*)gtkOpts)->n_entries;
449         wxArrayString namesOptions, descOptions;
450 
451         for ( size_t n = 0; n < n_entries; n++ )
452         {
453             if ( entries[n].flags & G_OPTION_FLAG_HIDDEN )
454                 continue;       // skip
455 
456             names.push_back(wxGetNameFromGtkOptionEntry(&entries[n]));
457 
458             const gchar * const entryDesc = entries[n].description;
459             desc.push_back(wxString(entryDesc));
460         }
461 
462         g_option_group_free (gtkOpts);
463     }
464 
465     return usage;
466 }
467 
468 #endif // __UNIX__
469