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