lock xft, plugin index builder lock, clear clip thumbnails, clear vwin clock, setpoin...
[goodguy/history.git] / cinelerra-5.1 / guicast / bcwindowbase.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include "bcbitmap.h"
23 #include "bcclipboard.h"
24 #include "bcdisplay.h"
25 #include "bcdisplayinfo.h"
26 #include "bcmenubar.h"
27 #include "bcpixmap.h"
28 #include "bcpopup.h"
29 #include "bcpopupmenu.h"
30 #include "bcrepeater.h"
31 #include "bcresources.h"
32 #include "bcsignals.h"
33 #include "bcsubwindow.h"
34 #include "bcsynchronous.h"
35 #include "bctimer.h"
36 #include "bcwindowbase.h"
37 #include "bcwindowevents.h"
38 #include "bccmodels.h"
39 #include "bccolors.h"
40 #include "condition.h"
41 #include "cursors.h"
42 #include "bchash.h"
43 #include "fonts.h"
44 #include "keys.h"
45 #include "language.h"
46 #include "mutex.h"
47 #include "sizes.h"
48 #include "vframe.h"
49 #include "workarounds.h"
50
51 #ifdef HAVE_GL
52 #include <GL/gl.h>
53 #endif
54 #include <string.h>
55 #include <unistd.h>
56 #include <wchar.h>
57 #include <typeinfo>
58
59 #include <X11/extensions/Xinerama.h>
60 #include <X11/extensions/Xvlib.h>
61 #include <X11/extensions/shape.h>
62 #include <X11/XF86keysym.h>
63 #include <X11/Sunkeysym.h>
64
65
66 BC_ResizeCall::BC_ResizeCall(int w, int h)
67 {
68         this->w = w;
69         this->h = h;
70 }
71
72
73
74
75
76
77
78 int BC_WindowBase::shm_completion_event = -1;
79
80
81
82 BC_Resources BC_WindowBase::resources;
83
84 Window XGroupLeader = 0;
85
86 Mutex BC_KeyboardHandlerLock::keyboard_listener_mutex("keyboard_listener",0);
87 ArrayList<BC_KeyboardHandler*> BC_KeyboardHandler::listeners;
88
89 BC_WindowBase::BC_WindowBase()
90 {
91 //printf("BC_WindowBase::BC_WindowBase 1\n");
92         BC_WindowBase::initialize();
93 }
94
95 BC_WindowBase::~BC_WindowBase()
96 {
97 #ifdef SINGLE_THREAD
98         BC_Display::lock_display("BC_WindowBase::~BC_WindowBase");
99 #else
100         if(window_type == MAIN_WINDOW)
101                 lock_window("BC_WindowBase::~BC_WindowBase");
102 #endif
103
104 #ifdef HAVE_LIBXXF86VM
105         if(window_type == VIDMODE_SCALED_WINDOW && vm_switched) {
106                 restore_vm();
107         }
108 #endif
109         is_deleting = 1;
110
111         hide_tooltip();
112         if(window_type != MAIN_WINDOW)
113         {
114 // stop event input
115                 XSelectInput(top_level->display, this->win, 0);
116                 XSync(top_level->display,0);
117 #ifndef SINGLE_THREAD
118                 top_level->dequeue_events(win);
119 #endif
120 // drop active window refs to this
121                 if(top_level->active_menubar == this) top_level->active_menubar = 0;
122                 if(top_level->active_popup_menu == this) top_level->active_popup_menu = 0;
123                 if(top_level->active_subwindow == this) top_level->active_subwindow = 0;
124 // drop motion window refs to this
125                 if(top_level->motion_events && top_level->last_motion_win == this->win)
126                         top_level->motion_events = 0;
127
128 // Remove pointer from parent window to this
129                 parent_window->subwindows->remove(this);
130         }
131
132         if(grab_active) grab_active->active_grab = 0;
133         if(icon_window) delete icon_window;
134         if(window_type == POPUP_WINDOW)
135                 parent_window->remove_popup(this);
136
137 // Delete the subwindows
138         if(subwindows)
139         {
140                 while(subwindows->total)
141                 {
142 // Subwindow removes its own pointer
143                         delete subwindows->values[0];
144                 }
145                 delete subwindows;
146         }
147
148         delete pixmap;
149
150 //printf("delete glx=%08x, win=%08x %s\n", (unsigned)glx_win, (unsigned)win, title);
151 #ifdef HAVE_GL
152         if( get_resources()->get_synchronous() && glx_win != 0 ) {
153                 get_resources()->get_synchronous()->delete_window(this);
154         }
155 #endif
156         XDestroyWindow(top_level->display, win);
157
158         if(bg_pixmap && !shared_bg_pixmap) delete bg_pixmap;
159         if(icon_pixmap) delete icon_pixmap;
160         if(temp_bitmap) delete temp_bitmap;
161         top_level->active_bitmaps.remove_buffers(this);
162         if(_7segment_pixmaps)
163         {
164                 for(int i = 0; i < TOTAL_7SEGMENT; i++)
165                         delete _7segment_pixmaps[i];
166
167                 delete [] _7segment_pixmaps;
168         }
169
170
171
172         if(window_type == MAIN_WINDOW)
173         {
174                 XFreeGC(display, gc);
175                 static XFontStruct *BC_WindowBase::*xfont[] = {
176                          &BC_WindowBase::smallfont,
177                          &BC_WindowBase::mediumfont,
178                          &BC_WindowBase::largefont,
179                          &BC_WindowBase::bigfont,
180                          &BC_WindowBase::clockfont,
181                 };
182                 for( int i=sizeof(xfont)/sizeof(xfont[0]); --i>=0; )
183                         XFreeFont(display, this->*xfont[i]);
184
185 // past bug in X caused XRenderExtensionInfo to be damaged
186 // if this is done here. left to be done in XCloseDisplay by Xlib.
187 // works in more modern systems, and needed for leak testing.
188 #if defined(HAVE_XFT) && defined(VALGRIND)
189                 static void *BC_WindowBase::*xft_font[] = {
190                          &BC_WindowBase::smallfont_xft,
191                          &BC_WindowBase::mediumfont_xft,
192                          &BC_WindowBase::largefont_xft,
193                          &BC_WindowBase::bigfont_xft,
194                          &BC_WindowBase::bold_smallfont_xft,
195                          &BC_WindowBase::bold_mediumfont_xft,
196                          &BC_WindowBase::bold_largefont_xft,
197                          &BC_WindowBase::clockfont_xft,
198                 };
199                 for( int i=sizeof(xft_font)/sizeof(xft_font[0]); --i>=0; ) {
200                         XftFont *xft = (XftFont *)(this->*xft_font[i]);
201                         if( xft ) xftFontClose (display, xft);
202                 }
203 #endif
204                 finit_im();
205                 flush();
206                 sync_display();
207
208                 if( xinerama_info )
209                         XFree(xinerama_info);
210                 xinerama_screens = 0;
211                 xinerama_info = 0;
212                 if( xvideo_port_id >= 0 )
213                         XvUngrabPort(display, xvideo_port_id, CurrentTime);
214
215                 unlock_window();
216 // Must be last reference to display.
217 // _XftDisplayInfo needs a lock.
218                 get_resources()->create_window_lock->lock("BC_WindowBase::~BC_WindowBase");
219                 XCloseDisplay(display);
220                 get_resources()->create_window_lock->unlock();
221
222 // clipboard uses a different display connection
223                 clipboard->stop_clipboard();
224                 delete clipboard;
225         }
226
227         resize_history.remove_all_objects();
228
229 #ifndef SINGLE_THREAD
230         common_events.remove_all_objects();
231         delete event_lock;
232         delete event_condition;
233         delete init_lock;
234 #else
235         top_level->window_lock = 0;
236         BC_Display::unlock_display();
237 #endif
238         delete cursor_timer;
239
240 #if HAVE_GL
241         if( glx_fbcfgs_window ) XFree(glx_fbcfgs_window);
242         if( glx_fbcfgs_pbuffer) XFree(glx_fbcfgs_pbuffer);
243         if( glx_fbcfgs_pixmap ) XFree(glx_fbcfgs_pixmap);
244 #endif
245
246         UNSET_ALL_LOCKS(this)
247 }
248
249 int BC_WindowBase::initialize()
250 {
251         done = 0;
252         done_set = 0;
253         window_running = 0;
254         display_lock_owner = 0;
255         test_keypress = 0;
256         keys_return[0] = 0;
257         is_deleting = 0;
258         window_lock = 0;
259         resend_event_window = 0;
260         x = 0;
261         y = 0;
262         w = 0;
263         h = 0;
264         bg_color = -1;
265         line_width = 1;
266         line_dashes = 0;
267         top_level = 0;
268         parent_window = 0;
269         subwindows = 0;
270         xinerama_info = 0;
271         xinerama_screens = 0;
272         xvideo_port_id = -1;
273         video_on = 0;
274         motion_events = 0;
275         resize_events = 0;
276         translation_events = 0;
277         ctrl_mask = shift_mask = alt_mask = 0;
278         cursor_x = cursor_y = button_number = 0;
279         button_down = 0;
280         button_pressed = 0;
281         button_time1 = 0;
282         button_time2 = 0;
283         button_time3 = 0;
284         double_click = 0;
285         triple_click = 0;
286         event_win = 0;
287         last_motion_win = 0;
288         key_pressed = 0;
289         active_grab = 0;
290         grab_active = 0;
291         active_menubar = 0;
292         active_popup_menu = 0;
293         active_subwindow = 0;
294         cursor_entered = 0;
295         pixmap = 0;
296         bg_pixmap = 0;
297         _7segment_pixmaps = 0;
298         tooltip_text = 0;
299         force_tooltip = 0;
300 //      next_repeat_id = 0;
301         tooltip_popup = 0;
302         current_font = MEDIUMFONT;
303         current_color = BLACK;
304         current_cursor = ARROW_CURSOR;
305         hourglass_total = 0;
306         is_dragging = 0;
307         shared_bg_pixmap = 0;
308         icon_pixmap = 0;
309         icon_window = 0;
310         window_type = MAIN_WINDOW;
311         translation_count = 0;
312         x_correction = y_correction = 0;
313         temp_bitmap = 0;
314         tooltip_on = 0;
315         temp_cursor = 0;
316         toggle_value = 0;
317         toggle_drag = 0;
318         has_focus = 0;
319         is_hourglass = 0;
320         is_transparent = 0;
321 #ifdef HAVE_LIBXXF86VM
322         vm_switched = 0;
323 #endif
324         input_method = 0;
325         input_context = 0;
326
327         smallfont = 0;
328         mediumfont = 0;
329         largefont = 0;
330         bigfont = 0;
331         clockfont = 0;
332
333         smallfont_xft = 0;
334         mediumfont_xft = 0;
335         largefont_xft = 0;
336         bigfont_xft = 0;
337         clockfont_xft = 0;
338
339         bold_smallfont_xft = 0;
340         bold_mediumfont_xft = 0;
341         bold_largefont_xft = 0;
342 #ifdef SINGLE_THREAD
343         completion_lock = new Condition(0, "BC_WindowBase::completion_lock");
344 #else
345 // Need these right away since put_event is called before run_window sometimes.
346         event_lock = new Mutex("BC_WindowBase::event_lock");
347         event_condition = new Condition(0, "BC_WindowBase::event_condition");
348         init_lock = new Condition(0, "BC_WindowBase::init_lock");
349 #endif
350
351         cursor_timer = new Timer;
352         event_thread = 0;
353 #ifdef HAVE_GL
354         glx_fbcfgs_window = 0;  n_fbcfgs_window = 0;
355         glx_fbcfgs_pbuffer = 0; n_fbcfgs_pbuffer = 0;
356         glx_fbcfgs_pixmap = 0;  n_fbcfgs_pixmap = 0;
357
358         glx_fb_config = 0;
359         glx_win_context = 0;
360         glx_win = 0;
361 #endif
362
363         flash_enabled = 1;
364         win = 0;
365         return 0;
366 }
367
368
369
370 #define DEFAULT_EVENT_MASKS EnterWindowMask | \
371                         LeaveWindowMask | \
372                         ButtonPressMask | \
373                         ButtonReleaseMask | \
374                         PointerMotionMask | \
375                         FocusChangeMask
376
377
378 int BC_WindowBase::create_window(BC_WindowBase *parent_window, const char *title,
379                 int x, int y, int w, int h, int minw, int minh, int allow_resize,
380                 int private_color, int hide, int bg_color, const char *display_name,
381                 int window_type, BC_Pixmap *bg_pixmap, int group_it)
382 {
383         XSetWindowAttributes attr;
384         unsigned long mask;
385         XSizeHints size_hints;
386         int root_w;
387         int root_h;
388 #ifdef HAVE_LIBXXF86VM
389         int vm;
390 #endif
391
392         id = get_resources()->get_id();
393         int need_lock = 0;
394         if(parent_window) top_level = parent_window->top_level;
395         if( top_level ) { // need this to avoid deadlock with Xlib's locks
396                 need_lock = 1;
397                 lock_window("BC_WindowBase::create_window");
398         }
399         get_resources()->create_window_lock->lock("BC_WindowBase::create_window");
400
401 #ifdef HAVE_LIBXXF86VM
402         if(window_type == VIDMODE_SCALED_WINDOW)
403                 closest_vm(&vm,&w,&h);
404 #endif
405
406         this->x = x;
407         this->y = y;
408         this->w = w;
409         this->h = h;
410         this->bg_color = bg_color;
411         this->window_type = window_type;
412         this->hidden = hide;
413         this->private_color = private_color;
414         this->parent_window = parent_window;
415         this->bg_pixmap = bg_pixmap;
416         this->allow_resize = allow_resize;
417         if(display_name)
418                 strcpy(this->display_name, display_name);
419         else
420                 this->display_name[0] = 0;
421
422         put_title(title);
423         if(bg_pixmap) shared_bg_pixmap = 1;
424
425         subwindows = new BC_SubWindowList;
426
427         if(window_type == MAIN_WINDOW)
428         {
429                 top_level = this;
430                 parent_window = this;
431
432
433 #ifdef SINGLE_THREAD
434                 display = BC_Display::get_display(display_name);
435                 BC_Display::lock_display("BC_WindowBase::create_window");
436 //              BC_Display::display_global->new_window(this);
437 #else
438
439 // get the display connection
440
441 // This function must be the first Xlib
442 // function a multi-threaded program calls
443                 XInitThreads();
444                 display = init_display(display_name);
445                 if( shm_completion_event < 0 ) shm_completion_event =
446                         ShmCompletion + XShmGetEventBase(display);
447 #endif
448
449                 screen = DefaultScreen(display);
450                 rootwin = RootWindow(display, screen);
451 // window placement boundaries
452                 if( !xinerama_screens && XineramaIsActive(display) )
453                         xinerama_info = XineramaQueryScreens(display, &xinerama_screens);
454                 root_w = get_root_w(0);
455                 root_h = get_root_h(0);
456
457 #if HAVE_GL
458                 vis = get_glx_visual(display);
459                 if( !vis )
460 #endif
461                         vis = DefaultVisual(display, screen);
462
463                 default_depth = DefaultDepth(display, screen);
464
465                 client_byte_order = (*(const u_int32_t*)"a   ") & 0x00000001;
466                 server_byte_order = (XImageByteOrder(display) == MSBFirst) ? 0 : 1;
467
468
469 // This must be done before fonts to know if antialiasing is available.
470                 init_colors();
471 // get the resources
472                 if(resources.use_shm < 0) resources.initialize_display(this);
473                 x_correction = BC_DisplayInfo::get_left_border();
474                 y_correction = BC_DisplayInfo::get_top_border();
475
476 // clamp window placement
477                 if(this->x + this->w + x_correction > root_w)
478                         this->x = root_w - this->w - x_correction;
479                 if(this->y + this->h + y_correction > root_h)
480                         this->y = root_h - this->h - y_correction;
481                 if(this->x < 0) this->x = 0;
482                 if(this->y < 0) this->y = 0;
483
484                 if(this->bg_color == -1)
485                         this->bg_color = resources.get_bg_color();
486
487 // printf("bcwindowbase 1 %s\n", title);
488 // if(window_type == MAIN_WINDOW) sleep(1);
489 // printf("bcwindowbase 10\n");
490                 init_fonts();
491                 init_gc();
492                 init_cursors();
493
494 // Create the window
495                 mask = CWEventMask | CWBackPixel | CWColormap | CWCursor;
496
497                 attr.event_mask = DEFAULT_EVENT_MASKS |
498                         StructureNotifyMask |
499                         KeyPressMask |
500                         KeyReleaseMask;
501
502                 attr.background_pixel = get_color(this->bg_color);
503                 attr.colormap = cmap;
504                 attr.cursor = get_cursor_struct(ARROW_CURSOR);
505
506                 win = XCreateWindow(display, rootwin,
507                         this->x, this->y, this->w, this->h, 0,
508                         top_level->default_depth, InputOutput,
509                         vis, mask, &attr);
510                 XGetNormalHints(display, win, &size_hints);
511
512                 size_hints.flags = PSize | PMinSize | PMaxSize;
513                 size_hints.width = this->w;
514                 size_hints.height = this->h;
515                 size_hints.min_width = allow_resize ? minw : this->w;
516                 size_hints.max_width = allow_resize ? 32767 : this->w;
517                 size_hints.min_height = allow_resize ? minh : this->h;
518                 size_hints.max_height = allow_resize ? 32767 : this->h;
519                 if(x > -BC_INFINITY && x < BC_INFINITY)
520                 {
521                         size_hints.flags |= PPosition;
522                         size_hints.x = this->x;
523                         size_hints.y = this->y;
524                 }
525                 XSetWMProperties(display, win, 0, 0, 0, 0, &size_hints, 0, 0);
526                 get_atoms();
527                 set_title(title);
528 #ifndef SINGLE_THREAD
529                 clipboard = new BC_Clipboard(this);
530                 clipboard->start_clipboard();
531 #endif
532
533
534                 if (group_it)
535                 {
536                         Atom ClientLeaderXAtom;
537                         if (XGroupLeader == 0)
538                                 XGroupLeader = win;
539                         const char *instance_name = "cinelerra";
540                         const char *class_name = "Cinelerra";
541                         XClassHint *class_hints = XAllocClassHint();
542                         class_hints->res_name = (char*)instance_name;
543                         class_hints->res_class = (char*)class_name;
544                         XSetClassHint(top_level->display, win, class_hints);
545                         XFree(class_hints);
546                         ClientLeaderXAtom = XInternAtom(display, "WM_CLIENT_LEADER", True);
547                         XChangeProperty(display, win, ClientLeaderXAtom, XA_WINDOW, 32,
548                                 PropModeReplace, (unsigned char *)&XGroupLeader, true);
549                 }
550                 init_im();
551         }
552
553 #ifdef HAVE_LIBXXF86VM
554         if(window_type == VIDMODE_SCALED_WINDOW && vm != -1)
555         {
556                 scale_vm (vm);
557                 vm_switched = 1;
558         }
559 #endif
560
561 #ifdef HAVE_LIBXXF86VM
562         if(window_type == POPUP_WINDOW || window_type == VIDMODE_SCALED_WINDOW)
563 #else
564         if(window_type == POPUP_WINDOW)
565 #endif
566         {
567                 mask = CWEventMask | CWBackPixel | CWColormap |
568                         CWOverrideRedirect | CWSaveUnder | CWCursor;
569
570                 attr.event_mask = DEFAULT_EVENT_MASKS |
571                         KeyPressMask |
572                         KeyReleaseMask;
573
574                 if(this->bg_color == -1)
575                         this->bg_color = resources.get_bg_color();
576                 attr.background_pixel = top_level->get_color(bg_color);
577                 attr.colormap = top_level->cmap;
578                 if(top_level->is_hourglass)
579                         attr.cursor = top_level->get_cursor_struct(HOURGLASS_CURSOR);
580                 else
581                         attr.cursor = top_level->get_cursor_struct(ARROW_CURSOR);
582                 attr.override_redirect = True;
583                 attr.save_under = True;
584
585                 win = XCreateWindow(top_level->display,
586                         top_level->rootwin, this->x, this->y, this->w, this->h, 0,
587                         top_level->default_depth, InputOutput, top_level->vis, mask,
588                         &attr);
589                 top_level->add_popup(this);
590         }
591
592         if(window_type == SUB_WINDOW)
593         {
594                 mask = CWEventMask | CWBackPixel | CWCursor;
595                 attr.event_mask = DEFAULT_EVENT_MASKS;
596                 attr.background_pixel = top_level->get_color(this->bg_color);
597                 if(top_level->is_hourglass)
598                         attr.cursor = top_level->get_cursor_struct(HOURGLASS_CURSOR);
599                 else
600                         attr.cursor = top_level->get_cursor_struct(ARROW_CURSOR);
601                 win = XCreateWindow(top_level->display,
602                         parent_window->win, this->x, this->y, this->w, this->h, 0,
603                         top_level->default_depth, InputOutput, top_level->vis, mask,
604                         &attr);
605                 init_window_shape();
606                 if(!hidden) XMapWindow(top_level->display, win);
607         }
608
609 // Create pixmap for all windows
610         pixmap = new BC_Pixmap(this, this->w, this->h);
611
612 // Set up options for main window
613         if(window_type == MAIN_WINDOW)
614         {
615                 if(get_resources()->bg_image && !bg_pixmap && bg_color < 0)
616                 {
617                         this->bg_pixmap = new BC_Pixmap(this,
618                                 get_resources()->bg_image,
619                                 PIXMAP_OPAQUE);
620                 }
621
622                 if(!hidden) show_window();
623
624         }
625
626         draw_background(0, 0, this->w, this->h);
627
628         flash(-1, -1, -1, -1, 0);
629
630 // Set up options for popup window
631 #ifdef HAVE_LIBXXF86VM
632         if(window_type == POPUP_WINDOW || window_type == VIDMODE_SCALED_WINDOW)
633 #else
634         if(window_type == POPUP_WINDOW)
635 #endif
636         {
637                 init_window_shape();
638                 if(!hidden) show_window();
639         }
640         get_resources()->create_window_lock->unlock();
641         if(need_lock) unlock_window();
642
643         return 0;
644 }
645
646 Display* BC_WindowBase::init_display(const char *display_name)
647 {
648         Display* display;
649
650         if(display_name && display_name[0] == 0) display_name = NULL;
651         if((display = XOpenDisplay(display_name)) == NULL) {
652                 printf("BC_WindowBase::init_display: cannot connect to X server %s\n",
653                         display_name);
654                 if(getenv("DISPLAY") == NULL) {
655                         printf(_("'DISPLAY' environment variable not set.\n"));
656                         exit(1);
657                 }
658                 else {
659 // Try again with default display.
660                         if((display = XOpenDisplay(0)) == NULL) {
661                                 printf("BC_WindowBase::init_display: cannot connect to default X server.\n");
662                                 exit(1);
663                         }
664                 }
665         }
666
667         static int xsynch = -1;
668         if( xsynch < 0 ) {
669                 const char *cp = getenv("CIN_XSYNCH");
670                 xsynch = !cp ? 0 : atoi(cp);
671         }
672         if( xsynch > 0 )
673                 XSynchronize(display, True);
674
675         return display;
676 }
677
678 Display* BC_WindowBase::get_display()
679 {
680         return top_level->display;
681 }
682
683 int BC_WindowBase::get_screen()
684 {
685         return top_level->screen;
686 }
687
688 int BC_WindowBase::run_window()
689 {
690         done_set = done = 0;
691         return_value = 0;
692
693
694 // Events may have been sent before run_window so can't initialize them here.
695
696 #ifdef SINGLE_THREAD
697         set_repeat(get_resources()->tooltip_delay);
698         BC_Display::display_global->new_window(this);
699
700 // If the first window created, run the display loop in this thread.
701         if(BC_Display::display_global->is_first(this))
702         {
703                 BC_Display::unlock_display();
704                 BC_Display::display_global->loop();
705         }
706         else
707         {
708                 BC_Display::unlock_display();
709                 completion_lock->lock("BC_WindowBase::run_window");
710         }
711
712         BC_Display::lock_display("BC_WindowBase::run_window");
713         BC_Display::display_global->delete_window(this);
714
715         unset_all_repeaters();
716         hide_tooltip();
717         BC_Display::unlock_display();
718
719 #else // SINGLE_THREAD
720
721
722
723 // Start tooltips
724         set_repeat(get_resources()->tooltip_delay);
725
726 // Start X server events
727         event_thread = new BC_WindowEvents(this);
728         event_thread->start();
729
730 // Release wait lock
731         window_running = 1;
732         init_lock->unlock();
733
734 // Handle common events
735         while(!done)
736         {
737                 dispatch_event(0);
738         }
739
740         unset_all_repeaters();
741         hide_tooltip();
742         delete event_thread;
743         event_thread = 0;
744         event_condition->reset();
745         common_events.remove_all_objects();
746         window_running = 0;
747         done = 0;
748
749 #endif // SINGLE_THREAD
750
751         return return_value;
752 }
753
754 int BC_WindowBase::get_key_masks(unsigned int key_state)
755 {
756 // printf("BC_WindowBase::get_key_masks %llx\n",
757 // event->xkey.state);
758         ctrl_mask = (key_state & ControlMask) ? 1 : 0;  // ctrl key down
759         shift_mask = (key_state & ShiftMask) ? 1 : 0;   // shift key down
760         alt_mask = (key_state & Mod1Mask) ? 1 : 0;      // alt key down
761         return 0;
762 }
763
764
765 void BC_WindowBase::add_keyboard_listener(int(BC_WindowBase::*handler)(BC_WindowBase *))
766 {
767         BC_KeyboardHandlerLock set;
768         BC_KeyboardHandler::listeners.append(new BC_KeyboardHandler(handler, this));
769 }
770
771 void BC_WindowBase::del_keyboard_listener(int(BC_WindowBase::*handler)(BC_WindowBase *))
772 {
773         BC_KeyboardHandlerLock set;
774         int i = BC_KeyboardHandler::listeners.size();
775         while( --i >= 0 && BC_KeyboardHandler::listeners[i]->handler!=handler );
776         if( i >= 0 ) BC_KeyboardHandler::listeners.remove_object_number(i);
777 }
778
779 int BC_KeyboardHandler::run_event(BC_WindowBase *wp)
780 {
781         int result = (win->*handler)(wp);
782         return result;
783 }
784
785 int BC_KeyboardHandler::run_listeners(BC_WindowBase *wp)
786 {
787         int result = 0;
788         BC_KeyboardHandlerLock set;
789         for( int i=0; !result && i<listeners.size(); ++i ) {
790                 BC_KeyboardHandler *listener = listeners[i];
791                 result = listener->run_event(wp);
792         }
793         return result;
794 }
795
796 void BC_KeyboardHandler::kill_grabs()
797 {
798         BC_KeyboardHandlerLock set;
799         for( int i=0; i<listeners.size(); ++i ) {
800                 BC_WindowBase *win = listeners[i]->win;
801                 if( win->get_window_type() != POPUP_WINDOW ) continue;
802                 ((BC_Popup *)win)->ungrab_keyboard();
803         }
804 }
805
806 void BC_ActiveBitmaps::reque(XEvent *event)
807 {
808         XShmCompletionEvent *shm_ev = (XShmCompletionEvent *)event;
809         ShmSeg shmseg = shm_ev->shmseg;
810         Drawable drawable = shm_ev->drawable;
811 //printf("BC_BitmapImage::reque %08lx\n",shmseg);
812         active_lock.lock("BC_BitmapImage::reque");
813         BC_BitmapImage *bfr = first;
814         while( bfr && bfr->get_shmseg() != shmseg ) bfr = bfr->next;
815         if( bfr && bfr->drawable == drawable )
816                 remove_pointer(bfr);
817         active_lock.unlock();
818         if( !bfr ) {
819 // sadly, X reports two drawable completions and creates false reporting, so no boobytrap
820 //              printf("BC_BitmapImage::reque missed shmseg %08x, drawable %08x\n",
821 //                       (int)shmseg, (int)drawable);
822                 return;
823         }
824         if( bfr->drawable != drawable ) return;
825         if( bfr->is_zombie() ) { --BC_Bitmap::zombies; delete bfr; return; }
826         bfr->bitmap->reque(bfr);
827 }
828
829 void BC_ActiveBitmaps::insert(BC_BitmapImage *bfr, Drawable pixmap)
830 {
831         active_lock.lock("BC_BitmapImage::insert");
832         bfr->drawable = pixmap;
833         append(bfr);
834         active_lock.unlock();
835 }
836
837 void BC_ActiveBitmaps::remove_buffers(BC_WindowBase *wdw)
838 {
839         active_lock.lock("BC_ActiveBitmaps::remove");
840         for( BC_BitmapImage *nxt=0, *bfr=first; bfr; bfr=nxt ) {
841                 nxt = bfr->next;
842                 if( bfr->is_zombie() ) { --BC_Bitmap::zombies; delete bfr; continue; }
843                 if( bfr->bitmap->parent_window == wdw ) remove_pointer(bfr);
844         }
845         active_lock.unlock();
846 }
847
848 BC_ActiveBitmaps::BC_ActiveBitmaps()
849 {
850 }
851
852 BC_ActiveBitmaps::~BC_ActiveBitmaps()
853 {
854 }
855
856
857
858 int BC_WindowBase::keysym_lookup(XEvent *event)
859 {
860         for( int i = 0; i < KEYPRESSLEN; ++i ) keys_return[i] = 0;
861         for( int i = 0; i < 4; ++i ) wkey_string[i] = 0;
862
863         if( event->xany.send_event && !event->xany.serial ) {
864                 keysym = (KeySym) event->xkey.keycode;
865                 keys_return[0] = keysym;
866                 return 0;
867         }
868         wkey_string_length = 0;
869
870         if( input_context ) {
871                 wkey_string_length = XwcLookupString(input_context,
872                         (XKeyEvent*)event, wkey_string, 4, &keysym, 0);
873 //printf("keysym_lookup 1 %d %d %lx %x %x %x %x\n", wkey_string_length, keysym,
874 //  wkey_string[0], wkey_string[1], wkey_string[2], wkey_string[3]);
875
876                 Status stat;
877                 int ret = Xutf8LookupString(input_context, (XKeyEvent*)event,
878                                 keys_return, KEYPRESSLEN, &keysym, &stat);
879 //printf("keysym_lookup 2 %d %d %lx %x %x\n", ret, stat, keysym, keys_return[0], keys_return[1]);
880                 if( stat == XLookupBoth ) return ret;
881                 if( stat == XLookupKeySym ) return 0;
882         }
883         int ret = XLookupString((XKeyEvent*)event, keys_return, KEYPRESSLEN, &keysym, 0);
884         wkey_string_length = ret;
885         for( int i=0; i<ret; ++i ) wkey_string[i] = keys_return[i];
886         return ret;
887 }
888
889 pthread_t locking_task = (pthread_t)-1L;
890 int locking_event = -1;
891 int locking_message = -1;
892
893 int BC_WindowBase::dispatch_event(XEvent *event)
894 {
895         Window tempwin;
896         int result;
897         XClientMessageEvent *ptr;
898         int cancel_resize, cancel_translation;
899         const int debug = 0;
900
901         key_pressed = 0;
902
903 #ifndef SINGLE_THREAD
904 // If an event is waiting get it, otherwise
905 // wait for next event only if there are no compressed events.
906         if(get_event_count() ||
907                 (!motion_events && !resize_events && !translation_events))
908         {
909                 event = get_event();
910 // Lock out window deletions
911                 lock_window("BC_WindowBase::dispatch_event 1");
912 locking_event = event->type;
913 locking_task = pthread_self();
914 locking_message = event->xclient.message_type;
915         }
916         else
917 // Handle compressed events
918         {
919                 lock_window("BC_WindowBase::dispatch_event 2");
920                 if(resize_events)
921                         dispatch_resize_event(last_resize_w, last_resize_h);
922                 if(motion_events)
923                         dispatch_motion_event();
924                 if(translation_events)
925                         dispatch_translation_event();
926
927                 unlock_window();
928                 return 0;
929         }
930
931 #endif
932
933
934
935
936 //static const char *event_names[] = {
937 //  "Reply", "Error", "KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease", "MotionNotify",
938 //  "EnterNotify", "LeaveNotify", "FocusIn", "FocusOut", "KeymapNotify", "Expose", "GraphicsExpose",
939 //  "NoExpose", "VisibilityNotify", "CreateNotify", "DestroyNotify", "UnmapNotify", "MapNotify",
940 //  "MapRequest", "ReparentNotify", "ConfigureNotify", "ConfigureRequest", "GravityNotify",
941 //  "ResizeRequest", "CirculateNotify", "CirculateRequest", "PropertyNotify", "SelectionClear",
942 //  "SelectionRequest", "SelectionNotify", "ColormapNotify", "ClientMessage", "MappingNotify",
943 //  "GenericEvent", "LASTEvent",
944 //};
945 //
946 //if(debug)
947 //if(event->type != ClientMessage) {
948 // printf("BC_WindowBase::dispatch_event %d %s %p %d (%s)\n",
949 //__LINE__, title, event, event->type,
950 //  event->type>=0 && event->type<sizeof(event_names)/sizeof(event_names[0]) ?
951 //   event_names[event->type] : "Unknown");
952 //}
953
954         if( active_grab ) {
955                 unlock_window();
956                 active_grab->lock_window("BC_WindowBase::dispatch_event 3");
957                 result = active_grab->grab_event(event);
958                 active_grab->unlock_window();
959                 if( result ) return result;
960                 lock_window("BC_WindowBase::dispatch_event 4");
961         }
962
963         switch(event->type) {
964         case ClientMessage:
965 // Clear the resize buffer
966                 if(resize_events) dispatch_resize_event(last_resize_w, last_resize_h);
967 // Clear the motion buffer since this can clear the window
968                 if(motion_events)
969                 {
970                         dispatch_motion_event();
971                 }
972
973                 ptr = (XClientMessageEvent*)event;
974
975
976                 if(ptr->message_type == ProtoXAtom &&
977                         (Atom)ptr->data.l[0] == DelWinXAtom)
978                 {
979                         close_event();
980                 }
981                 else
982                 if(ptr->message_type == RepeaterXAtom)
983                 {
984                         dispatch_repeat_event(ptr->data.l[0]);
985 // Make sure the repeater still exists.
986 //                              for(int i = 0; i < repeaters.total; i++)
987 //                              {
988 //                                      if(repeaters.values[i]->repeat_id == ptr->data.l[0])
989 //                                      {
990 //                                              dispatch_repeat_event_master(ptr->data.l[0]);
991 //                                              break;
992 //                                      }
993 //                              }
994                 }
995                 else
996                 if(ptr->message_type == SetDoneXAtom)
997                 {
998                         done = 1;
999                         } else
1000                         { // We currently use X marshalling for xatom events, we can switch to something else later
1001                                 recieve_custom_xatoms((xatom_event *)ptr);
1002                 }
1003                 break;
1004
1005         case FocusIn:
1006                 has_focus = 1;
1007                 dispatch_focus_in();
1008                 break;
1009
1010         case FocusOut:
1011                 has_focus = 0;
1012                 dispatch_focus_out();
1013                 break;
1014
1015 // Maximized
1016         case MapNotify:
1017                 break;
1018
1019 // Minimized
1020         case UnmapNotify:
1021                 break;
1022
1023         case ButtonPress:
1024                 if(motion_events)
1025                 {
1026                         dispatch_motion_event();
1027                 }
1028                 get_key_masks(event->xbutton.state);
1029                 cursor_x = event->xbutton.x;
1030                 cursor_y = event->xbutton.y;
1031                 button_number = event->xbutton.button;
1032
1033 //printf("BC_WindowBase::dispatch_event %d %d\n", __LINE__, button_number);
1034                 event_win = event->xany.window;
1035                 if (button_number < 6)
1036                 {
1037                         if(button_number < 4)
1038                                 button_down = 1;
1039                         button_pressed = event->xbutton.button;
1040                         button_time1 = button_time2;
1041                         button_time2 = button_time3;
1042                         button_time3 = event->xbutton.time;
1043                         drag_x = cursor_x;
1044                         drag_y = cursor_y;
1045                         drag_win = event_win;
1046                         drag_x1 = cursor_x - get_resources()->drag_radius;
1047                         drag_x2 = cursor_x + get_resources()->drag_radius;
1048                         drag_y1 = cursor_y - get_resources()->drag_radius;
1049                         drag_y2 = cursor_y + get_resources()->drag_radius;
1050
1051                         if((long)(button_time3 - button_time1) < resources.double_click * 2)
1052                         {
1053                                 triple_click = 1;
1054                                 button_time3 = button_time2 = button_time1 = 0;
1055                         }
1056                         if((long)(button_time3 - button_time2) < resources.double_click)
1057                         {
1058                                 double_click = 1;
1059 //                              button_time3 = button_time2 = button_time1 = 0;
1060                         }
1061                         else
1062                         {
1063                                 triple_click = 0;
1064                                 double_click = 0;
1065                         }
1066
1067                         dispatch_button_press();
1068                 }
1069                 break;
1070
1071         case ButtonRelease:
1072                 if(motion_events)
1073                 {
1074                         dispatch_motion_event();
1075                 }
1076                 get_key_masks(event->xbutton.state);
1077                 button_number = event->xbutton.button;
1078                 event_win = event->xany.window;
1079                 if (button_number < 6)
1080                 {
1081                         if(button_number < 4)
1082                                 button_down = 0;
1083 //printf("BC_WindowBase::dispatch_event %d %d\n", __LINE__, button_number);
1084
1085                         dispatch_button_release();
1086                 }
1087                 break;
1088
1089         case Expose:
1090                 event_win = event->xany.window;
1091                 dispatch_expose_event();
1092                 break;
1093
1094         case MotionNotify:
1095                 get_key_masks(event->xmotion.state);
1096 // Dispatch previous motion event if this is a subsequent motion from a different window
1097                 if(motion_events && last_motion_win != event->xany.window)
1098                 {
1099                         dispatch_motion_event();
1100                 }
1101
1102 // Buffer the current motion
1103                 motion_events = 1;
1104                 last_motion_state = event->xmotion.state;
1105                 last_motion_x = event->xmotion.x;
1106                 last_motion_y = event->xmotion.y;
1107                 last_motion_win = event->xany.window;
1108                 break;
1109
1110         case ConfigureNotify:
1111 // printf("BC_WindowBase::dispatch_event %d win=%p this->win=%p\n",
1112 // __LINE__,
1113 // event->xany.window,
1114 // win);
1115 // dump_windows();
1116                 XTranslateCoordinates(top_level->display,
1117                         top_level->win,
1118                         top_level->rootwin,
1119                         0,
1120                         0,
1121                         &last_translate_x,
1122                         &last_translate_y,
1123                         &tempwin);
1124                 last_resize_w = event->xconfigure.width;
1125                 last_resize_h = event->xconfigure.height;
1126
1127                 cancel_resize = 0;
1128                 cancel_translation = 0;
1129
1130 // Resize history prevents responses to recursive resize requests
1131                 for(int i = 0; i < resize_history.total && !cancel_resize; i++)
1132                 {
1133                         if(resize_history.values[i]->w == last_resize_w &&
1134                                 resize_history.values[i]->h == last_resize_h)
1135                         {
1136                                 delete resize_history.values[i];
1137                                 resize_history.remove_number(i);
1138                                 cancel_resize = 1;
1139                         }
1140                 }
1141
1142                 if(last_resize_w == w && last_resize_h == h)
1143                         cancel_resize = 1;
1144
1145                 if(!cancel_resize)
1146                 {
1147                         resize_events = 1;
1148                 }
1149
1150                 if((last_translate_x == x && last_translate_y == y))
1151                         cancel_translation = 1;
1152
1153                 if(!cancel_translation)
1154                 {
1155                         translation_events = 1;
1156                 }
1157
1158                 translation_count++;
1159                 break;
1160
1161         case KeyPress:
1162                 get_key_masks(event->xkey.state);
1163                 keys_return[0] = 0;  keysym = -1;
1164                 if(XFilterEvent(event, win)) {
1165                         break;
1166                 }
1167                 if( keysym_lookup(event) < 0 ) {
1168                         printf("keysym %x\n", (uint32_t)keysym);
1169                         break;
1170                 }
1171
1172 //printf("BC_WindowBase::dispatch_event %d keysym=0x%x\n",
1173 //__LINE__,
1174 //keysym);
1175
1176 // block out control keys
1177                 if(keysym > 0xffe0 && keysym < 0xffff) break;
1178 // block out Alt_GR key
1179                 if(keysym == 0xfe03) break;
1180
1181                 if(test_keypress)
1182                          printf("BC_WindowBase::dispatch_event %x\n", (uint32_t)keysym);
1183
1184 #ifdef X_HAVE_UTF8_STRING
1185 //It's Ascii or UTF8?
1186 //              if (keysym != 0xffff && (keys_return[0] & 0xff) >= 0x7f )
1187 //printf("BC_WindowBase::dispatch_event %d %02x%02x\n", __LINE__, keys_return[0], keys_return[1]);
1188
1189                 if( ((keys_return[1] & 0xff) > 0x80) &&
1190                     ((keys_return[0] & 0xff) > 0xC0) ) {
1191 //printf("BC_WindowBase::dispatch_event %d\n", __LINE__);
1192                         key_pressed = keysym & 0xff;
1193                 }
1194                 else {
1195 #endif
1196
1197                 switch(keysym) {
1198 // block out extra keys
1199                 case XK_Alt_L:
1200                 case XK_Alt_R:
1201                 case XK_Shift_L:
1202                 case XK_Shift_R:
1203                 case XK_Control_L:
1204                 case XK_Control_R:
1205                         key_pressed = 0;
1206                         break;
1207
1208 // Translate key codes
1209                 case XK_Return:         key_pressed = RETURN;   break;
1210                 case XK_Up:             key_pressed = UP;       break;
1211                 case XK_Down:           key_pressed = DOWN;     break;
1212                 case XK_Left:           key_pressed = LEFT;     break;
1213                 case XK_Right:          key_pressed = RIGHT;    break;
1214                 case XK_Next:           key_pressed = PGDN;     break;
1215                 case XK_Prior:          key_pressed = PGUP;     break;
1216                 case XK_BackSpace:      key_pressed = BACKSPACE; break;
1217                 case XK_Escape:         key_pressed = ESC;      break;
1218                 case XK_Tab:
1219                         if(shift_down())
1220                                 key_pressed = LEFTTAB;
1221                         else
1222                                 key_pressed = TAB;
1223                         break;
1224                 case XK_ISO_Left_Tab:   key_pressed = LEFTTAB;  break;
1225                 case XK_underscore:     key_pressed = '_';      break;
1226                 case XK_asciitilde:     key_pressed = '~';      break;
1227                 case XK_Delete:         key_pressed = DELETE;   break;
1228                 case XK_Home:           key_pressed = HOME;     break;
1229                 case XK_End:            key_pressed = END;      break;
1230
1231 // number pad
1232                 case XK_KP_Enter:       key_pressed = KPENTER;  break;
1233                 case XK_KP_Add:         key_pressed = KPPLUS;   break;
1234                 case XK_KP_Subtract:    key_pressed = KPMINUS;  break;
1235                 case XK_KP_Multiply:    key_pressed = KPSTAR;   break;
1236                 case XK_KP_Divide:      key_pressed = KPSLASH;  break;
1237                 case XK_KP_1:
1238                 case XK_KP_End:         key_pressed = KP1;      break;
1239                 case XK_KP_2:
1240                 case XK_KP_Down:        key_pressed = KP2;      break;
1241                 case XK_KP_3:
1242                 case XK_KP_Page_Down:   key_pressed = KP3;      break;
1243                 case XK_KP_4:
1244                 case XK_KP_Left:        key_pressed = KP4;      break;
1245                 case XK_KP_5:
1246                 case XK_KP_Begin:       key_pressed = KP5;      break;
1247                 case XK_KP_6:
1248                 case XK_KP_Right:       key_pressed = KP6;      break;
1249                 case XK_KP_7:
1250                 case XK_KP_Home:        key_pressed = KP7;      break;
1251                 case XK_KP_8:
1252                 case XK_KP_Up:          key_pressed = KP8;      break;
1253                 case XK_KP_9:
1254                 case XK_KP_Page_Up:     key_pressed = KP9;      break;
1255                 case XK_KP_0:
1256                 case XK_KP_Insert:      key_pressed = KPINS;    break;
1257                 case XK_KP_Decimal:
1258                 case XK_KP_Delete:      key_pressed = KPDEL;    break;
1259
1260                 case XK_F1:             key_pressed = KEY_F1;   break;
1261                 case XK_F2:             key_pressed = KEY_F2;   break;
1262                 case XK_F3:             key_pressed = KEY_F3;   break;
1263                 case XK_F4:             key_pressed = KEY_F4;   break;
1264                 case XK_F5:             key_pressed = KEY_F5;   break;
1265                 case XK_F6:             key_pressed = KEY_F6;   break;
1266                 case XK_F7:             key_pressed = KEY_F7;   break;
1267                 case XK_F8:             key_pressed = KEY_F8;   break;
1268                 case XK_F9:             key_pressed = KEY_F9;   break;
1269                 case XK_F10:            key_pressed = KEY_F10;  break;
1270                 case XK_F11:            key_pressed = KEY_F11;  break;
1271                 case XK_F12:            key_pressed = KEY_F12;  break;
1272
1273                 case XK_Menu:           key_pressed = KPMENU;   break;  /* menu */
1274 // remote control
1275 // above        case XK_KP_Enter:       key_pressed = KPENTER;  break;  /* check */
1276                 case XF86XK_MenuKB:     key_pressed = KPMENU;   break;  /* menu */
1277 // intercepted  case XF86XK_PowerDown: key_pressed = KPPOWER;   break;  /* Power */
1278                 case XF86XK_Launch1:    key_pressed = KPTV;     break;  /* TV */
1279                 case XF86XK_Launch2:    key_pressed = KPDVD;    break;  /* DVD */
1280 // intercepted  case XF86XK_WWW:        key_pressed = KPWWEB;   break;  /* WEB */
1281                 case XF86XK_Launch3:    key_pressed = KPBOOK;   break;  /* book */
1282                 case XF86XK_Launch4:    key_pressed = KPHAND;   break;  /* hand */
1283                 case XF86XK_Reply:      key_pressed = KPTMR;    break;  /* timer */
1284                 case SunXK_Front:       key_pressed = KPMAXW;   break;  /* max */
1285 // above        case XK_Left:           key_pressed = LEFT;     break;  /* left */
1286 // above        case XK_Right:          key_pressed = RIGHT;    break;  /* right */
1287 // above        case XK_Down:           key_pressed = DOWN;     break;  /* down */
1288 // above        case XK_Up:             key_pressed = UP;       break;  /* up */
1289 // above        case XK_SPACE:          key_pressed = KPSPACE;  break;  /* ok */
1290 // intercepted  case XF86XK_AudioRaiseVolume: key_pressed = KPVOLU;     break;  /* VOL + */
1291 // intercepted  case XF86XK_AudioMute: key_pressed = KPMUTE;    break;  /* MUTE */
1292 // intercepted  case XF86XK_AudioLowerVolume: key_pressed = KPVOLD;     break;  /* VOL - */
1293                 case XF86XK_ScrollUp:   key_pressed = KPCHUP;   break;  /* CH + */
1294                 case XF86XK_ScrollDown: key_pressed = KPCHDN;   break;  /* CH - */
1295                 case XF86XK_AudioRecord: key_pressed = KPRECD;  break;  /* ( o) red */
1296                 case XF86XK_Forward:    key_pressed = KPPLAY;   break;  /* ( >) */
1297                 case XK_Redo:           key_pressed = KPFWRD;   break;  /* (>>) */
1298                 case XF86XK_Back:       key_pressed = KPBACK;   break;  /* (<<) */
1299                 case XK_Cancel:         key_pressed = KPSTOP;   break;  /* ([]) */
1300                 case XK_Pause:          key_pressed = KPAUSE;   break;  /* ('') */
1301
1302                 default:
1303                         key_pressed = keysym & 0xff;
1304 #ifdef X_HAVE_UTF8_STRING
1305 //printf("BC_WindowBase::dispatch_event %d\n", __LINE__);
1306                         keys_return[1] = 0;
1307 #endif
1308                         break;
1309                 }
1310 #ifdef X_HAVE_UTF8_STRING
1311                 }
1312                 key_pressed_utf8 = keys_return;
1313 #endif
1314
1315
1316                 result = 0;
1317                 if( top_level == this )
1318                         result = BC_KeyboardHandler::run_listeners(this);
1319
1320 //printf("BC_WindowBase::dispatch_event %d %d %x\n", shift_down(), alt_down(), key_pressed);
1321                 if( !result )
1322                         result = dispatch_keypress_event();
1323 // Handle some default keypresses
1324                 if(!result)
1325                 {
1326                         if(key_pressed == 'w' ||
1327                                 key_pressed == 'W')
1328                         {
1329                                 close_event();
1330                         }
1331                 }
1332                 break;
1333
1334         case KeyRelease:
1335                 XLookupString((XKeyEvent*)event, keys_return, 1, &keysym, 0);
1336                 dispatch_keyrelease_event();
1337 // printf("BC_WindowBase::dispatch_event KeyRelease keysym=0x%x keystate=0x%lld\n",
1338 // keysym, event->xkey.state);
1339                 break;
1340
1341         case LeaveNotify:
1342                 if( cursor_entered && event->xcrossing.window == win ) {
1343                         cursor_entered = 0;
1344                 }
1345                 event_win = event->xany.window;
1346                 dispatch_cursor_leave();
1347                 break;
1348
1349         case EnterNotify:
1350                 if( !cursor_entered && event->xcrossing.window == win ) {
1351                         if( !event->xcrossing.focus && get_resources()->grab_input_focus ) {
1352                                 XSetInputFocus(display, win, RevertToParent, CurrentTime);
1353                         }
1354                         cursor_entered = 1;
1355                 }
1356                 event_win = event->xany.window;
1357                 cursor_x = event->xcrossing.x;
1358                 cursor_y = event->xcrossing.y;
1359                 dispatch_cursor_enter();
1360                 break;
1361
1362         default:
1363                 break;
1364         }
1365 //printf("100 %s %p %d\n", title, event, event->type);
1366 //if(event->type != ClientMessage) dump();
1367
1368 #ifndef SINGLE_THREAD
1369         unlock_window();
1370         if(event) {
1371                 if( resend_event_window ) {
1372                         resend_event_window->put_event(event);
1373                         resend_event_window = 0;
1374                 }
1375                 else
1376                         delete event;
1377         }
1378 #else
1379 //      if(done) completion_lock->unlock();
1380 #endif
1381
1382 if(debug) printf("BC_WindowBase::dispatch_event this=%p %d\n", this, __LINE__);
1383         return 0;
1384 }
1385
1386 int BC_WindowBase::dispatch_expose_event()
1387 {
1388         int result = 0;
1389         for(int i = 0; i < subwindows->total && !result; i++)
1390         {
1391                 result = subwindows->values[i]->dispatch_expose_event();
1392         }
1393
1394 // Propagate to user
1395         if(!result) expose_event();
1396         return result;
1397 }
1398
1399 int BC_WindowBase::dispatch_resize_event(int w, int h)
1400 {
1401 // Can't store new w and h until the event is handles
1402 // because bcfilebox depends on the old w and h to
1403 // reposition widgets.
1404         if( window_type == MAIN_WINDOW ) {
1405                 flash_enabled = 0;
1406                 resize_events = 0;
1407
1408                 delete pixmap;
1409                 pixmap = new BC_Pixmap(this, w, h);
1410                 clear_box(0, 0, w, h);
1411         }
1412
1413 // Propagate to subwindows
1414         for(int i = 0; i < subwindows->total; i++) {
1415                 subwindows->values[i]->dispatch_resize_event(w, h);
1416         }
1417
1418 // Propagate to user
1419         resize_event(w, h);
1420
1421         if( window_type == MAIN_WINDOW ) {
1422                 this->w = w;
1423                 this->h = h;
1424                 dispatch_flash();
1425                 flush();
1426         }
1427         return 0;
1428 }
1429
1430 int BC_WindowBase::dispatch_flash()
1431 {
1432         flash_enabled = 1;
1433         for(int i = 0; i < subwindows->total; i++)
1434                 subwindows->values[i]->dispatch_flash();
1435         return flash(0);
1436 }
1437
1438 int BC_WindowBase::dispatch_translation_event()
1439 {
1440         translation_events = 0;
1441         if(window_type == MAIN_WINDOW)
1442         {
1443                 prev_x = x;
1444                 prev_y = y;
1445                 x = last_translate_x;
1446                 y = last_translate_y;
1447 // Correct for window manager offsets
1448                 x -= x_correction;
1449                 y -= y_correction;
1450         }
1451
1452         for(int i = 0; i < subwindows->total; i++)
1453         {
1454                 subwindows->values[i]->dispatch_translation_event();
1455         }
1456
1457         translation_event();
1458         return 0;
1459 }
1460
1461 int BC_WindowBase::dispatch_motion_event()
1462 {
1463         int result = 0;
1464         unhide_cursor();
1465
1466         if(top_level == this)
1467         {
1468                 motion_events = 0;
1469                 event_win = last_motion_win;
1470                 get_key_masks(last_motion_state);
1471
1472 // Test for grab
1473                 if(get_button_down() && !active_menubar && !active_popup_menu)
1474                 {
1475                         if(!result)
1476                         {
1477                                 cursor_x = last_motion_x;
1478                                 cursor_y = last_motion_y;
1479                                 result = dispatch_drag_motion();
1480                         }
1481
1482                         if(!result &&
1483                                 (last_motion_x < drag_x1 || last_motion_x >= drag_x2 ||
1484                                 last_motion_y < drag_y1 || last_motion_y >= drag_y2))
1485                         {
1486                                 cursor_x = drag_x;
1487                                 cursor_y = drag_y;
1488
1489                                 result = dispatch_drag_start();
1490                         }
1491                 }
1492
1493                 cursor_x = last_motion_x;
1494                 cursor_y = last_motion_y;
1495
1496 // printf("BC_WindowBase::dispatch_motion_event %d %p %p %p\n",
1497 // __LINE__,
1498 // active_menubar,
1499 // active_popup_menu,
1500 // active_subwindow);
1501
1502                 if(active_menubar && !result) result = active_menubar->dispatch_motion_event();
1503                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_motion_event();
1504                 if(active_subwindow && !result) result = active_subwindow->dispatch_motion_event();
1505         }
1506
1507 // Dispatch in stacking order
1508         for(int i = subwindows->size() - 1; i >= 0 && !result; i--)
1509         {
1510                 result = subwindows->values[i]->dispatch_motion_event();
1511         }
1512
1513         if(!result) result = cursor_motion_event();    // give to user
1514         return result;
1515 }
1516
1517 int BC_WindowBase::dispatch_keypress_event()
1518 {
1519         int result = 0;
1520         if(top_level == this)
1521         {
1522                 if(active_subwindow) result = active_subwindow->dispatch_keypress_event();
1523         }
1524
1525         for(int i = 0; i < subwindows->total && !result; i++)
1526         {
1527                 result = subwindows->values[i]->dispatch_keypress_event();
1528         }
1529
1530         if(!result) result = keypress_event();
1531
1532         return result;
1533 }
1534
1535 int BC_WindowBase::dispatch_keyrelease_event()
1536 {
1537         int result = 0;
1538         if(top_level == this)
1539         {
1540                 if(active_subwindow) result = active_subwindow->dispatch_keyrelease_event();
1541         }
1542
1543         for(int i = 0; i < subwindows->total && !result; i++)
1544         {
1545                 result = subwindows->values[i]->dispatch_keyrelease_event();
1546         }
1547
1548         if(!result) result = keyrelease_event();
1549
1550         return result;
1551 }
1552
1553 int BC_WindowBase::dispatch_focus_in()
1554 {
1555         for(int i = 0; i < subwindows->total; i++)
1556         {
1557                 subwindows->values[i]->dispatch_focus_in();
1558         }
1559
1560         focus_in_event();
1561
1562         return 0;
1563 }
1564
1565 int BC_WindowBase::dispatch_focus_out()
1566 {
1567         for(int i = 0; i < subwindows->total; i++)
1568         {
1569                 subwindows->values[i]->dispatch_focus_out();
1570         }
1571
1572         focus_out_event();
1573
1574         return 0;
1575 }
1576
1577 int BC_WindowBase::get_has_focus()
1578 {
1579         return top_level->has_focus;
1580 }
1581
1582 int BC_WindowBase::get_deleting()
1583 {
1584         if(is_deleting) return 1;
1585         if(parent_window && parent_window->get_deleting()) return 1;
1586         return 0;
1587 }
1588
1589 int BC_WindowBase::dispatch_button_press()
1590 {
1591         int result = 0;
1592
1593
1594         if(top_level == this)
1595         {
1596                 if(active_menubar) result = active_menubar->dispatch_button_press();
1597                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_button_press();
1598                 if(active_subwindow && !result) result = active_subwindow->dispatch_button_press();
1599         }
1600
1601         for(int i = 0; i < subwindows->total && !result; i++)
1602         {
1603                 result = subwindows->values[i]->dispatch_button_press();
1604         }
1605
1606         if(!result) result = button_press_event();
1607
1608
1609         return result;
1610 }
1611
1612 int BC_WindowBase::dispatch_button_release()
1613 {
1614         int result = 0;
1615         if(top_level == this)
1616         {
1617                 if(active_menubar) result = active_menubar->dispatch_button_release();
1618                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_button_release();
1619                 if(active_subwindow && !result) result = active_subwindow->dispatch_button_release();
1620                 if(!result && button_number != 4 && button_number != 5)
1621                         result = dispatch_drag_stop();
1622         }
1623
1624         for(int i = 0; i < subwindows->total && !result; i++)
1625         {
1626                 result = subwindows->values[i]->dispatch_button_release();
1627         }
1628
1629         if(!result)
1630         {
1631                 result = button_release_event();
1632         }
1633
1634         return result;
1635 }
1636
1637
1638 int BC_WindowBase::dispatch_repeat_event(int64_t duration)
1639 {
1640
1641 // all repeat event handlers get called and decide based on activity and duration
1642 // whether to respond
1643         for(int i = 0; i < subwindows->total; i++)
1644         {
1645                 subwindows->values[i]->dispatch_repeat_event(duration);
1646         }
1647
1648
1649         repeat_event(duration);
1650
1651
1652
1653 // Unlock next repeat signal
1654         if(window_type == MAIN_WINDOW)
1655         {
1656 #ifdef SINGLE_THREAD
1657                 BC_Display::display_global->unlock_repeaters(duration);
1658 #else
1659                 for(int i = 0; i < repeaters.total; i++)
1660                 {
1661                         if(repeaters.values[i]->delay == duration)
1662                         {
1663                                 repeaters.values[i]->repeat_lock->unlock();
1664                         }
1665                 }
1666 #endif
1667         }
1668         return 0;
1669 }
1670
1671 void BC_WindowBase::unhide_cursor()
1672 {
1673         if(is_transparent)
1674         {
1675                 is_transparent = 0;
1676                 if(top_level->is_hourglass)
1677                         set_cursor(HOURGLASS_CURSOR, 1, 0);
1678                 else
1679                         set_cursor(current_cursor, 1, 0);
1680         }
1681         cursor_timer->update();
1682 }
1683
1684
1685 void BC_WindowBase::update_video_cursor()
1686 {
1687         if(video_on && !is_transparent)
1688         {
1689                 if(cursor_timer->get_difference() > VIDEO_CURSOR_TIMEOUT && !is_transparent)
1690                 {
1691                         is_transparent = 1;
1692                         set_cursor(TRANSPARENT_CURSOR, 1, 1);
1693                         cursor_timer->update();
1694                 }
1695         }
1696         else
1697         {
1698                 cursor_timer->update();
1699         }
1700 }
1701
1702
1703 int BC_WindowBase::dispatch_cursor_leave()
1704 {
1705         unhide_cursor();
1706
1707         for(int i = 0; i < subwindows->total; i++)
1708         {
1709                 subwindows->values[i]->dispatch_cursor_leave();
1710         }
1711
1712         cursor_leave_event();
1713         return 0;
1714 }
1715
1716 int BC_WindowBase::dispatch_cursor_enter()
1717 {
1718         int result = 0;
1719
1720         unhide_cursor();
1721
1722         if(active_menubar) result = active_menubar->dispatch_cursor_enter();
1723         if(!result && active_popup_menu) result = active_popup_menu->dispatch_cursor_enter();
1724         if(!result && active_subwindow) result = active_subwindow->dispatch_cursor_enter();
1725
1726         for(int i = 0; !result && i < subwindows->total; i++)
1727         {
1728                 result = subwindows->values[i]->dispatch_cursor_enter();
1729         }
1730
1731         if(!result) result = cursor_enter_event();
1732         return result;
1733 }
1734
1735 int BC_WindowBase::cursor_enter_event()
1736 {
1737         return 0;
1738 }
1739
1740 int BC_WindowBase::cursor_leave_event()
1741 {
1742         return 0;
1743 }
1744
1745 int BC_WindowBase::close_event()
1746 {
1747         set_done(1);
1748         return 1;
1749 }
1750
1751 int BC_WindowBase::dispatch_drag_start()
1752 {
1753         int result = 0;
1754         if(active_menubar) result = active_menubar->dispatch_drag_start();
1755         if(!result && active_popup_menu) result = active_popup_menu->dispatch_drag_start();
1756         if(!result && active_subwindow) result = active_subwindow->dispatch_drag_start();
1757
1758         for(int i = 0; i < subwindows->total && !result; i++)
1759         {
1760                 result = subwindows->values[i]->dispatch_drag_start();
1761         }
1762
1763         if(!result) result = is_dragging = drag_start_event();
1764         return result;
1765 }
1766
1767 int BC_WindowBase::dispatch_drag_stop()
1768 {
1769         int result = 0;
1770
1771         for(int i = 0; i < subwindows->total && !result; i++)
1772         {
1773                 result = subwindows->values[i]->dispatch_drag_stop();
1774         }
1775
1776         if(is_dragging && !result)
1777         {
1778                 drag_stop_event();
1779                 is_dragging = 0;
1780                 result = 1;
1781         }
1782
1783         return result;
1784 }
1785
1786 int BC_WindowBase::dispatch_drag_motion()
1787 {
1788         int result = 0;
1789         for(int i = 0; i < subwindows->total && !result; i++)
1790         {
1791                 result = subwindows->values[i]->dispatch_drag_motion();
1792         }
1793
1794         if(is_dragging && !result)
1795         {
1796                 drag_motion_event();
1797                 result = 1;
1798         }
1799
1800         return result;
1801 }
1802
1803
1804 int BC_WindowBase::show_tooltip(const char *text, int x, int y, int w, int h)
1805 {
1806 // default text
1807         int forced = !text ? force_tooltip : 1;
1808         if( !text ) text = tooltip_text;
1809         if( !text || (!forced && !get_resources()->tooltips_enabled) ) {
1810                 top_level->hide_tooltip();
1811                 return 1;
1812         }
1813 // default w,h
1814         if(w < 0) w = get_text_width(MEDIUMFONT, text)  + TOOLTIP_MARGIN * 2;
1815         if(h < 0) h = get_text_height(MEDIUMFONT, text) + TOOLTIP_MARGIN * 2;
1816 // default x,y (win relative)
1817         if( x < 0 ) x = get_w();
1818         if( y < 0 ) y = get_h();
1819         int wx, wy;
1820         get_root_coordinates(x, y, &wx, &wy);
1821 // keep the tip inside the window/display
1822         int x0 = top_level->get_x(), x1 = x0 + top_level->get_w();
1823         int x2 = top_level->get_screen_x(0, -1) + top_level->get_screen_w(0, -1);
1824         if( x1 > x2 ) x1 = x2;
1825         if( wx < x0 ) wx = x0;
1826         if( wx >= (x1-=w) ) wx = x1;
1827         int y0 = top_level->get_y(), y1 = y0 + top_level->get_h();
1828         int y2 = top_level->get_root_h(0);
1829         if( y1 > y2 ) y1 = y2;
1830         if( wy < y0 ) wy = y0;
1831         if( wy >= (y1-=h) ) wy = y1;
1832 // avoid tip under cursor (flickers)
1833         int abs_x, abs_y;
1834         get_abs_cursor(abs_x,abs_y, 0);
1835         if( wx < abs_x && abs_x < wx+w && wy < abs_y && abs_y < wy+h ) {
1836                 if( wx-abs_x < wy-abs_y )
1837                         wx = abs_x+1;
1838                 else
1839                         wy = abs_y+1;
1840         }
1841         if( !tooltip_on ) {
1842                 tooltip_on = 1;
1843                 tooltip_popup = new BC_Popup(top_level, wx, wy, w, h,
1844                                 get_resources()->tooltip_bg_color);
1845         }
1846         else
1847                 tooltip_popup->reposition_window(wx, wy, w, h);
1848
1849         draw_tooltip(text);
1850         tooltip_popup->flash();
1851         tooltip_popup->flush();
1852         return 0;
1853 }
1854
1855 int BC_WindowBase::hide_tooltip()
1856 {
1857         if(subwindows)
1858                 for(int i = 0; i < subwindows->total; i++)
1859                 {
1860                         subwindows->values[i]->hide_tooltip();
1861                 }
1862
1863         if(tooltip_on)
1864         {
1865                 tooltip_on = 0;
1866                 delete tooltip_popup;
1867                 tooltip_popup = 0;
1868         }
1869         return 0;
1870 }
1871
1872 const char *BC_WindowBase::get_tooltip()
1873 {
1874         return tooltip_text;
1875 }
1876
1877 int BC_WindowBase::set_tooltip(const char *text)
1878 {
1879         tooltip_text = text;
1880
1881 // Update existing tooltip if it is visible
1882         if(tooltip_on)
1883         {
1884                 draw_tooltip();
1885                 tooltip_popup->flash();
1886         }
1887         return 0;
1888 }
1889 // signal the event handler to repeat
1890 int BC_WindowBase::set_repeat(int64_t duration)
1891 {
1892         if(duration <= 0)
1893         {
1894                 printf("BC_WindowBase::set_repeat duration=%jd\n", duration);
1895                 return 0;
1896         }
1897         if(window_type != MAIN_WINDOW) return top_level->set_repeat(duration);
1898
1899 #ifdef SINGLE_THREAD
1900         BC_Display::display_global->set_repeat(this, duration);
1901 #else
1902 // test repeater database for duplicates
1903         for(int i = 0; i < repeaters.total; i++)
1904         {
1905 // Already exists
1906                 if(repeaters.values[i]->delay == duration)
1907                 {
1908                         repeaters.values[i]->start_repeating(this);
1909                         return 0;
1910                 }
1911         }
1912
1913         BC_Repeater *repeater = new BC_Repeater(this, duration);
1914         repeater->initialize();
1915         repeaters.append(repeater);
1916         repeater->start_repeating();
1917 #endif
1918         return 0;
1919 }
1920
1921 int BC_WindowBase::unset_repeat(int64_t duration)
1922 {
1923         if(window_type != MAIN_WINDOW) return top_level->unset_repeat(duration);
1924
1925 #ifdef SINGLE_THREAD
1926         BC_Display::display_global->unset_repeat(this, duration);
1927 #else
1928         for(int i = 0; i < repeaters.total; i++)
1929         {
1930                 if(repeaters.values[i]->delay == duration)
1931                 {
1932                         repeaters.values[i]->stop_repeating();
1933                 }
1934         }
1935 #endif
1936         return 0;
1937 }
1938
1939
1940 int BC_WindowBase::unset_all_repeaters()
1941 {
1942 #ifdef SINGLE_THREAD
1943         BC_Display::display_global->unset_all_repeaters(this);
1944 #else
1945         for(int i = 0; i < repeaters.total; i++)
1946         {
1947                 repeaters.values[i]->stop_repeating();
1948         }
1949         repeaters.remove_all_objects();
1950 #endif
1951         return 0;
1952 }
1953
1954 // long BC_WindowBase::get_repeat_id()
1955 // {
1956 //      return top_level->next_repeat_id++;
1957 // }
1958
1959 XEvent *BC_WindowBase::new_xevent()
1960 {
1961         XEvent *event = new XEvent;
1962         memset(event, 0, sizeof(*event));
1963         return event;
1964 }
1965
1966 #ifndef SINGLE_THREAD
1967 int BC_WindowBase::arm_repeat(int64_t duration)
1968 {
1969         XEvent *event = new_xevent();
1970         XClientMessageEvent *ptr = (XClientMessageEvent*)event;
1971         ptr->type = ClientMessage;
1972         ptr->message_type = RepeaterXAtom;
1973         ptr->format = 32;
1974         ptr->data.l[0] = duration;
1975
1976 // Couldn't use XSendEvent since it locked up randomly.
1977         put_event(event);
1978         return 0;
1979 }
1980 #endif
1981
1982 int BC_WindowBase::recieve_custom_xatoms(xatom_event *event)
1983 {
1984         return 0;
1985 }
1986
1987 int BC_WindowBase::send_custom_xatom(xatom_event *event)
1988 {
1989 #ifndef SINGLE_THREAD
1990         XEvent *myevent = new_xevent();
1991         XClientMessageEvent *ptr = (XClientMessageEvent*)myevent;
1992         ptr->type = ClientMessage;
1993         ptr->message_type = event->message_type;
1994         ptr->format = event->format;
1995         ptr->data.l[0] = event->data.l[0];
1996         ptr->data.l[1] = event->data.l[1];
1997         ptr->data.l[2] = event->data.l[2];
1998         ptr->data.l[3] = event->data.l[3];
1999         ptr->data.l[4] = event->data.l[4];
2000
2001         put_event(myevent);
2002 #endif
2003         return 0;
2004 }
2005
2006
2007
2008 Atom BC_WindowBase::create_xatom(const char *atom_name)
2009 {
2010         return XInternAtom(display, atom_name, False);
2011 }
2012
2013 int BC_WindowBase::get_atoms()
2014 {
2015         SetDoneXAtom =  XInternAtom(display, "BC_REPEAT_EVENT", False);
2016         RepeaterXAtom = XInternAtom(display, "BC_CLOSE_EVENT", False);
2017         DestroyAtom =   XInternAtom(display, "BC_DESTROY_WINDOW", False);
2018         DelWinXAtom =   XInternAtom(display, "WM_DELETE_WINDOW", False);
2019         if( (ProtoXAtom = XInternAtom(display, "WM_PROTOCOLS", False)) != 0 )
2020                 XChangeProperty(display, win, ProtoXAtom, XA_ATOM, 32,
2021                         PropModeReplace, (unsigned char *)&DelWinXAtom, True);
2022         return 0;
2023
2024 }
2025
2026
2027 void BC_WindowBase::init_cursors()
2028 {
2029         arrow_cursor = XCreateFontCursor(display, XC_top_left_arrow);
2030         cross_cursor = XCreateFontCursor(display, XC_crosshair);
2031         ibeam_cursor = XCreateFontCursor(display, XC_xterm);
2032         vseparate_cursor = XCreateFontCursor(display, XC_sb_v_double_arrow);
2033         hseparate_cursor = XCreateFontCursor(display, XC_sb_h_double_arrow);
2034         move_cursor = XCreateFontCursor(display, XC_fleur);
2035         left_cursor = XCreateFontCursor(display, XC_sb_left_arrow);
2036         right_cursor = XCreateFontCursor(display, XC_sb_right_arrow);
2037         upright_arrow_cursor = XCreateFontCursor(display, XC_arrow);
2038         upleft_resize_cursor = XCreateFontCursor(display, XC_top_left_corner);
2039         upright_resize_cursor = XCreateFontCursor(display, XC_top_right_corner);
2040         downleft_resize_cursor = XCreateFontCursor(display, XC_bottom_left_corner);
2041         downright_resize_cursor = XCreateFontCursor(display, XC_bottom_right_corner);
2042         hourglass_cursor = XCreateFontCursor(display, XC_watch);
2043         grabbed_cursor = create_grab_cursor();
2044
2045         static char cursor_data[] = { 0,0,0,0, 0,0,0,0 };
2046         Colormap colormap = DefaultColormap(display, screen);
2047         Pixmap pixmap_bottom = XCreateBitmapFromData(display,
2048                 rootwin, cursor_data, 8, 8);
2049         XColor black, dummy;
2050         XAllocNamedColor(display, colormap, "black", &black, &dummy);
2051         transparent_cursor = XCreatePixmapCursor(display,
2052                 pixmap_bottom, pixmap_bottom, &black, &black, 0, 0);
2053 //      XDefineCursor(display, win, transparent_cursor);
2054         XFreePixmap(display, pixmap_bottom);
2055 }
2056
2057 int BC_WindowBase::evaluate_color_model(int client_byte_order, int server_byte_order, int depth)
2058 {
2059         int color_model = BC_TRANSPARENCY;
2060         switch(depth)
2061         {
2062                 case 8:
2063                         color_model = BC_RGB8;
2064                         break;
2065                 case 16:
2066                         color_model = (server_byte_order == client_byte_order) ? BC_RGB565 : BC_BGR565;
2067                         break;
2068                 case 24:
2069                         color_model = server_byte_order ? BC_BGR888 : BC_RGB888;
2070                         break;
2071                 case 32:
2072                         color_model = server_byte_order ? BC_BGR8888 : BC_ARGB8888;
2073                         break;
2074         }
2075         return color_model;
2076 }
2077
2078 int BC_WindowBase::init_colors()
2079 {
2080         total_colors = 0;
2081         current_color_value = current_color_pixel = 0;
2082
2083 // Get the real depth
2084         char *data = 0;
2085         XImage *ximage;
2086         ximage = XCreateImage(top_level->display,
2087                                         top_level->vis,
2088                                         top_level->default_depth,
2089                                         ZPixmap,
2090                                         0,
2091                                         data,
2092                                         16,
2093                                         16,
2094                                         8,
2095                                         0);
2096         bits_per_pixel = ximage->bits_per_pixel;
2097         XDestroyImage(ximage);
2098
2099         color_model = evaluate_color_model(client_byte_order,
2100                 server_byte_order,
2101                 bits_per_pixel);
2102 // Get the color model
2103         switch(color_model)
2104         {
2105                 case BC_RGB8:
2106                         if(private_color)
2107                         {
2108                                 cmap = XCreateColormap(display, rootwin, vis, AllocNone);
2109                                 create_private_colors();
2110                         }
2111                         else
2112                         {
2113                                 cmap = DefaultColormap(display, screen);
2114                                 create_shared_colors();
2115                         }
2116
2117                         allocate_color_table();
2118                         break;
2119
2120                 default:
2121                         //cmap = DefaultColormap(display, screen);
2122                         cmap = XCreateColormap(display, rootwin, vis, AllocNone );
2123                         break;
2124         }
2125         return 0;
2126 }
2127
2128 int BC_WindowBase::create_private_colors()
2129 {
2130         int color;
2131         total_colors = 256;
2132
2133         for(int i = 0; i < 255; i++)
2134         {
2135                 color = (i & 0xc0) << 16;
2136                 color += (i & 0x38) << 10;
2137                 color += (i & 0x7) << 5;
2138                 color_table[i][0] = color;
2139         }
2140         create_shared_colors();        // overwrite the necessary colors on the table
2141         return 0;
2142 }
2143
2144
2145 int BC_WindowBase::create_color(int color)
2146 {
2147         if(total_colors == 256)
2148         {
2149 // replace the closest match with an exact match
2150                 color_table[get_color_rgb8(color)][0] = color;
2151         }
2152         else
2153         {
2154 // add the color to the table
2155                 color_table[total_colors][0] = color;
2156                 total_colors++;
2157         }
2158         return 0;
2159 }
2160
2161 int BC_WindowBase::create_shared_colors()
2162 {
2163         create_color(BLACK);
2164         create_color(WHITE);
2165
2166         create_color(LTGREY);
2167         create_color(MEGREY);
2168         create_color(MDGREY);
2169         create_color(DKGREY);
2170
2171         create_color(LTCYAN);
2172         create_color(MECYAN);
2173         create_color(MDCYAN);
2174         create_color(DKCYAN);
2175
2176         create_color(LTGREEN);
2177         create_color(GREEN);
2178         create_color(DKGREEN);
2179
2180         create_color(LTPINK);
2181         create_color(PINK);
2182         create_color(RED);
2183
2184         create_color(LTBLUE);
2185         create_color(BLUE);
2186         create_color(DKBLUE);
2187
2188         create_color(LTYELLOW);
2189         create_color(MEYELLOW);
2190         create_color(MDYELLOW);
2191         create_color(DKYELLOW);
2192
2193         create_color(LTPURPLE);
2194         create_color(MEPURPLE);
2195         create_color(MDPURPLE);
2196         create_color(DKPURPLE);
2197
2198         create_color(FGGREY);
2199         create_color(MNBLUE);
2200         create_color(ORANGE);
2201         create_color(FTGREY);
2202
2203         return 0;
2204 }
2205
2206 Cursor BC_WindowBase::create_grab_cursor()
2207 {
2208         int iw = 23, iw1 = iw-1, iw2 = iw/2;
2209         int ih = 23, ih1 = ih-1, ih2 = ih/2;
2210         VFrame grab(iw,ih,BC_RGB888);
2211         grab.clear_frame();
2212         grab.set_pixel_color(RED);   // fg
2213         grab.draw_smooth(iw2,0,   iw1,0,   iw1,ih2);
2214         grab.draw_smooth(iw1,ih2, iw1,ih1, iw2,ih1);
2215         grab.draw_smooth(iw2,ih1, 0,ih1,   0,ih2);
2216         grab.draw_smooth(0,ih2,   0,0,     iw2,0);
2217         grab.set_pixel_color(WHITE); // bg
2218         grab.draw_line(0,ih2,     iw2-2,ih2);
2219         grab.draw_line(iw2+2,ih2, iw1,ih2);
2220         grab.draw_line(iw2,0,     iw2,ih2-2);
2221         grab.draw_line(iw2,ih2+2, iw2,ih1);
2222
2223         int bpl = (iw+7)/8, isz = bpl * ih;
2224         char img[isz];  memset(img, 0, isz);
2225         char msk[isz];  memset(msk, 0, isz);
2226         unsigned char **rows = grab.get_rows();
2227         for( int iy=0; iy<ih; ++iy ) {
2228                 char *op = img + iy*bpl;
2229                 char *mp = msk + iy*bpl;
2230                 unsigned char *ip = rows[iy];
2231                 for( int ix=0; ix<iw; ++ix,ip+=3 ) {
2232                         if( ip[0] ) mp[ix>>3] |= (1<<(ix&7));
2233                         if( !ip[1] ) op[ix>>3] |= (1<<(ix&7));
2234                 }
2235         }
2236         unsigned long white_pix = WhitePixel(display, screen);
2237         unsigned long black_pix = BlackPixel(display, screen);
2238         Pixmap img_xpm = XCreatePixmapFromBitmapData(display, rootwin,
2239                 img, iw,ih, white_pix,black_pix, 1);
2240         Pixmap msk_xpm = XCreatePixmapFromBitmapData(display, rootwin,
2241                 msk, iw,ih, white_pix,black_pix, 1);
2242
2243         XColor fc, bc;
2244         fc.flags = bc.flags = DoRed | DoGreen | DoBlue;
2245         fc.red = 0xffff; fc.green = fc.blue = 0;  // fg
2246         bc.red = bc.green = bc.blue = 0x0000;     // bg
2247         Cursor cursor = XCreatePixmapCursor(display, img_xpm,msk_xpm, &fc,&bc, iw2,ih2);
2248         XFreePixmap(display, img_xpm);
2249         XFreePixmap(display, msk_xpm);
2250         return cursor;
2251 }
2252
2253 int BC_WindowBase::allocate_color_table()
2254 {
2255         int red, green, blue, color;
2256         XColor col;
2257
2258         for(int i = 0; i < total_colors; i++)
2259         {
2260                 color = color_table[i][0];
2261                 red = (color & 0xFF0000) >> 16;
2262                 green = (color & 0x00FF00) >> 8;
2263                 blue = color & 0xFF;
2264
2265                 col.flags = DoRed | DoGreen | DoBlue;
2266                 col.red   = red<<8   | red;
2267                 col.green = green<<8 | green;
2268                 col.blue  = blue<<8  | blue;
2269
2270                 XAllocColor(display, cmap, &col);
2271                 color_table[i][1] = col.pixel;
2272         }
2273
2274         XInstallColormap(display, cmap);
2275         return 0;
2276 }
2277
2278 int BC_WindowBase::init_window_shape()
2279 {
2280         if(bg_pixmap && bg_pixmap->use_alpha())
2281         {
2282                 XShapeCombineMask(top_level->display,
2283                         this->win, ShapeBounding, 0, 0,
2284                         bg_pixmap->get_alpha(), ShapeSet);
2285         }
2286         return 0;
2287 }
2288
2289
2290 int BC_WindowBase::init_gc()
2291 {
2292         unsigned long gcmask;
2293         gcmask = GCFont | GCGraphicsExposures;
2294
2295         XGCValues gcvalues;
2296         gcvalues.font = mediumfont->fid;        // set the font
2297         gcvalues.graphics_exposures = 0;        // prevent expose events for every redraw
2298         gc = XCreateGC(display, rootwin, gcmask, &gcvalues);
2299
2300 // gcmask = GCCapStyle | GCJoinStyle;
2301 // XGetGCValues(display, gc, gcmask, &gcvalues);
2302 // printf("BC_WindowBase::init_gc %d %d %d\n", __LINE__, gcvalues.cap_style, gcvalues.join_style);
2303         return 0;
2304 }
2305
2306 int BC_WindowBase::init_fonts()
2307 {
2308         if( !(smallfont = XLoadQueryFont(display, _(resources.small_font))) )
2309                 if( !(smallfont = XLoadQueryFont(display, _(resources.small_font2))) )
2310                         smallfont = XLoadQueryFont(display, "fixed");
2311         if( !(mediumfont = XLoadQueryFont(display, _(resources.medium_font))) )
2312                 if( !(mediumfont = XLoadQueryFont(display, _(resources.medium_font2))) )
2313                         mediumfont = XLoadQueryFont(display, "fixed");
2314         if( !(largefont = XLoadQueryFont(display, _(resources.large_font))) )
2315                 if( !(largefont = XLoadQueryFont(display, _(resources.large_font2))) )
2316                         largefont = XLoadQueryFont(display, "fixed");
2317         if( !(bigfont = XLoadQueryFont(display, _(resources.big_font))) )
2318                 if( !(bigfont = XLoadQueryFont(display, _(resources.big_font2))) )
2319                         bigfont = XLoadQueryFont(display, "fixed");
2320
2321         if((clockfont = XLoadQueryFont(display, _(resources.clock_font))) == NULL)
2322                 if((clockfont = XLoadQueryFont(display, _(resources.clock_font2))) == NULL)
2323                         clockfont = XLoadQueryFont(display, "fixed");
2324
2325         init_xft();
2326         if(get_resources()->use_fontset)
2327         {
2328                 char **m, *d;
2329                 int n;
2330
2331 // FIXME: should check the m,d,n values
2332                 smallfontset = XCreateFontSet(display, resources.small_fontset, &m, &n, &d);
2333                 if( !smallfontset )
2334                         smallfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2335                 mediumfontset = XCreateFontSet(display, resources.medium_fontset, &m, &n, &d);
2336                 if( !mediumfontset )
2337                         mediumfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2338                 largefontset = XCreateFontSet(display, resources.large_fontset, &m, &n, &d);
2339                 if( !largefontset )
2340                         largefontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2341                 bigfontset = XCreateFontSet(display, resources.big_fontset, &m, &n, &d);
2342                 if( !bigfontset )
2343                         bigfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2344                 clockfontset = XCreateFontSet(display, resources.clock_fontset, &m, &n, &d);
2345                 if( !clockfontset )
2346                         clockfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2347                 if(clockfontset && bigfontset && largefontset && mediumfontset && smallfontset) {
2348                         curr_fontset = mediumfontset;
2349                         get_resources()->use_fontset = 1;
2350                 }
2351                 else {
2352                         curr_fontset = 0;
2353                         get_resources()->use_fontset = 0;
2354                 }
2355         }
2356
2357         return 0;
2358 }
2359
2360 void BC_WindowBase::init_xft()
2361 {
2362 #ifdef HAVE_XFT
2363         if( !get_resources()->use_xft ) return;
2364 // apparently, xft is not reentrant, more than this is needed
2365 static Mutex xft_init_lock("BC_WindowBase::xft_init_lock", 0);
2366 xft_init_lock.lock("BC_WindowBase::init_xft");
2367         if(!(smallfont_xft =
2368                 (resources.small_font_xft[0] == '-' ?
2369                         xftFontOpenXlfd(display, screen, resources.small_font_xft) :
2370                         xftFontOpenName(display, screen, resources.small_font_xft))) )
2371                 if(!(smallfont_xft =
2372                         xftFontOpenXlfd(display, screen, resources.small_font_xft2)))
2373                         smallfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2374         if(!(mediumfont_xft =
2375                 (resources.medium_font_xft[0] == '-' ?
2376                         xftFontOpenXlfd(display, screen, resources.medium_font_xft) :
2377                         xftFontOpenName(display, screen, resources.medium_font_xft))) )
2378                 if(!(mediumfont_xft =
2379                         xftFontOpenXlfd(display, screen, resources.medium_font_xft2)))
2380                         mediumfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2381         if(!(largefont_xft =
2382                 (resources.large_font_xft[0] == '-' ?
2383                         xftFontOpenXlfd(display, screen, resources.large_font_xft) :
2384                         xftFontOpenName(display, screen, resources.large_font_xft))) )
2385                 if(!(largefont_xft =
2386                         xftFontOpenXlfd(display, screen, resources.large_font_xft2)))
2387                         largefont_xft = xftFontOpenXlfd(display, screen, "fixed");
2388         if(!(bigfont_xft =
2389                 (resources.big_font_xft[0] == '-' ?
2390                         xftFontOpenXlfd(display, screen, resources.big_font_xft) :
2391                         xftFontOpenName(display, screen, resources.big_font_xft))) )
2392                 if(!(bigfont_xft =
2393                         xftFontOpenXlfd(display, screen, resources.big_font_xft2)))
2394                         bigfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2395         if(!(clockfont_xft =
2396                 (resources.clock_font_xft[0] == '-' ?
2397                         xftFontOpenXlfd(display, screen, resources.clock_font_xft) :
2398                         xftFontOpenName(display, screen, resources.clock_font_xft))) )
2399                 clockfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2400
2401
2402         if(!(bold_smallfont_xft =
2403                 (resources.small_b_font_xft[0] == '-' ?
2404                         xftFontOpenXlfd(display, screen, resources.small_b_font_xft) :
2405                         xftFontOpenName(display, screen, resources.small_b_font_xft))) )
2406                 bold_smallfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2407         if(!(bold_mediumfont_xft =
2408                 (resources.medium_b_font_xft[0] == '-' ?
2409                         xftFontOpenXlfd(display, screen, resources.medium_b_font_xft) :
2410                         xftFontOpenName(display, screen, resources.medium_b_font_xft))) )
2411                 bold_mediumfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2412         if(!(bold_largefont_xft =
2413                 (resources.large_b_font_xft[0] == '-' ?
2414                         xftFontOpenXlfd(display, screen, resources.large_b_font_xft) :
2415                         xftFontOpenName(display, screen, resources.large_b_font_xft))) )
2416                 bold_largefont_xft = xftFontOpenXlfd(display, screen, "fixed");
2417
2418         if( !smallfont_xft || !mediumfont_xft || !largefont_xft || !bigfont_xft ||
2419             !bold_largefont_xft || !bold_mediumfont_xft || !bold_largefont_xft ||
2420             !clockfont_xft ) {
2421                 printf("BC_WindowBase::init_fonts: no xft fonts found:"
2422                         " %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n",
2423                         resources.small_font_xft, smallfont_xft,
2424                         resources.medium_font_xft, mediumfont_xft,
2425                         resources.large_font_xft, largefont_xft,
2426                         resources.big_font_xft, bigfont_xft,
2427                         resources.clock_font_xft, clockfont_xft,
2428                         resources.small_b_font_xft, bold_smallfont_xft,
2429                         resources.medium_b_font_xft, bold_mediumfont_xft,
2430                         resources.large_b_font_xft, bold_largefont_xft);
2431                 get_resources()->use_xft = 0;
2432                 exit(1);
2433         }
2434 // _XftDisplayInfo needs a lock.
2435         xftDefaultHasRender(display);
2436 xft_init_lock.unlock();
2437 #endif // HAVE_XFT
2438 }
2439
2440 void BC_WindowBase::init_im()
2441 {
2442         XIMStyles *xim_styles;
2443         XIMStyle xim_style;
2444
2445         if(!(input_method = XOpenIM(display, NULL, NULL, NULL)))
2446         {
2447                 printf("BC_WindowBase::init_im: Could not open input method.\n");
2448                 exit(1);
2449         }
2450         if(XGetIMValues(input_method, XNQueryInputStyle, &xim_styles, NULL) ||
2451                         xim_styles == NULL)
2452         {
2453                 printf("BC_WindowBase::init_im: Input method doesn't support any styles.\n");
2454                 XCloseIM(input_method);
2455                 exit(1);
2456         }
2457
2458         xim_style = 0;
2459         for(int z = 0;  z < xim_styles->count_styles;  z++)
2460         {
2461                 if(xim_styles->supported_styles[z] == (XIMPreeditNothing | XIMStatusNothing))
2462                 {
2463                         xim_style = xim_styles->supported_styles[z];
2464                         break;
2465                 }
2466         }
2467         XFree(xim_styles);
2468
2469         if(xim_style == 0)
2470         {
2471                 printf("BC_WindowBase::init_im: Input method doesn't support the style we need.\n");
2472                 XCloseIM(input_method);
2473                 exit(1);
2474         }
2475
2476         input_context = XCreateIC(input_method, XNInputStyle, xim_style,
2477                 XNClientWindow, win, XNFocusWindow, win, NULL);
2478         if(!input_context)
2479         {
2480                 printf("BC_WindowBase::init_im: Failed to create input context.\n");
2481                 XCloseIM(input_method);
2482                 exit(1);
2483         }
2484 }
2485
2486 void BC_WindowBase::finit_im()
2487 {
2488         if( input_context ) {
2489                 XDestroyIC(input_context);
2490                 input_context = 0;
2491         }
2492         if( input_method ) {
2493                 XCloseIM(input_method);
2494                 input_method = 0;
2495         }
2496 }
2497
2498
2499 int BC_WindowBase::get_color(int64_t color)
2500 {
2501 // return pixel of color
2502 // use this only for drawing subwindows not for bitmaps
2503          int i, test, difference;
2504
2505         switch(color_model)
2506         {
2507         case BC_RGB8:
2508                 if(private_color)
2509                         return get_color_rgb8(color);
2510 // test last color looked up
2511                 if(current_color_value == color)
2512                         return current_color_pixel;
2513
2514 // look up in table
2515                 current_color_value = color;
2516                 for(i = 0; i < total_colors; i++)
2517                 {
2518                         if(color_table[i][0] == color)
2519                         {
2520                                 current_color_pixel = color_table[i][1];
2521                                 return current_color_pixel;
2522                         }
2523                 }
2524
2525 // find nearest match
2526                 difference = 0xFFFFFF;
2527
2528                 for(i = 0; i < total_colors; i++)
2529                 {
2530                         test = abs((int)(color_table[i][0] - color));
2531
2532                         if(test < difference)
2533                         {
2534                                 current_color_pixel = color_table[i][1];
2535                                 difference = test;
2536                         }
2537                 }
2538                 return current_color_pixel;
2539
2540         case BC_RGB565:
2541                 return get_color_rgb16(color);
2542
2543         case BC_BGR565:
2544                 return get_color_bgr16(color);
2545
2546         case BC_RGB888:
2547         case BC_BGR888:
2548                 return client_byte_order == server_byte_order ?
2549                         color : get_color_bgr24(color);
2550
2551         default:
2552                 return color;
2553         }
2554         return 0;
2555 }
2556
2557 int BC_WindowBase::get_color_rgb8(int color)
2558 {
2559         int pixel;
2560
2561         pixel = (color & 0xc00000) >> 16;
2562         pixel += (color & 0xe000) >> 10;
2563         pixel += (color & 0xe0) >> 5;
2564         return pixel;
2565 }
2566
2567 int64_t BC_WindowBase::get_color_rgb16(int color)
2568 {
2569         int64_t result;
2570         result = (color & 0xf80000) >> 8;
2571         result += (color & 0xfc00) >> 5;
2572         result += (color & 0xf8) >> 3;
2573
2574         return result;
2575 }
2576
2577 int64_t BC_WindowBase::get_color_bgr16(int color)
2578 {
2579         int64_t result;
2580         result = (color & 0xf80000) >> 19;
2581         result += (color & 0xfc00) >> 5;
2582         result += (color & 0xf8) << 8;
2583
2584         return result;
2585 }
2586
2587 int64_t BC_WindowBase::get_color_bgr24(int color)
2588 {
2589         int64_t result;
2590         result = (color & 0xff) << 16;
2591         result += (color & 0xff00);
2592         result += (color & 0xff0000) >> 16;
2593         return result;
2594 }
2595
2596 void BC_WindowBase::start_video()
2597 {
2598         cursor_timer->update();
2599         video_on = 1;
2600 //      set_color(BLACK);
2601 //      draw_box(0, 0, get_w(), get_h());
2602 //      flash();
2603 }
2604
2605 void BC_WindowBase::stop_video()
2606 {
2607         video_on = 0;
2608         unhide_cursor();
2609 }
2610
2611
2612
2613 int64_t BC_WindowBase::get_color()
2614 {
2615         return top_level->current_color;
2616 }
2617
2618 void BC_WindowBase::set_color(int64_t color)
2619 {
2620         top_level->current_color = color;
2621         XSetForeground(top_level->display,
2622                 top_level->gc,
2623                 top_level->get_color(color));
2624 }
2625
2626 void BC_WindowBase::set_opaque()
2627 {
2628         XSetFunction(top_level->display, top_level->gc, GXcopy);
2629 }
2630
2631 void BC_WindowBase::set_inverse()
2632 {
2633         XSetFunction(top_level->display, top_level->gc, GXxor);
2634 }
2635
2636 void BC_WindowBase::set_line_width(int value)
2637 {
2638         this->line_width = value;
2639         XSetLineAttributes(top_level->display, top_level->gc, value,    /* line_width */
2640                 line_dashes == 0 ? LineSolid : LineOnOffDash,           /* line_style */
2641                 line_dashes == 0 ? CapRound : CapNotLast,               /* cap_style */
2642                 JoinMiter);                                             /* join_style */
2643
2644         if(line_dashes > 0) {
2645                 const char dashes = line_dashes;
2646                 XSetDashes(top_level->display, top_level->gc, 0, &dashes, 1);
2647         }
2648
2649 // XGCValues gcvalues;
2650 // unsigned long gcmask;
2651 // gcmask = GCCapStyle | GCJoinStyle;
2652 // XGetGCValues(top_level->display, top_level->gc, gcmask, &gcvalues);
2653 // printf("BC_WindowBase::set_line_width %d %d %d\n", __LINE__, gcvalues.cap_style, gcvalues.join_style);
2654 }
2655
2656 void BC_WindowBase::set_line_dashes(int value)
2657 {
2658         line_dashes = value;
2659 // call XSetLineAttributes
2660         set_line_width(line_width);
2661 }
2662
2663
2664 Cursor BC_WindowBase::get_cursor_struct(int cursor)
2665 {
2666         switch(cursor)
2667         {
2668                 case ARROW_CURSOR:         return top_level->arrow_cursor;
2669                 case CROSS_CURSOR:         return top_level->cross_cursor;
2670                 case IBEAM_CURSOR:         return top_level->ibeam_cursor;
2671                 case VSEPARATE_CURSOR:     return top_level->vseparate_cursor;
2672                 case HSEPARATE_CURSOR:     return top_level->hseparate_cursor;
2673                 case MOVE_CURSOR:          return top_level->move_cursor;
2674                 case LEFT_CURSOR:          return top_level->left_cursor;
2675                 case RIGHT_CURSOR:         return top_level->right_cursor;
2676                 case UPRIGHT_ARROW_CURSOR: return top_level->upright_arrow_cursor;
2677                 case UPLEFT_RESIZE:        return top_level->upleft_resize_cursor;
2678                 case UPRIGHT_RESIZE:       return top_level->upright_resize_cursor;
2679                 case DOWNLEFT_RESIZE:      return top_level->downleft_resize_cursor;
2680                 case DOWNRIGHT_RESIZE:     return top_level->downright_resize_cursor;
2681                 case HOURGLASS_CURSOR:     return top_level->hourglass_cursor;
2682                 case TRANSPARENT_CURSOR:   return top_level->transparent_cursor;
2683                 case GRABBED_CURSOR:       return top_level->grabbed_cursor;
2684         }
2685         return 0;
2686 }
2687
2688 void BC_WindowBase::set_cursor(int cursor, int override, int flush)
2689 {
2690 // inherit cursor from parent
2691         if(cursor < 0)
2692         {
2693                 XUndefineCursor(top_level->display, win);
2694                 current_cursor = cursor;
2695         }
2696         else
2697 // don't change cursor if overridden
2698         if((!top_level->is_hourglass && !is_transparent) ||
2699                 override)
2700         {
2701                 XDefineCursor(top_level->display, win, get_cursor_struct(cursor));
2702                 if(flush) this->flush();
2703         }
2704
2705         if(!override) current_cursor = cursor;
2706 }
2707
2708 void BC_WindowBase::set_x_cursor(int cursor)
2709 {
2710         temp_cursor = XCreateFontCursor(top_level->display, cursor);
2711         XDefineCursor(top_level->display, win, temp_cursor);
2712         current_cursor = cursor;
2713         flush();
2714 }
2715
2716 int BC_WindowBase::get_cursor()
2717 {
2718         return current_cursor;
2719 }
2720
2721 void BC_WindowBase::start_hourglass()
2722 {
2723         top_level->start_hourglass_recursive();
2724         top_level->flush();
2725 }
2726
2727 void BC_WindowBase::stop_hourglass()
2728 {
2729         top_level->stop_hourglass_recursive();
2730         top_level->flush();
2731 }
2732
2733 void BC_WindowBase::start_hourglass_recursive()
2734 {
2735         if(this == top_level)
2736         {
2737                 hourglass_total++;
2738                 is_hourglass = 1;
2739         }
2740
2741         if(!is_transparent)
2742         {
2743                 set_cursor(HOURGLASS_CURSOR, 1, 0);
2744                 for(int i = 0; i < subwindows->total; i++)
2745                 {
2746                         subwindows->values[i]->start_hourglass_recursive();
2747                 }
2748         }
2749 }
2750
2751 void BC_WindowBase::stop_hourglass_recursive()
2752 {
2753         if(this == top_level)
2754         {
2755                 if(hourglass_total == 0) return;
2756                 top_level->hourglass_total--;
2757         }
2758
2759         if(!top_level->hourglass_total)
2760         {
2761                 top_level->is_hourglass = 0;
2762
2763 // Cause set_cursor to perform change
2764                 if(!is_transparent)
2765                         set_cursor(current_cursor, 1, 0);
2766
2767                 for(int i = 0; i < subwindows->total; i++)
2768                 {
2769                         subwindows->values[i]->stop_hourglass_recursive();
2770                 }
2771         }
2772 }
2773
2774
2775
2776
2777 XFontStruct* BC_WindowBase::get_font_struct(int font)
2778 {
2779 // Clear out unrelated flags
2780         if(font & BOLDFACE) font ^= BOLDFACE;
2781
2782         switch(font) {
2783                 case SMALLFONT:  return top_level->smallfont;  break;
2784                 case MEDIUMFONT: return top_level->mediumfont; break;
2785                 case LARGEFONT:  return top_level->largefont;  break;
2786                 case BIGFONT:    return top_level->bigfont;    break;
2787                 case CLOCKFONT:  return top_level->clockfont;  break;
2788         }
2789         return 0;
2790 }
2791
2792 XFontSet BC_WindowBase::get_fontset(int font)
2793 {
2794         XFontSet fs = 0;
2795
2796         if(get_resources()->use_fontset)
2797         {
2798                 switch(font & 0xff) {
2799                         case SMALLFONT:  fs = top_level->smallfontset; break;
2800                         case MEDIUMFONT: fs = top_level->mediumfontset; break;
2801                         case LARGEFONT:  fs = top_level->largefontset; break;
2802                         case BIGFONT:    fs = top_level->bigfontset;   break;
2803                         case CLOCKFONT: fs = top_level->clockfontset; break;
2804                 }
2805         }
2806
2807         return fs;
2808 }
2809
2810 #ifdef HAVE_XFT
2811 XftFont* BC_WindowBase::get_xft_struct(int font)
2812 {
2813         switch(font) {
2814                 case SMALLFONT:    return (XftFont*)top_level->smallfont_xft;
2815                 case MEDIUMFONT:   return (XftFont*)top_level->mediumfont_xft;
2816                 case LARGEFONT:    return (XftFont*)top_level->largefont_xft;
2817                 case BIGFONT:      return (XftFont*)top_level->bigfont_xft;
2818                 case CLOCKFONT:    return (XftFont*)top_level->clockfont_xft;
2819                 case MEDIUMFONT_3D: return (XftFont*)top_level->bold_mediumfont_xft;
2820                 case SMALLFONT_3D:  return (XftFont*)top_level->bold_smallfont_xft;
2821                 case LARGEFONT_3D:  return (XftFont*)top_level->bold_largefont_xft;
2822         }
2823
2824         return 0;
2825 }
2826 #endif
2827
2828
2829 int BC_WindowBase::get_current_font()
2830 {
2831         return top_level->current_font;
2832 }
2833
2834 void BC_WindowBase::set_font(int font)
2835 {
2836         top_level->current_font = font;
2837
2838 #ifdef HAVE_XFT
2839         if(get_resources()->use_xft) {}
2840         else
2841 #endif
2842         if(get_resources()->use_fontset) {
2843                 set_fontset(font);
2844         }
2845
2846         if(get_font_struct(font))
2847         {
2848                 XSetFont(top_level->display, top_level->gc, get_font_struct(font)->fid);
2849         }
2850
2851         return;
2852 }
2853
2854 void BC_WindowBase::set_fontset(int font)
2855 {
2856         XFontSet fs = 0;
2857
2858         if(get_resources()->use_fontset) {
2859                 switch(font) {
2860                         case SMALLFONT:  fs = top_level->smallfontset; break;
2861                         case MEDIUMFONT: fs = top_level->mediumfontset; break;
2862                         case LARGEFONT:  fs = top_level->largefontset; break;
2863                         case BIGFONT:    fs = top_level->bigfontset;   break;
2864                         case CLOCKFONT:  fs = top_level->clockfontset; break;
2865                 }
2866         }
2867
2868         curr_fontset = fs;
2869 }
2870
2871
2872 XFontSet BC_WindowBase::get_curr_fontset(void)
2873 {
2874         if(get_resources()->use_fontset)
2875                 return curr_fontset;
2876         return 0;
2877 }
2878
2879 int BC_WindowBase::get_single_text_width(int font, const char *text, int length)
2880 {
2881 #ifdef HAVE_XFT
2882         if(get_resources()->use_xft && get_xft_struct(font))
2883         {
2884                 XGlyphInfo extents;
2885 #ifdef X_HAVE_UTF8_STRING
2886                 if(get_resources()->locale_utf8)
2887                 {
2888                         xftTextExtentsUtf8(top_level->display,
2889                                 get_xft_struct(font),
2890                                 (const XftChar8 *)text,
2891                                 length,
2892                                 &extents);
2893                 }
2894                 else
2895 #endif
2896                 {
2897                         xftTextExtents8(top_level->display,
2898                                 get_xft_struct(font),
2899                                 (const XftChar8 *)text,
2900                                 length,
2901                                 &extents);
2902                 }
2903                 return extents.xOff;
2904         }
2905         else
2906 #endif
2907         if(get_resources()->use_fontset && top_level->get_fontset(font))
2908                 return XmbTextEscapement(top_level->get_fontset(font), text, length);
2909         else
2910         if(get_font_struct(font))
2911                 return XTextWidth(get_font_struct(font), text, length);
2912         else
2913         {
2914                 int w = 0;
2915                 switch(font)
2916                 {
2917                         case MEDIUM_7SEGMENT:
2918                                 return get_resources()->medium_7segment[0]->get_w() * length;
2919                                 break;
2920
2921                         default:
2922                                 return 0;
2923                 }
2924                 return w;
2925         }
2926 }
2927
2928 int BC_WindowBase::get_text_width(int font, const char *text, int length)
2929 {
2930         int i, j, w = 0, line_w = 0;
2931         if(length < 0) length = strlen(text);
2932
2933         for(i = 0, j = 0; i <= length; i++)
2934         {
2935                 line_w = 0;
2936                 if(text[i] == '\n')
2937                 {
2938                         line_w = get_single_text_width(font, &text[j], i - j);
2939                         j = i + 1;
2940                 }
2941                 else
2942                 if(text[i] == 0)
2943                 {
2944                         line_w = get_single_text_width(font, &text[j], length - j);
2945                 }
2946                 if(line_w > w) w = line_w;
2947         }
2948
2949         if(i > length && w == 0)
2950         {
2951                 w = get_single_text_width(font, text, length);
2952         }
2953
2954         return w;
2955 }
2956
2957 int BC_WindowBase::get_text_width(int font, const wchar_t *text, int length)
2958 {
2959         int i, j, w = 0;
2960         if( length < 0 ) length = wcslen(text);
2961
2962         for( i=j=0; i<length && text[i]; ++i ) {
2963                 if( text[i] != '\n' ) continue;
2964                 if( i > j ) {
2965                         int lw = get_single_text_width(font, &text[j], i-j);
2966                         if( w < lw ) w = lw;
2967                 }
2968                 j = i + 1;
2969         }
2970         if( j < length ) {
2971                 int lw = get_single_text_width(font, &text[j], length-j);
2972                 if( w < lw ) w = lw;
2973         }
2974
2975         return w;
2976 }
2977
2978 int BC_WindowBase::get_text_ascent(int font)
2979 {
2980 #ifdef HAVE_XFT
2981         XftFont *fstruct;
2982         if( (fstruct = get_xft_struct(font)) != 0 )
2983                 return fstruct->ascent;
2984 #endif
2985         if(get_resources()->use_fontset && top_level->get_fontset(font))
2986         {
2987                 XFontSetExtents *extents;
2988
2989                 extents = XExtentsOfFontSet(top_level->get_fontset(font));
2990                 return -extents->max_logical_extent.y;
2991         }
2992
2993         if(get_font_struct(font))
2994                 return top_level->get_font_struct(font)->ascent;
2995
2996         switch(font) {
2997                 case MEDIUM_7SEGMENT:
2998                         return get_resources()->medium_7segment[0]->get_h();
2999         }
3000         return 0;
3001 }
3002
3003 int BC_WindowBase::get_text_descent(int font)
3004 {
3005 #ifdef HAVE_XFT
3006         XftFont *fstruct;
3007         if( (fstruct = get_xft_struct(font)) != 0 )
3008                 return fstruct->descent;
3009 #endif
3010         if(get_resources()->use_fontset && top_level->get_fontset(font)) {
3011                 XFontSetExtents *extents;
3012                 extents = XExtentsOfFontSet(top_level->get_fontset(font));
3013                 return (extents->max_logical_extent.height
3014                         + extents->max_logical_extent.y);
3015         }
3016
3017         if(get_font_struct(font))
3018                 return top_level->get_font_struct(font)->descent;
3019
3020         return 0;
3021 }
3022
3023 int BC_WindowBase::get_text_height(int font, const char *text)
3024 {
3025         int rowh;
3026 #ifdef HAVE_XFT
3027         XftFont *fstruct;
3028         if( (fstruct = get_xft_struct(font)) != 0 )
3029                 rowh = fstruct->height;
3030         else
3031 #endif
3032                 rowh = get_text_ascent(font) + get_text_descent(font);
3033
3034         if(!text) return rowh;
3035
3036 // Add height of lines
3037         int h = 0, i, length = strlen(text);
3038         for(i = 0; i <= length; i++)
3039         {
3040                 if(text[i] == '\n')
3041                         h++;
3042                 else
3043                 if(text[i] == 0)
3044                         h++;
3045         }
3046         return h * rowh;
3047 }
3048
3049 BC_Bitmap* BC_WindowBase::new_bitmap(int w, int h, int color_model)
3050 {
3051         if(color_model < 0) color_model = top_level->get_color_model();
3052         return new BC_Bitmap(top_level, w, h, color_model);
3053 }
3054
3055 void BC_WindowBase::init_wait()
3056 {
3057 #ifndef SINGLE_THREAD
3058         if(window_type != MAIN_WINDOW)
3059                 top_level->init_wait();
3060         init_lock->lock("BC_WindowBase::init_wait");
3061         init_lock->unlock();
3062 #endif
3063 }
3064
3065 int BC_WindowBase::accel_available(int color_model, int lock_it)
3066 {
3067         if( window_type != MAIN_WINDOW )
3068                 return top_level->accel_available(color_model, lock_it);
3069         if( lock_it )
3070                 lock_window("BC_WindowBase::accel_available");
3071
3072         switch(color_model) {
3073         case BC_YUV420P:
3074                 grab_port_id(color_model);
3075                 break;
3076
3077         case BC_YUV422:
3078                 grab_port_id(color_model);
3079                 break;
3080
3081         default:
3082                 break;
3083         }
3084
3085         if( lock_it )
3086                 unlock_window();
3087 //printf("BC_WindowBase::accel_available %d %d\n", color_model, xvideo_port_id);
3088         return xvideo_port_id >= 0 ? 1 : 0;
3089 }
3090
3091
3092 int BC_WindowBase::grab_port_id(int color_model)
3093 {
3094         if( !get_resources()->use_xvideo ||     // disabled
3095             !get_resources()->use_shm )         // Only local server is fast enough.
3096                 return -1;
3097         if( xvideo_port_id >= 0 )
3098                 return xvideo_port_id;
3099
3100         unsigned int ver, rev, reqBase, eventBase, errorBase;
3101         if( Success != XvQueryExtension(display, // XV extension is available
3102                     &ver, &rev, &reqBase, &eventBase, &errorBase) )
3103                 return -1;
3104
3105 // XV adaptors are available
3106         unsigned int numAdapt = 0;
3107         XvAdaptorInfo *info = 0;
3108         XvQueryAdaptors(display, DefaultRootWindow(display), &numAdapt, &info);
3109         if( !numAdapt )
3110                 return -1;
3111
3112 // Translate from color_model to X color model
3113         int x_color_model = BC_CModels::bc_to_x(color_model);
3114
3115 // Get adaptor with desired color model
3116         for( int i = 0; i < (int)numAdapt && xvideo_port_id == -1; i++) {
3117                 if( !(info[i].type & XvImageMask) || !info[i].num_ports ) continue;
3118 // adaptor supports XvImages
3119                 int numFormats = 0, numPorts = info[i].num_ports;
3120                 XvImageFormatValues *formats =
3121                         XvListImageFormats(display, info[i].base_id, &numFormats);
3122                 if( !formats ) continue;
3123
3124                 for( int j=0; j<numFormats && xvideo_port_id<0; ++j ) {
3125                         if( formats[j].id != x_color_model ) continue;
3126 // this adaptor supports the desired format, grab a port
3127                         for( int k=0; k<numPorts; ++k ) {
3128                                 if( Success == XvGrabPort(top_level->display,
3129                                         info[i].base_id+k, CurrentTime) ) {
3130 //printf("BC_WindowBase::grab_port_id %llx\n", info[i].base_id);
3131                                         xvideo_port_id = info[i].base_id + k;
3132                                         break;
3133                                 }
3134                         }
3135                 }
3136                 XFree(formats);
3137         }
3138
3139         XvFreeAdaptorInfo(info);
3140
3141         return xvideo_port_id;
3142 }
3143
3144
3145 int BC_WindowBase::show_window(int flush)
3146 {
3147         for(int i = 0; i < subwindows->size(); i++)
3148         {
3149                 subwindows->get(i)->show_window(0);
3150         }
3151
3152         XMapWindow(top_level->display, win);
3153         if(flush) XFlush(top_level->display);
3154 //      XSync(top_level->display, 0);
3155         hidden = 0;
3156         return 0;
3157 }
3158
3159 int BC_WindowBase::hide_window(int flush)
3160 {
3161         for(int i = 0; i < subwindows->size(); i++)
3162         {
3163                 subwindows->get(i)->hide_window(0);
3164         }
3165
3166         XUnmapWindow(top_level->display, win);
3167         if(flush) this->flush();
3168         hidden = 1;
3169         return 0;
3170 }
3171
3172 BC_MenuBar* BC_WindowBase::add_menubar(BC_MenuBar *menu_bar)
3173 {
3174         subwindows->append((BC_SubWindow*)menu_bar);
3175
3176         menu_bar->parent_window = this;
3177         menu_bar->top_level = this->top_level;
3178         menu_bar->initialize();
3179         return menu_bar;
3180 }
3181
3182 BC_WindowBase* BC_WindowBase::add_popup(BC_WindowBase *window)
3183 {
3184 //printf("BC_WindowBase::add_popup window=%p win=%p\n", window, window->win);
3185         if(this != top_level) return top_level->add_popup(window);
3186         popups.append(window);
3187         return window;
3188 }
3189
3190 void BC_WindowBase::remove_popup(BC_WindowBase *window)
3191 {
3192 //printf("BC_WindowBase::remove_popup %d size=%d window=%p win=%p\n", __LINE__, popups.size(), window, window->win);
3193         if(this != top_level)
3194                 top_level->remove_popup(window);
3195         else
3196                 popups.remove(window);
3197 //printf("BC_WindowBase::remove_popup %d size=%d window=%p win=%p\n", __LINE__, popups.size(), window, window->win);
3198 }
3199
3200
3201 BC_WindowBase* BC_WindowBase::add_subwindow(BC_WindowBase *subwindow)
3202 {
3203         subwindows->append(subwindow);
3204
3205         if(subwindow->bg_color == -1) subwindow->bg_color = this->bg_color;
3206
3207 // parent window must be set before the subwindow initialization
3208         subwindow->parent_window = this;
3209         subwindow->top_level = this->top_level;
3210
3211 // Execute derived initialization
3212         subwindow->initialize();
3213         return subwindow;
3214 }
3215
3216
3217 BC_WindowBase* BC_WindowBase::add_tool(BC_WindowBase *subwindow)
3218 {
3219         return add_subwindow(subwindow);
3220 }
3221
3222 int BC_WindowBase::flash(int x, int y, int w, int h, int flush)
3223 {
3224         if( !top_level->flash_enabled ) return 0;
3225 //printf("BC_WindowBase::flash %d %d %d %d %d\n", __LINE__, w, h, this->w, this->h);
3226         set_opaque();
3227         XSetWindowBackgroundPixmap(top_level->display, win, pixmap->opaque_pixmap);
3228         if(x >= 0)
3229         {
3230                 XClearArea(top_level->display, win, x, y, w, h, 0);
3231         }
3232         else
3233         {
3234                 XClearWindow(top_level->display, win);
3235         }
3236
3237         if(flush)
3238                 this->flush();
3239         return 0;
3240 }
3241
3242 int BC_WindowBase::flash(int flush)
3243 {
3244         flash(-1, -1, -1, -1, flush);
3245         return 0;
3246 }
3247
3248 void BC_WindowBase::flush()
3249 {
3250         //if(!get_window_lock())
3251         //      printf("BC_WindowBase::flush %s not locked\n", top_level->title);
3252         // X gets hosed if Flush/Sync are not user locked (at libX11-1.1.5 / libxcb-1.1.91)
3253         //   _XReply deadlocks in condition_wait waiting for xlib lock when waiters!=-1
3254         int locked  = get_window_lock();
3255         if( !locked ) lock_window("BC_WindowBase::flush");
3256         XFlush(top_level->display);
3257         if( !locked ) unlock_window();
3258 }
3259
3260 void BC_WindowBase::sync_display()
3261 {
3262         int locked  = get_window_lock();
3263         if( !locked ) lock_window("BC_WindowBase::sync_display");
3264         XSync(top_level->display, False);
3265         if( !locked ) unlock_window();
3266 }
3267
3268 int BC_WindowBase::get_window_lock()
3269 {
3270 #ifdef SINGLE_THREAD
3271         return BC_Display::display_global->get_display_locked();
3272 #else
3273         return top_level->window_lock;
3274 #endif
3275 }
3276
3277 int BC_WindowBase::lock_window(const char *location)
3278 {
3279         if(top_level && top_level != this)
3280         {
3281                 top_level->lock_window(location);
3282         }
3283         else
3284         if(top_level)
3285         {
3286                 SET_LOCK(this, title, location);
3287 #ifdef SINGLE_THREAD
3288                 BC_Display::lock_display(location);
3289 #else
3290                 XLockDisplay(top_level->display);
3291                 top_level->display_lock_owner = pthread_self();
3292 #endif
3293                 SET_LOCK2
3294                 ++top_level->window_lock;
3295         }
3296         else
3297         {
3298                 printf("BC_WindowBase::lock_window top_level NULL\n");
3299         }
3300         return 0;
3301 }
3302
3303 int BC_WindowBase::unlock_window()
3304 {
3305         if(top_level && top_level != this)
3306         {
3307                 top_level->unlock_window();
3308         }
3309         else
3310         if(top_level)
3311         {
3312                 UNSET_LOCK(this);
3313
3314 //              if(!top_level->window_lock)
3315 //              {
3316 //                      printf("BC_WindowBase::unlock_window %d %s already unlocked\n",
3317 //                              __LINE__,
3318 //                              title);
3319 //              }
3320                 if( top_level->window_lock > 0 )
3321                         if( --top_level->window_lock == 0 )
3322                                 top_level->display_lock_owner = 0;
3323 #ifdef SINGLE_THREAD
3324                 BC_Display::unlock_display();
3325 #else
3326                 XUnlockDisplay(top_level->display);
3327 #endif
3328         }
3329         else
3330         {
3331                 printf("BC_WindowBase::unlock_window top_level NULL\n");
3332         }
3333         return 0;
3334 }
3335
3336 void BC_WindowBase::set_done(int return_value)
3337 {
3338         if(done_set) return;
3339         done_set = 1;
3340         if(window_type != MAIN_WINDOW)
3341                 top_level->set_done(return_value);
3342         else
3343         {
3344 #ifdef SINGLE_THREAD
3345                 this->return_value = return_value;
3346                 BC_Display::display_global->arm_completion(this);
3347                 completion_lock->unlock();
3348 #else // SINGLE_THREAD
3349                 init_wait();
3350                 if( !event_thread ) return;
3351                 XEvent *event = new_xevent();
3352                 XClientMessageEvent *ptr = (XClientMessageEvent*)event;
3353                 event->type = ClientMessage;
3354                 ptr->message_type = SetDoneXAtom;
3355                 ptr->format = 32;
3356                 this->return_value = return_value;
3357 // May lock up here because XSendEvent doesn't work too well
3358 // asynchronous with XNextEvent.
3359 // This causes BC_WindowEvents to forward a copy of the event to run_window where
3360 // it is deleted.
3361 // Deletion of event_thread is done at the end of BC_WindowBase::run_window() - by calling the destructor
3362                 put_event(event);
3363 #endif
3364         }
3365 }
3366
3367 void BC_WindowBase::close(int return_value)
3368 {
3369         hide_window();  flush();
3370         set_done(return_value);
3371 }
3372
3373 int BC_WindowBase::grab(BC_WindowBase *window)
3374 {
3375         if( window->active_grab && this != window->active_grab ) return 0;
3376         window->active_grab = this;
3377         this->grab_active = window;
3378         return 1;
3379 }
3380 int BC_WindowBase::ungrab(BC_WindowBase *window)
3381 {
3382         if( window->active_grab && this != window->active_grab ) return 0;
3383         window->active_grab = 0;
3384         this->grab_active = 0;
3385         return 1;
3386 }
3387 int BC_WindowBase::grab_event_count()
3388 {
3389         int result = 0;
3390 #ifndef SINGLE_THREAD
3391         result = grab_active->get_event_count();
3392 #endif
3393         return result;
3394 }
3395 int BC_WindowBase::grab_buttons()
3396 {
3397         XSync(top_level->display, False);
3398         if( XGrabButton(top_level->display, AnyButton, AnyModifier,
3399                         top_level->rootwin, True, ButtonPressMask | ButtonReleaseMask,
3400                         GrabModeAsync, GrabModeSync, None, None) == GrabSuccess ) {
3401                 set_active_subwindow(this);
3402                 return 0;
3403         }
3404         return 1;
3405 }
3406 void BC_WindowBase::ungrab_buttons()
3407 {
3408         XUngrabButton(top_level->display, AnyButton, AnyModifier, top_level->rootwin);
3409         set_active_subwindow(0);
3410         unhide_cursor();
3411 }
3412 void BC_WindowBase::grab_cursor()
3413 {
3414         Cursor cursor_grab = get_cursor_struct(GRABBED_CURSOR);
3415         XGrabPointer(top_level->display, top_level->rootwin, True,
3416                 PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
3417                 GrabModeAsync, GrabModeAsync, None, cursor_grab, CurrentTime);
3418 }
3419 void BC_WindowBase::ungrab_cursor()
3420 {
3421        XUngrabPointer(top_level->display, CurrentTime);
3422 }
3423
3424 // for get_root_w/h
3425 //   WidthOfScreen/HeightOfScreen of XDefaultScreenOfDisplay
3426 //   this is the bounding box of all the screens
3427
3428 int BC_WindowBase::get_root_w(int lock_display)
3429 {
3430         if(lock_display) lock_window("BC_WindowBase::get_root_w");
3431         Screen *def_screen = XDefaultScreenOfDisplay(top_level->display);
3432         int result = WidthOfScreen(def_screen);
3433         if(lock_display) unlock_window();
3434         return result;
3435 }
3436
3437 int BC_WindowBase::get_root_h(int lock_display)
3438 {
3439         if(lock_display) lock_window("BC_WindowBase::get_root_h");
3440         Screen *def_screen = XDefaultScreenOfDisplay(top_level->display);
3441         int result = HeightOfScreen(def_screen);
3442         if(lock_display) unlock_window();
3443         return result;
3444 }
3445
3446 XineramaScreenInfo *
3447 BC_WindowBase::get_xinerama_info(int screen)
3448 {
3449         if( !xinerama_info || !xinerama_screens ) return 0;
3450         if( screen >= 0 ) {
3451                 for( int i=0; i<xinerama_screens; ++i )
3452                         if( xinerama_info[i].screen_number == screen )
3453                                 return &xinerama_info[i];
3454                 return 0;
3455         }
3456         int top_x = get_x(), top_y = get_y();
3457         if(  BC_DisplayInfo::left_border >= 0 ) top_x +=  BC_DisplayInfo::left_border;
3458         if(  BC_DisplayInfo::top_border >= 0 ) top_y +=  BC_DisplayInfo::top_border;
3459         for( int i=0; i<xinerama_screens; ++i ) {
3460                 int scr_y = top_y - xinerama_info[i].y_org;
3461                 if( scr_y < 0 || scr_y >= xinerama_info[i].height ) continue;
3462                 int scr_x = top_x - xinerama_info[i].x_org;
3463                 if( scr_x >= 0 && scr_x < xinerama_info[i].width )
3464                         return &xinerama_info[i];
3465         }
3466         return 0;
3467 }
3468
3469 int BC_WindowBase::get_screen_x(int lock_display, int screen)
3470 {
3471         int result = -1;
3472         if(lock_display) lock_window("BC_WindowBase::get_screen_x");
3473         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3474         if( !info ) {
3475                 result = 0;
3476                 int root_w = get_root_w(0);
3477                 int root_h = get_root_h(0);
3478 // Shift X based on position of current window if dual head
3479                 if( (float)root_w/root_h > 1.8 ) {
3480                         root_w = get_screen_w(0, 0);
3481                         if( top_level->get_x() >= root_w )
3482                                 result = root_w;
3483                 }
3484         }
3485         else
3486                 result = info->x_org;
3487         if(lock_display) unlock_window();
3488         return result;
3489 }
3490
3491 int BC_WindowBase::get_screen_y(int lock_display, int screen)
3492 {
3493         if(lock_display) lock_window("BC_WindowBase::get_screen_y");
3494         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3495         int result = !info ? 0 : info->y_org;
3496         if(lock_display) unlock_window();
3497         return result;
3498 }
3499
3500 int BC_WindowBase::get_screen_w(int lock_display, int screen)
3501 {
3502         int result = -1;
3503         if(lock_display) lock_window("BC_WindowBase::get_screen_w");
3504         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3505         if( !info ) {
3506                 int width = get_root_w(0);
3507                 int height = get_root_h(0);
3508                 if( (float)width/height > 1.8 ) {
3509                         // If dual head, the screen width is > 16x9
3510                         // but we only want to fill one screen
3511                         // this code assumes the "big" screen is on the right
3512                         int scr_w0 = width / 2;
3513                         switch( height ) {
3514                         case 600:  scr_w0 = 800;   break;
3515                         case 720:  scr_w0 = 1280;  break;
3516                         case 1024: scr_w0 = 1280;  break;
3517                         case 1200: scr_w0 = 1600;  break;
3518                         case 1080: scr_w0 = 1920;  break;
3519                         }
3520                         int scr_w1 = width - scr_w0;
3521                         result = screen > 0 ? scr_w1 :
3522                                 screen == 0 ? scr_w0 :
3523                                 top_level->get_x() < scr_w0 ? scr_w0 : scr_w1;
3524                 }
3525                 else
3526                         result = width;
3527         }
3528         else
3529                 result = info->width;
3530         if(lock_display) unlock_window();
3531         return result;
3532 }
3533
3534 int BC_WindowBase::get_screen_h(int lock_display, int screen)
3535 {
3536         if(lock_display) lock_window("BC_WindowBase::get_screen_h");
3537         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3538         int result = info ? info->height : get_root_h(0);
3539         if(lock_display) unlock_window();
3540         return result;
3541 }
3542
3543 // Bottom right corner
3544 int BC_WindowBase::get_x2()
3545 {
3546         return w + x;
3547 }
3548
3549 int BC_WindowBase::get_y2()
3550 {
3551         return y + h;
3552 }
3553
3554 int BC_WindowBase::get_video_on()
3555 {
3556         return video_on;
3557 }
3558
3559 int BC_WindowBase::get_hidden()
3560 {
3561         return top_level->hidden;
3562 }
3563
3564 int BC_WindowBase::cursor_inside()
3565 {
3566         return (top_level->cursor_x >= 0 &&
3567                         top_level->cursor_y >= 0 &&
3568                         top_level->cursor_x < w &&
3569                         top_level->cursor_y < h);
3570 }
3571
3572 BC_WindowBase* BC_WindowBase::get_top_level()
3573 {
3574         return top_level;
3575 }
3576
3577 BC_WindowBase* BC_WindowBase::get_parent()
3578 {
3579         return parent_window;
3580 }
3581
3582 int BC_WindowBase::get_color_model()
3583 {
3584         return top_level->color_model;
3585 }
3586
3587 BC_Resources* BC_WindowBase::get_resources()
3588 {
3589         return &BC_WindowBase::resources;
3590 }
3591
3592 BC_Synchronous* BC_WindowBase::get_synchronous()
3593 {
3594         return BC_WindowBase::resources.get_synchronous();
3595 }
3596
3597 int BC_WindowBase::get_bg_color()
3598 {
3599         return bg_color;
3600 }
3601
3602 void BC_WindowBase::set_bg_color(int color)
3603 {
3604         this->bg_color = color;
3605 }
3606
3607 BC_Pixmap* BC_WindowBase::get_bg_pixmap()
3608 {
3609         return bg_pixmap;
3610 }
3611
3612 void BC_WindowBase::set_active_subwindow(BC_WindowBase *subwindow)
3613 {
3614         top_level->active_subwindow = subwindow;
3615 }
3616
3617 int BC_WindowBase::activate()
3618 {
3619         return 0;
3620 }
3621
3622 int BC_WindowBase::deactivate()
3623 {
3624         if(window_type == MAIN_WINDOW)
3625         {
3626                 if( top_level->active_menubar ) {
3627                         top_level->active_menubar->deactivate();
3628                         top_level->active_menubar = 0;
3629                 }
3630                 if( top_level->active_popup_menu ) {
3631                         top_level->active_popup_menu->deactivate();
3632                         top_level->active_popup_menu = 0;
3633                 }
3634                 if( top_level->active_subwindow ) {
3635                         top_level->active_subwindow->deactivate();
3636                         top_level->active_subwindow = 0;
3637                 }
3638                 if( top_level->motion_events && top_level->last_motion_win == this->win )
3639                         top_level->motion_events = 0;
3640
3641         }
3642         return 0;
3643 }
3644
3645 int BC_WindowBase::cycle_textboxes(int amount)
3646 {
3647         int result = 0;
3648         BC_WindowBase *new_textbox = 0;
3649
3650         if(amount > 0)
3651         {
3652                 BC_WindowBase *first_textbox = 0;
3653                 find_next_textbox(&first_textbox, &new_textbox, result);
3654                 if(!new_textbox) new_textbox = first_textbox;
3655
3656         }
3657         else
3658         if(amount < 0)
3659         {
3660                 BC_WindowBase *last_textbox = 0;
3661                 find_prev_textbox(&last_textbox, &new_textbox, result);
3662                 if(!new_textbox) new_textbox = last_textbox;
3663
3664         }
3665
3666         if(new_textbox != active_subwindow)
3667         {
3668                 deactivate();
3669                 new_textbox->activate();
3670         }
3671
3672         return 0;
3673 }
3674
3675 int BC_WindowBase::find_next_textbox(BC_WindowBase **first_textbox, BC_WindowBase **next_textbox, int &result)
3676 {
3677 // Search subwindows for textbox
3678         for(int i = 0; i < subwindows->total && result < 2; i++)
3679         {
3680                 BC_WindowBase *test_subwindow = subwindows->values[i];
3681                 test_subwindow->find_next_textbox(first_textbox, next_textbox, result);
3682         }
3683
3684         if(result < 2)
3685         {
3686                 if(uses_text())
3687                 {
3688                         if(!*first_textbox) *first_textbox = this;
3689
3690                         if(result < 1)
3691                         {
3692                                 if(top_level->active_subwindow == this)
3693                                         result++;
3694                         }
3695                         else
3696                         {
3697                                 result++;
3698                                 *next_textbox = this;
3699                         }
3700                 }
3701         }
3702         return 0;
3703 }
3704
3705 int BC_WindowBase::find_prev_textbox(BC_WindowBase **last_textbox, BC_WindowBase **prev_textbox, int &result)
3706 {
3707         if(result < 2)
3708         {
3709                 if(uses_text())
3710                 {
3711                         if(!*last_textbox) *last_textbox = this;
3712
3713                         if(result < 1)
3714                         {
3715                                 if(top_level->active_subwindow == this)
3716                                         result++;
3717                         }
3718                         else
3719                         {
3720                                 result++;
3721                                 *prev_textbox = this;
3722                         }
3723                 }
3724         }
3725
3726 // Search subwindows for textbox
3727         for(int i = subwindows->total - 1; i >= 0 && result < 2; i--)
3728         {
3729                 BC_WindowBase *test_subwindow = subwindows->values[i];
3730                 test_subwindow->find_prev_textbox(last_textbox, prev_textbox, result);
3731         }
3732         return 0;
3733 }
3734
3735 BC_Clipboard* BC_WindowBase::get_clipboard()
3736 {
3737 #ifdef SINGLE_THREAD
3738         return BC_Display::display_global->clipboard;
3739 #else
3740         return top_level->clipboard;
3741 #endif
3742 }
3743
3744 Atom BC_WindowBase::to_clipboard(const char *data, long len, int clipboard_num)
3745 {
3746         return get_clipboard()->to_clipboard(this, data, len, clipboard_num);
3747 }
3748
3749 long BC_WindowBase::from_clipboard(char *data, long maxlen, int clipboard_num)
3750 {
3751         return get_clipboard()->from_clipboard(data, maxlen, clipboard_num);
3752 }
3753
3754 long BC_WindowBase::clipboard_len(int clipboard_num)
3755 {
3756         return get_clipboard()->clipboard_len(clipboard_num);
3757 }
3758
3759 int BC_WindowBase::do_selection_clear(Window win)
3760 {
3761         top_level->event_win = win;
3762         return dispatch_selection_clear();
3763 }
3764
3765 int BC_WindowBase::dispatch_selection_clear()
3766 {
3767         int result = 0;
3768         for( int i=0; i<subwindows->total && !result; ++i )
3769                 result = subwindows->values[i]->dispatch_selection_clear();
3770         if( !result )
3771                 result = selection_clear_event();
3772         return result;
3773 }
3774
3775
3776 void BC_WindowBase::get_relative_cursor(int &x, int &y, int lock_window)
3777 {
3778         int abs_x, abs_y, win_x, win_y;
3779         unsigned int temp_mask;
3780         Window temp_win;
3781
3782         if(lock_window) this->lock_window("BC_WindowBase::get_relative_cursor");
3783         XQueryPointer(top_level->display, top_level->win,
3784            &temp_win, &temp_win, &abs_x, &abs_y, &win_x, &win_y,
3785            &temp_mask);
3786
3787         XTranslateCoordinates(top_level->display, top_level->rootwin,
3788            win, abs_x, abs_y, &x, &y, &temp_win);
3789         if(lock_window) this->unlock_window();
3790 }
3791 int BC_WindowBase::get_relative_cursor_x(int lock_window)
3792 {
3793         int x, y;
3794         get_relative_cursor(x, y, lock_window);
3795         return x;
3796 }
3797 int BC_WindowBase::get_relative_cursor_y(int lock_window)
3798 {
3799         int x, y;
3800         get_relative_cursor(x, y, lock_window);
3801         return y;
3802 }
3803
3804 void BC_WindowBase::get_abs_cursor(int &abs_x, int &abs_y, int lock_window)
3805 {
3806         int win_x, win_y;
3807         unsigned int temp_mask;
3808         Window temp_win;
3809
3810         if(lock_window) this->lock_window("BC_WindowBase::get_abs_cursor");
3811         XQueryPointer(top_level->display, top_level->win,
3812                 &temp_win, &temp_win, &abs_x, &abs_y, &win_x, &win_y,
3813                 &temp_mask);
3814         if(lock_window) this->unlock_window();
3815 }
3816 int BC_WindowBase::get_abs_cursor_x(int lock_window)
3817 {
3818         int abs_x, abs_y;
3819         get_abs_cursor(abs_x, abs_y, lock_window);
3820         return abs_x;
3821 }
3822 int BC_WindowBase::get_abs_cursor_y(int lock_window)
3823 {
3824         int abs_x, abs_y;
3825         get_abs_cursor(abs_x, abs_y, lock_window);
3826         return abs_y;
3827 }
3828
3829 void BC_WindowBase::get_pop_cursor(int &px, int &py, int lock_window)
3830 {
3831         int margin = 100;
3832         get_abs_cursor(px, py, lock_window);
3833         if( px < margin ) px = margin;
3834         if( py < margin ) py = margin;
3835         int wd = get_screen_w(lock_window,-1) - margin;
3836         if( px > wd ) px = wd;
3837         int ht = get_screen_h(lock_window,-1) - margin;
3838         if( py > ht ) py = ht;
3839 }
3840 int BC_WindowBase::get_pop_cursor_x(int lock_window)
3841 {
3842         int px, py;
3843         get_pop_cursor(px, py, lock_window);
3844         return px;
3845 }
3846 int BC_WindowBase::get_pop_cursor_y(int lock_window)
3847 {
3848         int px, py;
3849         get_pop_cursor(px, py, lock_window);
3850         return py;
3851 }
3852
3853 int BC_WindowBase::match_window(Window win)
3854 {
3855         if (this->win == win) return 1;
3856         int result = 0;
3857         for(int i = 0; i < subwindows->total; i++) {
3858                 result = subwindows->values[i]->match_window(win);
3859                 if (result) return result;
3860         }
3861         return 0;
3862
3863 }
3864
3865 int BC_WindowBase::get_cursor_over_window()
3866 {
3867         int abs_x, abs_y, win_x, win_y;
3868         unsigned int mask_return;
3869         Window root_return, child_return;
3870
3871         int ret = XQueryPointer(top_level->display, top_level->rootwin,
3872                 &root_return, &child_return, &abs_x, &abs_y,
3873                 &win_x, &win_y, &mask_return);
3874         if( ret && child_return == None ) ret = 0;
3875         if( ret && win != child_return )
3876                 ret = top_level->match_window(child_return);
3877 // query pointer can return a window manager window with this top_level as a child
3878 //  for kde this can be two levels deep
3879         unsigned int nchildren_return = 0;
3880         Window parent_return, *children_return = 0;
3881         Window top_win = top_level->win;
3882         while( !ret && top_win != top_level->rootwin && top_win != root_return &&
3883                 XQueryTree(top_level->display, top_win, &root_return,
3884                         &parent_return, &children_return, &nchildren_return) ) {
3885                 if( children_return ) XFree(children_return);
3886                 if( (top_win=parent_return) == child_return ) ret = 1;
3887         }
3888         return ret;
3889 }
3890
3891 int BC_WindowBase::cursor_above()
3892 {
3893         int rx, ry;
3894         get_relative_cursor(rx, ry);
3895         return rx < 0 || rx >= get_w() ||
3896                 ry < 0 || ry >= get_h() ? 0 : 1;
3897 }
3898
3899 int BC_WindowBase::get_drag_x()
3900 {
3901         return top_level->drag_x;
3902 }
3903
3904 int BC_WindowBase::get_drag_y()
3905 {
3906         return top_level->drag_y;
3907 }
3908
3909 int BC_WindowBase::get_cursor_x()
3910 {
3911         return top_level->cursor_x;
3912 }
3913
3914 int BC_WindowBase::get_cursor_y()
3915 {
3916         return top_level->cursor_y;
3917 }
3918
3919 int BC_WindowBase::dump_windows()
3920 {
3921         printf("\tBC_WindowBase::dump_windows window=%p win=%p '%s', %dx%d+%d+%d %s\n",
3922                 this, (void*)this->win, title, w,h,x,y, typeid(*this).name());
3923         for(int i = 0; i < subwindows->size(); i++)
3924                 subwindows->get(i)->dump_windows();
3925         for(int i = 0; i < popups.size(); i++) {
3926                 BC_WindowBase *p = popups[i];
3927                 printf("\tBC_WindowBase::dump_windows popup=%p win=%p '%s', %dx%d+%d+%d %s\n",
3928                         p, (void*)p->win, p->title, p->w,p->h,p->x,p->y, typeid(*p).name());
3929         }
3930         return 0;
3931 }
3932
3933 int BC_WindowBase::is_event_win()
3934 {
3935         return this->win == top_level->event_win;
3936 }
3937
3938 void BC_WindowBase::set_dragging(int value)
3939 {
3940         is_dragging = value;
3941 }
3942
3943 int BC_WindowBase::get_dragging()
3944 {
3945         return is_dragging;
3946 }
3947
3948 int BC_WindowBase::get_buttonpress()
3949 {
3950         return top_level->button_number;
3951 }
3952
3953 int BC_WindowBase::get_button_down()
3954 {
3955         return top_level->button_down;
3956 }
3957
3958 int BC_WindowBase::alt_down()
3959 {
3960         return top_level->alt_mask;
3961 }
3962
3963 int BC_WindowBase::shift_down()
3964 {
3965         return top_level->shift_mask;
3966 }
3967
3968 int BC_WindowBase::ctrl_down()
3969 {
3970         return top_level->ctrl_mask;
3971 }
3972
3973 wchar_t* BC_WindowBase::get_wkeystring(int *length)
3974 {
3975         if(length)
3976                 *length = top_level->wkey_string_length;
3977         return top_level->wkey_string;
3978 }
3979
3980 #ifdef X_HAVE_UTF8_STRING
3981 char* BC_WindowBase::get_keypress_utf8()
3982 {
3983         return top_level->key_pressed_utf8;
3984 }
3985 #endif
3986
3987
3988 int BC_WindowBase::get_keypress()
3989 {
3990         return top_level->key_pressed;
3991 }
3992
3993 int BC_WindowBase::get_double_click()
3994 {
3995         return top_level->double_click;
3996 }
3997
3998 int BC_WindowBase::get_triple_click()
3999 {
4000         return top_level->triple_click;
4001 }
4002
4003 int BC_WindowBase::get_bgcolor()
4004 {
4005         return bg_color;
4006 }
4007
4008 int BC_WindowBase::resize_window(int w, int h)
4009 {
4010         if(this->w == w && this->h == h) return 0;
4011
4012         if(window_type == MAIN_WINDOW && !allow_resize)
4013         {
4014                 XSizeHints size_hints;
4015                 size_hints.flags = PSize | PMinSize | PMaxSize;
4016                 size_hints.width = w;
4017                 size_hints.height = h;
4018                 size_hints.min_width = w;
4019                 size_hints.max_width = w;
4020                 size_hints.min_height = h;
4021                 size_hints.max_height = h;
4022                 XSetNormalHints(top_level->display, win, &size_hints);
4023         }
4024         XResizeWindow(top_level->display, win, w, h);
4025
4026         this->w = w;
4027         this->h = h;
4028         delete pixmap;
4029         pixmap = new BC_Pixmap(this, w, h);
4030
4031 // Propagate to menubar
4032         for(int i = 0; i < subwindows->total; i++)
4033         {
4034                 subwindows->values[i]->dispatch_resize_event(w, h);
4035         }
4036
4037         draw_background(0, 0, w, h);
4038         if(top_level == this && get_resources()->recursive_resizing)
4039                 resize_history.append(new BC_ResizeCall(w, h));
4040         return 0;
4041 }
4042
4043 // The only way for resize events to be propagated is by updating the internal w and h
4044 int BC_WindowBase::resize_event(int w, int h)
4045 {
4046         if(window_type == MAIN_WINDOW)
4047         {
4048                 this->w = w;
4049                 this->h = h;
4050         }
4051         return 0;
4052 }
4053
4054 int BC_WindowBase::reposition_window(int x, int y)
4055 {
4056         reposition_window(x, y, -1, -1);
4057         return 0;
4058 }
4059
4060
4061 int BC_WindowBase::reposition_window(int x, int y, int w, int h)
4062 {
4063         int resize = 0;
4064
4065 // Some tools set their own dimensions before calling this, causing the
4066 // resize check to skip.
4067         this->x = x;
4068         this->y = y;
4069
4070         if(w > 0 && w != this->w)
4071         {
4072                 resize = 1;
4073                 this->w = w;
4074         }
4075
4076         if(h > 0 && h != this->h)
4077         {
4078                 resize = 1;
4079                 this->h = h;
4080         }
4081
4082 //printf("BC_WindowBase::reposition_window %d %d %d\n", translation_count, x_correction, y_correction);
4083
4084         if(this->w <= 0)
4085                 printf("BC_WindowBase::reposition_window this->w == %d\n", this->w);
4086         if(this->h <= 0)
4087                 printf("BC_WindowBase::reposition_window this->h == %d\n", this->h);
4088
4089         if(translation_count && window_type == MAIN_WINDOW)
4090         {
4091 // KDE shifts window right and down.
4092 // FVWM leaves window alone and adds border around it.
4093                 XMoveResizeWindow(top_level->display,
4094                         win,
4095                         x - BC_DisplayInfo::auto_reposition_x,
4096                         y - BC_DisplayInfo::auto_reposition_y,
4097                         this->w,
4098                         this->h);
4099         }
4100         else
4101         {
4102                 XMoveResizeWindow(top_level->display,
4103                         win,
4104                         x,
4105                         y,
4106                         this->w,
4107                         this->h);
4108         }
4109
4110         if(resize)
4111         {
4112                 delete pixmap;
4113                 pixmap = new BC_Pixmap(this, this->w, this->h);
4114                 clear_box(0,0, this->w, this->h);
4115 // Propagate to menubar
4116                 for(int i = 0; i < subwindows->total; i++)
4117                 {
4118                         subwindows->values[i]->dispatch_resize_event(this->w, this->h);
4119                 }
4120
4121 //              draw_background(0, 0, w, h);
4122         }
4123
4124         return 0;
4125 }
4126
4127 int BC_WindowBase::reposition_window_relative(int dx, int dy, int w, int h)
4128 {
4129         return reposition_window(get_x()+dx, get_y()+dy, w, h);
4130 }
4131
4132 int BC_WindowBase::reposition_window_relative(int dx, int dy)
4133 {
4134         return reposition_window_relative(dx, dy, -1, -1);
4135 }
4136
4137 void BC_WindowBase::set_tooltips(int v)
4138 {
4139         get_resources()->tooltips_enabled = v;
4140 }
4141
4142 void BC_WindowBase::set_force_tooltip(int v)
4143 {
4144         force_tooltip = v;
4145 }
4146
4147 int BC_WindowBase::raise_window(int do_flush)
4148 {
4149         XRaiseWindow(top_level->display, win);
4150         if(do_flush) XFlush(top_level->display);
4151         return 0;
4152 }
4153
4154 int BC_WindowBase::lower_window(int do_flush)
4155 {
4156         XLowerWindow(top_level->display, win);
4157         if(do_flush) XFlush(top_level->display);
4158         return 0;
4159 }
4160
4161 void BC_WindowBase::set_background(VFrame *bitmap)
4162 {
4163         if(bg_pixmap && !shared_bg_pixmap) delete bg_pixmap;
4164
4165         bg_pixmap = new BC_Pixmap(this, bitmap, PIXMAP_OPAQUE);
4166         shared_bg_pixmap = 0;
4167         draw_background(0, 0, w, h);
4168 }
4169
4170 void BC_WindowBase::put_title(const char *text)
4171 {
4172         char *cp = this->title, *ep = cp+sizeof(this->title)-1;
4173         for( const unsigned char *bp = (const unsigned char *)text; *bp && cp<ep; ++bp )
4174                 *cp++ = *bp >= ' ' ? *bp : ' ';
4175         *cp = 0;
4176 }
4177
4178 void BC_WindowBase::set_title(const char *text, int utf8)
4179 {
4180 // utf8>0: wm + net_wm, utf8=0: wm only,  utf<0: net_wm only
4181         put_title(text);
4182         const unsigned char *wm_title = (const unsigned char *)title;
4183         int title_len = strlen((const char *)title);
4184         if( utf8 >= 0 ) {
4185                 Atom xa_wm_name = XA_WM_NAME;
4186                 Atom xa_icon_name = XA_WM_ICON_NAME;
4187                 Atom xa_string = XA_STRING;
4188                 XChangeProperty(display, win, xa_wm_name, xa_string, 8,
4189                                 PropModeReplace, wm_title, title_len);
4190                 XChangeProperty(display, win, xa_icon_name, xa_string, 8,
4191                                 PropModeReplace, wm_title, title_len);
4192         }
4193         if( utf8 != 0 ) {
4194                 Atom xa_net_wm_name = XInternAtom(display, "_NET_WM_NAME", True);
4195                 Atom xa_net_icon_name = XInternAtom(display, "_NET_WM_ICON_NAME", True);
4196                 Atom xa_utf8_string = XInternAtom(display, "UTF8_STRING", True);
4197                 XChangeProperty(display, win, xa_net_wm_name, xa_utf8_string, 8,
4198                                         PropModeReplace, wm_title, title_len);
4199                 XChangeProperty(display, win, xa_net_icon_name, xa_utf8_string, 8,
4200                                         PropModeReplace, wm_title, title_len);
4201         }
4202         flush();
4203 }
4204
4205 const char *BC_WindowBase::get_title()
4206 {
4207         return title;
4208 }
4209
4210 int BC_WindowBase::get_toggle_value()
4211 {
4212         return toggle_value;
4213 }
4214
4215 int BC_WindowBase::get_toggle_drag()
4216 {
4217         return toggle_drag;
4218 }
4219
4220 int BC_WindowBase::set_icon(VFrame *data)
4221 {
4222         if(icon_pixmap) delete icon_pixmap;
4223         icon_pixmap = new BC_Pixmap(top_level, data, PIXMAP_ALPHA, 1);
4224
4225         if(icon_window) delete icon_window;
4226         icon_window = new BC_Popup(this,
4227                 (int)BC_INFINITY,
4228                 (int)BC_INFINITY,
4229                 icon_pixmap->get_w(),
4230                 icon_pixmap->get_h(),
4231                 -1,
4232                 1, // All windows are hidden initially
4233                 icon_pixmap);
4234
4235         XWMHints wm_hints;
4236         wm_hints.flags = WindowGroupHint | IconPixmapHint | IconMaskHint | IconWindowHint;
4237         wm_hints.icon_pixmap = icon_pixmap->get_pixmap();
4238         wm_hints.icon_mask = icon_pixmap->get_alpha();
4239         wm_hints.icon_window = icon_window->win;
4240         wm_hints.window_group = XGroupLeader;
4241
4242 // for(int i = 0; i < 1000; i++)
4243 // printf("02x ", icon_pixmap->get_alpha()->get_row_pointers()[0][i]);
4244 // printf("\n");
4245
4246         XSetWMHints(top_level->display, top_level->win, &wm_hints);
4247         XSync(top_level->display, 0);
4248         return 0;
4249 }
4250
4251 int BC_WindowBase::set_w(int w)
4252 {
4253         this->w = w;
4254         return 0;
4255 }
4256
4257 int BC_WindowBase::set_h(int h)
4258 {
4259         this->h = h;
4260         return 0;
4261 }
4262
4263 int BC_WindowBase::load_defaults(BC_Hash *defaults)
4264 {
4265         BC_Resources *resources = get_resources();
4266         char string[BCTEXTLEN];
4267         int newest_id = - 1;
4268         for(int i = 0; i < FILEBOX_HISTORY_SIZE; i++)
4269         {
4270                 sprintf(string, "FILEBOX_HISTORY_PATH%d", i);
4271                 resources->filebox_history[i].path[0] = 0;
4272                 defaults->get(string, resources->filebox_history[i].path);
4273                 sprintf(string, "FILEBOX_HISTORY_ID%d", i);
4274                 resources->filebox_history[i].id = defaults->get(string, resources->get_id());
4275                 if(resources->filebox_history[i].id > newest_id)
4276                         newest_id = resources->filebox_history[i].id;
4277         }
4278
4279         resources->filebox_id = newest_id + 1;
4280         resources->filebox_mode = defaults->get("FILEBOX_MODE", get_resources()->filebox_mode);
4281         resources->filebox_w = defaults->get("FILEBOX_W", get_resources()->filebox_w);
4282         resources->filebox_h = defaults->get("FILEBOX_H", get_resources()->filebox_h);
4283         resources->filebox_columntype[0] = defaults->get("FILEBOX_TYPE0", resources->filebox_columntype[0]);
4284         resources->filebox_columntype[1] = defaults->get("FILEBOX_TYPE1", resources->filebox_columntype[1]);
4285         resources->filebox_columntype[2] = defaults->get("FILEBOX_TYPE2", resources->filebox_columntype[2]);
4286         resources->filebox_columntype[3] = defaults->get("FILEBOX_TYPE3", resources->filebox_columntype[3]);
4287         resources->filebox_columnwidth[0] = defaults->get("FILEBOX_WIDTH0", resources->filebox_columnwidth[0]);
4288         resources->filebox_columnwidth[1] = defaults->get("FILEBOX_WIDTH1", resources->filebox_columnwidth[1]);
4289         resources->filebox_columnwidth[2] = defaults->get("FILEBOX_WIDTH2", resources->filebox_columnwidth[2]);
4290         resources->filebox_columnwidth[3] = defaults->get("FILEBOX_WIDTH3", resources->filebox_columnwidth[3]);
4291         resources->filebox_size_format = defaults->get("FILEBOX_SIZE_FORMAT", get_resources()->filebox_size_format);
4292         defaults->get("FILEBOX_FILTER", resources->filebox_filter);
4293         return 0;
4294 }
4295
4296 int BC_WindowBase::save_defaults(BC_Hash *defaults)
4297 {
4298         BC_Resources *resources = get_resources();
4299         char string[BCTEXTLEN];
4300         for(int i = 0; i < FILEBOX_HISTORY_SIZE; i++)
4301         {
4302                 sprintf(string, "FILEBOX_HISTORY_PATH%d", i);
4303                 defaults->update(string, resources->filebox_history[i].path);
4304                 sprintf(string, "FILEBOX_HISTORY_ID%d", i);
4305                 defaults->update(string, resources->filebox_history[i].id);
4306         }
4307         defaults->update("FILEBOX_MODE", resources->filebox_mode);
4308         defaults->update("FILEBOX_W", resources->filebox_w);
4309         defaults->update("FILEBOX_H", resources->filebox_h);
4310         defaults->update("FILEBOX_TYPE0", resources->filebox_columntype[0]);
4311         defaults->update("FILEBOX_TYPE1", resources->filebox_columntype[1]);
4312         defaults->update("FILEBOX_TYPE2", resources->filebox_columntype[2]);
4313         defaults->update("FILEBOX_TYPE3", resources->filebox_columntype[3]);
4314         defaults->update("FILEBOX_WIDTH0", resources->filebox_columnwidth[0]);
4315         defaults->update("FILEBOX_WIDTH1", resources->filebox_columnwidth[1]);
4316         defaults->update("FILEBOX_WIDTH2", resources->filebox_columnwidth[2]);
4317         defaults->update("FILEBOX_WIDTH3", resources->filebox_columnwidth[3]);
4318         defaults->update("FILEBOX_FILTER", resources->filebox_filter);
4319         defaults->update("FILEBOX_SIZE_FORMAT", get_resources()->filebox_size_format);
4320         return 0;
4321 }
4322
4323
4324
4325 // For some reason XTranslateCoordinates can take a long time to return.
4326 // We work around this by only calling it when the event windows are different.
4327 void BC_WindowBase::translate_coordinates(Window src_w,
4328                 Window dest_w,
4329                 int src_x,
4330                 int src_y,
4331                 int *dest_x_return,
4332                 int *dest_y_return)
4333 {
4334         Window tempwin = 0;
4335 //Timer timer;
4336 //timer.update();
4337         if(src_w == dest_w)
4338         {
4339                 *dest_x_return = src_x;
4340                 *dest_y_return = src_y;
4341         }
4342         else
4343         {
4344                 XTranslateCoordinates(top_level->display,
4345                         src_w,
4346                         dest_w,
4347                         src_x,
4348                         src_y,
4349                         dest_x_return,
4350                         dest_y_return,
4351                         &tempwin);
4352 //printf("BC_WindowBase::translate_coordinates 1 %lld\n", timer.get_difference());
4353         }
4354 }
4355
4356 void BC_WindowBase::get_root_coordinates(int x, int y, int *abs_x, int *abs_y)
4357 {
4358         translate_coordinates(win, top_level->rootwin, x, y, abs_x, abs_y);
4359 }
4360
4361 void BC_WindowBase::get_win_coordinates(int abs_x, int abs_y, int *x, int *y)
4362 {
4363         translate_coordinates(top_level->rootwin, win, abs_x, abs_y, x, y);
4364 }
4365
4366
4367
4368
4369
4370
4371 #ifdef HAVE_LIBXXF86VM
4372 void BC_WindowBase::closest_vm(int *vm, int *width, int *height)
4373 {
4374    int foo,bar;
4375    *vm = 0;
4376    if(XF86VidModeQueryExtension(top_level->display,&foo,&bar)) {
4377            int vm_count,i;
4378            XF86VidModeModeInfo **vm_modelines;
4379            XF86VidModeGetAllModeLines(top_level->display,XDefaultScreen(top_level->display),&vm_count,&vm_modelines);
4380            for (i = 0; i < vm_count; i++) {
4381                    if (vm_modelines[i]->hdisplay < vm_modelines[*vm]->hdisplay && vm_modelines[i]->hdisplay >= *width)
4382                            *vm = i;
4383            }
4384            display = top_level->display;
4385            if (vm_modelines[*vm]->hdisplay == *width)
4386                    *vm = -1;
4387            else
4388            {
4389                    *width = vm_modelines[*vm]->hdisplay;
4390                    *height = vm_modelines[*vm]->vdisplay;
4391            }
4392    }
4393 }
4394
4395 void BC_WindowBase::scale_vm(int vm)
4396 {
4397    int foo,bar,dotclock;
4398    if(XF86VidModeQueryExtension(top_level->display,&foo,&bar))
4399    {
4400            int vm_count;
4401            XF86VidModeModeInfo **vm_modelines;
4402            XF86VidModeModeLine vml;
4403            XF86VidModeGetAllModeLines(top_level->display,XDefaultScreen(top_level->display),&vm_count,&vm_modelines);
4404            XF86VidModeGetModeLine(top_level->display,XDefaultScreen(top_level->display),&dotclock,&vml);
4405            orig_modeline.dotclock = dotclock;
4406            orig_modeline.hdisplay = vml.hdisplay;
4407            orig_modeline.hsyncstart = vml.hsyncstart;
4408            orig_modeline.hsyncend = vml.hsyncend;
4409            orig_modeline.htotal = vml.htotal;
4410            orig_modeline.vdisplay = vml.vdisplay;
4411            orig_modeline.vsyncstart = vml.vsyncstart;
4412            orig_modeline.vsyncend = vml.vsyncend;
4413            orig_modeline.vtotal = vml.vtotal;
4414            orig_modeline.flags = vml.flags;
4415            orig_modeline.privsize = vml.privsize;
4416            // orig_modeline.private = vml.private;
4417            XF86VidModeSwitchToMode(top_level->display,XDefaultScreen(top_level->display),vm_modelines[vm]);
4418            XF86VidModeSetViewPort(top_level->display,XDefaultScreen(top_level->display),0,0);
4419            XFlush(top_level->display);
4420    }
4421 }
4422
4423 void BC_WindowBase::restore_vm()
4424 {
4425    XF86VidModeSwitchToMode(top_level->display,XDefaultScreen(top_level->display),&orig_modeline);
4426    XFlush(top_level->display);
4427 }
4428
4429
4430 #endif
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449 #ifndef SINGLE_THREAD
4450 int BC_WindowBase::get_event_count()
4451 {
4452         event_lock->lock("BC_WindowBase::get_event_count");
4453         int result = common_events.total;
4454         event_lock->unlock();
4455         return result;
4456 }
4457
4458 XEvent* BC_WindowBase::get_event()
4459 {
4460         XEvent *result = 0;
4461         while(!done && !result)
4462         {
4463                 event_condition->lock("BC_WindowBase::get_event");
4464                 event_lock->lock("BC_WindowBase::get_event");
4465
4466                 if(common_events.total && !done)
4467                 {
4468                         result = common_events.values[0];
4469                         common_events.remove_number(0);
4470                 }
4471
4472                 event_lock->unlock();
4473         }
4474         return result;
4475 }
4476
4477 void BC_WindowBase::put_event(XEvent *event)
4478 {
4479         event_lock->lock("BC_WindowBase::put_event");
4480         common_events.append(event);
4481         event_lock->unlock();
4482         event_condition->unlock();
4483 }
4484
4485 void BC_WindowBase::dequeue_events(Window win)
4486 {
4487         event_lock->lock("BC_WindowBase::dequeue_events");
4488
4489         int out = 0, total = common_events.size();
4490         for( int in=0; in<total; ++in ) {
4491                 if( common_events[in]->xany.window == win ) continue;
4492                 common_events[out++] = common_events[in];
4493         }
4494         common_events.total = out;
4495
4496         event_lock->unlock();
4497 }
4498
4499 int BC_WindowBase::resend_event(BC_WindowBase *window)
4500 {
4501         if( resend_event_window ) return 1;
4502         resend_event_window = window;
4503         return 0;
4504 }
4505
4506 #else
4507
4508 int BC_WindowBase::resend_event(BC_WindowBase *window)
4509 {
4510         return 1;
4511 }
4512
4513 #endif // SINGLE_THREAD
4514
4515 int BC_WindowBase::get_id()
4516 {
4517         return id;
4518 }
4519
4520
4521 BC_Pixmap *BC_WindowBase::create_pixmap(VFrame *vframe)
4522 {
4523         int w = vframe->get_w(), h = vframe->get_h();
4524         BC_Pixmap *icon = new BC_Pixmap(this, w, h);
4525         icon->draw_vframe(vframe, 0,0, w,h, 0,0);
4526         return icon;
4527 }
4528
4529
4530 void BC_WindowBase::flicker(int n, int ms)
4531 {
4532         int color = get_bg_color();
4533         for( int i=2*n; --i>=0; ) {
4534                 set_inverse();          set_bg_color(WHITE);
4535                 clear_box(0,0, w,h);    flash(1);
4536                 sync_display();         Timer::delay(ms);
4537         }
4538         set_bg_color(color);
4539         set_opaque();
4540 }
4541