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