implement wxGetCientDisplayRect() correctly for X11-based ports
[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/sysopt.h"
22 #include "wx/apptrait.h"
23 #include "wx/process.h"
24 #include "wx/sysopt.h"
25 #include "wx/unix/execute.h"
26
27 #include "wx/gtk/private/timer.h"
28 #include "wx/evtloop.h"
29
30 #ifdef __WXDEBUG__
31 #include "wx/gtk/assertdlg_gtk.h"
32 #if wxUSE_STACKWALKER
33 #include "wx/stackwalk.h"
34 #endif // wxUSE_STACKWALKER
35 #endif // __WXDEBUG__
36
37 #include <stdarg.h>
38 #include <string.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <sys/wait.h> // for WNOHANG
42 #include <unistd.h>
43
44 #include "glib.h"
45 #include "gdk/gdk.h"
46 #include "gtk/gtk.h"
47 #include "gdk/gdkx.h"
48
49 #ifdef HAVE_X11_XKBLIB_H
50 /* under HP-UX and Solaris 2.6, at least, XKBlib.h defines structures with
51 * field named "explicit" - which is, of course, an error for a C++
52 * compiler. To be on the safe side, just redefine it everywhere. */
53 #define explicit __wx_explicit
54
55 #include "X11/XKBlib.h"
56
57 #undef explicit
58 #endif // HAVE_X11_XKBLIB_H
59
60
61 #if wxUSE_DETECT_SM
62 #include "X11/Xlib.h"
63 #include "X11/SM/SMlib.h"
64 #endif
65
66 //-----------------------------------------------------------------------------
67 // data
68 //-----------------------------------------------------------------------------
69
70 extern GtkWidget *wxGetRootWindow();
71
72 //----------------------------------------------------------------------------
73 // misc.
74 //----------------------------------------------------------------------------
75 #ifndef __EMX__
76 // on OS/2, we use the wxBell from wxBase library
77
78 void wxBell()
79 {
80 gdk_beep();
81 }
82 #endif
83
84 /* Don't synthesize KeyUp events holding down a key and producing
85 KeyDown events with autorepeat. */
86 #ifdef HAVE_X11_XKBLIB_H
87 bool wxSetDetectableAutoRepeat( bool flag )
88 {
89 Bool result;
90 XkbSetDetectableAutoRepeat( GDK_DISPLAY(), flag, &result );
91 return result; /* true if keyboard hardware supports this mode */
92 }
93 #else
94 bool wxSetDetectableAutoRepeat( bool WXUNUSED(flag) )
95 {
96 return false;
97 }
98 #endif
99
100 // Escapes string so that it is valid Pango markup XML string:
101 wxString wxEscapeStringForPangoMarkup(const wxString& str)
102 {
103 size_t len = str.length();
104 wxString out;
105 out.Alloc(len);
106 for (size_t i = 0; i < len; i++)
107 {
108 wxChar c = str[i];
109 switch (c)
110 {
111 case _T('&'):
112 out << _T("&amp;");
113 break;
114 case _T('<'):
115 out << _T("&lt;");
116 break;
117 case _T('>'):
118 out << _T("&gt;");
119 break;
120 case _T('\''):
121 out << _T("&apos;");
122 break;
123 case _T('"'):
124 out << _T("&quot;");
125 break;
126 default:
127 out << c;
128 break;
129 }
130 }
131 return out;
132 }
133
134
135 // ----------------------------------------------------------------------------
136 // display characterstics
137 // ----------------------------------------------------------------------------
138
139 void *wxGetDisplay()
140 {
141 return GDK_DISPLAY();
142 }
143
144 void wxDisplaySize( int *width, int *height )
145 {
146 int marginX = wxSystemOptions::GetOptionInt(wxT("gtk.desktopmargin.x"));
147 int marginY = wxSystemOptions::GetOptionInt(wxT("gtk.desktopmargin.y"));
148
149 if (width) *width = gdk_screen_width() - marginX;
150 if (height) *height = gdk_screen_height() - marginY;
151 }
152
153 void wxDisplaySizeMM( int *width, int *height )
154 {
155 if (width) *width = gdk_screen_width_mm();
156 if (height) *height = gdk_screen_height_mm();
157 }
158
159 void wxGetMousePosition( int* x, int* y )
160 {
161 gdk_window_get_pointer( (GdkWindow*) NULL, x, y, (GdkModifierType*) NULL );
162 }
163
164 bool wxColourDisplay()
165 {
166 return true;
167 }
168
169 int wxDisplayDepth()
170 {
171 return gdk_drawable_get_visual( wxGetRootWindow()->window )->depth;
172 }
173
174 wxWindow* wxFindWindowAtPoint(const wxPoint& pt)
175 {
176 return wxGenericFindWindowAtPoint(pt);
177 }
178
179 #if !wxUSE_UNICODE
180
181 WXDLLIMPEXP_CORE wxCharBuffer
182 wxConvertToGTK(const wxString& s, wxFontEncoding enc)
183 {
184 wxWCharBuffer wbuf;
185 if ( enc == wxFONTENCODING_SYSTEM || enc == wxFONTENCODING_DEFAULT )
186 {
187 wbuf = wxConvUI->cMB2WC(s.c_str());
188 }
189 else // another encoding, use generic conversion class
190 {
191 wbuf = wxCSConv(enc).cMB2WC(s.c_str());
192 }
193
194 if ( !wbuf && !s.empty() )
195 {
196 // conversion failed, but we still want to show something to the user
197 // even if it's going to be wrong it is better than nothing
198 //
199 // we choose ISO8859-1 here arbitrarily, it's just the most common
200 // encoding probably and, also importantly here, conversion from it
201 // never fails as it's done internally by wxCSConv
202 wbuf = wxCSConv(wxFONTENCODING_ISO8859_1).cMB2WC(s.c_str());
203 }
204
205 return wxConvUTF8.cWC2MB(wbuf);
206 }
207
208 WXDLLIMPEXP_CORE wxCharBuffer
209 wxConvertFromGTK(const wxString& s, wxFontEncoding enc)
210 {
211 // this conversion should never fail as GTK+ always uses UTF-8 internally
212 // so there are no complications here
213 const wxWCharBuffer wbuf(wxConvUTF8.cMB2WC(s.c_str()));
214 if ( enc == wxFONTENCODING_SYSTEM )
215 return wxConvUI->cWC2MB(wbuf);
216
217 return wxCSConv(enc).cWC2MB(wbuf);
218 }
219
220 #endif // !wxUSE_UNICODE
221
222 // Returns false if version is certainly greater or equal than major.minor.micro
223 // Returns true if version is lower than major.minor.micro OR it cannot be
224 // determined and one should not rely on the availability of pango version
225 // major.minor.micro, nor the non-availability
226 const gchar *wx_pango_version_check (int major, int minor, int micro)
227 {
228 #ifdef PANGO_VERSION_MAJOR
229 if (!gtk_check_version (2,11,0))
230 {
231 // GTK+ 2.11 requires Pango >= 1.15.3 and pango_version_check
232 // was added in Pango 1.15.2 thus we know for sure the pango lib we're
233 // using has the pango_version_check function:
234 return pango_version_check (major, minor, micro);
235 }
236
237 return "can't check";
238 #else // !PANGO_VERSION_MAJOR
239 wxUnusedVar(major);
240 wxUnusedVar(minor);
241 wxUnusedVar(micro);
242
243 return "too old headers";
244 #endif
245 }
246
247
248 // ----------------------------------------------------------------------------
249 // subprocess routines
250 // ----------------------------------------------------------------------------
251
252 extern "C" {
253 static
254 void GTK_EndProcessDetector(gpointer data, gint source,
255 GdkInputCondition WXUNUSED(condition) )
256 {
257 wxEndProcessData *proc_data = (wxEndProcessData *)data;
258
259 // has the process really terminated? unfortunately GDK (or GLib) seem to
260 // generate G_IO_HUP notification even when it simply tries to read from a
261 // closed fd and hasn't terminated at all
262 int pid = (proc_data->pid > 0) ? proc_data->pid : -(proc_data->pid);
263 int status = 0;
264 int rc = waitpid(pid, &status, WNOHANG);
265
266 if ( rc == 0 )
267 {
268 // no, it didn't exit yet, continue waiting
269 return;
270 }
271
272 // set exit code to -1 if something bad happened
273 proc_data->exitcode = rc != -1 && WIFEXITED(status) ? WEXITSTATUS(status)
274 : -1;
275
276 // child exited, end waiting
277 close(source);
278
279 // don't call us again!
280 gdk_input_remove(proc_data->tag);
281
282 wxHandleProcessTermination(proc_data);
283 }
284 }
285
286 int wxAddProcessCallback(wxEndProcessData *proc_data, int fd)
287 {
288 int tag = gdk_input_add(fd,
289 GDK_INPUT_READ,
290 GTK_EndProcessDetector,
291 (gpointer)proc_data);
292
293 return tag;
294 }
295
296
297
298 // ----------------------------------------------------------------------------
299 // wxPlatformInfo-related
300 // ----------------------------------------------------------------------------
301
302 wxPortId wxGUIAppTraits::GetToolkitVersion(int *verMaj, int *verMin) const
303 {
304 if ( verMaj )
305 *verMaj = gtk_major_version;
306 if ( verMin )
307 *verMin = gtk_minor_version;
308
309 return wxPORT_GTK;
310 }
311
312 #if wxUSE_TIMER
313
314 wxTimerImpl *wxGUIAppTraits::CreateTimerImpl(wxTimer *timer)
315 {
316 return new wxGTKTimerImpl(timer);
317 }
318
319 #endif // wxUSE_TIMER
320
321 #if wxUSE_DETECT_SM
322 static wxString GetSM()
323 {
324 class Dpy
325 {
326 public:
327 Dpy() { m_dpy = XOpenDisplay(NULL); }
328 ~Dpy() { if ( m_dpy ) XCloseDisplay(m_dpy); }
329
330 operator Display *() const { return m_dpy; }
331 private:
332 Display *m_dpy;
333 } dpy;
334
335 if ( !dpy )
336 return wxEmptyString;
337
338 char smerr[256];
339 char *client_id;
340 SmcConn smc_conn = SmcOpenConnection(NULL, NULL,
341 999, 999,
342 0 /* mask */, NULL /* callbacks */,
343 NULL, &client_id,
344 WXSIZEOF(smerr), smerr);
345
346 if ( !smc_conn )
347 {
348 wxLogWarning(_("Failed to connect to session manager: %s"), smerr);
349 return wxEmptyString;
350 }
351
352 char *vendor = SmcVendor(smc_conn);
353 wxString ret = wxString::FromAscii( vendor );
354 free(vendor);
355
356 SmcCloseConnection(smc_conn, 0, NULL);
357 free(client_id);
358
359 return ret;
360 }
361 #endif // wxUSE_DETECT_SM
362
363
364 //-----------------------------------------------------------------------------
365 // wxGUIAppTraits
366 //-----------------------------------------------------------------------------
367
368 wxEventLoopBase *wxGUIAppTraits::CreateEventLoop()
369 {
370 return new wxEventLoop();
371 }
372
373
374 #if wxUSE_INTL
375 void wxGUIAppTraits::SetLocale()
376 {
377 gtk_set_locale();
378 wxUpdateLocaleIsUtf8();
379 }
380 #endif
381
382 #ifdef __WXDEBUG__
383
384 #if wxUSE_STACKWALKER
385
386 // private helper class
387 class StackDump : public wxStackWalker
388 {
389 public:
390 StackDump(GtkAssertDialog *dlg) { m_dlg=dlg; }
391
392 protected:
393 virtual void OnStackFrame(const wxStackFrame& frame)
394 {
395 wxString fncname = frame.GetName();
396 wxString fncargs = fncname;
397
398 size_t n = fncname.find(wxT('('));
399 if (n != wxString::npos)
400 {
401 // remove arguments from function name
402 fncname.erase(n);
403
404 // remove function name and brackets from arguments
405 fncargs = fncargs.substr(n+1, fncargs.length()-n-2);
406 }
407 else
408 fncargs = wxEmptyString;
409
410 // append this stack frame's info in the dialog
411 if (!frame.GetFileName().empty() || !fncname.empty())
412 gtk_assert_dialog_append_stack_frame(m_dlg,
413 fncname.mb_str(),
414 fncargs.mb_str(),
415 frame.GetFileName().mb_str(),
416 frame.GetLine());
417 }
418
419 private:
420 GtkAssertDialog *m_dlg;
421 };
422
423 // the callback functions must be extern "C" to comply with GTK+ declarations
424 extern "C"
425 {
426 void get_stackframe_callback(StackDump *dump)
427 {
428 // skip over frames up to including wxOnAssert()
429 dump->ProcessFrames(3);
430 }
431 }
432
433 #endif // wxUSE_STACKWALKER
434
435 bool wxGUIAppTraits::ShowAssertDialog(const wxString& msg)
436 {
437 // under GTK2 we prefer to use a dialog widget written using directly GTK+;
438 // in fact we cannot use a dialog written using wxWidgets: it would need
439 // the wxWidgets idle processing to work correctly!
440 GtkWidget *dialog = gtk_assert_dialog_new();
441 gtk_assert_dialog_set_message(GTK_ASSERT_DIALOG(dialog), msg.mb_str());
442
443 #if wxUSE_STACKWALKER
444 // don't show more than maxLines or we could get a dialog too tall to be
445 // shown on screen: 20 should be ok everywhere as even with 15 pixel high
446 // characters it is still only 300 pixels...
447 static const int maxLines = 20;
448
449 // save current stack frame...
450 StackDump dump(GTK_ASSERT_DIALOG(dialog));
451 dump.SaveStack(maxLines);
452
453 // ...but process it only if the user needs it
454 gtk_assert_dialog_set_backtrace_callback(GTK_ASSERT_DIALOG(dialog),
455 (GtkAssertDialogStackFrameCallback)get_stackframe_callback,
456 &dump);
457 #endif // wxUSE_STACKWALKER
458
459 gint result = gtk_dialog_run(GTK_DIALOG (dialog));
460 bool returnCode = false;
461 switch (result)
462 {
463 case GTK_ASSERT_DIALOG_STOP:
464 wxTrap();
465 break;
466 case GTK_ASSERT_DIALOG_CONTINUE:
467 // nothing to do
468 break;
469 case GTK_ASSERT_DIALOG_CONTINUE_SUPPRESSING:
470 // no more asserts
471 returnCode = true;
472 break;
473
474 default:
475 wxFAIL_MSG( _T("unexpected return code from GtkAssertDialog") );
476 }
477
478 gtk_widget_destroy(dialog);
479 return returnCode;
480 }
481
482 #endif // __WXDEBUG__
483
484 wxString wxGUIAppTraits::GetDesktopEnvironment() const
485 {
486 wxString de = wxSystemOptions::GetOption(_T("gtk.desktop"));
487 #if wxUSE_DETECT_SM
488 if ( de.empty() )
489 {
490 static const wxString s_SM = GetSM();
491
492 if (s_SM == wxT("GnomeSM"))
493 de = wxT("GNOME");
494 else if (s_SM == wxT("KDE"))
495 de = wxT("KDE");
496 }
497 #endif // wxUSE_DETECT_SM
498
499 return de;
500 }
501
502 #ifdef __WXGTK26__
503
504 // see the hack below in wxCmdLineParser::GetUsageString().
505 // TODO: replace this hack with a g_option_group_get_entries()
506 // call as soon as such function exists
507 struct _GOptionGroup
508 {
509 gchar *name;
510 gchar *description;
511 gchar *help_description;
512
513 GDestroyNotify destroy_notify;
514 gpointer user_data;
515
516 GTranslateFunc translate_func;
517 GDestroyNotify translate_notify;
518 gpointer translate_data;
519
520 GOptionEntry *entries;
521 gint n_entries;
522
523 GOptionParseFunc pre_parse_func;
524 GOptionParseFunc post_parse_func;
525 GOptionErrorFunc error_func;
526 };
527
528 wxString wxGetNameFromGtkOptionEntry(const GOptionEntry *opt)
529 {
530 wxString ret;
531
532 if (opt->short_name)
533 ret << _T("-") << opt->short_name;
534 if (opt->long_name)
535 {
536 if (!ret.empty())
537 ret << _T(", ");
538 ret << _T("--") << opt->long_name;
539
540 if (opt->arg_description)
541 ret << _T("=") << opt->arg_description;
542 }
543
544 return _T(" ") + ret;
545 }
546
547 #endif // __WXGTK26__
548
549 wxString
550 wxGUIAppTraits::GetStandardCmdLineOptions(wxArrayString& names,
551 wxArrayString& desc) const
552 {
553 wxString usage;
554
555 #ifdef __WXGTK26__
556 // check whether GTK version is greater than 2.6 but also lower than 2.12
557 // because, as we use the undocumented _GOptionGroup struct, we don't want
558 // to run this code with future versions which might change it (2.11 is the
559 // latest one at the time of this writing)
560 if (!gtk_check_version(2,6,0) &&
561 gtk_check_version(2,12,0))
562 {
563 usage << _("The following standard GTK+ options are also supported:\n");
564
565 // passing true here means that the function can open the default
566 // display while parsing (not really used here anyhow)
567 GOptionGroup *gtkOpts = gtk_get_option_group(true);
568
569 // WARNING: here we access the internals of GOptionGroup:
570 GOptionEntry *entries = ((_GOptionGroup*)gtkOpts)->entries;
571 unsigned int n_entries = ((_GOptionGroup*)gtkOpts)->n_entries;
572 wxArrayString namesOptions, descOptions;
573
574 for ( size_t n = 0; n < n_entries; n++ )
575 {
576 if ( entries[n].flags & G_OPTION_FLAG_HIDDEN )
577 continue; // skip
578
579 names.push_back(wxGetNameFromGtkOptionEntry(&entries[n]));
580
581 const gchar * const entryDesc = entries[n].description;
582 desc.push_back(entryDesc ? wxString(entryDesc) : _T(""));
583 }
584
585 g_option_group_free (gtkOpts);
586 }
587 #else
588 wxUnusedVar(names);
589 wxUnusedVar(desc);
590 #endif // __WXGTK26__
591
592 return usage;
593 }
594