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