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