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