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