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