convert assertdlg_gtk to C++
[wxWidgets.git] / src / gtk / utilsgtk.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/gtk/utilsgtk.cpp
3 // Purpose:
4 // Author: Robert Roebling
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #include "wx/utils.h"
14
15 #ifndef WX_PRECOMP
16 #include "wx/string.h"
17 #include "wx/intl.h"
18 #include "wx/log.h"
19 #endif
20
21 #include "wx/apptrait.h"
22 #include "wx/process.h"
23 #include "wx/sysopt.h"
24 #include "wx/unix/execute.h"
25
26 #include "wx/gtk/private/timer.h"
27 #include "wx/evtloop.h"
28
29 #include <gtk/gtk.h>
30 #include <gdk/gdkx.h>
31
32 #if wxDEBUG_LEVEL
33 #include "wx/gtk/assertdlg_gtk.h"
34 #if wxUSE_STACKWALKER
35 #include "wx/stackwalk.h"
36 #endif // wxUSE_STACKWALKER
37 #endif // wxDEBUG_LEVEL
38
39 #include <stdarg.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/wait.h> // for WNOHANG
44 #include <unistd.h>
45
46 #if wxUSE_DETECT_SM
47 #include <X11/SM/SMlib.h>
48
49 #include "wx/unix/utilsx11.h"
50 #endif
51
52 //-----------------------------------------------------------------------------
53 // data
54 //-----------------------------------------------------------------------------
55
56 extern GtkWidget *wxGetRootWindow();
57
58 //----------------------------------------------------------------------------
59 // misc.
60 //----------------------------------------------------------------------------
61 #ifndef __EMX__
62 // on OS/2, we use the wxBell from wxBase library
63
64 void wxBell()
65 {
66 gdk_beep();
67 }
68 #endif
69
70 // ----------------------------------------------------------------------------
71 // display characterstics
72 // ----------------------------------------------------------------------------
73
74 void *wxGetDisplay()
75 {
76 return GDK_DISPLAY();
77 }
78
79 void wxDisplaySize( int *width, int *height )
80 {
81 if (width) *width = gdk_screen_width();
82 if (height) *height = gdk_screen_height();
83 }
84
85 void wxDisplaySizeMM( int *width, int *height )
86 {
87 if (width) *width = gdk_screen_width_mm();
88 if (height) *height = gdk_screen_height_mm();
89 }
90
91 void wxGetMousePosition( int* x, int* y )
92 {
93 gdk_window_get_pointer( NULL, x, y, NULL );
94 }
95
96 bool wxColourDisplay()
97 {
98 return true;
99 }
100
101 int wxDisplayDepth()
102 {
103 return gtk_widget_get_visual(wxGetRootWindow())->depth;
104 }
105
106 wxWindow* wxFindWindowAtPoint(const wxPoint& pt)
107 {
108 return wxGenericFindWindowAtPoint(pt);
109 }
110
111 #if !wxUSE_UNICODE
112
113 WXDLLIMPEXP_CORE wxCharBuffer
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
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
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 PANGO_VERSION_MAJOR
165 if (!gtk_check_version (2,11,0))
166 {
167 // GTK+ 2.11 requires Pango >= 1.15.3 and pango_version_check
168 // was added in Pango 1.15.2 thus we know for sure the pango lib we're
169 // using has the pango_version_check function:
170 return pango_version_check (major, minor, micro);
171 }
172
173 return "can't check";
174 #else // !PANGO_VERSION_MAJOR
175 wxUnusedVar(major);
176 wxUnusedVar(minor);
177 wxUnusedVar(micro);
178
179 return "too old headers";
180 #endif
181 }
182
183
184 // ----------------------------------------------------------------------------
185 // subprocess routines
186 // ----------------------------------------------------------------------------
187
188 extern "C" {
189 static gboolean EndProcessDetector(GIOChannel* source, GIOCondition, void* data)
190 {
191 wxEndProcessData * const
192 proc_data = static_cast<wxEndProcessData *>(data);
193
194 // child exited, end waiting
195 close(g_io_channel_unix_get_fd(source));
196
197 wxHandleProcessTermination(proc_data);
198
199 // don't call us again!
200 return false;
201 }
202 }
203
204 int wxGUIAppTraits::AddProcessCallback(wxEndProcessData *proc_data, int fd)
205 {
206 return g_io_add_watch(
207 g_io_channel_unix_new(fd), G_IO_IN, EndProcessDetector, proc_data);
208 }
209
210
211
212 // ----------------------------------------------------------------------------
213 // wxPlatformInfo-related
214 // ----------------------------------------------------------------------------
215
216 wxPortId wxGUIAppTraits::GetToolkitVersion(int *verMaj, int *verMin) const
217 {
218 if ( verMaj )
219 *verMaj = gtk_major_version;
220 if ( verMin )
221 *verMin = gtk_minor_version;
222
223 return wxPORT_GTK;
224 }
225
226 #if wxUSE_TIMER
227
228 wxTimerImpl *wxGUIAppTraits::CreateTimerImpl(wxTimer *timer)
229 {
230 return new wxGTKTimerImpl(timer);
231 }
232
233 #endif // wxUSE_TIMER
234
235 #if wxUSE_DETECT_SM
236 static wxString GetSM()
237 {
238 wxX11Display dpy;
239 if ( !dpy )
240 return wxEmptyString;
241
242 char smerr[256];
243 char *client_id;
244 SmcConn smc_conn = SmcOpenConnection(NULL, NULL,
245 999, 999,
246 0 /* mask */, NULL /* callbacks */,
247 NULL, &client_id,
248 WXSIZEOF(smerr), smerr);
249
250 if ( !smc_conn )
251 {
252 wxLogDebug("Failed to connect to session manager: %s", smerr);
253 return wxEmptyString;
254 }
255
256 char *vendor = SmcVendor(smc_conn);
257 wxString ret = wxString::FromAscii( vendor );
258 free(vendor);
259
260 SmcCloseConnection(smc_conn, 0, NULL);
261 free(client_id);
262
263 return ret;
264 }
265 #endif // wxUSE_DETECT_SM
266
267
268 //-----------------------------------------------------------------------------
269 // wxGUIAppTraits
270 //-----------------------------------------------------------------------------
271
272 wxEventLoopBase *wxGUIAppTraits::CreateEventLoop()
273 {
274 return new wxEventLoop();
275 }
276
277
278 #if wxUSE_INTL
279 void wxGUIAppTraits::SetLocale()
280 {
281 gtk_set_locale();
282 wxUpdateLocaleIsUtf8();
283 }
284 #endif
285
286 #if wxDEBUG_LEVEL && wxUSE_STACKWALKER
287
288 // private helper class
289 class StackDump : public wxStackWalker
290 {
291 public:
292 StackDump(GtkAssertDialog *dlg) { m_dlg=dlg; }
293
294 protected:
295 virtual void OnStackFrame(const wxStackFrame& frame)
296 {
297 wxString fncname = frame.GetName();
298 wxString fncargs = fncname;
299
300 size_t n = fncname.find(wxT('('));
301 if (n != wxString::npos)
302 {
303 // remove arguments from function name
304 fncname.erase(n);
305
306 // remove function name and brackets from arguments
307 fncargs = fncargs.substr(n+1, fncargs.length()-n-2);
308 }
309 else
310 fncargs = wxEmptyString;
311
312 // append this stack frame's info in the dialog
313 if (!frame.GetFileName().empty() || !fncname.empty())
314 gtk_assert_dialog_append_stack_frame(m_dlg,
315 fncname.mb_str(),
316 fncargs.mb_str(),
317 frame.GetFileName().mb_str(),
318 frame.GetLine());
319 }
320
321 private:
322 GtkAssertDialog *m_dlg;
323 };
324
325 static void get_stackframe_callback(void* p)
326 {
327 StackDump* dump = static_cast<StackDump*>(p);
328 // skip over frames up to including wxOnAssert()
329 dump->ProcessFrames(3);
330 }
331
332 #endif // wxDEBUG_LEVEL && wxUSE_STACKWALKER
333
334 bool wxGUIAppTraits::ShowAssertDialog(const wxString& msg)
335 {
336 #if wxDEBUG_LEVEL
337 // we can't show the dialog from another thread
338 if ( wxIsMainThread() )
339 {
340 // under GTK2 we prefer to use a dialog widget written using directly
341 // in GTK+ as use a dialog written using wxWidgets would need the
342 // wxWidgets idle processing to work correctly which might not be the
343 // case when assert happens
344 GtkWidget *dialog = gtk_assert_dialog_new();
345 gtk_assert_dialog_set_message(GTK_ASSERT_DIALOG(dialog), msg.mb_str());
346
347 #if wxUSE_STACKWALKER
348 // save the current stack ow...
349 StackDump dump(GTK_ASSERT_DIALOG(dialog));
350 dump.SaveStack(100); // showing more than 100 frames is not very useful
351
352 // ...but process it only if the user needs it
353 gtk_assert_dialog_set_backtrace_callback
354 (
355 GTK_ASSERT_DIALOG(dialog),
356 get_stackframe_callback,
357 &dump
358 );
359 #endif // wxUSE_STACKWALKER
360
361 gint result = gtk_dialog_run(GTK_DIALOG (dialog));
362 bool returnCode = false;
363 switch (result)
364 {
365 case GTK_ASSERT_DIALOG_STOP:
366 wxTrap();
367 break;
368 case GTK_ASSERT_DIALOG_CONTINUE:
369 // nothing to do
370 break;
371 case GTK_ASSERT_DIALOG_CONTINUE_SUPPRESSING:
372 // no more asserts
373 returnCode = true;
374 break;
375
376 default:
377 wxFAIL_MSG( wxT("unexpected return code from GtkAssertDialog") );
378 }
379
380 gtk_widget_destroy(dialog);
381 return returnCode;
382 }
383 #endif // wxDEBUG_LEVEL
384
385 return wxAppTraitsBase::ShowAssertDialog(msg);
386 }
387
388 wxString wxGUIAppTraits::GetDesktopEnvironment() const
389 {
390 wxString de = wxSystemOptions::GetOption(wxT("gtk.desktop"));
391 #if wxUSE_DETECT_SM
392 if ( de.empty() )
393 {
394 static const wxString s_SM = GetSM();
395
396 if (s_SM == wxT("GnomeSM"))
397 de = wxT("GNOME");
398 else if (s_SM == wxT("KDE"))
399 de = wxT("KDE");
400 }
401 #endif // wxUSE_DETECT_SM
402
403 return de;
404 }
405
406 #ifdef __WXGTK26__
407
408 // see the hack below in wxCmdLineParser::GetUsageString().
409 // TODO: replace this hack with a g_option_group_get_entries()
410 // call as soon as such function exists;
411 // see http://bugzilla.gnome.org/show_bug.cgi?id=431021 for the relative
412 // feature request
413 struct _GOptionGroup
414 {
415 gchar *name;
416 gchar *description;
417 gchar *help_description;
418
419 GDestroyNotify destroy_notify;
420 gpointer user_data;
421
422 GTranslateFunc translate_func;
423 GDestroyNotify translate_notify;
424 gpointer translate_data;
425
426 GOptionEntry *entries;
427 gint n_entries;
428
429 GOptionParseFunc pre_parse_func;
430 GOptionParseFunc post_parse_func;
431 GOptionErrorFunc error_func;
432 };
433
434 wxString wxGetNameFromGtkOptionEntry(const GOptionEntry *opt)
435 {
436 wxString ret;
437
438 if (opt->short_name)
439 ret << wxT("-") << opt->short_name;
440 if (opt->long_name)
441 {
442 if (!ret.empty())
443 ret << wxT(", ");
444 ret << wxT("--") << opt->long_name;
445
446 if (opt->arg_description)
447 ret << wxT("=") << opt->arg_description;
448 }
449
450 return wxT(" ") + ret;
451 }
452
453 #endif // __WXGTK26__
454
455 wxString
456 wxGUIAppTraits::GetStandardCmdLineOptions(wxArrayString& names,
457 wxArrayString& desc) const
458 {
459 wxString usage;
460
461 #ifdef __WXGTK26__
462 if (!gtk_check_version(2,6,0))
463 {
464 // since GTK>=2.6, we can use the glib_check_version() symbol...
465
466 // check whether GLib version is greater than 2.6 but also lower than 2.19
467 // because, as we use the undocumented _GOptionGroup struct, we don't want
468 // to run this code with future versions which might change it (2.19 is the
469 // latest one at the time of this writing)
470 if (!glib_check_version(2,6,0) && glib_check_version(2,20,0))
471 {
472 usage << _("The following standard GTK+ options are also supported:\n");
473
474 // passing true here means that the function can open the default
475 // display while parsing (not really used here anyhow)
476 GOptionGroup *gtkOpts = gtk_get_option_group(true);
477
478 // WARNING: here we access the internals of GOptionGroup:
479 GOptionEntry *entries = ((_GOptionGroup*)gtkOpts)->entries;
480 unsigned int n_entries = ((_GOptionGroup*)gtkOpts)->n_entries;
481 wxArrayString namesOptions, descOptions;
482
483 for ( size_t n = 0; n < n_entries; n++ )
484 {
485 if ( entries[n].flags & G_OPTION_FLAG_HIDDEN )
486 continue; // skip
487
488 names.push_back(wxGetNameFromGtkOptionEntry(&entries[n]));
489
490 const gchar * const entryDesc = entries[n].description;
491 desc.push_back(wxString(entryDesc));
492 }
493
494 g_option_group_free (gtkOpts);
495 }
496 }
497 #else
498 wxUnusedVar(names);
499 wxUnusedVar(desc);
500 #endif // __WXGTK26__
501
502 return usage;
503 }
504