font debug env var, drag fixes, cposer hide scrollbar, plugin tool tip
[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(int opts)
89 {
90         this->options = opts;
91 //printf("BC_WindowBase::BC_WindowBase 1\n");
92         BC_WindowBase::initialize();
93 }
94
95 BC_WindowBase::~BC_WindowBase()
96 {
97 #ifdef SINGLE_THREAD
98         BC_Display::lock_display("BC_WindowBase::~BC_WindowBase");
99 #else
100         if(window_type == MAIN_WINDOW)
101                 lock_window("BC_WindowBase::~BC_WindowBase");
102 #endif
103
104 #ifdef HAVE_LIBXXF86VM
105         if(window_type == VIDMODE_SCALED_WINDOW && vm_switched) {
106                 restore_vm();
107         }
108 #endif
109         is_deleting = 1;
110
111         hide_tooltip();
112         if(window_type != MAIN_WINDOW)
113         {
114 // stop event input
115                 XSelectInput(top_level->display, this->win, 0);
116                 XSync(top_level->display,0);
117 #ifndef SINGLE_THREAD
118                 top_level->dequeue_events(win);
119 #endif
120 // drop active window refs to this
121                 if(top_level->active_menubar == this) top_level->active_menubar = 0;
122                 if(top_level->active_popup_menu == this) top_level->active_popup_menu = 0;
123                 if(top_level->active_subwindow == this) top_level->active_subwindow = 0;
124 // drop motion window refs to this
125                 if(top_level->motion_events && top_level->last_motion_win == this->win)
126                         top_level->motion_events = 0;
127
128 // Remove pointer from parent window to this
129                 parent_window->subwindows->remove(this);
130         }
131
132         if(grab_active) grab_active->active_grab = 0;
133         if(icon_window) delete icon_window;
134         if(window_type == POPUP_WINDOW)
135                 parent_window->remove_popup(this);
136
137 // Delete the subwindows
138         if(subwindows)
139         {
140                 while(subwindows->total)
141                 {
142 // Subwindow removes its own pointer
143                         delete subwindows->values[0];
144                 }
145                 delete subwindows;
146         }
147
148         delete pixmap;
149
150 #ifdef HAVE_GL
151         if( get_resources()->get_synchronous() &&
152                 (top_level->options & GLX_WINDOW) && glx_win != 0 )
153                 get_resources()->get_synchronous()->delete_window(this);
154         else
155 #endif
156                 XDestroyWindow(top_level->display, win);
157
158         if(bg_pixmap && !shared_bg_pixmap) delete bg_pixmap;
159         if(icon_pixmap) delete icon_pixmap;
160         if(temp_bitmap) delete temp_bitmap;
161         top_level->active_bitmaps.remove_buffers(this);
162         if(_7segment_pixmaps)
163         {
164                 for(int i = 0; i < TOTAL_7SEGMENT; i++)
165                         delete _7segment_pixmaps[i];
166
167                 delete [] _7segment_pixmaps;
168         }
169
170
171
172         if(window_type == MAIN_WINDOW)
173         {
174                 XFreeGC(display, gc);
175                 static XFontStruct *BC_WindowBase::*xfont[] = {
176                          &BC_WindowBase::smallfont,
177                          &BC_WindowBase::mediumfont,
178                          &BC_WindowBase::largefont,
179                          &BC_WindowBase::bigfont,
180                 };
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                 };
197                 for( int i=sizeof(xft_font)/sizeof(xft_font[0]); --i>=0; ) {
198                         XftFont *xft = (XftFont *)(this->*xft_font[i]);
199                         if( xft ) XftFontClose (display, xft);
200                 }
201 #endif
202                 finit_im();
203                 flush();
204                 sync_display();
205
206                 if( xinerama_info )
207                         XFree(xinerama_info);
208                 xinerama_screens = 0;
209                 xinerama_info = 0;
210                 if( xvideo_port_id >= 0 )
211                         XvUngrabPort(display, xvideo_port_id, CurrentTime);
212
213                 unlock_window();
214 // Can't close display if another thread is waiting for events.
215 // Synchronous thread must delete display it owns a GLX_WINDOW
216 // Must be last reference to display.
217 #ifndef SINGLE_THREAD
218 #ifdef HAVE_GL
219                 if( (options & GLX_DISPLAY) != 0 && get_resources()->get_synchronous() ) {
220                         printf(_("BC_WindowBase::~BC_WindowBase window deleted but opengl deletion is not\n"
221                                 "implemented for BC_Pixmap.\n"));
222                         get_resources()->get_synchronous()->delete_display(this);
223                 }
224                 else
225 #endif
226                 {
227 // _XftDisplayInfo needs a lock.
228                         get_resources()->create_window_lock->lock("BC_WindowBase::~BC_WindowBase");
229                         XCloseDisplay(display);
230                         get_resources()->create_window_lock->unlock();
231                 }
232 // clipboard uses a different display connection
233                 clipboard->stop_clipboard();
234                 delete clipboard;
235 #endif // SINGLE_THREAD
236         }
237
238         resize_history.remove_all_objects();
239
240 #ifndef SINGLE_THREAD
241         common_events.remove_all_objects();
242         delete event_lock;
243         delete event_condition;
244         delete init_lock;
245 #else
246         top_level->window_lock = 0;
247         BC_Display::unlock_display();
248 #endif
249         delete cursor_timer;
250
251 #if HAVE_GL
252         if( glx_fbcfgs_window ) XFree(glx_fbcfgs_window);
253         if( glx_fbcfgs_pbuffer) XFree(glx_fbcfgs_pbuffer);
254         if( glx_fbcfgs_pixmap ) XFree(glx_fbcfgs_pixmap);
255 #endif
256
257         UNSET_ALL_LOCKS(this)
258 }
259
260 int BC_WindowBase::initialize()
261 {
262         done = 0;
263         done_set = 0;
264         window_running = 0;
265         display_lock_owner = 0;
266         test_keypress = 0;
267         keys_return[0] = 0;
268         is_deleting = 0;
269         window_lock = 0;
270         x = 0;
271         y = 0;
272         w = 0;
273         h = 0;
274         bg_color = -1;
275         line_width = 1;
276         line_dashes = 0;
277         top_level = 0;
278         parent_window = 0;
279         subwindows = 0;
280         xinerama_info = 0;
281         xinerama_screens = 0;
282         xvideo_port_id = -1;
283         video_on = 0;
284         motion_events = 0;
285         resize_events = 0;
286         translation_events = 0;
287         ctrl_mask = shift_mask = alt_mask = 0;
288         cursor_x = cursor_y = button_number = 0;
289         button_down = 0;
290         button_pressed = 0;
291         button_time1 = 0;
292         button_time2 = 0;
293         button_time3 = 0;
294         double_click = 0;
295         triple_click = 0;
296         event_win = 0;
297         last_motion_win = 0;
298         key_pressed = 0;
299         active_grab = 0;
300         grab_active = 0;
301         active_menubar = 0;
302         active_popup_menu = 0;
303         active_subwindow = 0;
304         cursor_entered = 0;
305         pixmap = 0;
306         bg_pixmap = 0;
307         _7segment_pixmaps = 0;
308         tooltip_text = 0;
309         force_tooltip = 0;
310 //      next_repeat_id = 0;
311         tooltip_popup = 0;
312         current_font = MEDIUMFONT;
313         current_color = BLACK;
314         current_cursor = ARROW_CURSOR;
315         hourglass_total = 0;
316         is_dragging = 0;
317         shared_bg_pixmap = 0;
318         icon_pixmap = 0;
319         icon_window = 0;
320         window_type = MAIN_WINDOW;
321         translation_count = 0;
322         x_correction = y_correction = 0;
323         temp_bitmap = 0;
324         tooltip_on = 0;
325         temp_cursor = 0;
326         toggle_value = 0;
327         toggle_drag = 0;
328         has_focus = 0;
329         is_hourglass = 0;
330         is_transparent = 0;
331 #ifdef HAVE_LIBXXF86VM
332         vm_switched = 0;
333 #endif
334         input_method = 0;
335         input_context = 0;
336
337         smallfont = 0;
338         mediumfont = 0;
339         largefont = 0;
340         bigfont = 0;
341         clockfont = 0;
342
343         smallfont_xft = 0;
344         mediumfont_xft = 0;
345         largefont_xft = 0;
346         bigfont_xft = 0;
347         clockfont_xft = 0;
348
349         bold_smallfont_xft = 0;
350         bold_mediumfont_xft = 0;
351         bold_largefont_xft = 0;
352 #ifdef SINGLE_THREAD
353         completion_lock = new Condition(0, "BC_WindowBase::completion_lock");
354 #else
355 // Need these right away since put_event is called before run_window sometimes.
356         event_lock = new Mutex("BC_WindowBase::event_lock");
357         event_condition = new Condition(0, "BC_WindowBase::event_condition");
358         init_lock = new Condition(0, "BC_WindowBase::init_lock");
359 #endif
360
361         cursor_timer = new Timer;
362         event_thread = 0;
363 #ifdef HAVE_GL
364         glx_fbcfgs_window = 0;  n_fbcfgs_window = 0;
365         glx_fbcfgs_pbuffer = 0; n_fbcfgs_pbuffer = 0;
366         glx_fbcfgs_pixmap = 0;  n_fbcfgs_pixmap = 0;
367
368         glx_fb_config = 0;
369         glx_win_context = 0;
370         glx_win = 0;
371 #endif
372
373         flash_enabled = 1;
374         win = 0;
375         return 0;
376 }
377
378
379
380 #define DEFAULT_EVENT_MASKS EnterWindowMask | \
381                         LeaveWindowMask | \
382                         ButtonPressMask | \
383                         ButtonReleaseMask | \
384                         PointerMotionMask | \
385                         FocusChangeMask
386
387
388 int BC_WindowBase::create_window(BC_WindowBase *parent_window, const char *title,
389                 int x, int y, int w, int h, int minw, int minh, int allow_resize,
390                 int private_color, int hide, int bg_color, const char *display_name,
391                 int window_type, BC_Pixmap *bg_pixmap, int group_it)
392 {
393         XSetWindowAttributes attr;
394         unsigned long mask;
395         XSizeHints size_hints;
396         int root_w;
397         int root_h;
398 #ifdef HAVE_LIBXXF86VM
399         int vm;
400 #endif
401
402         id = get_resources()->get_id();
403         int need_lock = 0;
404         if(parent_window) top_level = parent_window->top_level;
405         if( top_level ) { // need this to avoid deadlock with Xlib's locks
406                 need_lock = 1;
407                 lock_window("BC_WindowBase::create_window");
408         }
409         get_resources()->create_window_lock->lock("BC_WindowBase::create_window");
410
411 #ifdef HAVE_LIBXXF86VM
412         if(window_type == VIDMODE_SCALED_WINDOW)
413                 closest_vm(&vm,&w,&h);
414 #endif
415
416         this->x = x;
417         this->y = y;
418         this->w = w;
419         this->h = h;
420         this->bg_color = bg_color;
421         this->window_type = window_type;
422         this->hidden = hide;
423         this->private_color = private_color;
424         this->parent_window = parent_window;
425         this->bg_pixmap = bg_pixmap;
426         this->allow_resize = allow_resize;
427         if(display_name)
428                 strcpy(this->display_name, display_name);
429         else
430                 this->display_name[0] = 0;
431
432         put_title(_(title));
433         if(bg_pixmap) shared_bg_pixmap = 1;
434
435         subwindows = new BC_SubWindowList;
436
437         if(window_type == MAIN_WINDOW)
438         {
439                 top_level = this;
440                 parent_window = this;
441
442
443 #ifdef SINGLE_THREAD
444                 display = BC_Display::get_display(display_name);
445                 BC_Display::lock_display("BC_WindowBase::create_window");
446 //              BC_Display::display_global->new_window(this);
447 #else
448
449 // get the display connection
450
451 // This function must be the first Xlib
452 // function a multi-threaded program calls
453                 XInitThreads();
454                 display = init_display(display_name);
455                 if( shm_completion_event < 0 ) shm_completion_event =
456                         ShmCompletion + XShmGetEventBase(display);
457 #endif
458
459                 screen = DefaultScreen(display);
460                 rootwin = RootWindow(display, screen);
461 // window placement boundaries
462                 if( !xinerama_screens && XineramaIsActive(display) )
463                         xinerama_info = XineramaQueryScreens(display, &xinerama_screens);
464                 root_w = get_root_w(0);
465                 root_h = get_root_h(0);
466
467 #if HAVE_GL
468                 vis = get_glx_visual(display);
469                 if( !vis )
470 #endif
471                         vis = DefaultVisual(display, screen);
472
473                 default_depth = DefaultDepth(display, screen);
474
475                 client_byte_order = (*(const u_int32_t*)"a   ") & 0x00000001;
476                 server_byte_order = (XImageByteOrder(display) == MSBFirst) ? 0 : 1;
477
478
479 // This must be done before fonts to know if antialiasing is available.
480                 init_colors();
481 // get the resources
482                 if(resources.use_shm < 0) resources.initialize_display(this);
483                 x_correction = BC_DisplayInfo::get_left_border();
484                 y_correction = BC_DisplayInfo::get_top_border();
485
486 // clamp window placement
487                 if(this->x + this->w + x_correction > root_w)
488                         this->x = root_w - this->w - x_correction;
489                 if(this->y + this->h + y_correction > root_h)
490                         this->y = root_h - this->h - y_correction;
491                 if(this->x < 0) this->x = 0;
492                 if(this->y < 0) this->y = 0;
493
494                 if(this->bg_color == -1)
495                         this->bg_color = resources.get_bg_color();
496
497 // printf("bcwindowbase 1 %s\n", title);
498 // if(window_type == MAIN_WINDOW) sleep(1);
499 // printf("bcwindowbase 10\n");
500                 init_fonts();
501                 init_gc();
502                 init_cursors();
503
504 // Create the window
505                 mask = CWEventMask | CWBackPixel | CWColormap | CWCursor;
506
507                 attr.event_mask = DEFAULT_EVENT_MASKS |
508                         StructureNotifyMask |
509                         KeyPressMask |
510                         KeyReleaseMask;
511
512                 attr.background_pixel = get_color(this->bg_color);
513                 attr.colormap = cmap;
514                 attr.cursor = get_cursor_struct(ARROW_CURSOR);
515
516                 win = XCreateWindow(display, rootwin,
517                         this->x, this->y, this->w, this->h, 0,
518                         top_level->default_depth, InputOutput,
519                         vis, mask, &attr);
520                 XGetNormalHints(display, win, &size_hints);
521
522                 size_hints.flags = PSize | PMinSize | PMaxSize;
523                 size_hints.width = this->w;
524                 size_hints.height = this->h;
525                 size_hints.min_width = allow_resize ? minw : this->w;
526                 size_hints.max_width = allow_resize ? 32767 : this->w;
527                 size_hints.min_height = allow_resize ? minh : this->h;
528                 size_hints.max_height = allow_resize ? 32767 : this->h;
529                 if(x > -BC_INFINITY && x < BC_INFINITY)
530                 {
531                         size_hints.flags |= PPosition;
532                         size_hints.x = this->x;
533                         size_hints.y = this->y;
534                 }
535                 XSetWMProperties(display, win, 0, 0, 0, 0, &size_hints, 0, 0);
536                 get_atoms();
537                 set_title(title);
538 #ifndef SINGLE_THREAD
539                 clipboard = new BC_Clipboard(this);
540                 clipboard->start_clipboard();
541 #endif
542
543
544                 if (group_it)
545                 {
546                         Atom ClientLeaderXAtom;
547                         if (XGroupLeader == 0)
548                                 XGroupLeader = win;
549                         const char *instance_name = "cinelerra";
550                         const char *class_name = "Cinelerra";
551                         XClassHint *class_hints = XAllocClassHint();
552                         class_hints->res_name = (char*)instance_name;
553                         class_hints->res_class = (char*)class_name;
554                         XSetClassHint(top_level->display, win, class_hints);
555                         XFree(class_hints);
556                         ClientLeaderXAtom = XInternAtom(display, "WM_CLIENT_LEADER", True);
557                         XChangeProperty(display, win, ClientLeaderXAtom, XA_WINDOW, 32,
558                                 PropModeReplace, (unsigned char *)&XGroupLeader, true);
559                 }
560                 init_im();
561         }
562
563 #ifdef HAVE_LIBXXF86VM
564         if(window_type == VIDMODE_SCALED_WINDOW && vm != -1)
565         {
566                 scale_vm (vm);
567                 vm_switched = 1;
568         }
569 #endif
570
571 #ifdef HAVE_LIBXXF86VM
572         if(window_type == POPUP_WINDOW || window_type == VIDMODE_SCALED_WINDOW)
573 #else
574         if(window_type == POPUP_WINDOW)
575 #endif
576         {
577                 mask = CWEventMask | CWBackPixel | CWColormap |
578                         CWOverrideRedirect | CWSaveUnder | CWCursor;
579
580                 attr.event_mask = DEFAULT_EVENT_MASKS |
581                         KeyPressMask |
582                         KeyReleaseMask;
583
584                 if(this->bg_color == -1)
585                         this->bg_color = resources.get_bg_color();
586                 attr.background_pixel = top_level->get_color(bg_color);
587                 attr.colormap = top_level->cmap;
588                 if(top_level->is_hourglass)
589                         attr.cursor = top_level->get_cursor_struct(HOURGLASS_CURSOR);
590                 else
591                         attr.cursor = top_level->get_cursor_struct(ARROW_CURSOR);
592                 attr.override_redirect = True;
593                 attr.save_under = True;
594
595                 win = XCreateWindow(top_level->display,
596                         top_level->rootwin, this->x, this->y, this->w, this->h, 0,
597                         top_level->default_depth, InputOutput, top_level->vis, mask,
598                         &attr);
599                 top_level->add_popup(this);
600         }
601
602         if(window_type == SUB_WINDOW)
603         {
604                 mask = CWEventMask | CWBackPixel | CWCursor;
605                 attr.event_mask = DEFAULT_EVENT_MASKS;
606                 attr.background_pixel = top_level->get_color(this->bg_color);
607                 if(top_level->is_hourglass)
608                         attr.cursor = top_level->get_cursor_struct(HOURGLASS_CURSOR);
609                 else
610                         attr.cursor = top_level->get_cursor_struct(ARROW_CURSOR);
611                 win = XCreateWindow(top_level->display,
612                         parent_window->win, this->x, this->y, this->w, this->h, 0,
613                         top_level->default_depth, InputOutput, top_level->vis, mask,
614                         &attr);
615                 init_window_shape();
616                 if(!hidden) XMapWindow(top_level->display, win);
617         }
618
619 // Create pixmap for all windows
620         pixmap = new BC_Pixmap(this, this->w, this->h);
621
622 // Set up options for main window
623         if(window_type == MAIN_WINDOW)
624         {
625                 if(get_resources()->bg_image && !bg_pixmap && bg_color < 0)
626                 {
627                         this->bg_pixmap = new BC_Pixmap(this,
628                                 get_resources()->bg_image,
629                                 PIXMAP_OPAQUE);
630                 }
631
632                 if(!hidden) show_window();
633
634         }
635
636         draw_background(0, 0, this->w, this->h);
637
638         flash(-1, -1, -1, -1, 0);
639
640 // Set up options for popup window
641 #ifdef HAVE_LIBXXF86VM
642         if(window_type == POPUP_WINDOW || window_type == VIDMODE_SCALED_WINDOW)
643 #else
644         if(window_type == POPUP_WINDOW)
645 #endif
646         {
647                 init_window_shape();
648                 if(!hidden) show_window();
649         }
650         get_resources()->create_window_lock->unlock();
651         if(need_lock) unlock_window();
652
653         return 0;
654 }
655
656 Display* BC_WindowBase::init_display(const char *display_name)
657 {
658         Display* display;
659
660         if(display_name && display_name[0] == 0) display_name = NULL;
661         if((display = XOpenDisplay(display_name)) == NULL) {
662                 printf("BC_WindowBase::init_display: cannot connect to X server %s\n",
663                         display_name);
664                 if(getenv("DISPLAY") == NULL) {
665                         printf(_("'DISPLAY' environment variable not set.\n"));
666                         exit(1);
667                 }
668                 else {
669 // Try again with default display.
670                         if((display = XOpenDisplay(0)) == NULL) {
671                                 printf("BC_WindowBase::init_display: cannot connect to default X server.\n");
672                                 exit(1);
673                         }
674                 }
675         }
676
677         static int xsynch = -1;
678         if( xsynch < 0 ) {
679                 const char *cp = getenv("CIN_XSYNCH");
680                 xsynch = !cp ? 0 : atoi(cp);
681         }
682         if( xsynch > 0 )
683                 XSynchronize(display, True);
684
685         return display;
686 }
687
688 Display* BC_WindowBase::get_display()
689 {
690         return top_level->display;
691 }
692
693 int BC_WindowBase::get_screen()
694 {
695         return top_level->screen;
696 }
697
698 int BC_WindowBase::run_window()
699 {
700         done_set = done = 0;
701         return_value = 0;
702
703
704 // Events may have been sent before run_window so can't initialize them here.
705
706 #ifdef SINGLE_THREAD
707         set_repeat(get_resources()->tooltip_delay);
708         BC_Display::display_global->new_window(this);
709
710 // If the first window created, run the display loop in this thread.
711         if(BC_Display::display_global->is_first(this))
712         {
713                 BC_Display::unlock_display();
714                 BC_Display::display_global->loop();
715         }
716         else
717         {
718                 BC_Display::unlock_display();
719                 completion_lock->lock("BC_WindowBase::run_window");
720         }
721
722         BC_Display::lock_display("BC_WindowBase::run_window");
723         BC_Display::display_global->delete_window(this);
724
725         unset_all_repeaters();
726         hide_tooltip();
727         BC_Display::unlock_display();
728
729 #else // SINGLE_THREAD
730
731
732
733 // Start tooltips
734         set_repeat(get_resources()->tooltip_delay);
735
736 // Start X server events
737         event_thread = new BC_WindowEvents(this);
738         event_thread->start();
739
740 // Release wait lock
741         window_running = 1;
742         init_lock->unlock();
743
744 // Handle common events
745         while(!done)
746         {
747                 dispatch_event(0);
748         }
749
750         unset_all_repeaters();
751         hide_tooltip();
752         delete event_thread;
753         event_thread = 0;
754         event_condition->reset();
755         common_events.remove_all_objects();
756         window_running = 0;
757         done = 0;
758
759 #endif // SINGLE_THREAD
760
761         return return_value;
762 }
763
764 int BC_WindowBase::get_key_masks(unsigned int key_state)
765 {
766 // printf("BC_WindowBase::get_key_masks %llx\n",
767 // event->xkey.state);
768         ctrl_mask = (key_state & ControlMask) ? 1 : 0;  // ctrl key down
769         shift_mask = (key_state & ShiftMask) ? 1 : 0;   // shift key down
770         alt_mask = (key_state & Mod1Mask) ? 1 : 0;      // alt key down
771         return 0;
772 }
773
774
775 void BC_WindowBase::add_keyboard_listener(int(BC_WindowBase::*handler)(BC_WindowBase *))
776 {
777         BC_KeyboardHandlerLock set;
778         BC_KeyboardHandler::listeners.append(new BC_KeyboardHandler(handler, this));
779 }
780
781 void BC_WindowBase::del_keyboard_listener(int(BC_WindowBase::*handler)(BC_WindowBase *))
782 {
783         BC_KeyboardHandlerLock set;
784         int i = BC_KeyboardHandler::listeners.size();
785         while( --i >= 0 && BC_KeyboardHandler::listeners[i]->handler!=handler );
786         if( i >= 0 ) BC_KeyboardHandler::listeners.remove_object_number(i);
787 }
788
789 int BC_KeyboardHandler::run_event(BC_WindowBase *wp)
790 {
791         int result = (win->*handler)(wp);
792         return result;
793 }
794
795 int BC_KeyboardHandler::run_listeners(BC_WindowBase *wp)
796 {
797         int result = 0;
798         BC_KeyboardHandlerLock set;
799         for( int i=0; !result && i<listeners.size(); ++i ) {
800                 BC_KeyboardHandler *listener = listeners[i];
801                 result = listener->run_event(wp);
802         }
803         return result;
804 }
805
806 void BC_KeyboardHandler::kill_grabs()
807 {
808         BC_KeyboardHandlerLock set;
809         for( int i=0; i<listeners.size(); ++i ) {
810                 BC_WindowBase *win = listeners[i]->win;
811                 if( win->get_window_type() != POPUP_WINDOW ) continue;
812                 ((BC_Popup *)win)->ungrab_keyboard();
813         }
814 }
815
816 void BC_ActiveBitmaps::reque(XEvent *event)
817 {
818         XShmCompletionEvent *shm_ev = (XShmCompletionEvent *)event;
819         ShmSeg shmseg = shm_ev->shmseg;
820         Drawable drawable = shm_ev->drawable;
821 //printf("BC_BitmapImage::reque %08lx\n",shmseg);
822         active_lock.lock("BC_BitmapImage::reque");
823         BC_BitmapImage *bfr = first;
824         while( bfr && bfr->get_shmseg() != shmseg ) bfr = bfr->next;
825         if( bfr && bfr->drawable == drawable )
826                 remove_pointer(bfr);
827         active_lock.unlock();
828         if( !bfr ) {
829 // sadly, X reports two drawable completions and creates false reporting, so no boobytrap
830 //              printf("BC_BitmapImage::reque missed shmseg %08x, drawable %08x\n",
831 //                       (int)shmseg, (int)drawable);
832                 return;
833         }
834         if( bfr->drawable != drawable ) return;
835         if( bfr->is_zombie() ) { --BC_Bitmap::zombies; delete bfr; return; }
836         bfr->bitmap->reque(bfr);
837 }
838
839 void BC_ActiveBitmaps::insert(BC_BitmapImage *bfr, Drawable pixmap)
840 {
841         active_lock.lock("BC_BitmapImage::insert");
842         bfr->drawable = pixmap;
843         append(bfr);
844         active_lock.unlock();
845 }
846
847 void BC_ActiveBitmaps::remove_buffers(BC_WindowBase *wdw)
848 {
849         active_lock.lock("BC_ActiveBitmaps::remove");
850         for( BC_BitmapImage *nxt=0, *bfr=first; bfr; bfr=nxt ) {
851                 nxt = bfr->next;
852                 if( bfr->is_zombie() ) { --BC_Bitmap::zombies; delete bfr; continue; }
853                 if( bfr->bitmap->parent_window == wdw ) remove_pointer(bfr);
854         }
855         active_lock.unlock();
856 }
857
858 BC_ActiveBitmaps::BC_ActiveBitmaps()
859 {
860 }
861
862 BC_ActiveBitmaps::~BC_ActiveBitmaps()
863 {
864 }
865
866
867
868 int BC_WindowBase::keysym_lookup(XEvent *event)
869 {
870         for( int i = 0; i < KEYPRESSLEN; ++i ) keys_return[i] = 0;
871         for( int i = 0; i < 4; ++i ) wkey_string[i] = 0;
872
873         if( event->xany.send_event && !event->xany.serial ) {
874                 keysym = (KeySym) event->xkey.keycode;
875                 keys_return[0] = keysym;
876                 return 0;
877         }
878         wkey_string_length = 0;
879
880         if( input_context ) {
881                 wkey_string_length = XwcLookupString(input_context,
882                         (XKeyEvent*)event, wkey_string, 4, &keysym, 0);
883 //printf("keysym_lookup 1 %d %d %lx %x %x %x %x\n", wkey_string_length, keysym,
884 //  wkey_string[0], wkey_string[1], wkey_string[2], wkey_string[3]);
885
886                 Status stat;
887                 int ret = Xutf8LookupString(input_context, (XKeyEvent*)event,
888                                 keys_return, KEYPRESSLEN, &keysym, &stat);
889 //printf("keysym_lookup 2 %d %d %lx %x %x\n", ret, stat, keysym, keys_return[0], keys_return[1]);
890                 if( stat == XLookupBoth ) return ret;
891                 if( stat == XLookupKeySym ) return 0;
892         }
893         int ret = XLookupString((XKeyEvent*)event, keys_return, KEYPRESSLEN, &keysym, 0);
894         wkey_string_length = ret;
895         for( int i=0; i<ret; ++i ) wkey_string[i] = keys_return[i];
896         return ret;
897 }
898
899 pthread_t locking_task = (pthread_t)-1L;
900 int locking_event = -1;
901 int locking_message = -1;
902
903 int BC_WindowBase::dispatch_event(XEvent *event)
904 {
905         Window tempwin;
906         int result;
907         XClientMessageEvent *ptr;
908         int cancel_resize, cancel_translation;
909         const int debug = 0;
910
911         key_pressed = 0;
912
913 #ifndef SINGLE_THREAD
914 // If an event is waiting get it, otherwise
915 // wait for next event only if there are no compressed events.
916         if(get_event_count() ||
917                 (!motion_events && !resize_events && !translation_events))
918         {
919                 event = get_event();
920 // Lock out window deletions
921                 lock_window("BC_WindowBase::dispatch_event 1");
922 locking_event = event->type;
923 locking_task = pthread_self();
924 locking_message = event->xclient.message_type;
925         }
926         else
927 // Handle compressed events
928         {
929                 lock_window("BC_WindowBase::dispatch_event 2");
930                 if(resize_events)
931                         dispatch_resize_event(last_resize_w, last_resize_h);
932                 if(motion_events)
933                         dispatch_motion_event();
934                 if(translation_events)
935                         dispatch_translation_event();
936
937                 unlock_window();
938                 return 0;
939         }
940
941 #endif
942
943
944
945
946 //static const char *event_names[] = {
947 //  "Reply", "Error", "KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease", "MotionNotify",
948 //  "EnterNotify", "LeaveNotify", "FocusIn", "FocusOut", "KeymapNotify", "Expose", "GraphicsExpose",
949 //  "NoExpose", "VisibilityNotify", "CreateNotify", "DestroyNotify", "UnmapNotify", "MapNotify",
950 //  "MapRequest", "ReparentNotify", "ConfigureNotify", "ConfigureRequest", "GravityNotify",
951 //  "ResizeRequest", "CirculateNotify", "CirculateRequest", "PropertyNotify", "SelectionClear",
952 //  "SelectionRequest", "SelectionNotify", "ColormapNotify", "ClientMessage", "MappingNotify",
953 //  "GenericEvent", "LASTEvent",
954 //};
955 //
956 //if(debug)
957 //if(event->type != ClientMessage) {
958 // printf("BC_WindowBase::dispatch_event %d %s %p %d (%s)\n",
959 //__LINE__, title, event, event->type,
960 //  event->type>=0 && event->type<sizeof(event_names)/sizeof(event_names[0]) ?
961 //   event_names[event->type] : "Unknown");
962 //}
963
964         if( active_grab ) {
965                 unlock_window();
966                 active_grab->lock_window("BC_WindowBase::dispatch_event 3");
967                 result = active_grab->grab_event(event);
968                 active_grab->unlock_window();
969                 if( result ) return result;
970                 lock_window("BC_WindowBase::dispatch_event 4");
971         }
972
973         switch(event->type) {
974         case ClientMessage:
975 // Clear the resize buffer
976                 if(resize_events) dispatch_resize_event(last_resize_w, last_resize_h);
977 // Clear the motion buffer since this can clear the window
978                 if(motion_events)
979                 {
980                         dispatch_motion_event();
981                 }
982
983                 ptr = (XClientMessageEvent*)event;
984
985
986                 if(ptr->message_type == ProtoXAtom &&
987                         (Atom)ptr->data.l[0] == DelWinXAtom)
988                 {
989                         close_event();
990                 }
991                 else
992                 if(ptr->message_type == RepeaterXAtom)
993                 {
994                         dispatch_repeat_event(ptr->data.l[0]);
995 // Make sure the repeater still exists.
996 //                              for(int i = 0; i < repeaters.total; i++)
997 //                              {
998 //                                      if(repeaters.values[i]->repeat_id == ptr->data.l[0])
999 //                                      {
1000 //                                              dispatch_repeat_event_master(ptr->data.l[0]);
1001 //                                              break;
1002 //                                      }
1003 //                              }
1004                 }
1005                 else
1006                 if(ptr->message_type == SetDoneXAtom)
1007                 {
1008                         done = 1;
1009                         } else
1010                         { // We currently use X marshalling for xatom events, we can switch to something else later
1011                                 recieve_custom_xatoms((xatom_event *)ptr);
1012                 }
1013                 break;
1014
1015         case FocusIn:
1016                 has_focus = 1;
1017                 dispatch_focus_in();
1018                 break;
1019
1020         case FocusOut:
1021                 has_focus = 0;
1022                 dispatch_focus_out();
1023                 break;
1024
1025 // Maximized
1026         case MapNotify:
1027                 break;
1028
1029 // Minimized
1030         case UnmapNotify:
1031                 break;
1032
1033         case ButtonPress:
1034                 get_key_masks(event->xbutton.state);
1035                 cursor_x = event->xbutton.x;
1036                 cursor_y = event->xbutton.y;
1037                 button_number = event->xbutton.button;
1038
1039 //printf("BC_WindowBase::dispatch_event %d %d\n", __LINE__, button_number);
1040                 event_win = event->xany.window;
1041                 if (button_number < 6)
1042                 {
1043                         if(button_number < 4)
1044                                 button_down = 1;
1045                         button_pressed = event->xbutton.button;
1046                         button_time1 = button_time2;
1047                         button_time2 = button_time3;
1048                         button_time3 = event->xbutton.time;
1049                         drag_x = cursor_x;
1050                         drag_y = cursor_y;
1051                         drag_win = event_win;
1052                         drag_x1 = cursor_x - get_resources()->drag_radius;
1053                         drag_x2 = cursor_x + get_resources()->drag_radius;
1054                         drag_y1 = cursor_y - get_resources()->drag_radius;
1055                         drag_y2 = cursor_y + get_resources()->drag_radius;
1056
1057                         if((long)(button_time3 - button_time1) < resources.double_click * 2)
1058                         {
1059                                 triple_click = 1;
1060                                 button_time3 = button_time2 = button_time1 = 0;
1061                         }
1062                         if((long)(button_time3 - button_time2) < resources.double_click)
1063                         {
1064                                 double_click = 1;
1065 //                              button_time3 = button_time2 = button_time1 = 0;
1066                         }
1067                         else
1068                         {
1069                                 triple_click = 0;
1070                                 double_click = 0;
1071                         }
1072
1073                         dispatch_button_press();
1074                 }
1075                 break;
1076
1077         case ButtonRelease:
1078                 get_key_masks(event->xbutton.state);
1079                 button_number = event->xbutton.button;
1080                 event_win = event->xany.window;
1081                 if (button_number < 6)
1082                 {
1083                         if(button_number < 4)
1084                                 button_down = 0;
1085 //printf("BC_WindowBase::dispatch_event %d %d\n", __LINE__, button_number);
1086
1087                         dispatch_button_release();
1088                 }
1089                 break;
1090
1091         case Expose:
1092                 event_win = event->xany.window;
1093                 dispatch_expose_event();
1094                 break;
1095
1096         case MotionNotify:
1097                 get_key_masks(event->xmotion.state);
1098 // Dispatch previous motion event if this is a subsequent motion from a different window
1099                 if(motion_events && last_motion_win != event->xany.window)
1100                 {
1101                         dispatch_motion_event();
1102                 }
1103
1104 // Buffer the current motion
1105                 motion_events = 1;
1106                 last_motion_state = event->xmotion.state;
1107                 last_motion_x = event->xmotion.x;
1108                 last_motion_y = event->xmotion.y;
1109                 last_motion_win = event->xany.window;
1110                 break;
1111
1112         case ConfigureNotify:
1113 // printf("BC_WindowBase::dispatch_event %d win=%p this->win=%p\n",
1114 // __LINE__,
1115 // event->xany.window,
1116 // win);
1117 // dump_windows();
1118                 XTranslateCoordinates(top_level->display,
1119                         top_level->win,
1120                         top_level->rootwin,
1121                         0,
1122                         0,
1123                         &last_translate_x,
1124                         &last_translate_y,
1125                         &tempwin);
1126                 last_resize_w = event->xconfigure.width;
1127                 last_resize_h = event->xconfigure.height;
1128
1129                 cancel_resize = 0;
1130                 cancel_translation = 0;
1131
1132 // Resize history prevents responses to recursive resize requests
1133                 for(int i = 0; i < resize_history.total && !cancel_resize; i++)
1134                 {
1135                         if(resize_history.values[i]->w == last_resize_w &&
1136                                 resize_history.values[i]->h == last_resize_h)
1137                         {
1138                                 delete resize_history.values[i];
1139                                 resize_history.remove_number(i);
1140                                 cancel_resize = 1;
1141                         }
1142                 }
1143
1144                 if(last_resize_w == w && last_resize_h == h)
1145                         cancel_resize = 1;
1146
1147                 if(!cancel_resize)
1148                 {
1149                         resize_events = 1;
1150                 }
1151
1152                 if((last_translate_x == x && last_translate_y == y))
1153                         cancel_translation = 1;
1154
1155                 if(!cancel_translation)
1156                 {
1157                         translation_events = 1;
1158                 }
1159
1160                 translation_count++;
1161                 break;
1162
1163         case KeyPress:
1164                 get_key_masks(event->xkey.state);
1165                 keys_return[0] = 0;  keysym = -1;
1166                 if(XFilterEvent(event, win)) {
1167                         break;
1168                 }
1169                 if( keysym_lookup(event) < 0 ) {
1170                         printf("keysym %x\n", (uint32_t)keysym);
1171                         break;
1172                 }
1173
1174 //printf("BC_WindowBase::dispatch_event %d keysym=0x%x\n",
1175 //__LINE__,
1176 //keysym);
1177
1178 // block out control keys
1179                 if(keysym > 0xffe0 && keysym < 0xffff) break;
1180 // block out Alt_GR key
1181                 if(keysym == 0xfe03) break;
1182
1183                 if(test_keypress)
1184                          printf("BC_WindowBase::dispatch_event %x\n", (uint32_t)keysym);
1185
1186 #ifdef X_HAVE_UTF8_STRING
1187 //It's Ascii or UTF8?
1188 //              if (keysym != 0xffff && (keys_return[0] & 0xff) >= 0x7f )
1189 //printf("BC_WindowBase::dispatch_event %d %02x%02x\n", __LINE__, keys_return[0], keys_return[1]);
1190
1191                 if( ((keys_return[1] & 0xff) > 0x80) &&
1192                     ((keys_return[0] & 0xff) > 0xC0) ) {
1193 //printf("BC_WindowBase::dispatch_event %d\n", __LINE__);
1194                         key_pressed = keysym & 0xff;
1195                 }
1196                 else {
1197 #endif
1198
1199                 switch(keysym) {
1200 // block out extra keys
1201                 case XK_Alt_L:
1202                 case XK_Alt_R:
1203                 case XK_Shift_L:
1204                 case XK_Shift_R:
1205                 case XK_Control_L:
1206                 case XK_Control_R:
1207                         key_pressed = 0;
1208                         break;
1209
1210 // Translate key codes
1211                 case XK_Return:         key_pressed = RETURN;   break;
1212                 case XK_Up:             key_pressed = UP;       break;
1213                 case XK_Down:           key_pressed = DOWN;     break;
1214                 case XK_Left:           key_pressed = LEFT;     break;
1215                 case XK_Right:          key_pressed = RIGHT;    break;
1216                 case XK_Next:           key_pressed = PGDN;     break;
1217                 case XK_Prior:          key_pressed = PGUP;     break;
1218                 case XK_BackSpace:      key_pressed = BACKSPACE; break;
1219                 case XK_Escape:         key_pressed = ESC;      break;
1220                 case XK_Tab:
1221                         if(shift_down())
1222                                 key_pressed = LEFTTAB;
1223                         else
1224                                 key_pressed = TAB;
1225                         break;
1226                 case XK_ISO_Left_Tab:   key_pressed = LEFTTAB;  break;
1227                 case XK_underscore:     key_pressed = '_';      break;
1228                 case XK_asciitilde:     key_pressed = '~';      break;
1229                 case XK_Delete:         key_pressed = DELETE;   break;
1230                 case XK_Home:           key_pressed = HOME;     break;
1231                 case XK_End:            key_pressed = END;      break;
1232
1233 // number pad
1234                 case XK_KP_Enter:       key_pressed = KPENTER;  break;
1235                 case XK_KP_Add:         key_pressed = KPPLUS;   break;
1236                 case XK_KP_Subtract:    key_pressed = KPMINUS;  break;
1237                 case XK_KP_Multiply:    key_pressed = KPSTAR;   break;
1238                 case XK_KP_Divide:      key_pressed = KPSLASH;  break;
1239                 case XK_KP_1:
1240                 case XK_KP_End:         key_pressed = KP1;      break;
1241                 case XK_KP_2:
1242                 case XK_KP_Down:        key_pressed = KP2;      break;
1243                 case XK_KP_3:
1244                 case XK_KP_Page_Down:   key_pressed = KP3;      break;
1245                 case XK_KP_4:
1246                 case XK_KP_Left:        key_pressed = KP4;      break;
1247                 case XK_KP_5:
1248                 case XK_KP_Begin:       key_pressed = KP5;      break;
1249                 case XK_KP_6:
1250                 case XK_KP_Right:       key_pressed = KP6;      break;
1251                 case XK_KP_7:
1252                 case XK_KP_Home:        key_pressed = KP7;      break;
1253                 case XK_KP_8:
1254                 case XK_KP_Up:          key_pressed = KP8;      break;
1255                 case XK_KP_9:
1256                 case XK_KP_Page_Up:     key_pressed = KP9;      break;
1257                 case XK_KP_0:
1258                 case XK_KP_Insert:      key_pressed = KPINS;    break;
1259                 case XK_KP_Decimal:
1260                 case XK_KP_Delete:      key_pressed = KPDEL;    break;
1261                 case XK_Menu:           key_pressed = KPMENU;   break;  /* menu */
1262 // remote control
1263 // above        case XK_KP_Enter:       key_pressed = KPENTER;  break;  /* check */
1264                 case XF86XK_MenuKB:     key_pressed = KPMENU;   break;  /* menu */
1265 // intercepted  case XF86XK_PowerDown: key_pressed = KPPOWER;   break;  /* Power */
1266                 case XF86XK_Launch1:    key_pressed = KPTV;     break;  /* TV */
1267                 case XF86XK_Launch2:    key_pressed = KPDVD;    break;  /* DVD */
1268 // intercepted  case XF86XK_WWW:        key_pressed = KPWWEB;   break;  /* WEB */
1269                 case XF86XK_Launch3:    key_pressed = KPBOOK;   break;  /* book */
1270                 case XF86XK_Launch4:    key_pressed = KPHAND;   break;  /* hand */
1271                 case XF86XK_Reply:      key_pressed = KPTMR;    break;  /* timer */
1272                 case SunXK_Front:       key_pressed = KPMAXW;   break;  /* max */
1273 // above        case XK_Left:           key_pressed = LEFT;     break;  /* left */
1274 // above        case XK_Right:          key_pressed = RIGHT;    break;  /* right */
1275 // above        case XK_Down:           key_pressed = DOWN;     break;  /* down */
1276 // above        case XK_Up:             key_pressed = UP;       break;  /* up */
1277 // above        case XK_SPACE:          key_pressed = KPSPACE;  break;  /* ok */
1278 // intercepted  case XF86XK_AudioRaiseVolume: key_pressed = KPVOLU;     break;  /* VOL + */
1279 // intercepted  case XF86XK_AudioMute: key_pressed = KPMUTE;    break;  /* MUTE */
1280 // intercepted  case XF86XK_AudioLowerVolume: key_pressed = KPVOLD;     break;  /* VOL - */
1281                 case XF86XK_ScrollUp:   key_pressed = KPCHUP;   break;  /* CH + */
1282                 case XF86XK_ScrollDown: key_pressed = KPCHDN;   break;  /* CH - */
1283                 case XF86XK_AudioRecord: key_pressed = KPRECD;  break;  /* ( o) red */
1284                 case XF86XK_Forward:    key_pressed = KPPLAY;   break;  /* ( >) */
1285                 case XK_Redo:           key_pressed = KPFWRD;   break;  /* (>>) */
1286                 case XF86XK_Back:       key_pressed = KPBACK;   break;  /* (<<) */
1287                 case XK_Cancel:         key_pressed = KPSTOP;   break;  /* ([]) */
1288                 case XK_Pause:          key_pressed = KPAUSE;   break;  /* ('') */
1289
1290                 default:
1291                         key_pressed = keysym & 0xff;
1292 #ifdef X_HAVE_UTF8_STRING
1293 //printf("BC_WindowBase::dispatch_event %d\n", __LINE__);
1294                         keys_return[1] = 0;
1295 #endif
1296                         break;
1297                 }
1298 #ifdef X_HAVE_UTF8_STRING
1299                 }
1300                 key_pressed_utf8 = keys_return;
1301 #endif
1302
1303
1304                 result = 0;
1305                 if( top_level == this )
1306                         result = BC_KeyboardHandler::run_listeners(this);
1307
1308 //printf("BC_WindowBase::dispatch_event %d %d %x\n", shift_down(), alt_down(), key_pressed);
1309                 if( !result )
1310                         result = dispatch_keypress_event();
1311 // Handle some default keypresses
1312                 if(!result)
1313                 {
1314                         if(key_pressed == 'w' ||
1315                                 key_pressed == 'W')
1316                         {
1317                                 close_event();
1318                         }
1319                 }
1320                 break;
1321
1322         case KeyRelease:
1323                 XLookupString((XKeyEvent*)event, keys_return, 1, &keysym, 0);
1324                 dispatch_keyrelease_event();
1325 // printf("BC_WindowBase::dispatch_event KeyRelease keysym=0x%x keystate=0x%lld\n",
1326 // keysym, event->xkey.state);
1327                 break;
1328
1329         case LeaveNotify:
1330                 if( cursor_entered && event->xcrossing.window == win ) {
1331                         cursor_entered = 0;
1332                 }
1333                 event_win = event->xany.window;
1334                 dispatch_cursor_leave();
1335                 break;
1336
1337         case EnterNotify:
1338                 if( !cursor_entered && event->xcrossing.window == win ) {
1339                         if( !event->xcrossing.focus && get_resources()->grab_input_focus ) {
1340                                 XSetInputFocus(display, win, RevertToParent, CurrentTime);
1341                         }
1342                         cursor_entered = 1;
1343                 }
1344                 event_win = event->xany.window;
1345                 cursor_x = event->xcrossing.x;
1346                 cursor_y = event->xcrossing.y;
1347                 dispatch_cursor_enter();
1348                 break;
1349
1350         default:
1351                 break;
1352         }
1353 //printf("100 %s %p %d\n", title, event, event->type);
1354 //if(event->type != ClientMessage) dump();
1355
1356 #ifndef SINGLE_THREAD
1357         unlock_window();
1358         if(event) delete event;
1359 #else
1360 //      if(done) completion_lock->unlock();
1361 #endif
1362
1363 if(debug) printf("BC_WindowBase::dispatch_event this=%p %d\n", this, __LINE__);
1364         return 0;
1365 }
1366
1367 int BC_WindowBase::dispatch_expose_event()
1368 {
1369         int result = 0;
1370         for(int i = 0; i < subwindows->total && !result; i++)
1371         {
1372                 result = subwindows->values[i]->dispatch_expose_event();
1373         }
1374
1375 // Propagate to user
1376         if(!result) expose_event();
1377         return result;
1378 }
1379
1380 int BC_WindowBase::dispatch_resize_event(int w, int h)
1381 {
1382 // Can't store new w and h until the event is handles
1383 // because bcfilebox depends on the old w and h to
1384 // reposition widgets.
1385         if( window_type == MAIN_WINDOW ) {
1386                 flash_enabled = 0;
1387                 resize_events = 0;
1388
1389                 delete pixmap;
1390                 pixmap = new BC_Pixmap(this, w, h);
1391                 clear_box(0, 0, w, h);
1392         }
1393
1394 // Propagate to subwindows
1395         for(int i = 0; i < subwindows->total; i++) {
1396                 subwindows->values[i]->dispatch_resize_event(w, h);
1397         }
1398
1399 // Propagate to user
1400         resize_event(w, h);
1401
1402         if( window_type == MAIN_WINDOW ) {
1403                 this->w = w;
1404                 this->h = h;
1405                 dispatch_flash();
1406                 flush();
1407         }
1408         return 0;
1409 }
1410
1411 int BC_WindowBase::dispatch_flash()
1412 {
1413         flash_enabled = 1;
1414         for(int i = 0; i < subwindows->total; i++)
1415                 subwindows->values[i]->dispatch_flash();
1416         return flash(0);
1417 }
1418
1419 int BC_WindowBase::dispatch_translation_event()
1420 {
1421         translation_events = 0;
1422         if(window_type == MAIN_WINDOW)
1423         {
1424                 prev_x = x;
1425                 prev_y = y;
1426                 x = last_translate_x;
1427                 y = last_translate_y;
1428 // Correct for window manager offsets
1429                 x -= x_correction;
1430                 y -= y_correction;
1431         }
1432
1433         for(int i = 0; i < subwindows->total; i++)
1434         {
1435                 subwindows->values[i]->dispatch_translation_event();
1436         }
1437
1438         translation_event();
1439         return 0;
1440 }
1441
1442 int BC_WindowBase::dispatch_motion_event()
1443 {
1444         int result = 0;
1445         unhide_cursor();
1446
1447         if(top_level == this)
1448         {
1449                 motion_events = 0;
1450                 event_win = last_motion_win;
1451                 get_key_masks(last_motion_state);
1452
1453 // Test for grab
1454                 if(get_button_down() && !active_menubar && !active_popup_menu)
1455                 {
1456                         if(!result)
1457                         {
1458                                 cursor_x = last_motion_x;
1459                                 cursor_y = last_motion_y;
1460                                 result = dispatch_drag_motion();
1461                         }
1462
1463                         if(!result &&
1464                                 (last_motion_x < drag_x1 || last_motion_x >= drag_x2 ||
1465                                 last_motion_y < drag_y1 || last_motion_y >= drag_y2))
1466                         {
1467                                 cursor_x = drag_x;
1468                                 cursor_y = drag_y;
1469
1470                                 result = dispatch_drag_start();
1471                         }
1472                 }
1473
1474                 cursor_x = last_motion_x;
1475                 cursor_y = last_motion_y;
1476
1477 // printf("BC_WindowBase::dispatch_motion_event %d %p %p %p\n",
1478 // __LINE__,
1479 // active_menubar,
1480 // active_popup_menu,
1481 // active_subwindow);
1482
1483                 if(active_menubar && !result) result = active_menubar->dispatch_motion_event();
1484                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_motion_event();
1485                 if(active_subwindow && !result) result = active_subwindow->dispatch_motion_event();
1486         }
1487
1488 // Dispatch in stacking order
1489         for(int i = subwindows->size() - 1; i >= 0 && !result; i--)
1490         {
1491                 result = subwindows->values[i]->dispatch_motion_event();
1492         }
1493
1494         if(!result) result = cursor_motion_event();    // give to user
1495         return result;
1496 }
1497
1498 int BC_WindowBase::dispatch_keypress_event()
1499 {
1500         int result = 0;
1501         if(top_level == this)
1502         {
1503                 if(active_subwindow) result = active_subwindow->dispatch_keypress_event();
1504         }
1505
1506         for(int i = 0; i < subwindows->total && !result; i++)
1507         {
1508                 result = subwindows->values[i]->dispatch_keypress_event();
1509         }
1510
1511         if(!result) result = keypress_event();
1512
1513         return result;
1514 }
1515
1516 int BC_WindowBase::dispatch_keyrelease_event()
1517 {
1518         int result = 0;
1519         if(top_level == this)
1520         {
1521                 if(active_subwindow) result = active_subwindow->dispatch_keyrelease_event();
1522         }
1523
1524         for(int i = 0; i < subwindows->total && !result; i++)
1525         {
1526                 result = subwindows->values[i]->dispatch_keyrelease_event();
1527         }
1528
1529         if(!result) result = keyrelease_event();
1530
1531         return result;
1532 }
1533
1534 int BC_WindowBase::dispatch_focus_in()
1535 {
1536         for(int i = 0; i < subwindows->total; i++)
1537         {
1538                 subwindows->values[i]->dispatch_focus_in();
1539         }
1540
1541         focus_in_event();
1542
1543         return 0;
1544 }
1545
1546 int BC_WindowBase::dispatch_focus_out()
1547 {
1548         for(int i = 0; i < subwindows->total; i++)
1549         {
1550                 subwindows->values[i]->dispatch_focus_out();
1551         }
1552
1553         focus_out_event();
1554
1555         return 0;
1556 }
1557
1558 int BC_WindowBase::get_has_focus()
1559 {
1560         return top_level->has_focus;
1561 }
1562
1563 int BC_WindowBase::get_deleting()
1564 {
1565         if(is_deleting) return 1;
1566         if(parent_window && parent_window->get_deleting()) return 1;
1567         return 0;
1568 }
1569
1570 int BC_WindowBase::dispatch_button_press()
1571 {
1572         int result = 0;
1573
1574
1575         if(top_level == this)
1576         {
1577                 if(active_menubar) result = active_menubar->dispatch_button_press();
1578                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_button_press();
1579                 if(active_subwindow && !result) result = active_subwindow->dispatch_button_press();
1580         }
1581
1582         for(int i = 0; i < subwindows->total && !result; i++)
1583         {
1584                 result = subwindows->values[i]->dispatch_button_press();
1585         }
1586
1587         if(!result) result = button_press_event();
1588
1589
1590         return result;
1591 }
1592
1593 int BC_WindowBase::dispatch_button_release()
1594 {
1595         int result = 0;
1596         if(top_level == this)
1597         {
1598                 if(active_menubar) result = active_menubar->dispatch_button_release();
1599                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_button_release();
1600                 if(active_subwindow && !result) result = active_subwindow->dispatch_button_release();
1601                 if(!result && button_number != 4 && button_number != 5)
1602                         result = dispatch_drag_stop();
1603         }
1604
1605         for(int i = 0; i < subwindows->total && !result; i++)
1606         {
1607                 result = subwindows->values[i]->dispatch_button_release();
1608         }
1609
1610         if(!result)
1611         {
1612                 result = button_release_event();
1613         }
1614
1615         return result;
1616 }
1617
1618
1619 int BC_WindowBase::dispatch_repeat_event(int64_t duration)
1620 {
1621
1622 // all repeat event handlers get called and decide based on activity and duration
1623 // whether to respond
1624         for(int i = 0; i < subwindows->total; i++)
1625         {
1626                 subwindows->values[i]->dispatch_repeat_event(duration);
1627         }
1628
1629
1630         repeat_event(duration);
1631
1632
1633
1634 // Unlock next repeat signal
1635         if(window_type == MAIN_WINDOW)
1636         {
1637 #ifdef SINGLE_THREAD
1638                 BC_Display::display_global->unlock_repeaters(duration);
1639 #else
1640                 for(int i = 0; i < repeaters.total; i++)
1641                 {
1642                         if(repeaters.values[i]->delay == duration)
1643                         {
1644                                 repeaters.values[i]->repeat_lock->unlock();
1645                         }
1646                 }
1647 #endif
1648         }
1649         return 0;
1650 }
1651
1652 void BC_WindowBase::unhide_cursor()
1653 {
1654         if(is_transparent)
1655         {
1656                 is_transparent = 0;
1657                 if(top_level->is_hourglass)
1658                         set_cursor(HOURGLASS_CURSOR, 1, 0);
1659                 else
1660                         set_cursor(current_cursor, 1, 0);
1661         }
1662         cursor_timer->update();
1663 }
1664
1665
1666 void BC_WindowBase::update_video_cursor()
1667 {
1668         if(video_on && !is_transparent)
1669         {
1670                 if(cursor_timer->get_difference() > VIDEO_CURSOR_TIMEOUT && !is_transparent)
1671                 {
1672                         is_transparent = 1;
1673                         set_cursor(TRANSPARENT_CURSOR, 1, 1);
1674                         cursor_timer->update();
1675                 }
1676         }
1677         else
1678         {
1679                 cursor_timer->update();
1680         }
1681 }
1682
1683
1684 int BC_WindowBase::dispatch_cursor_leave()
1685 {
1686         unhide_cursor();
1687
1688         for(int i = 0; i < subwindows->total; i++)
1689         {
1690                 subwindows->values[i]->dispatch_cursor_leave();
1691         }
1692
1693         cursor_leave_event();
1694         return 0;
1695 }
1696
1697 int BC_WindowBase::dispatch_cursor_enter()
1698 {
1699         int result = 0;
1700
1701         unhide_cursor();
1702
1703         if(active_menubar) result = active_menubar->dispatch_cursor_enter();
1704         if(!result && active_popup_menu) result = active_popup_menu->dispatch_cursor_enter();
1705         if(!result && active_subwindow) result = active_subwindow->dispatch_cursor_enter();
1706
1707         for(int i = 0; !result && i < subwindows->total; i++)
1708         {
1709                 result = subwindows->values[i]->dispatch_cursor_enter();
1710         }
1711
1712         if(!result) result = cursor_enter_event();
1713         return result;
1714 }
1715
1716 int BC_WindowBase::cursor_enter_event()
1717 {
1718         return 0;
1719 }
1720
1721 int BC_WindowBase::cursor_leave_event()
1722 {
1723         return 0;
1724 }
1725
1726 int BC_WindowBase::close_event()
1727 {
1728         set_done(1);
1729         return 1;
1730 }
1731
1732 int BC_WindowBase::dispatch_drag_start()
1733 {
1734         int result = 0;
1735         if(active_menubar) result = active_menubar->dispatch_drag_start();
1736         if(!result && active_popup_menu) result = active_popup_menu->dispatch_drag_start();
1737         if(!result && active_subwindow) result = active_subwindow->dispatch_drag_start();
1738
1739         for(int i = 0; i < subwindows->total && !result; i++)
1740         {
1741                 result = subwindows->values[i]->dispatch_drag_start();
1742         }
1743
1744         if(!result) result = is_dragging = drag_start_event();
1745         return result;
1746 }
1747
1748 int BC_WindowBase::dispatch_drag_stop()
1749 {
1750         int result = 0;
1751
1752         for(int i = 0; i < subwindows->total && !result; i++)
1753         {
1754                 result = subwindows->values[i]->dispatch_drag_stop();
1755         }
1756
1757         if(is_dragging && !result)
1758         {
1759                 drag_stop_event();
1760                 is_dragging = 0;
1761                 result = 1;
1762         }
1763
1764         return result;
1765 }
1766
1767 int BC_WindowBase::dispatch_drag_motion()
1768 {
1769         int result = 0;
1770         for(int i = 0; i < subwindows->total && !result; i++)
1771         {
1772                 result = subwindows->values[i]->dispatch_drag_motion();
1773         }
1774
1775         if(is_dragging && !result)
1776         {
1777                 drag_motion_event();
1778                 result = 1;
1779         }
1780
1781         return result;
1782 }
1783
1784
1785 int BC_WindowBase::show_tooltip(const char *text, int x, int y, int w, int h)
1786 {
1787 // default text
1788         int forced = !text ? force_tooltip : 1;
1789         if( !text ) text = tooltip_text;
1790         if( !text || (!forced && !get_resources()->tooltips_enabled) ) {
1791                 top_level->hide_tooltip();
1792                 return 1;
1793         }
1794 // default w,h
1795         if(w < 0) w = get_text_width(MEDIUMFONT, text)  + TOOLTIP_MARGIN * 2;
1796         if(h < 0) h = get_text_height(MEDIUMFONT, text) + TOOLTIP_MARGIN * 2;
1797 // default x,y (win relative)
1798         if( x < 0 ) x = get_w();
1799         if( y < 0 ) y = get_h();
1800         int wx, wy;
1801         get_root_coordinates(x, y, &wx, &wy);
1802 // keep the tip inside the window/display
1803         int x0 = top_level->get_x(), x1 = x0 + top_level->get_w();
1804         int x2 = top_level->get_screen_x(0, -1) + top_level->get_screen_w(0, -1);
1805         if( x1 > x2 ) x1 = x2;
1806         if( wx < x0 ) wx = x0;
1807         if( wx >= (x1-=w) ) wx = x1;
1808         int y0 = top_level->get_y(), y1 = y0 + top_level->get_h();
1809         int y2 = top_level->get_root_h(0);
1810         if( y1 > y2 ) y1 = y2;
1811         if( wy < y0 ) wy = y0;
1812         if( wy >= (y1-=h) ) wy = y1;
1813 // avoid tip under cursor (flickers)
1814         int abs_x, abs_y;
1815         get_abs_cursor_xy(abs_x,abs_y, 0);
1816         if( wx < abs_x && abs_x < wx+w && wy < abs_y && abs_y < wy+h ) {
1817                 if( wx-abs_x < wy-abs_y )
1818                         wx = abs_x+1;
1819                 else
1820                         wy = abs_y+1;
1821         }
1822         if( !tooltip_on ) {
1823                 tooltip_on = 1;
1824                 tooltip_popup = new BC_Popup(top_level, wx, wy, w, h,
1825                                 get_resources()->tooltip_bg_color);
1826         }
1827         else
1828                 tooltip_popup->reposition_window(wx, wy, w, h);
1829
1830         draw_tooltip(text);
1831         tooltip_popup->flash();
1832         tooltip_popup->flush();
1833         return 0;
1834 }
1835
1836 int BC_WindowBase::hide_tooltip()
1837 {
1838         if(subwindows)
1839                 for(int i = 0; i < subwindows->total; i++)
1840                 {
1841                         subwindows->values[i]->hide_tooltip();
1842                 }
1843
1844         if(tooltip_on)
1845         {
1846                 tooltip_on = 0;
1847                 delete tooltip_popup;
1848                 tooltip_popup = 0;
1849         }
1850         return 0;
1851 }
1852
1853 const char *BC_WindowBase::get_tooltip()
1854 {
1855         return tooltip_text;
1856 }
1857
1858 int BC_WindowBase::set_tooltip(const char *text)
1859 {
1860         tooltip_text = text;
1861
1862 // Update existing tooltip if it is visible
1863         if(tooltip_on)
1864         {
1865                 draw_tooltip();
1866                 tooltip_popup->flash();
1867         }
1868         return 0;
1869 }
1870 // signal the event handler to repeat
1871 int BC_WindowBase::set_repeat(int64_t duration)
1872 {
1873         if(duration <= 0)
1874         {
1875                 printf("BC_WindowBase::set_repeat duration=%jd\n", duration);
1876                 return 0;
1877         }
1878         if(window_type != MAIN_WINDOW) return top_level->set_repeat(duration);
1879
1880 #ifdef SINGLE_THREAD
1881         BC_Display::display_global->set_repeat(this, duration);
1882 #else
1883 // test repeater database for duplicates
1884         for(int i = 0; i < repeaters.total; i++)
1885         {
1886 // Already exists
1887                 if(repeaters.values[i]->delay == duration)
1888                 {
1889                         repeaters.values[i]->start_repeating(this);
1890                         return 0;
1891                 }
1892         }
1893
1894         BC_Repeater *repeater = new BC_Repeater(this, duration);
1895         repeater->initialize();
1896         repeaters.append(repeater);
1897         repeater->start_repeating();
1898 #endif
1899         return 0;
1900 }
1901
1902 int BC_WindowBase::unset_repeat(int64_t duration)
1903 {
1904         if(window_type != MAIN_WINDOW) return top_level->unset_repeat(duration);
1905
1906 #ifdef SINGLE_THREAD
1907         BC_Display::display_global->unset_repeat(this, duration);
1908 #else
1909         for(int i = 0; i < repeaters.total; i++)
1910         {
1911                 if(repeaters.values[i]->delay == duration)
1912                 {
1913                         repeaters.values[i]->stop_repeating();
1914                 }
1915         }
1916 #endif
1917         return 0;
1918 }
1919
1920
1921 int BC_WindowBase::unset_all_repeaters()
1922 {
1923 #ifdef SINGLE_THREAD
1924         BC_Display::display_global->unset_all_repeaters(this);
1925 #else
1926         for(int i = 0; i < repeaters.total; i++)
1927         {
1928                 repeaters.values[i]->stop_repeating();
1929         }
1930         repeaters.remove_all_objects();
1931 #endif
1932         return 0;
1933 }
1934
1935 // long BC_WindowBase::get_repeat_id()
1936 // {
1937 //      return top_level->next_repeat_id++;
1938 // }
1939
1940 XEvent *BC_WindowBase::new_xevent()
1941 {
1942         XEvent *event = new XEvent;
1943         memset(event, 0, sizeof(*event));
1944         return event;
1945 }
1946
1947 #ifndef SINGLE_THREAD
1948 int BC_WindowBase::arm_repeat(int64_t duration)
1949 {
1950         XEvent *event = new_xevent();
1951         XClientMessageEvent *ptr = (XClientMessageEvent*)event;
1952         ptr->type = ClientMessage;
1953         ptr->message_type = RepeaterXAtom;
1954         ptr->format = 32;
1955         ptr->data.l[0] = duration;
1956
1957 // Couldn't use XSendEvent since it locked up randomly.
1958         put_event(event);
1959         return 0;
1960 }
1961 #endif
1962
1963 int BC_WindowBase::recieve_custom_xatoms(xatom_event *event)
1964 {
1965         return 0;
1966 }
1967
1968 int BC_WindowBase::send_custom_xatom(xatom_event *event)
1969 {
1970 #ifndef SINGLE_THREAD
1971         XEvent *myevent = new_xevent();
1972         XClientMessageEvent *ptr = (XClientMessageEvent*)myevent;
1973         ptr->type = ClientMessage;
1974         ptr->message_type = event->message_type;
1975         ptr->format = event->format;
1976         ptr->data.l[0] = event->data.l[0];
1977         ptr->data.l[1] = event->data.l[1];
1978         ptr->data.l[2] = event->data.l[2];
1979         ptr->data.l[3] = event->data.l[3];
1980         ptr->data.l[4] = event->data.l[4];
1981
1982         put_event(myevent);
1983 #endif
1984         return 0;
1985 }
1986
1987
1988
1989 Atom BC_WindowBase::create_xatom(const char *atom_name)
1990 {
1991         return XInternAtom(display, atom_name, False);
1992 }
1993
1994 int BC_WindowBase::get_atoms()
1995 {
1996         SetDoneXAtom =  XInternAtom(display, "BC_REPEAT_EVENT", False);
1997         RepeaterXAtom = XInternAtom(display, "BC_CLOSE_EVENT", False);
1998         DestroyAtom =   XInternAtom(display, "BC_DESTROY_WINDOW", False);
1999         DelWinXAtom =   XInternAtom(display, "WM_DELETE_WINDOW", False);
2000         if( (ProtoXAtom = XInternAtom(display, "WM_PROTOCOLS", False)) != 0 )
2001                 XChangeProperty(display, win, ProtoXAtom, XA_ATOM, 32,
2002                         PropModeReplace, (unsigned char *)&DelWinXAtom, True);
2003         return 0;
2004
2005 }
2006
2007
2008 void BC_WindowBase::init_cursors()
2009 {
2010         arrow_cursor = XCreateFontCursor(display, XC_top_left_arrow);
2011         cross_cursor = XCreateFontCursor(display, XC_crosshair);
2012         ibeam_cursor = XCreateFontCursor(display, XC_xterm);
2013         vseparate_cursor = XCreateFontCursor(display, XC_sb_v_double_arrow);
2014         hseparate_cursor = XCreateFontCursor(display, XC_sb_h_double_arrow);
2015         move_cursor = XCreateFontCursor(display, XC_fleur);
2016         left_cursor = XCreateFontCursor(display, XC_sb_left_arrow);
2017         right_cursor = XCreateFontCursor(display, XC_sb_right_arrow);
2018         upright_arrow_cursor = XCreateFontCursor(display, XC_arrow);
2019         upleft_resize_cursor = XCreateFontCursor(display, XC_top_left_corner);
2020         upright_resize_cursor = XCreateFontCursor(display, XC_top_right_corner);
2021         downleft_resize_cursor = XCreateFontCursor(display, XC_bottom_left_corner);
2022         downright_resize_cursor = XCreateFontCursor(display, XC_bottom_right_corner);
2023         hourglass_cursor = XCreateFontCursor(display, XC_watch);
2024         grabbed_cursor = create_grab_cursor();
2025
2026         static char cursor_data[] = { 0,0,0,0, 0,0,0,0 };
2027         Colormap colormap = DefaultColormap(display, screen);
2028         Pixmap pixmap_bottom = XCreateBitmapFromData(display,
2029                 rootwin, cursor_data, 8, 8);
2030         XColor black, dummy;
2031         XAllocNamedColor(display, colormap, "black", &black, &dummy);
2032         transparent_cursor = XCreatePixmapCursor(display,
2033                 pixmap_bottom, pixmap_bottom, &black, &black, 0, 0);
2034 //      XDefineCursor(display, win, transparent_cursor);
2035         XFreePixmap(display, pixmap_bottom);
2036 }
2037
2038 int BC_WindowBase::evaluate_color_model(int client_byte_order, int server_byte_order, int depth)
2039 {
2040         int color_model = BC_TRANSPARENCY;
2041         switch(depth)
2042         {
2043                 case 8:
2044                         color_model = BC_RGB8;
2045                         break;
2046                 case 16:
2047                         color_model = (server_byte_order == client_byte_order) ? BC_RGB565 : BC_BGR565;
2048                         break;
2049                 case 24:
2050                         color_model = server_byte_order ? BC_BGR888 : BC_RGB888;
2051                         break;
2052                 case 32:
2053                         color_model = server_byte_order ? BC_BGR8888 : BC_ARGB8888;
2054                         break;
2055         }
2056         return color_model;
2057 }
2058
2059 int BC_WindowBase::init_colors()
2060 {
2061         total_colors = 0;
2062         current_color_value = current_color_pixel = 0;
2063
2064 // Get the real depth
2065         char *data = 0;
2066         XImage *ximage;
2067         ximage = XCreateImage(top_level->display,
2068                                         top_level->vis,
2069                                         top_level->default_depth,
2070                                         ZPixmap,
2071                                         0,
2072                                         data,
2073                                         16,
2074                                         16,
2075                                         8,
2076                                         0);
2077         bits_per_pixel = ximage->bits_per_pixel;
2078         XDestroyImage(ximage);
2079
2080         color_model = evaluate_color_model(client_byte_order,
2081                 server_byte_order,
2082                 bits_per_pixel);
2083 // Get the color model
2084         switch(color_model)
2085         {
2086                 case BC_RGB8:
2087                         if(private_color)
2088                         {
2089                                 cmap = XCreateColormap(display, rootwin, vis, AllocNone);
2090                                 create_private_colors();
2091                         }
2092                         else
2093                         {
2094                                 cmap = DefaultColormap(display, screen);
2095                                 create_shared_colors();
2096                         }
2097
2098                         allocate_color_table();
2099                         break;
2100
2101                 default:
2102                         //cmap = DefaultColormap(display, screen);
2103                         cmap = XCreateColormap(display, rootwin, vis, AllocNone );
2104                         break;
2105         }
2106         return 0;
2107 }
2108
2109 int BC_WindowBase::create_private_colors()
2110 {
2111         int color;
2112         total_colors = 256;
2113
2114         for(int i = 0; i < 255; i++)
2115         {
2116                 color = (i & 0xc0) << 16;
2117                 color += (i & 0x38) << 10;
2118                 color += (i & 0x7) << 5;
2119                 color_table[i][0] = color;
2120         }
2121         create_shared_colors();        // overwrite the necessary colors on the table
2122         return 0;
2123 }
2124
2125
2126 int BC_WindowBase::create_color(int color)
2127 {
2128         if(total_colors == 256)
2129         {
2130 // replace the closest match with an exact match
2131                 color_table[get_color_rgb8(color)][0] = color;
2132         }
2133         else
2134         {
2135 // add the color to the table
2136                 color_table[total_colors][0] = color;
2137                 total_colors++;
2138         }
2139         return 0;
2140 }
2141
2142 int BC_WindowBase::create_shared_colors()
2143 {
2144         create_color(BLACK);
2145         create_color(WHITE);
2146
2147         create_color(LTGREY);
2148         create_color(MEGREY);
2149         create_color(MDGREY);
2150         create_color(DKGREY);
2151
2152         create_color(LTCYAN);
2153         create_color(MECYAN);
2154         create_color(MDCYAN);
2155         create_color(DKCYAN);
2156
2157         create_color(LTGREEN);
2158         create_color(GREEN);
2159         create_color(DKGREEN);
2160
2161         create_color(LTPINK);
2162         create_color(PINK);
2163         create_color(RED);
2164
2165         create_color(LTBLUE);
2166         create_color(BLUE);
2167         create_color(DKBLUE);
2168
2169         create_color(LTYELLOW);
2170         create_color(MEYELLOW);
2171         create_color(MDYELLOW);
2172         create_color(DKYELLOW);
2173
2174         create_color(LTPURPLE);
2175         create_color(MEPURPLE);
2176         create_color(MDPURPLE);
2177         create_color(DKPURPLE);
2178
2179         create_color(FGGREY);
2180         create_color(MNBLUE);
2181         create_color(ORANGE);
2182         create_color(FTGREY);
2183
2184         return 0;
2185 }
2186
2187 Cursor BC_WindowBase::create_grab_cursor()
2188 {
2189         int iw = 23, iw1 = iw-1, iw2 = iw/2;
2190         int ih = 23, ih1 = ih-1, ih2 = ih/2;
2191         VFrame grab(iw,ih,BC_RGB888);
2192         grab.clear_frame();
2193         grab.set_pixel_color(RED);   // fg
2194         grab.draw_smooth(iw2,0,   iw1,0,   iw1,ih2);
2195         grab.draw_smooth(iw1,ih2, iw1,ih1, iw2,ih1);
2196         grab.draw_smooth(iw2,ih1, 0,ih1,   0,ih2);
2197         grab.draw_smooth(0,ih2,   0,0,     iw2,0);
2198         grab.set_pixel_color(WHITE); // bg
2199         grab.draw_line(0,ih2,     iw2-2,ih2);
2200         grab.draw_line(iw2+2,ih2, iw1,ih2);
2201         grab.draw_line(iw2,0,     iw2,ih2-2);
2202         grab.draw_line(iw2,ih2+2, iw2,ih1);
2203
2204         int bpl = (iw+7)/8, isz = bpl * ih;
2205         char img[isz];  memset(img, 0, isz);
2206         char msk[isz];  memset(msk, 0, isz);
2207         unsigned char **rows = grab.get_rows();
2208         for( int iy=0; iy<ih; ++iy ) {
2209                 char *op = img + iy*bpl;
2210                 char *mp = msk + iy*bpl;
2211                 unsigned char *ip = rows[iy];
2212                 for( int ix=0; ix<iw; ++ix,ip+=3 ) {
2213                         if( ip[0] ) mp[ix>>3] |= (1<<(ix&7));
2214                         if( !ip[1] ) op[ix>>3] |= (1<<(ix&7));
2215                 }
2216         }
2217         unsigned long white_pix = WhitePixel(display, screen);
2218         unsigned long black_pix = BlackPixel(display, screen);
2219         Pixmap img_xpm = XCreatePixmapFromBitmapData(display, rootwin,
2220                 img, iw,ih, white_pix,black_pix, 1);
2221         Pixmap msk_xpm = XCreatePixmapFromBitmapData(display, rootwin,
2222                 msk, iw,ih, white_pix,black_pix, 1);
2223
2224         XColor fc, bc;
2225         fc.flags = bc.flags = DoRed | DoGreen | DoBlue;
2226         fc.red = 0xffff; fc.green = fc.blue = 0;  // fg
2227         bc.red = bc.green = bc.blue = 0x0000;     // bg
2228         Cursor cursor = XCreatePixmapCursor(display, img_xpm,msk_xpm, &fc,&bc, iw2,ih2);
2229         XFreePixmap(display, img_xpm);
2230         XFreePixmap(display, msk_xpm);
2231         return cursor;
2232 }
2233
2234 int BC_WindowBase::allocate_color_table()
2235 {
2236         int red, green, blue, color;
2237         XColor col;
2238
2239         for(int i = 0; i < total_colors; i++)
2240         {
2241                 color = color_table[i][0];
2242                 red = (color & 0xFF0000) >> 16;
2243                 green = (color & 0x00FF00) >> 8;
2244                 blue = color & 0xFF;
2245
2246                 col.flags = DoRed | DoGreen | DoBlue;
2247                 col.red   = red<<8   | red;
2248                 col.green = green<<8 | green;
2249                 col.blue  = blue<<8  | blue;
2250
2251                 XAllocColor(display, cmap, &col);
2252                 color_table[i][1] = col.pixel;
2253         }
2254
2255         XInstallColormap(display, cmap);
2256         return 0;
2257 }
2258
2259 int BC_WindowBase::init_window_shape()
2260 {
2261         if(bg_pixmap && bg_pixmap->use_alpha())
2262         {
2263                 XShapeCombineMask(top_level->display,
2264                         this->win, ShapeBounding, 0, 0,
2265                         bg_pixmap->get_alpha(), ShapeSet);
2266         }
2267         return 0;
2268 }
2269
2270
2271 int BC_WindowBase::init_gc()
2272 {
2273         unsigned long gcmask;
2274         gcmask = GCFont | GCGraphicsExposures;
2275
2276         XGCValues gcvalues;
2277         gcvalues.font = mediumfont->fid;        // set the font
2278         gcvalues.graphics_exposures = 0;        // prevent expose events for every redraw
2279         gc = XCreateGC(display, rootwin, gcmask, &gcvalues);
2280
2281 // gcmask = GCCapStyle | GCJoinStyle;
2282 // XGetGCValues(display, gc, gcmask, &gcvalues);
2283 // printf("BC_WindowBase::init_gc %d %d %d\n", __LINE__, gcvalues.cap_style, gcvalues.join_style);
2284         return 0;
2285 }
2286
2287 int BC_WindowBase::init_fonts()
2288 {
2289         if( !(smallfont = XLoadQueryFont(display, _(resources.small_font))) )
2290                 if( !(smallfont = XLoadQueryFont(display, _(resources.small_font2))) )
2291                         smallfont = XLoadQueryFont(display, "fixed");
2292         if( !(mediumfont = XLoadQueryFont(display, _(resources.medium_font))) )
2293                 if( !(mediumfont = XLoadQueryFont(display, _(resources.medium_font2))) )
2294                         mediumfont = XLoadQueryFont(display, "fixed");
2295         if( !(largefont = XLoadQueryFont(display, _(resources.large_font))) )
2296                 if( !(largefont = XLoadQueryFont(display, _(resources.large_font2))) )
2297                         largefont = XLoadQueryFont(display, "fixed");
2298         if( !(bigfont = XLoadQueryFont(display, _(resources.big_font))) )
2299                 if( !(bigfont = XLoadQueryFont(display, _(resources.big_font2))) )
2300                         bigfont = XLoadQueryFont(display, "fixed");
2301
2302         if((clockfont = XLoadQueryFont(display, _(resources.clock_font))) == NULL)
2303                 if((clockfont = XLoadQueryFont(display, _(resources.clock_font2))) == NULL)
2304                         clockfont = XLoadQueryFont(display, "fixed");
2305
2306         init_xft();
2307         if(get_resources()->use_fontset)
2308         {
2309                 char **m, *d;
2310                 int n;
2311
2312 // FIXME: should check the m,d,n values
2313                 smallfontset = XCreateFontSet(display, resources.small_fontset, &m, &n, &d);
2314                 if( !smallfontset )
2315                         smallfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2316                 mediumfontset = XCreateFontSet(display, resources.medium_fontset, &m, &n, &d);
2317                 if( !mediumfontset )
2318                         mediumfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2319                 largefontset = XCreateFontSet(display, resources.large_fontset, &m, &n, &d);
2320                 if( !largefontset )
2321                         largefontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2322                 bigfontset = XCreateFontSet(display, resources.big_fontset, &m, &n, &d);
2323                 if( !bigfontset )
2324                         bigfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2325                 clockfontset = XCreateFontSet(display, resources.clock_fontset, &m, &n, &d);
2326                 if( !clockfontset )
2327                         clockfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2328                 if(clockfontset && bigfontset && largefontset && mediumfontset && smallfontset) {
2329                         curr_fontset = mediumfontset;
2330                         get_resources()->use_fontset = 1;
2331                 }
2332                 else {
2333                         curr_fontset = 0;
2334                         get_resources()->use_fontset = 0;
2335                 }
2336         }
2337
2338         return 0;
2339 }
2340
2341 void BC_WindowBase::init_xft()
2342 {
2343 #ifdef HAVE_XFT
2344         if( !get_resources()->use_xft ) return;
2345         if(!(smallfont_xft =
2346                 (resources.small_font_xft[0] == '-' ?
2347                         XftFontOpenXlfd(display, screen, resources.small_font_xft) :
2348                         XftFontOpenName(display, screen, resources.small_font_xft))) )
2349                 if(!(smallfont_xft =
2350                         XftFontOpenXlfd(display, screen, resources.small_font_xft2)))
2351                         smallfont_xft = XftFontOpenXlfd(display, screen, "fixed");
2352         if(!(mediumfont_xft =
2353                 (resources.medium_font_xft[0] == '-' ?
2354                         XftFontOpenXlfd(display, screen, resources.medium_font_xft) :
2355                         XftFontOpenName(display, screen, resources.medium_font_xft))) )
2356                 if(!(mediumfont_xft =
2357                         XftFontOpenXlfd(display, screen, resources.medium_font_xft2)))
2358                         mediumfont_xft = XftFontOpenXlfd(display, screen, "fixed");
2359         if(!(largefont_xft =
2360                 (resources.large_font_xft[0] == '-' ?
2361                         XftFontOpenXlfd(display, screen, resources.large_font_xft) :
2362                         XftFontOpenName(display, screen, resources.large_font_xft))) )
2363                 if(!(largefont_xft =
2364                         XftFontOpenXlfd(display, screen, resources.large_font_xft2)))
2365                         largefont_xft = XftFontOpenXlfd(display, screen, "fixed");
2366         if(!(bigfont_xft =
2367                 (resources.big_font_xft[0] == '-' ?
2368                         XftFontOpenXlfd(display, screen, resources.big_font_xft) :
2369                         XftFontOpenName(display, screen, resources.big_font_xft))) )
2370                 if(!(bigfont_xft =
2371                         XftFontOpenXlfd(display, screen, resources.big_font_xft2)))
2372                         bigfont_xft = XftFontOpenXlfd(display, screen, "fixed");
2373         if(!(clockfont_xft =
2374                 (resources.clock_font_xft[0] == '-' ?
2375                         XftFontOpenXlfd(display, screen, resources.clock_font_xft) :
2376                         XftFontOpenName(display, screen, resources.clock_font_xft))) )
2377                 clockfont_xft = XftFontOpenXlfd(display, screen, "fixed");
2378
2379
2380         if(!(bold_smallfont_xft =
2381                 (resources.small_b_font_xft[0] == '-' ?
2382                         XftFontOpenXlfd(display, screen, resources.small_b_font_xft) :
2383                         XftFontOpenName(display, screen, resources.small_b_font_xft))) )
2384                 bold_smallfont_xft = XftFontOpenXlfd(display, screen, "fixed");
2385         if(!(bold_mediumfont_xft =
2386                 (resources.medium_b_font_xft[0] == '-' ?
2387                         XftFontOpenXlfd(display, screen, resources.medium_b_font_xft) :
2388                         XftFontOpenName(display, screen, resources.medium_b_font_xft))) )
2389                 bold_mediumfont_xft = XftFontOpenXlfd(display, screen, "fixed");
2390         if(!(bold_largefont_xft =
2391                 (resources.large_b_font_xft[0] == '-' ?
2392                         XftFontOpenXlfd(display, screen, resources.large_b_font_xft) :
2393                         XftFontOpenName(display, screen, resources.large_b_font_xft))) )
2394                 bold_largefont_xft = XftFontOpenXlfd(display, screen, "fixed");
2395
2396         if( !smallfont_xft || !mediumfont_xft || !largefont_xft || !bigfont_xft ||
2397             !bold_largefont_xft || !bold_mediumfont_xft || !bold_largefont_xft ||
2398             !clockfont_xft ) {
2399                 printf("BC_WindowBase::init_fonts: no xft fonts found:"
2400                         " %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n",
2401                         resources.small_font_xft, smallfont_xft,
2402                         resources.medium_font_xft, mediumfont_xft,
2403                         resources.large_font_xft, largefont_xft,
2404                         resources.big_font_xft, bigfont_xft,
2405                         resources.clock_font_xft, clockfont_xft,
2406                         resources.small_b_font_xft, bold_smallfont_xft,
2407                         resources.medium_b_font_xft, bold_mediumfont_xft,
2408                         resources.large_b_font_xft, bold_largefont_xft);
2409                 get_resources()->use_xft = 0;
2410                 exit(1);
2411         }
2412 // _XftDisplayInfo needs a lock.
2413         XftDefaultHasRender(display);
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_buttons()
3365 {
3366         XSync(top_level->display, False);
3367         if( XGrabButton(top_level->display, AnyButton, AnyModifier,
3368                         top_level->rootwin, True, ButtonPressMask | ButtonReleaseMask,
3369                         GrabModeAsync, GrabModeSync, None, None) == GrabSuccess ) {
3370                 set_active_subwindow(this);
3371                 return 0;
3372         }
3373         return 1;
3374 }
3375 void BC_WindowBase::ungrab_buttons()
3376 {
3377         XUngrabButton(top_level->display, AnyButton, AnyModifier, top_level->rootwin);
3378         set_active_subwindow(0);
3379         unhide_cursor();
3380 }
3381 void BC_WindowBase::grab_cursor()
3382 {
3383         Cursor cursor_grab = get_cursor_struct(GRABBED_CURSOR);
3384         XGrabPointer(top_level->display, top_level->rootwin, True,
3385                 PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
3386                 GrabModeAsync, GrabModeAsync, None, cursor_grab, CurrentTime);
3387 }
3388 void BC_WindowBase::ungrab_cursor()
3389 {
3390        XUngrabPointer(top_level->display, CurrentTime);
3391 }
3392
3393 // for get_root_w/h
3394 //   WidthOfScreen/HeightOfScreen of XDefaultScreenOfDisplay
3395 //   this is the bounding box of all the screens
3396
3397 int BC_WindowBase::get_root_w(int lock_display)
3398 {
3399         if(lock_display) lock_window("BC_WindowBase::get_root_w");
3400         Screen *def_screen = XDefaultScreenOfDisplay(top_level->display);
3401         int result = WidthOfScreen(def_screen);
3402         if(lock_display) unlock_window();
3403         return result;
3404 }
3405
3406 int BC_WindowBase::get_root_h(int lock_display)
3407 {
3408         if(lock_display) lock_window("BC_WindowBase::get_root_h");
3409         Screen *def_screen = XDefaultScreenOfDisplay(top_level->display);
3410         int result = HeightOfScreen(def_screen);
3411         if(lock_display) unlock_window();
3412         return result;
3413 }
3414
3415 XineramaScreenInfo *
3416 BC_WindowBase::get_xinerama_info(int screen)
3417 {
3418         if( !xinerama_info || !xinerama_screens ) return 0;
3419         if( screen >= 0 ) {
3420                 for( int i=0; i<xinerama_screens; ++i )
3421                         if( xinerama_info[i].screen_number == screen )
3422                                 return &xinerama_info[i];
3423                 return 0;
3424         }
3425         int top_x = get_x(), top_y = get_y();
3426         for( int i=0; i<xinerama_screens; ++i ) {
3427                 int scr_y = top_y - xinerama_info[i].y_org;
3428                 if( scr_y < 0 || scr_y >= xinerama_info[i].height ) continue;
3429                 int scr_x = top_x - xinerama_info[i].x_org;
3430                 if( scr_x >= 0 && scr_x < xinerama_info[i].width )
3431                         return &xinerama_info[i];
3432         }
3433         return 0;
3434 }
3435
3436 int BC_WindowBase::get_screen_x(int lock_display, int screen)
3437 {
3438         int result = -1;
3439         if(lock_display) lock_window("BC_WindowBase::get_screen_x");
3440         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3441         if( !info ) {
3442                 result = 0;
3443                 int root_w = get_root_w(0);
3444                 int root_h = get_root_h(0);
3445 // Shift X based on position of current window if dual head
3446                 if( (float)root_w/root_h > 1.8 ) {
3447                         root_w = get_screen_w(0, 0);
3448                         if( top_level->get_x() >= root_w )
3449                                 result = root_w;
3450                 }
3451         }
3452         else
3453                 result = info->x_org;
3454         if(lock_display) unlock_window();
3455         return result;
3456 }
3457
3458 int BC_WindowBase::get_screen_y(int lock_display, int screen)
3459 {
3460         if(lock_display) lock_window("BC_WindowBase::get_screen_y");
3461         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3462         int result = !info ? 0 : info->y_org;
3463         if(lock_display) unlock_window();
3464         return result;
3465 }
3466
3467 int BC_WindowBase::get_screen_w(int lock_display, int screen)
3468 {
3469         int result = -1;
3470         if(lock_display) lock_window("BC_WindowBase::get_screen_w");
3471         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3472         if( !info ) {
3473                 int width = get_root_w(0);
3474                 int height = get_root_h(0);
3475                 if( (float)width/height > 1.8 ) {
3476                         // If dual head, the screen width is > 16x9
3477                         // but we only want to fill one screen
3478                         // this code assumes the "big" screen is on the right
3479                         int scr_w0 = width / 2;
3480                         switch( height ) {
3481                         case 600:  scr_w0 = 800;   break;
3482                         case 720:  scr_w0 = 1280;  break;
3483                         case 1024: scr_w0 = 1280;  break;
3484                         case 1200: scr_w0 = 1600;  break;
3485                         case 1080: scr_w0 = 1920;  break;
3486                         }
3487                         int scr_w1 = width - scr_w0;
3488                         result = screen > 0 ? scr_w1 :
3489                                 screen == 0 ? scr_w0 :
3490                                 top_level->get_x() < scr_w0 ? scr_w0 : scr_w1;
3491                 }
3492                 else
3493                         result = width;
3494         }
3495         else
3496                 result = info->width;
3497         if(lock_display) unlock_window();
3498         return result;
3499 }
3500
3501 int BC_WindowBase::get_screen_h(int lock_display, int screen)
3502 {
3503         if(lock_display) lock_window("BC_WindowBase::get_screen_h");
3504         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3505         int result = info ? info->height : get_root_h(0);
3506         if(lock_display) unlock_window();
3507         return result;
3508 }
3509
3510 // Bottom right corner
3511 int BC_WindowBase::get_x2()
3512 {
3513         return w + x;
3514 }
3515
3516 int BC_WindowBase::get_y2()
3517 {
3518         return y + h;
3519 }
3520
3521 int BC_WindowBase::get_video_on()
3522 {
3523         return video_on;
3524 }
3525
3526 int BC_WindowBase::get_hidden()
3527 {
3528         return top_level->hidden;
3529 }
3530
3531 int BC_WindowBase::cursor_inside()
3532 {
3533         return (top_level->cursor_x >= 0 &&
3534                         top_level->cursor_y >= 0 &&
3535                         top_level->cursor_x < w &&
3536                         top_level->cursor_y < h);
3537 }
3538
3539 BC_WindowBase* BC_WindowBase::get_top_level()
3540 {
3541         return top_level;
3542 }
3543
3544 BC_WindowBase* BC_WindowBase::get_parent()
3545 {
3546         return parent_window;
3547 }
3548
3549 int BC_WindowBase::get_color_model()
3550 {
3551         return top_level->color_model;
3552 }
3553
3554 BC_Resources* BC_WindowBase::get_resources()
3555 {
3556         return &BC_WindowBase::resources;
3557 }
3558
3559 BC_Synchronous* BC_WindowBase::get_synchronous()
3560 {
3561         return BC_WindowBase::resources.get_synchronous();
3562 }
3563
3564 int BC_WindowBase::get_bg_color()
3565 {
3566         return bg_color;
3567 }
3568
3569 void BC_WindowBase::set_bg_color(int color)
3570 {
3571         this->bg_color = color;
3572 }
3573
3574 BC_Pixmap* BC_WindowBase::get_bg_pixmap()
3575 {
3576         return bg_pixmap;
3577 }
3578
3579 void BC_WindowBase::set_active_subwindow(BC_WindowBase *subwindow)
3580 {
3581         top_level->active_subwindow = subwindow;
3582 }
3583
3584 int BC_WindowBase::activate()
3585 {
3586         return 0;
3587 }
3588
3589 int BC_WindowBase::deactivate()
3590 {
3591         if(window_type == MAIN_WINDOW)
3592         {
3593                 if( top_level->active_menubar ) {
3594                         top_level->active_menubar->deactivate();
3595                         top_level->active_menubar = 0;
3596                 }
3597                 if( top_level->active_popup_menu ) {
3598                         top_level->active_popup_menu->deactivate();
3599                         top_level->active_popup_menu = 0;
3600                 }
3601                 if( top_level->active_subwindow ) {
3602                         top_level->active_subwindow->deactivate();
3603                         top_level->active_subwindow = 0;
3604                 }
3605                 if( top_level->motion_events && top_level->last_motion_win == this->win )
3606                         top_level->motion_events = 0;
3607
3608         }
3609         return 0;
3610 }
3611
3612 int BC_WindowBase::cycle_textboxes(int amount)
3613 {
3614         int result = 0;
3615         BC_WindowBase *new_textbox = 0;
3616
3617         if(amount > 0)
3618         {
3619                 BC_WindowBase *first_textbox = 0;
3620                 find_next_textbox(&first_textbox, &new_textbox, result);
3621                 if(!new_textbox) new_textbox = first_textbox;
3622
3623         }
3624         else
3625         if(amount < 0)
3626         {
3627                 BC_WindowBase *last_textbox = 0;
3628                 find_prev_textbox(&last_textbox, &new_textbox, result);
3629                 if(!new_textbox) new_textbox = last_textbox;
3630
3631         }
3632
3633         if(new_textbox != active_subwindow)
3634         {
3635                 deactivate();
3636                 new_textbox->activate();
3637         }
3638
3639         return 0;
3640 }
3641
3642 int BC_WindowBase::find_next_textbox(BC_WindowBase **first_textbox, BC_WindowBase **next_textbox, int &result)
3643 {
3644 // Search subwindows for textbox
3645         for(int i = 0; i < subwindows->total && result < 2; i++)
3646         {
3647                 BC_WindowBase *test_subwindow = subwindows->values[i];
3648                 test_subwindow->find_next_textbox(first_textbox, next_textbox, result);
3649         }
3650
3651         if(result < 2)
3652         {
3653                 if(uses_text())
3654                 {
3655                         if(!*first_textbox) *first_textbox = this;
3656
3657                         if(result < 1)
3658                         {
3659                                 if(top_level->active_subwindow == this)
3660                                         result++;
3661                         }
3662                         else
3663                         {
3664                                 result++;
3665                                 *next_textbox = this;
3666                         }
3667                 }
3668         }
3669         return 0;
3670 }
3671
3672 int BC_WindowBase::find_prev_textbox(BC_WindowBase **last_textbox, BC_WindowBase **prev_textbox, int &result)
3673 {
3674         if(result < 2)
3675         {
3676                 if(uses_text())
3677                 {
3678                         if(!*last_textbox) *last_textbox = this;
3679
3680                         if(result < 1)
3681                         {
3682                                 if(top_level->active_subwindow == this)
3683                                         result++;
3684                         }
3685                         else
3686                         {
3687                                 result++;
3688                                 *prev_textbox = this;
3689                         }
3690                 }
3691         }
3692
3693 // Search subwindows for textbox
3694         for(int i = subwindows->total - 1; i >= 0 && result < 2; i--)
3695         {
3696                 BC_WindowBase *test_subwindow = subwindows->values[i];
3697                 test_subwindow->find_prev_textbox(last_textbox, prev_textbox, result);
3698         }
3699         return 0;
3700 }
3701
3702 BC_Clipboard* BC_WindowBase::get_clipboard()
3703 {
3704 #ifdef SINGLE_THREAD
3705         return BC_Display::display_global->clipboard;
3706 #else
3707         return top_level->clipboard;
3708 #endif
3709 }
3710
3711 Atom BC_WindowBase::to_clipboard(const char *data, long len, int clipboard_num)
3712 {
3713         return get_clipboard()->to_clipboard(this, data, len, clipboard_num);
3714 }
3715
3716 long BC_WindowBase::from_clipboard(char *data, long maxlen, int clipboard_num)
3717 {
3718         return get_clipboard()->from_clipboard(data, maxlen, clipboard_num);
3719 }
3720
3721 long BC_WindowBase::clipboard_len(int clipboard_num)
3722 {
3723         return get_clipboard()->clipboard_len(clipboard_num);
3724 }
3725
3726 int BC_WindowBase::do_selection_clear(Window win)
3727 {
3728         top_level->event_win = win;
3729         return dispatch_selection_clear();
3730 }
3731
3732 int BC_WindowBase::dispatch_selection_clear()
3733 {
3734         int result = 0;
3735         for( int i=0; i<subwindows->total && !result; ++i )
3736                 result = subwindows->values[i]->dispatch_selection_clear();
3737         if( !result )
3738                 result = selection_clear_event();
3739         return result;
3740 }
3741
3742
3743 void BC_WindowBase::get_relative_cursor_xy(int &x, int &y, int lock_window)
3744 {
3745         int abs_x, abs_y, win_x, win_y;
3746         unsigned int temp_mask;
3747         Window temp_win;
3748
3749         if(lock_window) this->lock_window("BC_WindowBase::get_relative_cursor_xy");
3750         XQueryPointer(top_level->display, top_level->win,
3751            &temp_win, &temp_win, &abs_x, &abs_y, &win_x, &win_y,
3752            &temp_mask);
3753
3754         XTranslateCoordinates(top_level->display, top_level->rootwin,
3755            win, abs_x, abs_y, &x, &y, &temp_win);
3756         if(lock_window) this->unlock_window();
3757 }
3758 int BC_WindowBase::get_relative_cursor_x(int lock_window)
3759 {
3760         int x, y;
3761         get_relative_cursor_xy(x, y, lock_window);
3762         return x;
3763 }
3764 int BC_WindowBase::get_relative_cursor_y(int lock_window)
3765 {
3766         int x, y;
3767         get_relative_cursor_xy(x, y, lock_window);
3768         return y;
3769 }
3770
3771 void BC_WindowBase::get_abs_cursor_xy(int &abs_x, int &abs_y, int lock_window)
3772 {
3773         int win_x, win_y;
3774         unsigned int temp_mask;
3775         Window temp_win;
3776
3777         if(lock_window) this->lock_window("BC_WindowBase::get_abs_cursor_xy");
3778         XQueryPointer(top_level->display, top_level->win,
3779                 &temp_win, &temp_win, &abs_x, &abs_y, &win_x, &win_y,
3780                 &temp_mask);
3781         if(lock_window) this->unlock_window();
3782 }
3783 int BC_WindowBase::get_abs_cursor_x(int lock_window)
3784 {
3785         int abs_x, abs_y;
3786         get_abs_cursor_xy(abs_x, abs_y, lock_window);
3787         return abs_x;
3788 }
3789 int BC_WindowBase::get_abs_cursor_y(int lock_window)
3790 {
3791         int abs_x, abs_y;
3792         get_abs_cursor_xy(abs_x, abs_y, lock_window);
3793         return abs_y;
3794 }
3795
3796 void BC_WindowBase::get_pop_cursor_xy(int &px, int &py, int lock_window)
3797 {
3798         int margin = 100;
3799         get_abs_cursor_xy(px, py, lock_window);
3800         if( px < margin ) px = margin;
3801         if( py < margin ) py = margin;
3802         int wd = get_screen_w(lock_window,-1) - margin;
3803         if( px > wd ) px = wd;
3804         int ht = get_screen_h(lock_window,-1) - margin;
3805         if( py > ht ) py = ht;
3806 }
3807 int BC_WindowBase::get_pop_cursor_x(int lock_window)
3808 {
3809         int px, py;
3810         get_pop_cursor_xy(px, py, lock_window);
3811         return px;
3812 }
3813 int BC_WindowBase::get_pop_cursor_y(int lock_window)
3814 {
3815         int px, py;
3816         get_pop_cursor_xy(px, py, lock_window);
3817         return py;
3818 }
3819
3820 int BC_WindowBase::match_window(Window win)
3821 {
3822         if (this->win == win) return 1;
3823         int result = 0;
3824         for(int i = 0; i < subwindows->total; i++) {
3825                 result = subwindows->values[i]->match_window(win);
3826                 if (result) return result;
3827         }
3828         return 0;
3829
3830 }
3831
3832 int BC_WindowBase::get_cursor_over_window()
3833 {
3834         if(top_level != this) return top_level->get_cursor_over_window();
3835
3836         int abs_x, abs_y, win_x, win_y;
3837         unsigned int temp_mask;
3838         Window root_return, child_return;
3839
3840         int ret = XQueryPointer(display, win,
3841                 &root_return, &child_return, &abs_x, &abs_y,
3842                 &win_x, &win_y, &temp_mask);
3843 //printf("BC_WindowBase::get_cursor_over_window %d %s 0x%x %d 0x%x\n",
3844 //  __LINE__, title, win, ret, child_return);
3845
3846         int result = !ret || child_return == None ? 0 :
3847                 match_window(child_return);
3848         return result;
3849 }
3850
3851 int BC_WindowBase::cursor_above()
3852 {
3853         int rx, ry;
3854         get_relative_cursor_xy(rx, ry);
3855         return rx < 0 || rx >= get_w() ||
3856                 ry < 0 || ry >= get_h() ? 0 : 1;
3857 }
3858
3859 int BC_WindowBase::get_drag_x()
3860 {
3861         return top_level->drag_x;
3862 }
3863
3864 int BC_WindowBase::get_drag_y()
3865 {
3866         return top_level->drag_y;
3867 }
3868
3869 int BC_WindowBase::get_cursor_x()
3870 {
3871         return top_level->cursor_x;
3872 }
3873
3874 int BC_WindowBase::get_cursor_y()
3875 {
3876         return top_level->cursor_y;
3877 }
3878
3879 int BC_WindowBase::dump_windows()
3880 {
3881         printf("\tBC_WindowBase::dump_windows window=%p win=%p '%s', %dx%d+%d+%d %s\n",
3882                 this, (void*)this->win, title, w,h,x,y, typeid(*this).name());
3883         for(int i = 0; i < subwindows->size(); i++)
3884                 subwindows->get(i)->dump_windows();
3885         for(int i = 0; i < popups.size(); i++) {
3886                 BC_WindowBase *p = popups[i];
3887                 printf("\tBC_WindowBase::dump_windows popup=%p win=%p '%s', %dx%d+%d+%d %s\n",
3888                         p, (void*)p->win, p->title, p->w,p->h,p->x,p->y, typeid(*p).name());
3889         }
3890         return 0;
3891 }
3892
3893 int BC_WindowBase::is_event_win()
3894 {
3895         return this->win == top_level->event_win;
3896 }
3897
3898 void BC_WindowBase::set_dragging(int value)
3899 {
3900         is_dragging = value;
3901 }
3902
3903 int BC_WindowBase::get_dragging()
3904 {
3905         return is_dragging;
3906 }
3907
3908 int BC_WindowBase::get_buttonpress()
3909 {
3910         return top_level->button_number;
3911 }
3912
3913 int BC_WindowBase::get_button_down()
3914 {
3915         return top_level->button_down;
3916 }
3917
3918 int BC_WindowBase::alt_down()
3919 {
3920         return top_level->alt_mask;
3921 }
3922
3923 int BC_WindowBase::shift_down()
3924 {
3925         return top_level->shift_mask;
3926 }
3927
3928 int BC_WindowBase::ctrl_down()
3929 {
3930         return top_level->ctrl_mask;
3931 }
3932
3933 wchar_t* BC_WindowBase::get_wkeystring(int *length)
3934 {
3935         if(length)
3936                 *length = top_level->wkey_string_length;
3937         return top_level->wkey_string;
3938 }
3939
3940 #ifdef X_HAVE_UTF8_STRING
3941 char* BC_WindowBase::get_keypress_utf8()
3942 {
3943         return top_level->key_pressed_utf8;
3944 }
3945 #endif
3946
3947
3948 int BC_WindowBase::get_keypress()
3949 {
3950         return top_level->key_pressed;
3951 }
3952
3953 int BC_WindowBase::get_double_click()
3954 {
3955         return top_level->double_click;
3956 }
3957
3958 int BC_WindowBase::get_triple_click()
3959 {
3960         return top_level->triple_click;
3961 }
3962
3963 int BC_WindowBase::get_bgcolor()
3964 {
3965         return bg_color;
3966 }
3967
3968 int BC_WindowBase::resize_window(int w, int h)
3969 {
3970         if(this->w == w && this->h == h) return 0;
3971
3972         if(window_type == MAIN_WINDOW && !allow_resize)
3973         {
3974                 XSizeHints size_hints;
3975                 size_hints.flags = PSize | PMinSize | PMaxSize;
3976                 size_hints.width = w;
3977                 size_hints.height = h;
3978                 size_hints.min_width = w;
3979                 size_hints.max_width = w;
3980                 size_hints.min_height = h;
3981                 size_hints.max_height = h;
3982                 XSetNormalHints(top_level->display, win, &size_hints);
3983         }
3984         XResizeWindow(top_level->display, win, w, h);
3985
3986         this->w = w;
3987         this->h = h;
3988         delete pixmap;
3989         pixmap = new BC_Pixmap(this, w, h);
3990
3991 // Propagate to menubar
3992         for(int i = 0; i < subwindows->total; i++)
3993         {
3994                 subwindows->values[i]->dispatch_resize_event(w, h);
3995         }
3996
3997         draw_background(0, 0, w, h);
3998         if(top_level == this && get_resources()->recursive_resizing)
3999                 resize_history.append(new BC_ResizeCall(w, h));
4000         return 0;
4001 }
4002
4003 // The only way for resize events to be propagated is by updating the internal w and h
4004 int BC_WindowBase::resize_event(int w, int h)
4005 {
4006         if(window_type == MAIN_WINDOW)
4007         {
4008                 this->w = w;
4009                 this->h = h;
4010         }
4011         return 0;
4012 }
4013
4014 int BC_WindowBase::reposition_window(int x, int y)
4015 {
4016         reposition_window(x, y, -1, -1);
4017         return 0;
4018 }
4019
4020
4021 int BC_WindowBase::reposition_window(int x, int y, int w, int h)
4022 {
4023         int resize = 0;
4024
4025 // Some tools set their own dimensions before calling this, causing the
4026 // resize check to skip.
4027         this->x = x;
4028         this->y = y;
4029
4030         if(w > 0 && w != this->w)
4031         {
4032                 resize = 1;
4033                 this->w = w;
4034         }
4035
4036         if(h > 0 && h != this->h)
4037         {
4038                 resize = 1;
4039                 this->h = h;
4040         }
4041
4042 //printf("BC_WindowBase::reposition_window %d %d %d\n", translation_count, x_correction, y_correction);
4043
4044         if(this->w <= 0)
4045                 printf("BC_WindowBase::reposition_window this->w == %d\n", this->w);
4046         if(this->h <= 0)
4047                 printf("BC_WindowBase::reposition_window this->h == %d\n", this->h);
4048
4049         if(translation_count && window_type == MAIN_WINDOW)
4050         {
4051 // KDE shifts window right and down.
4052 // FVWM leaves window alone and adds border around it.
4053                 XMoveResizeWindow(top_level->display,
4054                         win,
4055                         x - BC_DisplayInfo::auto_reposition_x,
4056                         y - BC_DisplayInfo::auto_reposition_y,
4057                         this->w,
4058                         this->h);
4059         }
4060         else
4061         {
4062                 XMoveResizeWindow(top_level->display,
4063                         win,
4064                         x,
4065                         y,
4066                         this->w,
4067                         this->h);
4068         }
4069
4070         if(resize)
4071         {
4072                 delete pixmap;
4073                 pixmap = new BC_Pixmap(this, this->w, this->h);
4074                 clear_box(0,0, this->w, this->h);
4075 // Propagate to menubar
4076                 for(int i = 0; i < subwindows->total; i++)
4077                 {
4078                         subwindows->values[i]->dispatch_resize_event(this->w, this->h);
4079                 }
4080
4081 //              draw_background(0, 0, w, h);
4082         }
4083
4084         return 0;
4085 }
4086
4087 int BC_WindowBase::reposition_window_relative(int dx, int dy, int w, int h)
4088 {
4089         return reposition_window(get_x()+dx, get_y()+dy, w, h);
4090 }
4091
4092 int BC_WindowBase::reposition_window_relative(int dx, int dy)
4093 {
4094         return reposition_window_relative(dx, dy, -1, -1);
4095 }
4096
4097 void BC_WindowBase::set_tooltips(int v)
4098 {
4099         get_resources()->tooltips_enabled = v;
4100 }
4101
4102 void BC_WindowBase::set_force_tooltip(int v)
4103 {
4104         force_tooltip = v;
4105 }
4106
4107 int BC_WindowBase::raise_window(int do_flush)
4108 {
4109         XRaiseWindow(top_level->display, win);
4110         if(do_flush) XFlush(top_level->display);
4111         return 0;
4112 }
4113
4114 int BC_WindowBase::lower_window(int do_flush)
4115 {
4116         XLowerWindow(top_level->display, win);
4117         if(do_flush) XFlush(top_level->display);
4118         return 0;
4119 }
4120
4121 void BC_WindowBase::set_background(VFrame *bitmap)
4122 {
4123         if(bg_pixmap && !shared_bg_pixmap) delete bg_pixmap;
4124
4125         bg_pixmap = new BC_Pixmap(this, bitmap, PIXMAP_OPAQUE);
4126         shared_bg_pixmap = 0;
4127         draw_background(0, 0, w, h);
4128 }
4129
4130 void BC_WindowBase::put_title(const char *text)
4131 {
4132         char *cp = this->title, *ep = cp+sizeof(this->title)-1;
4133         for( const unsigned char *bp = (const unsigned char *)text; *bp && cp<ep; ++bp )
4134                 *cp++ = *bp >= ' ' ? *bp : ' ';
4135         *cp = 0;
4136 }
4137
4138 void BC_WindowBase::set_title(const char *text, int utf8)
4139 {
4140 // utf8>0: wm + net_wm, utf8=0: wm only,  utf<0: net_wm only
4141         put_title(_(text));
4142         const unsigned char *wm_title = (const unsigned char *)title;
4143         int title_len = strlen((const char *)title);
4144         if( utf8 >= 0 ) {
4145                 Atom xa_wm_name = XA_WM_NAME;
4146                 Atom xa_icon_name = XA_WM_ICON_NAME;
4147                 Atom xa_string = XA_STRING;
4148                 XChangeProperty(display, win, xa_wm_name, xa_string, 8,
4149                                 PropModeReplace, wm_title, title_len);
4150                 XChangeProperty(display, win, xa_icon_name, xa_string, 8,
4151                                 PropModeReplace, wm_title, title_len);
4152         }
4153         if( utf8 != 0 ) {
4154                 Atom xa_net_wm_name = XInternAtom(display, "_NET_WM_NAME", True);
4155                 Atom xa_net_icon_name = XInternAtom(display, "_NET_WM_ICON_NAME", True);
4156                 Atom xa_utf8_string = XInternAtom(display, "UTF8_STRING", True);
4157                 XChangeProperty(display, win, xa_net_wm_name, xa_utf8_string, 8,
4158                                         PropModeReplace, wm_title, title_len);
4159                 XChangeProperty(display, win, xa_net_icon_name, xa_utf8_string, 8,
4160                                         PropModeReplace, wm_title, title_len);
4161         }
4162         flush();
4163 }
4164
4165 const char *BC_WindowBase::get_title()
4166 {
4167         return title;
4168 }
4169
4170 int BC_WindowBase::get_toggle_value()
4171 {
4172         return toggle_value;
4173 }
4174
4175 int BC_WindowBase::get_toggle_drag()
4176 {
4177         return toggle_drag;
4178 }
4179
4180 int BC_WindowBase::set_icon(VFrame *data)
4181 {
4182         if(icon_pixmap) delete icon_pixmap;
4183         icon_pixmap = new BC_Pixmap(top_level, data, PIXMAP_ALPHA, 1);
4184
4185         if(icon_window) delete icon_window;
4186         icon_window = new BC_Popup(this,
4187                 (int)BC_INFINITY,
4188                 (int)BC_INFINITY,
4189                 icon_pixmap->get_w(),
4190                 icon_pixmap->get_h(),
4191                 -1,
4192                 1, // All windows are hidden initially
4193                 icon_pixmap);
4194
4195         XWMHints wm_hints;
4196         wm_hints.flags = WindowGroupHint | IconPixmapHint | IconMaskHint | IconWindowHint;
4197         wm_hints.icon_pixmap = icon_pixmap->get_pixmap();
4198         wm_hints.icon_mask = icon_pixmap->get_alpha();
4199         wm_hints.icon_window = icon_window->win;
4200         wm_hints.window_group = XGroupLeader;
4201
4202 // for(int i = 0; i < 1000; i++)
4203 // printf("02x ", icon_pixmap->get_alpha()->get_row_pointers()[0][i]);
4204 // printf("\n");
4205
4206         XSetWMHints(top_level->display, top_level->win, &wm_hints);
4207         XSync(top_level->display, 0);
4208         return 0;
4209 }
4210
4211 int BC_WindowBase::set_w(int w)
4212 {
4213         this->w = w;
4214         return 0;
4215 }
4216
4217 int BC_WindowBase::set_h(int h)
4218 {
4219         this->h = h;
4220         return 0;
4221 }
4222
4223 int BC_WindowBase::load_defaults(BC_Hash *defaults)
4224 {
4225         BC_Resources *resources = get_resources();
4226         char string[BCTEXTLEN];
4227         int newest_id = - 1;
4228         for(int i = 0; i < FILEBOX_HISTORY_SIZE; i++)
4229         {
4230                 sprintf(string, "FILEBOX_HISTORY_PATH%d", i);
4231                 resources->filebox_history[i].path[0] = 0;
4232                 defaults->get(string, resources->filebox_history[i].path);
4233                 sprintf(string, "FILEBOX_HISTORY_ID%d", i);
4234                 resources->filebox_history[i].id = defaults->get(string, resources->get_id());
4235                 if(resources->filebox_history[i].id > newest_id)
4236                         newest_id = resources->filebox_history[i].id;
4237         }
4238
4239         resources->filebox_id = newest_id + 1;
4240         resources->filebox_mode = defaults->get("FILEBOX_MODE", get_resources()->filebox_mode);
4241         resources->filebox_w = defaults->get("FILEBOX_W", get_resources()->filebox_w);
4242         resources->filebox_h = defaults->get("FILEBOX_H", get_resources()->filebox_h);
4243         resources->filebox_columntype[0] = defaults->get("FILEBOX_TYPE0", resources->filebox_columntype[0]);
4244         resources->filebox_columntype[1] = defaults->get("FILEBOX_TYPE1", resources->filebox_columntype[1]);
4245         resources->filebox_columntype[2] = defaults->get("FILEBOX_TYPE2", resources->filebox_columntype[2]);
4246         resources->filebox_columntype[3] = defaults->get("FILEBOX_TYPE3", resources->filebox_columntype[3]);
4247         resources->filebox_columnwidth[0] = defaults->get("FILEBOX_WIDTH0", resources->filebox_columnwidth[0]);
4248         resources->filebox_columnwidth[1] = defaults->get("FILEBOX_WIDTH1", resources->filebox_columnwidth[1]);
4249         resources->filebox_columnwidth[2] = defaults->get("FILEBOX_WIDTH2", resources->filebox_columnwidth[2]);
4250         resources->filebox_columnwidth[3] = defaults->get("FILEBOX_WIDTH3", resources->filebox_columnwidth[3]);
4251         defaults->get("FILEBOX_FILTER", resources->filebox_filter);
4252         return 0;
4253 }
4254
4255 int BC_WindowBase::save_defaults(BC_Hash *defaults)
4256 {
4257         BC_Resources *resources = get_resources();
4258         char string[BCTEXTLEN];
4259         for(int i = 0; i < FILEBOX_HISTORY_SIZE; i++)
4260         {
4261                 sprintf(string, "FILEBOX_HISTORY_PATH%d", i);
4262                 defaults->update(string, resources->filebox_history[i].path);
4263                 sprintf(string, "FILEBOX_HISTORY_ID%d", i);
4264                 defaults->update(string, resources->filebox_history[i].id);
4265         }
4266         defaults->update("FILEBOX_MODE", resources->filebox_mode);
4267         defaults->update("FILEBOX_W", resources->filebox_w);
4268         defaults->update("FILEBOX_H", resources->filebox_h);
4269         defaults->update("FILEBOX_TYPE0", resources->filebox_columntype[0]);
4270         defaults->update("FILEBOX_TYPE1", resources->filebox_columntype[1]);
4271         defaults->update("FILEBOX_TYPE2", resources->filebox_columntype[2]);
4272         defaults->update("FILEBOX_TYPE3", resources->filebox_columntype[3]);
4273         defaults->update("FILEBOX_WIDTH0", resources->filebox_columnwidth[0]);
4274         defaults->update("FILEBOX_WIDTH1", resources->filebox_columnwidth[1]);
4275         defaults->update("FILEBOX_WIDTH2", resources->filebox_columnwidth[2]);
4276         defaults->update("FILEBOX_WIDTH3", resources->filebox_columnwidth[3]);
4277         defaults->update("FILEBOX_FILTER", resources->filebox_filter);
4278         return 0;
4279 }
4280
4281
4282
4283 // For some reason XTranslateCoordinates can take a long time to return.
4284 // We work around this by only calling it when the event windows are different.
4285 void BC_WindowBase::translate_coordinates(Window src_w,
4286                 Window dest_w,
4287                 int src_x,
4288                 int src_y,
4289                 int *dest_x_return,
4290                 int *dest_y_return)
4291 {
4292         Window tempwin = 0;
4293 //Timer timer;
4294 //timer.update();
4295         if(src_w == dest_w)
4296         {
4297                 *dest_x_return = src_x;
4298                 *dest_y_return = src_y;
4299         }
4300         else
4301         {
4302                 XTranslateCoordinates(top_level->display,
4303                         src_w,
4304                         dest_w,
4305                         src_x,
4306                         src_y,
4307                         dest_x_return,
4308                         dest_y_return,
4309                         &tempwin);
4310 //printf("BC_WindowBase::translate_coordinates 1 %lld\n", timer.get_difference());
4311         }
4312 }
4313
4314 void BC_WindowBase::get_root_coordinates(int x, int y, int *abs_x, int *abs_y)
4315 {
4316         translate_coordinates(win, top_level->rootwin, x, y, abs_x, abs_y);
4317 }
4318
4319 void BC_WindowBase::get_win_coordinates(int abs_x, int abs_y, int *x, int *y)
4320 {
4321         translate_coordinates(top_level->rootwin, win, abs_x, abs_y, x, y);
4322 }
4323
4324
4325
4326
4327
4328
4329 #ifdef HAVE_LIBXXF86VM
4330 void BC_WindowBase::closest_vm(int *vm, int *width, int *height)
4331 {
4332    int foo,bar;
4333    *vm = 0;
4334    if(XF86VidModeQueryExtension(top_level->display,&foo,&bar)) {
4335            int vm_count,i;
4336            XF86VidModeModeInfo **vm_modelines;
4337            XF86VidModeGetAllModeLines(top_level->display,XDefaultScreen(top_level->display),&vm_count,&vm_modelines);
4338            for (i = 0; i < vm_count; i++) {
4339                    if (vm_modelines[i]->hdisplay < vm_modelines[*vm]->hdisplay && vm_modelines[i]->hdisplay >= *width)
4340                            *vm = i;
4341            }
4342            display = top_level->display;
4343            if (vm_modelines[*vm]->hdisplay == *width)
4344                    *vm = -1;
4345            else
4346            {
4347                    *width = vm_modelines[*vm]->hdisplay;
4348                    *height = vm_modelines[*vm]->vdisplay;
4349            }
4350    }
4351 }
4352
4353 void BC_WindowBase::scale_vm(int vm)
4354 {
4355    int foo,bar,dotclock;
4356    if(XF86VidModeQueryExtension(top_level->display,&foo,&bar))
4357    {
4358            int vm_count;
4359            XF86VidModeModeInfo **vm_modelines;
4360            XF86VidModeModeLine vml;
4361            XF86VidModeGetAllModeLines(top_level->display,XDefaultScreen(top_level->display),&vm_count,&vm_modelines);
4362            XF86VidModeGetModeLine(top_level->display,XDefaultScreen(top_level->display),&dotclock,&vml);
4363            orig_modeline.dotclock = dotclock;
4364            orig_modeline.hdisplay = vml.hdisplay;
4365            orig_modeline.hsyncstart = vml.hsyncstart;
4366            orig_modeline.hsyncend = vml.hsyncend;
4367            orig_modeline.htotal = vml.htotal;
4368            orig_modeline.vdisplay = vml.vdisplay;
4369            orig_modeline.vsyncstart = vml.vsyncstart;
4370            orig_modeline.vsyncend = vml.vsyncend;
4371            orig_modeline.vtotal = vml.vtotal;
4372            orig_modeline.flags = vml.flags;
4373            orig_modeline.privsize = vml.privsize;
4374            // orig_modeline.private = vml.private;
4375            XF86VidModeSwitchToMode(top_level->display,XDefaultScreen(top_level->display),vm_modelines[vm]);
4376            XF86VidModeSetViewPort(top_level->display,XDefaultScreen(top_level->display),0,0);
4377            XFlush(top_level->display);
4378    }
4379 }
4380
4381 void BC_WindowBase::restore_vm()
4382 {
4383    XF86VidModeSwitchToMode(top_level->display,XDefaultScreen(top_level->display),&orig_modeline);
4384    XFlush(top_level->display);
4385 }
4386
4387
4388 #endif
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407 #ifndef SINGLE_THREAD
4408 int BC_WindowBase::get_event_count()
4409 {
4410         event_lock->lock("BC_WindowBase::get_event_count");
4411         int result = common_events.total;
4412         event_lock->unlock();
4413         return result;
4414 }
4415
4416 XEvent* BC_WindowBase::get_event()
4417 {
4418         XEvent *result = 0;
4419         while(!done && !result)
4420         {
4421                 event_condition->lock("BC_WindowBase::get_event");
4422                 event_lock->lock("BC_WindowBase::get_event");
4423
4424                 if(common_events.total && !done)
4425                 {
4426                         result = common_events.values[0];
4427                         common_events.remove_number(0);
4428                 }
4429
4430                 event_lock->unlock();
4431         }
4432         return result;
4433 }
4434
4435 void BC_WindowBase::put_event(XEvent *event)
4436 {
4437         event_lock->lock("BC_WindowBase::put_event");
4438         common_events.append(event);
4439         event_lock->unlock();
4440         event_condition->unlock();
4441 }
4442
4443 void BC_WindowBase::dequeue_events(Window win)
4444 {
4445         event_lock->lock("BC_WindowBase::dequeue_events");
4446
4447         int out = 0, total = common_events.size();
4448         for( int in=0; in<total; ++in ) {
4449                 if( common_events[in]->xany.window == win ) continue;
4450                 common_events[out++] = common_events[in];
4451         }
4452         common_events.total = out;
4453
4454         event_lock->unlock();
4455 }
4456
4457 #endif // SINGLE_THREAD
4458
4459 int BC_WindowBase::get_id()
4460 {
4461         return id;
4462 }
4463
4464
4465 BC_Pixmap *BC_WindowBase::create_pixmap(VFrame *vframe)
4466 {
4467         int w = vframe->get_w(), h = vframe->get_h();
4468         BC_Pixmap *icon = new BC_Pixmap(this, w, h);
4469         icon->draw_vframe(vframe, 0,0, w,h, 0,0);
4470         return icon;
4471 }
4472
4473
4474 void BC_WindowBase::flicker(int n, int ms)
4475 {
4476         int color = get_bg_color();
4477         for( int i=2*n; --i>=0; ) {
4478                 set_inverse();          set_bg_color(WHITE);
4479                 clear_box(0,0, w,h);    flash(1);
4480                 sync_display();         Timer::delay(ms);
4481         }
4482         set_bg_color(color);
4483         set_opaque();
4484 }
4485