As reported by Chris Elliott some releases of Lesstif crash
[wxWidgets.git] / src / motif / utils.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: utils.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 17/09/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __VMS
24 #define XtDisplay XTDISPLAY
25 #endif
26
27 #include "wx/setup.h"
28 #include "wx/utils.h"
29 #include "wx/apptrait.h"
30 #include "wx/app.h"
31 #include "wx/dcmemory.h"
32 #include "wx/bitmap.h"
33 #include "wx/evtloop.h"
34
35 #include <string.h>
36
37 #if (defined(__SUNCC__) || defined(__CLCC__))
38 #include <sysent.h>
39 #endif
40
41 #ifdef __VMS__
42 #pragma message disable nosimpint
43 #endif
44
45 #include "wx/unix/execute.h"
46
47 #include <Xm/Xm.h>
48 #include <Xm/Frame.h>
49
50 #include "wx/motif/private.h"
51
52 #if wxUSE_RESOURCES
53 #include "X11/Xresource.h"
54 #endif
55
56 #include "X11/Xutil.h"
57
58 #ifdef __VMS__
59 #pragma message enable nosimpint
60 #endif
61
62 // ----------------------------------------------------------------------------
63 // private functions
64 // ----------------------------------------------------------------------------
65
66 // Yuck this is really BOTH site and platform dependent
67 // so we should use some other strategy!
68 #ifdef sun
69 #define DEFAULT_XRESOURCE_DIR "/usr/openwin/lib/app-defaults"
70 #else
71 #define DEFAULT_XRESOURCE_DIR "/usr/lib/X11/app-defaults"
72 #endif
73
74 #if wxUSE_RESOURCES
75 static char *GetIniFile (char *dest, const char *filename);
76 #endif
77
78 // ============================================================================
79 // implementation
80 // ============================================================================
81
82 // ----------------------------------------------------------------------------
83 // async event processing
84 // ----------------------------------------------------------------------------
85
86 // Consume all events until no more left
87 void wxFlushEvents(WXDisplay* wxdisplay)
88 {
89 Display *display = (Display*)wxdisplay;
90 wxEventLoop evtLoop;
91
92 XSync (display, False);
93
94 while (evtLoop.Pending())
95 {
96 XFlush (display);
97 evtLoop.Dispatch();
98 }
99 }
100
101 // ----------------------------------------------------------------------------
102 // wxExecute stuff
103 // ----------------------------------------------------------------------------
104
105 static void xt_notify_end_process(XtPointer data, int *WXUNUSED(fid),
106 XtInputId *id)
107 {
108 wxEndProcessData *proc_data = (wxEndProcessData *)data;
109
110 wxHandleProcessTermination(proc_data);
111
112 // VZ: I think they should be the same...
113 wxASSERT( (int)*id == proc_data->tag );
114
115 XtRemoveInput(*id);
116 }
117
118 int wxAddProcessCallback(wxEndProcessData *proc_data, int fd)
119 {
120 XtInputId id = XtAppAddInput((XtAppContext) wxTheApp->GetAppContext(),
121 fd,
122 (XtPointer *) XtInputReadMask,
123 (XtInputCallbackProc) xt_notify_end_process,
124 (XtPointer) proc_data);
125
126 return (int)id;
127 }
128
129 // ----------------------------------------------------------------------------
130 // misc
131 // ----------------------------------------------------------------------------
132
133 // Emit a beeeeeep
134 #ifndef __EMX__
135 // on OS/2, we use the wxBell from wxBase library (src/os2/utils.cpp)
136 void wxBell()
137 {
138 // Use current setting for the bell
139 XBell (wxGlobalDisplay(), 0);
140 }
141 #endif
142
143 wxToolkitInfo& wxGUIAppTraits::GetToolkitInfo()
144 {
145 static wxToolkitInfo info;
146
147 info.shortName = _T("motif");
148 info.name = _T("wxMotif");
149 #ifdef __WXUNIVERSAL__
150 info.shortName << _T("univ");
151 info.name << _T("/wxUniversal");
152 #endif
153 // FIXME TODO
154 // This code is WRONG!! Does NOT return the
155 // Motif version of the libs but the X protocol
156 // version!
157 Display *display = wxGlobalDisplay();
158 if (display)
159 {
160 info.versionMajor = ProtocolVersion (display);
161 info.versionMinor = ProtocolRevision (display);
162 }
163 info.os = wxMOTIF_X;
164 return info;
165 }
166
167 // ----------------------------------------------------------------------------
168 // Reading and writing resources (eg WIN.INI, .Xdefaults)
169 // ----------------------------------------------------------------------------
170
171 #if wxUSE_RESOURCES
172
173 // Read $HOME for what it says is home, if not
174 // read $USER or $LOGNAME for user name else determine
175 // the Real User, then determine the Real home dir.
176 static char * GetIniFile (char *dest, const char *filename)
177 {
178 char *home = NULL;
179 if (filename && wxIsAbsolutePath(filename))
180 {
181 strcpy(dest, filename);
182 }
183 else if ((home = wxGetUserHome("")) != NULL)
184 {
185 strcpy(dest, home);
186 if (dest[strlen(dest) - 1] != '/')
187 strcat (dest, "/");
188 if (filename == NULL)
189 {
190 if ((filename = getenv ("XENVIRONMENT")) == NULL)
191 filename = ".Xdefaults";
192 }
193 else if (*filename != '.')
194 strcat (dest, ".");
195 strcat (dest, filename);
196 } else
197 {
198 dest[0] = '\0';
199 }
200 return dest;
201 }
202
203 static char *GetResourcePath(char *buf, const char *name, bool create = false)
204 {
205 if (create && wxFileExists (name) ) {
206 strcpy(buf, name);
207 return buf; // Exists so ...
208 }
209
210 if (*name == '/')
211 strcpy(buf, name);
212 else {
213 // Put in standard place for resource files if not absolute
214 strcpy (buf, DEFAULT_XRESOURCE_DIR);
215 strcat (buf, "/");
216 strcat (buf, wxFileNameFromPath (name).c_str());
217 }
218
219 if (create) {
220 // Touch the file to create it
221 FILE *fd = fopen (buf, "w");
222 if (fd) fclose (fd);
223 }
224 return buf;
225 }
226
227 /*
228 * We have a cache for writing different resource files,
229 * which will only get flushed when we call wxFlushResources().
230 * Build up a list of resource databases waiting to be written.
231 *
232 */
233
234 wxList wxResourceCache (wxKEY_STRING);
235
236 void
237 wxFlushResources (void)
238 {
239 char nameBuffer[512];
240
241 wxNode *node = wxResourceCache.First ();
242 while (node)
243 {
244 const char *file = node->GetKeyString();
245 // If file doesn't exist, create it first.
246 (void)GetResourcePath(nameBuffer, file, true);
247
248 XrmDatabase database = (XrmDatabase) node->Data ();
249 XrmPutFileDatabase (database, nameBuffer);
250 XrmDestroyDatabase (database);
251 wxNode *next = node->Next ();
252 delete node;
253 node = next;
254 }
255 }
256
257 static XrmDatabase wxResourceDatabase = 0;
258
259 void wxXMergeDatabases (wxApp * theApp, Display * display);
260
261 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
262 {
263 char buffer[500];
264
265 (void) GetIniFile (buffer, file);
266
267 XrmDatabase database;
268 wxNode *node = wxResourceCache.Find (buffer);
269 if (node)
270 database = (XrmDatabase) node->Data ();
271 else
272 {
273 database = XrmGetFileDatabase (buffer);
274 wxResourceCache.Append (buffer, (wxObject *) database);
275 }
276
277 char resName[300];
278 strcpy (resName, section.c_str());
279 strcat (resName, ".");
280 strcat (resName, entry.c_str());
281
282 XrmPutStringResource (&database, resName, value);
283 return true;
284 }
285
286 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
287 {
288 char buf[50];
289 sprintf(buf, "%.4f", value);
290 return wxWriteResource(section, entry, buf, file);
291 }
292
293 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
294 {
295 char buf[50];
296 sprintf(buf, "%ld", value);
297 return wxWriteResource(section, entry, buf, file);
298 }
299
300 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
301 {
302 char buf[50];
303 sprintf(buf, "%d", value);
304 return wxWriteResource(section, entry, buf, file);
305 }
306
307 bool wxGetResource(const wxString& section, const wxString& entry, char **value, const wxString& file)
308 {
309 if (!wxResourceDatabase)
310 {
311 Display *display = wxGlobalDisplay();
312 wxXMergeDatabases (wxTheApp, display);
313 }
314
315 XrmDatabase database;
316
317 if (file != "")
318 {
319 char buffer[500];
320
321 // Is this right? Trying to get it to look in the user's
322 // home directory instead of current directory -- JACS
323 (void) GetIniFile (buffer, file);
324
325 wxNode *node = wxResourceCache.Find (buffer);
326 if (node)
327 database = (XrmDatabase) node->Data ();
328 else
329 {
330 database = XrmGetFileDatabase (buffer);
331 wxResourceCache.Append (buffer, (wxObject *) database);
332 }
333 }
334 else
335 database = wxResourceDatabase;
336
337 XrmValue xvalue;
338 char *str_type[20];
339 char buf[150];
340 strcpy (buf, section);
341 strcat (buf, ".");
342 strcat (buf, entry);
343
344 Bool success = XrmGetResource (database, buf, "*", str_type,
345 &xvalue);
346 // Try different combinations of upper/lower case, just in case...
347 if (!success)
348 {
349 buf[0] = (isupper (buf[0]) ? tolower (buf[0]) : toupper (buf[0]));
350 success = XrmGetResource (database, buf, "*", str_type,
351 &xvalue);
352 }
353 if (success)
354 {
355 if (*value)
356 delete[] *value;
357
358 *value = new char[xvalue.size + 1];
359 strncpy (*value, xvalue.addr, (int) xvalue.size);
360 return true;
361 }
362 return false;
363 }
364
365 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
366 {
367 char *s = NULL;
368 bool succ = wxGetResource(section, entry, (char **)&s, file);
369 if (succ)
370 {
371 *value = (float)strtod(s, NULL);
372 delete[] s;
373 return true;
374 }
375 else return false;
376 }
377
378 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
379 {
380 char *s = NULL;
381 bool succ = wxGetResource(section, entry, (char **)&s, file);
382 if (succ)
383 {
384 *value = strtol(s, NULL, 10);
385 delete[] s;
386 return true;
387 }
388 else return false;
389 }
390
391 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
392 {
393 char *s = NULL;
394 bool succ = wxGetResource(section, entry, (char **)&s, file);
395 if (succ)
396 {
397 // Handle True, False here
398 // True, Yes, Enables, Set or Activated
399 if (*s == 'T' || *s == 'Y' || *s == 'E' || *s == 'S' || *s == 'A')
400 *value = true;
401 // False, No, Disabled, Reset, Cleared, Deactivated
402 else if (*s == 'F' || *s == 'N' || *s == 'D' || *s == 'R' || *s == 'C')
403 *value = false;
404 // Handle as Integer
405 else
406 *value = (int) strtol (s, NULL, 10);
407 delete[] s;
408 return true;
409 }
410 else
411 return false;
412 }
413
414 void wxXMergeDatabases (wxApp * theApp, Display * display)
415 {
416 XrmDatabase homeDB, serverDB, applicationDB;
417 char filenamebuf[1024];
418
419 char *filename = &filenamebuf[0];
420 char *environment;
421 wxString classname = theApp->GetClassName();
422 char name[256];
423 (void) strcpy (name, "/usr/lib/X11/app-defaults/");
424 (void) strcat (name, classname.c_str());
425
426 /* Get application defaults file, if any */
427 applicationDB = XrmGetFileDatabase (name);
428 (void) XrmMergeDatabases (applicationDB, &wxResourceDatabase);
429
430 /* Merge server defaults, created by xrdb, loaded as a property of the root
431 * window when the server initializes and loaded into the display
432 * structure on XOpenDisplay;
433 * if not defined, use .Xdefaults
434 */
435
436 if (XResourceManagerString (display) != NULL)
437 {
438 serverDB = XrmGetStringDatabase (XResourceManagerString (display));
439 }
440 else
441 {
442 (void) GetIniFile (filename, NULL);
443 serverDB = XrmGetFileDatabase (filename);
444 }
445 XrmMergeDatabases (serverDB, &wxResourceDatabase);
446
447 /* Open XENVIRONMENT file, or if not defined, the .Xdefaults,
448 * and merge into existing database
449 */
450
451 if ((environment = getenv ("XENVIRONMENT")) == NULL)
452 {
453 size_t len;
454 environment = GetIniFile (filename, NULL);
455 len = strlen (environment);
456 wxString hostname = wxGetHostName();
457 if ( !!hostname )
458 strncat(environment, hostname, 1024 - len);
459 }
460 homeDB = XrmGetFileDatabase (environment);
461 XrmMergeDatabases (homeDB, &wxResourceDatabase);
462 }
463
464 #if 0
465
466 /*
467 * Not yet used but may be useful.
468 *
469 */
470 void
471 wxSetDefaultResources (const Widget w, const char **resourceSpec, const char *name)
472 {
473 int i;
474 Display *dpy = XtDisplay (w); // Retrieve the display pointer
475
476 XrmDatabase rdb = NULL; // A resource data base
477
478 // Create an empty resource database
479 rdb = XrmGetStringDatabase ("");
480
481 // Add the Component resources, prepending the name of the component
482
483 i = 0;
484 while (resourceSpec[i] != NULL)
485 {
486 char buf[1000];
487
488 sprintf (buf, "*%s%s", name, resourceSpec[i++]);
489 XrmPutLineResource (&rdb, buf);
490 }
491
492 // Merge them into the Xt database, with lowest precendence
493
494 if (rdb)
495 {
496 #if (XlibSpecificationRelease>=5)
497 XrmDatabase db = XtDatabase (dpy);
498 XrmCombineDatabase (rdb, &db, False);
499 #else
500 XrmMergeDatabases (dpy->db, &rdb);
501 dpy->db = rdb;
502 #endif
503 }
504 }
505 #endif
506 // 0
507
508 #endif // wxUSE_RESOURCES
509
510 // ----------------------------------------------------------------------------
511 // display info
512 // ----------------------------------------------------------------------------
513
514 void wxGetMousePosition( int* x, int* y )
515 {
516 #if wxUSE_NANOX
517 // TODO
518 *x = 0;
519 *y = 0;
520 #else
521 XMotionEvent xev;
522 Window root, child;
523 XQueryPointer(wxGlobalDisplay(),
524 DefaultRootWindow(wxGlobalDisplay()),
525 &root, &child,
526 &(xev.x_root), &(xev.y_root),
527 &(xev.x), &(xev.y),
528 &(xev.state));
529 *x = xev.x_root;
530 *y = xev.y_root;
531 #endif
532 };
533
534 // Return true if we have a colour display
535 bool wxColourDisplay()
536 {
537 return wxDisplayDepth() > 1;
538 }
539
540 // Returns depth of screen
541 int wxDisplayDepth()
542 {
543 Display *dpy = wxGlobalDisplay();
544
545 return DefaultDepth (dpy, DefaultScreen (dpy));
546 }
547
548 // Get size of display
549 void wxDisplaySize(int *width, int *height)
550 {
551 Display *dpy = wxGlobalDisplay();
552
553 if ( width )
554 *width = DisplayWidth (dpy, DefaultScreen (dpy));
555 if ( height )
556 *height = DisplayHeight (dpy, DefaultScreen (dpy));
557 }
558
559 void wxDisplaySizeMM(int *width, int *height)
560 {
561 Display *dpy = wxGlobalDisplay();
562
563 if ( width )
564 *width = DisplayWidthMM(dpy, DefaultScreen (dpy));
565 if ( height )
566 *height = DisplayHeightMM(dpy, DefaultScreen (dpy));
567 }
568
569 void wxClientDisplayRect(int *x, int *y, int *width, int *height)
570 {
571 // This is supposed to return desktop dimensions minus any window
572 // manager panels, menus, taskbars, etc. If there is a way to do that
573 // for this platform please fix this function, otherwise it defaults
574 // to the entire desktop.
575 if (x) *x = 0;
576 if (y) *y = 0;
577 wxDisplaySize(width, height);
578 }
579
580
581 // Configurable display in wxX11 and wxMotif
582 static WXDisplay *gs_currentDisplay = NULL;
583 static wxString gs_displayName;
584
585 WXDisplay *wxGetDisplay()
586 {
587 if (gs_currentDisplay)
588 return gs_currentDisplay;
589 else if (wxTheApp)
590 return wxTheApp->GetInitialDisplay();
591 return NULL;
592 }
593
594 bool wxSetDisplay(const wxString& display_name)
595 {
596 gs_displayName = display_name;
597
598 if ( display_name.empty() )
599 {
600 gs_currentDisplay = NULL;
601
602 return true;
603 }
604 else
605 {
606 Cardinal argc = 0;
607
608 Display *display = XtOpenDisplay((XtAppContext) wxTheApp->GetAppContext(),
609 display_name.c_str(),
610 wxTheApp->GetAppName().c_str(),
611 wxTheApp->GetClassName().c_str(),
612 NULL,
613 #if XtSpecificationRelease < 5
614 0, &argc,
615 #else
616 0, (int *)&argc,
617 #endif
618 NULL);
619
620 if (display)
621 {
622 gs_currentDisplay = (WXDisplay*) display;
623 return true;
624 }
625 else
626 return false;
627 }
628 }
629
630 wxString wxGetDisplayName()
631 {
632 return gs_displayName;
633 }
634
635 wxWindow* wxFindWindowAtPoint(const wxPoint& pt)
636 {
637 return wxGenericFindWindowAtPoint(pt);
638 }
639
640 // ----------------------------------------------------------------------------
641 // Some colour manipulation routines
642 // ----------------------------------------------------------------------------
643
644 void wxHSVToXColor(wxHSV *hsv,XColor *rgb)
645 {
646 int h = hsv->h;
647 int s = hsv->s;
648 int v = hsv->v;
649 int r = 0, g = 0, b = 0;
650 int i, f;
651 int p, q, t;
652 s = (s * wxMAX_RGB) / wxMAX_SV;
653 v = (v * wxMAX_RGB) / wxMAX_SV;
654 if (h == 360) h = 0;
655 if (s == 0) { h = 0; r = g = b = v; }
656 i = h / 60;
657 f = h % 60;
658 p = v * (wxMAX_RGB - s) / wxMAX_RGB;
659 q = v * (wxMAX_RGB - s * f / 60) / wxMAX_RGB;
660 t = v * (wxMAX_RGB - s * (60 - f) / 60) / wxMAX_RGB;
661 switch (i)
662 {
663 case 0: r = v, g = t, b = p; break;
664 case 1: r = q, g = v, b = p; break;
665 case 2: r = p, g = v, b = t; break;
666 case 3: r = p, g = q, b = v; break;
667 case 4: r = t, g = p, b = v; break;
668 case 5: r = v, g = p, b = q; break;
669 }
670 rgb->red = r << 8;
671 rgb->green = g << 8;
672 rgb->blue = b << 8;
673 }
674
675 void wxXColorToHSV(wxHSV *hsv,XColor *rgb)
676 {
677 int r = rgb->red >> 8;
678 int g = rgb->green >> 8;
679 int b = rgb->blue >> 8;
680 int maxv = wxMax3(r, g, b);
681 int minv = wxMin3(r, g, b);
682 int h = 0, s, v;
683 v = maxv;
684 if (maxv) s = (maxv - minv) * wxMAX_RGB / maxv;
685 else s = 0;
686 if (s == 0) h = 0;
687 else
688 {
689 int rc, gc, bc, hex = 0;
690 rc = (maxv - r) * wxMAX_RGB / (maxv - minv);
691 gc = (maxv - g) * wxMAX_RGB / (maxv - minv);
692 bc = (maxv - b) * wxMAX_RGB / (maxv - minv);
693 if (r == maxv) { h = bc - gc, hex = 0; }
694 else if (g == maxv) { h = rc - bc, hex = 2; }
695 else if (b == maxv) { h = gc - rc, hex = 4; }
696 h = hex * 60 + (h * 60 / wxMAX_RGB);
697 if (h < 0) h += 360;
698 }
699 hsv->h = h;
700 hsv->s = (s * wxMAX_SV) / wxMAX_RGB;
701 hsv->v = (v * wxMAX_SV) / wxMAX_RGB;
702 }
703
704 void wxAllocNearestColor(Display *d,Colormap cmp,XColor *xc)
705 {
706 #if !wxUSE_NANOX
707 int llp;
708
709 int screen = DefaultScreen(d);
710 int num_colors = DisplayCells(d,screen);
711
712 XColor *color_defs = new XColor[num_colors];
713 for(llp = 0;llp < num_colors;llp++) color_defs[llp].pixel = llp;
714 XQueryColors(d,cmp,color_defs,num_colors);
715
716 wxHSV hsv_defs, hsv;
717 wxXColorToHSV(&hsv,xc);
718
719 int diff, min_diff = 0, pixel = 0;
720
721 for(llp = 0;llp < num_colors;llp++)
722 {
723 wxXColorToHSV(&hsv_defs,&color_defs[llp]);
724 diff = wxSIGN(wxH_WEIGHT * (hsv.h - hsv_defs.h)) +
725 wxSIGN(wxS_WEIGHT * (hsv.s - hsv_defs.s)) +
726 wxSIGN(wxV_WEIGHT * (hsv.v - hsv_defs.v));
727 if (llp == 0) min_diff = diff;
728 if (min_diff > diff) { min_diff = diff; pixel = llp; }
729 if (min_diff == 0) break;
730 }
731
732 xc -> red = color_defs[pixel].red;
733 xc -> green = color_defs[pixel].green;
734 xc -> blue = color_defs[pixel].blue;
735 xc -> flags = DoRed | DoGreen | DoBlue;
736
737 /* FIXME, TODO
738 if (!XAllocColor(d,cmp,xc))
739 cout << "wxAllocNearestColor : Warning : Cannot find nearest color !\n";
740 */
741
742 delete[] color_defs;
743 #endif
744 }
745
746 void wxAllocColor(Display *d,Colormap cmp,XColor *xc)
747 {
748 if (!XAllocColor(d,cmp,xc))
749 {
750 // cout << "wxAllocColor : Warning : Can not allocate color, attempt find nearest !\n";
751 wxAllocNearestColor(d,cmp,xc);
752 }
753 }
754
755 #ifdef __WXDEBUG__
756 wxString wxGetXEventName(XEvent& event)
757 {
758 #if wxUSE_NANOX
759 wxString str(wxT("(some event)"));
760 return str;
761 #else
762 int type = event.xany.type;
763 static char* event_name[] = {
764 "", "unknown(-)", // 0-1
765 "KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease", // 2-5
766 "MotionNotify", "EnterNotify", "LeaveNotify", "FocusIn", // 6-9
767 "FocusOut", "KeymapNotify", "Expose", "GraphicsExpose", // 10-13
768 "NoExpose", "VisibilityNotify", "CreateNotify", // 14-16
769 "DestroyNotify", "UnmapNotify", "MapNotify", "MapRequest",// 17-20
770 "ReparentNotify", "ConfigureNotify", "ConfigureRequest", // 21-23
771 "GravityNotify", "ResizeRequest", "CirculateNotify", // 24-26
772 "CirculateRequest", "PropertyNotify", "SelectionClear", // 27-29
773 "SelectionRequest", "SelectionNotify", "ColormapNotify", // 30-32
774 "ClientMessage", "MappingNotify", // 33-34
775 "unknown(+)"}; // 35
776 type = wxMin(35, type); type = wxMax(1, type);
777 wxString str(event_name[type]);
778 return str;
779 #endif
780 }
781 #endif
782
783 // ----------------------------------------------------------------------------
784 // accelerators
785 // ----------------------------------------------------------------------------
786
787 // Find the letter corresponding to the mnemonic, for Motif
788 char wxFindMnemonic (const char *s)
789 {
790 char mnem = 0;
791 int len = strlen (s);
792 int i;
793
794 for (i = 0; i < len; i++)
795 {
796 if (s[i] == '&')
797 {
798 // Carefully handle &&
799 if ((i + 1) <= len && s[i + 1] == '&')
800 i++;
801 else
802 {
803 mnem = s[i + 1];
804 break;
805 }
806 }
807 }
808 return mnem;
809 }
810
811 char* wxFindAccelerator( const char *s )
812 {
813 #if 1
814 // VZ: this function returns incorrect keysym which completely breaks kbd
815 // handling
816 return NULL;
817 #else
818 // The accelerator text is after the \t char.
819 s = strchr( s, '\t' );
820
821 if( !s ) return NULL;
822
823 /*
824 Now we need to format it as X standard:
825
826 input output
827
828 F7 --> <Key>F7
829 Ctrl+N --> Ctrl<Key>N
830 Alt+k --> Meta<Key>k
831 Ctrl+Shift+A --> Ctrl Shift<Key>A
832
833 and handle Ctrl-N & similia
834 */
835
836 static char buf[256];
837
838 buf[0] = '\0';
839 wxString tmp = s + 1; // skip TAB
840 size_t index = 0;
841
842 while( index < tmp.length() )
843 {
844 size_t plus = tmp.find( '+', index );
845 size_t minus = tmp.find( '-', index );
846
847 // neither '+' nor '-', add <Key>
848 if( plus == wxString::npos && minus == wxString::npos )
849 {
850 strcat( buf, "<Key>" );
851 strcat( buf, tmp.c_str() + index );
852
853 return buf;
854 }
855
856 // OK: npos is big and positive
857 size_t sep = wxMin( plus, minus );
858 wxString mod = tmp.substr( index, sep - index );
859
860 // Ctrl -> Ctrl
861 // Shift -> Shift
862 // Alt -> Meta
863 if( mod == "Alt" )
864 mod = "Meta";
865
866 if( buf[0] )
867 strcat( buf, " " );
868
869 strcat( buf, mod.c_str() );
870
871 index = sep + 1;
872 }
873
874 return NULL;
875 #endif
876 }
877
878 XmString wxFindAcceleratorText (const char *s)
879 {
880 #if 1
881 // VZ: this function returns incorrect keysym which completely breaks kbd
882 // handling
883 return NULL;
884 #else
885 // The accelerator text is after the \t char.
886 s = strchr( s, '\t' );
887
888 if( !s ) return NULL;
889
890 return wxStringToXmString( s + 1 ); // skip TAB!
891 #endif
892 }
893
894 // Change a widget's foreground and background colours.
895 void wxDoChangeForegroundColour(WXWidget widget, wxColour& foregroundColour)
896 {
897 // When should we specify the foreground, if it's calculated
898 // by wxComputeColours?
899 // Solution: say we start with the default (computed) foreground colour.
900 // If we call SetForegroundColour explicitly for a control or window,
901 // then the foreground is changed.
902 // Therefore SetBackgroundColour computes the foreground colour, and
903 // SetForegroundColour changes the foreground colour. The ordering is
904 // important.
905
906 XtVaSetValues ((Widget) widget,
907 XmNforeground, foregroundColour.AllocColour(XtDisplay((Widget) widget)),
908 NULL);
909 }
910
911 void wxDoChangeBackgroundColour(WXWidget widget, wxColour& backgroundColour, bool changeArmColour)
912 {
913 wxComputeColours (XtDisplay((Widget) widget), & backgroundColour,
914 (wxColour*) NULL);
915
916 XtVaSetValues ((Widget) widget,
917 XmNbackground, g_itemColors[wxBACK_INDEX].pixel,
918 XmNtopShadowColor, g_itemColors[wxTOPS_INDEX].pixel,
919 XmNbottomShadowColor, g_itemColors[wxBOTS_INDEX].pixel,
920 XmNforeground, g_itemColors[wxFORE_INDEX].pixel,
921 NULL);
922
923 if (changeArmColour)
924 XtVaSetValues ((Widget) widget,
925 XmNarmColor, g_itemColors[wxSELE_INDEX].pixel,
926 NULL);
927 }
928
929 extern void wxDoChangeFont(WXWidget widget, wxFont& font)
930 {
931 // Lesstif 0.87 hangs here, but 0.93 does not; MBN: sometimes it does
932 #if !wxCHECK_LESSTIF() // || wxCHECK_LESSTIF_VERSION( 0, 93 )
933 Widget w = (Widget)widget;
934 XtVaSetValues( w,
935 wxFont::GetFontTag(), font.GetFontTypeC( XtDisplay(w) ),
936 NULL );
937 #endif
938
939 }
940
941 wxString wxXmStringToString( const XmString& xmString )
942 {
943 char *txt;
944 if( XmStringGetLtoR( xmString, XmSTRING_DEFAULT_CHARSET, &txt ) )
945 {
946 wxString str(txt);
947 XtFree (txt);
948 return str;
949 }
950
951 return wxEmptyString;
952 }
953
954 XmString wxStringToXmString( const wxString& str )
955 {
956 return XmStringCreateLtoR((char *)str.c_str(), XmSTRING_DEFAULT_CHARSET);
957 }
958
959 XmString wxStringToXmString( const char* str )
960 {
961 return XmStringCreateLtoR((char *)str, XmSTRING_DEFAULT_CHARSET);
962 }
963
964 // ----------------------------------------------------------------------------
965 // wxBitmap utility functions
966 // ----------------------------------------------------------------------------
967
968 // Creates a bitmap with transparent areas drawn in
969 // the given colour.
970 wxBitmap wxCreateMaskedBitmap(const wxBitmap& bitmap, wxColour& colour)
971 {
972 wxBitmap newBitmap(bitmap.GetWidth(),
973 bitmap.GetHeight(),
974 bitmap.GetDepth());
975 wxMemoryDC destDC;
976 wxMemoryDC srcDC;
977
978 srcDC.SelectObject(bitmap);
979 destDC.SelectObject(newBitmap);
980
981 wxBrush brush(colour, wxSOLID);
982 destDC.SetBackground(brush);
983 destDC.Clear();
984 destDC.Blit(0, 0, bitmap.GetWidth(), bitmap.GetHeight(),
985 &srcDC, 0, 0, wxCOPY, true);
986
987 return newBitmap;
988 }
989
990 // ----------------------------------------------------------------------------
991 // Miscellaneous functions
992 // ----------------------------------------------------------------------------
993
994 WXWidget wxCreateBorderWidget( WXWidget parent, long style )
995 {
996 Widget borderWidget = (Widget)NULL, parentWidget = (Widget)parent;
997
998 if (style & wxSIMPLE_BORDER)
999 {
1000 borderWidget = XtVaCreateManagedWidget
1001 (
1002 "simpleBorder",
1003 xmFrameWidgetClass, parentWidget,
1004 XmNshadowType, XmSHADOW_ETCHED_IN,
1005 XmNshadowThickness, 1,
1006 NULL
1007 );
1008 }
1009 else if (style & wxSUNKEN_BORDER)
1010 {
1011 borderWidget = XtVaCreateManagedWidget
1012 (
1013 "sunkenBorder",
1014 xmFrameWidgetClass, parentWidget,
1015 XmNshadowType, XmSHADOW_IN,
1016 NULL
1017 );
1018 }
1019 else if (style & wxRAISED_BORDER)
1020 {
1021 borderWidget = XtVaCreateManagedWidget
1022 (
1023 "raisedBorder",
1024 xmFrameWidgetClass, parentWidget,
1025 XmNshadowType, XmSHADOW_OUT,
1026 NULL
1027 );
1028 }
1029
1030 return borderWidget;
1031 }