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