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