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