ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/video_x.cpp
(Generate patch)

Comparing BasiliskII/src/Unix/video_x.cpp (file contents):
Revision 1.49 by cebix, 2001-07-01T19:57:55Z vs.
Revision 1.69 by gbeauche, 2003-05-22T22:13:56Z

# Line 1 | Line 1
1   /*
2   *  video_x.cpp - Video/graphics emulation, X11 specific stuff
3   *
4 < *  Basilisk II (C) 1997-2001 Christian Bauer
4 > *  Basilisk II (C) 1997-2002 Christian Bauer
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
# Line 24 | Line 24
24   *      Ctrl-Tab = suspend DGA mode
25   *      Ctrl-Esc = emergency quit
26   *      Ctrl-F1 = mount floppy
27 + *      Ctrl-F5 = grab mouse (in windowed mode)
28   */
29  
30   #include "sysdeps.h"
# Line 36 | Line 37
37   #include <sys/shm.h>
38   #include <errno.h>
39  
40 + #include <algorithm>
41 +
42   #ifdef HAVE_PTHREADS
43   # include <pthread.h>
44   #endif
# Line 64 | Line 67
67   #include "debug.h"
68  
69  
70 + // Supported video modes
71 + static vector<video_mode> VideoModes;
72 +
73   // Display types
74   enum {
75          DISPLAY_WINDOW, // X11 window, using MIT SHM extensions if possible
# Line 86 | Line 92 | static int display_type = DISPLAY_WINDOW
92   static bool local_X11;                                                          // Flag: X server running on local machine?
93   static uint8 *the_buffer = NULL;                                        // Mac frame buffer (where MacOS draws into)
94   static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer (for refreshed modes)
95 + static uint32 the_buffer_size;                                          // Size of allocated the_buffer
96  
97   static bool redraw_thread_active = false;                       // Flag: Redraw thread installed
98   #ifdef HAVE_PTHREADS
99 + static pthread_attr_t redraw_thread_attr;                       // Redraw thread attributes
100   static volatile bool redraw_thread_cancel;                      // Flag: Cancel Redraw thread
101   static pthread_t redraw_thread;                                         // Redraw thread
102   #endif
# Line 115 | Line 123 | static int keycode_table[256];                                         // X
123  
124   // X11 variables
125   static int screen;                                                                      // Screen number
118 static int xdepth;                                                                      // Depth of X screen
126   static Window rootwin;                                                          // Root window and our window
127 < static XVisualInfo visualInfo;
128 < static Visual *vis;
122 < static Colormap cmap[2] = {0, 0};                                       // Colormaps for indexed modes (DGA needs two of them)
127 > static int num_depths = 0;                                                      // Number of available X depths
128 > static int *avail_depths = NULL;                                        // List of available X depths
129   static XColor black, white;
130   static unsigned long black_pixel, white_pixel;
131   static int eventmask;
132  
133 + static int xdepth;                                                                      // Depth of X screen
134 + static XVisualInfo visualInfo;
135 + static Visual *vis;
136 + static int color_class;
137 +
138   static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
139  
140 < static XColor palette[256];                                                     // Color palette to be used as CLUT and gamma table
141 < static bool palette_changed = false;                            // Flag: Palette changed, redraw thread must set new colors
140 > static Colormap cmap[2] = {0, 0};                                       // Colormaps for indexed modes (DGA needs two of them)
141 >
142 > static XColor x_palette[256];                                                   // Color palette to be used as CLUT and gamma table
143 > static bool x_palette_changed = false;                          // Flag: Palette changed, redraw thread must set new colors
144  
145   #ifdef ENABLE_FBDEV_DGA
146   static int fbdev_fd = -1;
# Line 140 | Line 153 | static int num_x_video_modes;
153  
154   // Mutex to protect palette
155   #ifdef HAVE_PTHREADS
156 < static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;
157 < #define LOCK_PALETTE pthread_mutex_lock(&palette_lock)
158 < #define UNLOCK_PALETTE pthread_mutex_unlock(&palette_lock)
156 > static pthread_mutex_t x_palette_lock = PTHREAD_MUTEX_INITIALIZER;
157 > #define LOCK_PALETTE pthread_mutex_lock(&x_palette_lock)
158 > #define UNLOCK_PALETTE pthread_mutex_unlock(&x_palette_lock)
159   #else
160   #define LOCK_PALETTE
161   #define UNLOCK_PALETTE
# Line 171 | Line 184 | static void (*video_refresh)(void);
184  
185   // Prototypes
186   static void *redraw_func(void *arg);
174 static int event2keycode(XKeyEvent &ev);
187  
188   // From main_unix.cpp
189   extern char *x_display_name;
# Line 182 | Line 194 | extern void SysMountFirstFloppy(void);
194  
195  
196   /*
197 + *  monitor_desc subclass for X11 display
198 + */
199 +
200 + class X11_monitor_desc : public monitor_desc {
201 + public:
202 +        X11_monitor_desc(const vector<video_mode> &available_modes, video_depth default_depth, uint32 default_id) : monitor_desc(available_modes, default_depth, default_id) {}
203 +        ~X11_monitor_desc() {}
204 +
205 +        virtual void switch_to_current_mode(void);
206 +        virtual void set_palette(uint8 *pal, int num);
207 +
208 +        bool video_open(void);
209 +        void video_close(void);
210 + };
211 +
212 +
213 + /*
214   *  Utility functions
215   */
216  
217 + // Map video_mode depth ID to numerical depth value
218 + static inline int depth_of_video_mode(video_mode const & mode)
219 + {
220 +        int depth = -1;
221 +        switch (mode.depth) {
222 +        case VDEPTH_1BIT:
223 +                depth = 1;
224 +                break;
225 +        case VDEPTH_2BIT:
226 +                depth = 2;
227 +                break;
228 +        case VDEPTH_4BIT:
229 +                depth = 4;
230 +                break;
231 +        case VDEPTH_8BIT:
232 +                depth = 8;
233 +                break;
234 +        case VDEPTH_16BIT:
235 +                depth = 16;
236 +                break;
237 +        case VDEPTH_32BIT:
238 +                depth = 32;
239 +                break;
240 +        default:
241 +                abort();
242 +        }
243 +        return depth;
244 + }
245 +
246   // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
247   static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
248   {
249          return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
250   }
251  
252 + // Do we have a visual for handling the specified Mac depth? If so, set the
253 + // global variables "xdepth", "visualInfo", "vis" and "color_class".
254 + static bool find_visual_for_depth(video_depth depth)
255 + {
256 +        D(bug("have_visual_for_depth(%d)\n", 1 << depth));
257 +
258 +        // 1-bit works always and uses default visual
259 +        if (depth == VDEPTH_1BIT) {
260 +                vis = DefaultVisual(x_display, screen);
261 +                visualInfo.visualid = XVisualIDFromVisual(vis);
262 +                int num = 0;
263 +                XVisualInfo *vi = XGetVisualInfo(x_display, VisualIDMask, &visualInfo, &num);
264 +                visualInfo = vi[0];
265 +                XFree(vi);
266 +                xdepth = visualInfo.depth;
267 +                color_class = visualInfo.c_class;
268 +                D(bug(" found visual ID 0x%02x, depth %d\n", visualInfo.visualid, xdepth));
269 +                return true;
270 +        }
271 +
272 +        // Calculate minimum and maximum supported X depth
273 +        int min_depth = 1, max_depth = 32;
274 +        switch (depth) {
275 + #ifdef ENABLE_VOSF
276 +                case VDEPTH_2BIT:
277 +                case VDEPTH_4BIT:       // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit
278 +                case VDEPTH_8BIT:
279 +                        min_depth = 8;
280 +                        max_depth = 32;
281 +                        break;
282 + #else
283 +                case VDEPTH_2BIT:
284 +                case VDEPTH_4BIT:       // 2/4-bit requires VOSF blitters
285 +                        return false;
286 +                case VDEPTH_8BIT:       // 8-bit without VOSF requires an 8-bit visual
287 +                        min_depth = 8;
288 +                        max_depth = 8;
289 +                        break;
290 + #endif
291 +                case VDEPTH_16BIT:      // 16-bit requires a 15/16-bit visual
292 +                        min_depth = 15;
293 +                        max_depth = 16;
294 +                        break;
295 +                case VDEPTH_32BIT:      // 32-bit requires a 24/32-bit visual
296 +                        min_depth = 24;
297 +                        max_depth = 32;
298 +                        break;
299 +        }
300 +        D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth));
301 +
302 +        // Try to find a visual for one of the color depths
303 +        bool visual_found = false;
304 +        for (int i=0; i<num_depths && !visual_found; i++) {
305 +
306 +                xdepth = avail_depths[i];
307 +                D(bug(" trying to find visual for depth %d\n", xdepth));
308 +                if (xdepth < min_depth || xdepth > max_depth)
309 +                        continue;
310 +
311 +                // Determine best color class for this depth
312 +                switch (xdepth) {
313 +                        case 1: // Try StaticGray or StaticColor
314 +                                if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo)
315 +                                 || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo))
316 +                                        visual_found = true;
317 +                                break;
318 +                        case 8: // Need PseudoColor
319 +                                if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo))
320 +                                        visual_found = true;
321 +                                break;
322 +                        case 15:
323 +                        case 16:
324 +                        case 24:
325 +                        case 32: // Try DirectColor first, as this will allow gamma correction
326 +                                if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo)
327 +                                 || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo))
328 +                                        visual_found = true;
329 +                                break;
330 +                        default:
331 +                                D(bug("  not a supported depth\n"));
332 +                                break;
333 +                }
334 +        }
335 +        if (!visual_found)
336 +                return false;
337 +
338 +        // Visual was found
339 +        vis = visualInfo.visual;
340 +        color_class = visualInfo.c_class;
341 +        D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth));
342 + #if DEBUG
343 +        switch (color_class) {
344 +                case StaticGray: D(bug("StaticGray\n")); break;
345 +                case GrayScale: D(bug("GrayScale\n")); break;
346 +                case StaticColor: D(bug("StaticColor\n")); break;
347 +                case PseudoColor: D(bug("PseudoColor\n")); break;
348 +                case TrueColor: D(bug("TrueColor\n")); break;
349 +                case DirectColor: D(bug("DirectColor\n")); break;
350 +        }
351 + #endif
352 +        return true;
353 + }
354 +
355   // Add mode to list of supported modes
356   static void add_mode(uint32 width, uint32 height, uint32 resolution_id, uint32 bytes_per_row, video_depth depth)
357   {
# Line 203 | Line 364 | static void add_mode(uint32 width, uint3
364          VideoModes.push_back(mode);
365   }
366  
367 + // Add standard list of windowed modes for given color depth
368 + static void add_window_modes(video_depth depth)
369 + {
370 +        add_mode(512, 384, 0x80, TrivialBytesPerRow(512, depth), depth);
371 +        add_mode(640, 480, 0x81, TrivialBytesPerRow(640, depth), depth);
372 +        add_mode(800, 600, 0x82, TrivialBytesPerRow(800, depth), depth);
373 +        add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, depth), depth);
374 +        add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, depth), depth);
375 +        add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, depth), depth);
376 +        add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, depth), depth);
377 + }
378 +
379   // Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac)
380 < static void set_mac_frame_buffer(video_depth depth, bool native_byte_order)
380 > static void set_mac_frame_buffer(X11_monitor_desc &monitor, video_depth depth, bool native_byte_order)
381   {
382   #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
383          int layout = FLAYOUT_DIRECT;
# Line 216 | Line 389 | static void set_mac_frame_buffer(video_d
389                  MacFrameLayout = layout;
390          else
391                  MacFrameLayout = FLAYOUT_DIRECT;
392 <        VideoMonitor.mac_frame_base = MacFrameBaseMac;
392 >        monitor.set_mac_frame_base(MacFrameBaseMac);
393  
394          // Set variables used by UAE memory banking
395 +        const video_mode &mode = monitor.get_current_mode();
396          MacFrameBaseHost = the_buffer;
397 <        MacFrameSize = VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y;
397 >        MacFrameSize = mode.bytes_per_row * mode.y;
398          InitFrameBufferMapping();
399   #else
400 <        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
227 <        D(bug("Host frame buffer = %p, ", the_buffer));
400 >        monitor.set_mac_frame_base(Host2MacAddr(the_buffer));
401   #endif
402 <        D(bug("VideoMonitor.mac_frame_base = %08x\n", VideoMonitor.mac_frame_base));
402 >        D(bug("monitor.mac_frame_base = %08x\n", monitor.get_mac_frame_base()));
403   }
404  
405   // Set window name and class
# Line 304 | Line 477 | static int error_handler(Display *d, XEr
477  
478   class driver_base {
479   public:
480 <        driver_base();
480 >        driver_base(X11_monitor_desc &m);
481          virtual ~driver_base();
482  
483          virtual void update_palette(void);
484          virtual void suspend(void) {}
485          virtual void resume(void) {}
486 +        virtual void toggle_mouse_grab(void) {}
487 +        virtual void mouse_moved(int x, int y) { ADBMouseMoved(x, y); }
488 +
489 +        void disable_mouse_accel(void);
490 +        void restore_mouse_accel(void);
491 +
492 +        virtual void grab_mouse(void) {}
493 +        virtual void ungrab_mouse(void) {}
494  
495   public:
496 +        X11_monitor_desc &monitor; // Associated video monitor
497 +        const video_mode &mode;    // Video mode handled by the driver
498 +
499          bool init_ok;   // Initialization succeeded (we can't use exceptions because of -fomit-frame-pointer)
500          Window w;               // The window we draw into
501 +
502 +        int orig_accel_numer, orig_accel_denom, orig_threshold; // Original mouse acceleration
503   };
504  
505   class driver_window;
# Line 327 | Line 513 | class driver_window : public driver_base
513          friend void update_display_static(driver_window *drv);
514  
515   public:
516 <        driver_window(const video_mode &mode);
516 >        driver_window(X11_monitor_desc &monitor);
517          ~driver_window();
518  
519 +        void toggle_mouse_grab(void);
520 +        void mouse_moved(int x, int y);
521 +
522 +        void grab_mouse(void);
523 +        void ungrab_mouse(void);
524 +
525   private:
526          GC gc;
527          XImage *img;
528 <        bool have_shm;                          // Flag: SHM extensions available
528 >        bool have_shm;                                  // Flag: SHM extensions available
529          XShmSegmentInfo shminfo;
530          Cursor mac_cursor;
531 +        bool mouse_grabbed;                             // Flag: mouse pointer grabbed, using relative mouse mode
532 +        int mouse_last_x, mouse_last_y; // Last mouse position (for relative mode)
533   };
534  
535   static driver_base *drv = NULL; // Pointer to currently used driver object
# Line 344 | Line 538 | static driver_base *drv = NULL;        // Point
538   # include "video_vosf.h"
539   #endif
540  
541 < driver_base::driver_base()
542 < : init_ok(false), w(0)
541 > driver_base::driver_base(X11_monitor_desc &m)
542 > : monitor(m), mode(m.get_current_mode()), init_ok(false), w(0)
543   {
544          the_buffer = NULL;
545          the_buffer_copy = NULL;
546 +        XGetPointerControl(x_display, &orig_accel_numer, &orig_accel_denom, &orig_threshold);
547   }
548  
549   driver_base::~driver_base()
550   {
551 +        ungrab_mouse();
552 +        restore_mouse_accel();
553 +
554          if (w) {
555                  XUnmapWindow(x_display, w);
556                  wait_unmapped(w);
# Line 375 | Line 573 | driver_base::~driver_base()
573          }
574   #ifdef ENABLE_VOSF
575          else {
576 <                if (the_buffer != (uint8 *)VM_MAP_FAILED) {
576 >                // the_buffer shall always be mapped through vm_acquire() so that we can vm_protect() it at will
577 >                if (the_buffer != VM_MAP_FAILED) {
578 >                        D(bug(" releasing the_buffer at %p (%d bytes)\n", the_buffer, the_buffer_size));
579                          vm_release(the_buffer, the_buffer_size);
580                          the_buffer = NULL;
581                  }
582 <                if (the_buffer_copy != (uint8 *)VM_MAP_FAILED) {
583 <                        vm_release(the_buffer_copy, the_buffer_size);
582 >                if (the_host_buffer) {
583 >                        D(bug(" freeing the_host_buffer at %p\n", the_host_buffer));
584 >                        free(the_host_buffer);
585 >                        the_host_buffer = NULL;
586 >                }
587 >                if (the_buffer_copy) {
588 >                        D(bug(" freeing the_buffer_copy at %p\n", the_buffer_copy));
589 >                        free(the_buffer_copy);
590                          the_buffer_copy = NULL;
591                  }
592          }
# Line 390 | Line 596 | driver_base::~driver_base()
596   // Palette has changed
597   void driver_base::update_palette(void)
598   {
599 <        if (cmap[0] && cmap[1]) {
600 <                int num = 256;
601 <                if (IsDirectMode(VideoMonitor.mode))
396 <                        num = vis->map_entries; // Palette is gamma table
397 <                else if (vis->c_class == DirectColor)
599 >        if (color_class == PseudoColor || color_class == DirectColor) {
600 >                int num = vis->map_entries;
601 >                if (!IsDirectMode(monitor.get_current_mode()) && color_class == DirectColor)
602                          return; // Indexed mode on true color screen, don't set CLUT
603 <                XStoreColors(x_display, cmap[0], palette, num);
604 <                XStoreColors(x_display, cmap[1], palette, num);
603 >                XStoreColors(x_display, cmap[0], x_palette, num);
604 >                XStoreColors(x_display, cmap[1], x_palette, num);
605          }
606          XSync(x_display, false);
607   }
608  
609 + // Disable mouse acceleration
610 + void driver_base::disable_mouse_accel(void)
611 + {
612 +        XChangePointerControl(x_display, True, False, 1, 1, 0);
613 + }
614 +
615 + // Restore mouse acceleration to original value
616 + void driver_base::restore_mouse_accel(void)
617 + {
618 +        XChangePointerControl(x_display, True, True, orig_accel_numer, orig_accel_denom, orig_threshold);
619 + }
620 +
621  
622   /*
623   *  Windowed display driver
624   */
625  
626   // Open display
627 < driver_window::driver_window(const video_mode &mode)
628 < : gc(0), img(NULL), have_shm(false), mac_cursor(0)
627 > driver_window::driver_window(X11_monitor_desc &m)
628 > : driver_base(m), gc(0), img(NULL), have_shm(false), mac_cursor(0), mouse_grabbed(false)
629   {
630          int width = mode.x, height = mode.y;
631          int aligned_width = (width + 15) & ~15;
632          int aligned_height = (height + 15) & ~15;
633  
634          // Set absolute mouse mode
635 <        ADBSetRelMouseMode(false);
635 >        ADBSetRelMouseMode(mouse_grabbed);
636  
637 <        // Create window
637 >        // Create window (setting background_pixel, border_pixel and colormap is
638 >        // mandatory when using a non-default visual; in 1-bit mode we use the
639 >        // default visual, so we can also use the default colormap)
640          XSetWindowAttributes wattr;
641          wattr.event_mask = eventmask = win_eventmask;
642 <        wattr.background_pixel = black_pixel;
643 <        wattr.colormap = (mode.depth == VDEPTH_1BIT && vis->c_class == PseudoColor ? DefaultColormap(x_display, screen) : cmap[0]);
642 >        wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
643 >        wattr.border_pixel = 0;
644 >        wattr.colormap = (mode.depth == VDEPTH_1BIT ? DefaultColormap(x_display, screen) : cmap[0]);
645          w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
646 <                InputOutput, vis, CWEventMask | CWBackPixel | (vis->c_class == PseudoColor || vis->c_class == DirectColor ? CWColormap : 0), &wattr);
646 >                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWColormap, &wattr);
647 >        D(bug(" window created\n"));
648  
649          // Set window name/class
650          set_window_name(w, STR_WINDOW_TITLE);
# Line 448 | Line 668 | driver_window::driver_window(const video
668                          XFree(hints);
669                  }
670          }
671 +        D(bug(" window attributes set\n"));
672          
673          // Show window
674          XMapWindow(x_display, w);
675          wait_mapped(w);
676 +        D(bug(" window mapped\n"));
677  
678          // 1-bit mode is big-endian; if the X server is little-endian, we can't
679          // use SHM because that doesn't allow changing the image byte order
# Line 462 | Line 684 | driver_window::driver_window(const video
684  
685                  // Create SHM image ("height + 2" for safety)
686                  img = XShmCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
687 +                D(bug(" shm image created\n"));
688                  shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
689                  the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
690                  shminfo.shmaddr = img->data = (char *)the_buffer_copy;
# Line 476 | Line 699 | driver_window::driver_window(const video
699                  if (shm_error) {
700                          shmdt(shminfo.shmaddr);
701                          XDestroyImage(img);
702 +                        img = NULL;
703                          shminfo.shmid = -1;
704                  } else {
705                          have_shm = true;
706                          shmctl(shminfo.shmid, IPC_RMID, 0);
707                  }
708 +                D(bug(" shm image attached\n"));
709          }
710          
711          // Create normal X image if SHM doesn't work ("height + 2" for safety)
# Line 488 | Line 713 | driver_window::driver_window(const video
713                  int bytes_per_row = (mode.depth == VDEPTH_1BIT ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth)));
714                  the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
715                  img = XCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
716 +                D(bug(" X image created\n"));
717          }
718  
719          if (need_msb_image) {
# Line 496 | Line 722 | driver_window::driver_window(const video
722          }
723  
724   #ifdef ENABLE_VOSF
725 +        use_vosf = true;
726          // Allocate memory for frame buffer (SIZE is extended to page-boundary)
727          the_host_buffer = the_buffer_copy;
728          the_buffer_size = page_extend((aligned_height + 2) * img->bytes_per_line);
502        the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
729          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
730 +        the_buffer_copy = (uint8 *)malloc(the_buffer_size);
731 +        D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
732   #else
733          // Allocate memory for frame buffer
734          the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
735 +        D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
736   #endif
737  
738          // Create GC
# Line 525 | Line 754 | driver_window::driver_window(const video
754          native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
755   #endif
756   #ifdef ENABLE_VOSF
757 <        Screen_blitter_init(&visualInfo, native_byte_order, mode.depth);
757 >        Screen_blitter_init(&visualInfo, native_byte_order, depth_of_video_mode(mode));
758   #endif
759  
760 <        // Set VideoMonitor
761 <        VideoMonitor.mode = mode;
533 <        set_mac_frame_buffer(mode.depth, native_byte_order);
760 >        // Set frame buffer base
761 >        set_mac_frame_buffer(monitor, mode.depth, native_byte_order);
762  
763          // Everything went well
764          init_ok = true;
# Line 539 | Line 767 | driver_window::driver_window(const video
767   // Close display
768   driver_window::~driver_window()
769   {
542        if (img)
543                XDestroyImage(img);
770          if (have_shm) {
771                  XShmDetach(x_display, &shminfo);
772 + #ifdef ENABLE_VOSF
773 +                the_host_buffer = NULL; // don't free() in driver_base dtor
774 + #else
775                  the_buffer_copy = NULL; // don't free() in driver_base dtor
776 + #endif
777 +        }
778 +        if (img) {
779 +                if (!have_shm)
780 +                        img->data = NULL;
781 +                XDestroyImage(img);
782 +        }
783 +        if (have_shm) {
784 +                shmdt(shminfo.shmaddr);
785 +                shmctl(shminfo.shmid, IPC_RMID, 0);
786          }
787          if (gc)
788                  XFreeGC(x_display, gc);
789   }
790  
791 + // Toggle mouse grab
792 + void driver_window::toggle_mouse_grab(void)
793 + {
794 +        if (mouse_grabbed)
795 +                ungrab_mouse();
796 +        else
797 +                grab_mouse();
798 + }
799 +
800 + // Grab mouse, switch to relative mouse mode
801 + void driver_window::grab_mouse(void)
802 + {
803 +        int result;
804 +        for (int i=0; i<10; i++) {
805 +                result = XGrabPointer(x_display, w, True, 0,
806 +                        GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
807 +                if (result != AlreadyGrabbed)
808 +                        break;
809 +                Delay_usec(100000);
810 +        }
811 +        if (result == GrabSuccess) {
812 +                XStoreName(x_display, w, GetString(STR_WINDOW_TITLE_GRABBED));
813 +                ADBSetRelMouseMode(mouse_grabbed = true);
814 +                disable_mouse_accel();
815 +        }
816 + }
817 +
818 + // Ungrab mouse, switch to absolute mouse mode
819 + void driver_window::ungrab_mouse(void)
820 + {
821 +        if (mouse_grabbed) {
822 +                XUngrabPointer(x_display, CurrentTime);
823 +                XStoreName(x_display, w, GetString(STR_WINDOW_TITLE));
824 +                ADBSetRelMouseMode(mouse_grabbed = false);
825 +                restore_mouse_accel();
826 +        }
827 + }
828 +
829 + // Mouse moved
830 + void driver_window::mouse_moved(int x, int y)
831 + {
832 +        if (!mouse_grabbed) {
833 +                mouse_last_x = x; mouse_last_y = y;
834 +                ADBMouseMoved(x, y);
835 +                return;
836 +        }
837 +
838 +        // Warped mouse motion (this code is taken from SDL)
839 +
840 +        // Post first mouse event
841 +        int width = monitor.get_current_mode().x, height = monitor.get_current_mode().y;
842 +        int delta_x = x - mouse_last_x, delta_y = y - mouse_last_y;
843 +        mouse_last_x = x; mouse_last_y = y;
844 +        ADBMouseMoved(delta_x, delta_y);
845 +
846 +        // Only warp the pointer when it has reached the edge
847 +        const int MOUSE_FUDGE_FACTOR = 8;
848 +        if (x < MOUSE_FUDGE_FACTOR || x > (width - MOUSE_FUDGE_FACTOR)
849 +         || y < MOUSE_FUDGE_FACTOR || y > (height - MOUSE_FUDGE_FACTOR)) {
850 +                XEvent event;
851 +                while (XCheckTypedEvent(x_display, MotionNotify, &event)) {
852 +                        delta_x = x - mouse_last_x; delta_y = y - mouse_last_y;
853 +                        mouse_last_x = x; mouse_last_y = y;
854 +                        ADBMouseMoved(delta_x, delta_y);
855 +                }
856 +                mouse_last_x = width/2;
857 +                mouse_last_y = height/2;
858 +                XWarpPointer(x_display, None, w, 0, 0, 0, 0, mouse_last_x, mouse_last_y);
859 +                for (int i=0; i<10; i++) {
860 +                        XMaskEvent(x_display, PointerMotionMask, &event);
861 +                        if (event.xmotion.x > (mouse_last_x - MOUSE_FUDGE_FACTOR)
862 +                         && event.xmotion.x < (mouse_last_x + MOUSE_FUDGE_FACTOR)
863 +                         && event.xmotion.y > (mouse_last_y - MOUSE_FUDGE_FACTOR)
864 +                         && event.xmotion.y < (mouse_last_y + MOUSE_FUDGE_FACTOR))
865 +                                break;
866 +                }
867 +        }
868 + }
869 +
870  
871   #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
872   /*
# Line 557 | Line 875 | driver_window::~driver_window()
875  
876   class driver_dga : public driver_base {
877   public:
878 <        driver_dga();
878 >        driver_dga(X11_monitor_desc &monitor);
879          ~driver_dga();
880  
881          void suspend(void);
# Line 568 | Line 886 | private:
886          void *fb_save;                  // Saved frame buffer for suspend/resume
887   };
888  
889 < driver_dga::driver_dga()
890 < : suspend_win(0), fb_save(NULL)
889 > driver_dga::driver_dga(X11_monitor_desc &m)
890 > : driver_base(m), suspend_win(0), fb_save(NULL)
891   {
892   }
893  
# Line 590 | Line 908 | void driver_dga::suspend(void)
908          LOCK_FRAME_BUFFER;
909  
910          // Save frame buffer
911 <        fb_save = malloc(VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
911 >        fb_save = malloc(mode.y * mode.bytes_per_row);
912          if (fb_save)
913 <                memcpy(fb_save, the_buffer, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
913 >                memcpy(fb_save, the_buffer, mode.y * mode.bytes_per_row);
914  
915          // Close full screen display
916   #ifdef ENABLE_XF86_DGA
# Line 600 | Line 918 | void driver_dga::suspend(void)
918   #endif
919          XUngrabPointer(x_display, CurrentTime);
920          XUngrabKeyboard(x_display, CurrentTime);
921 +        restore_mouse_accel();
922          XUnmapWindow(x_display, w);
923          wait_unmapped(w);
924  
# Line 627 | Line 946 | void driver_dga::resume(void)
946          XMapRaised(x_display, w);
947          wait_mapped(w);
948          XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
949 <        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
950 <        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
949 >        XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
950 >        XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
951 >        disable_mouse_accel();
952   #ifdef ENABLE_XF86_DGA
953          XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
954          XF86DGASetViewPort(x_display, screen, 0, 0);
# Line 643 | Line 963 | void driver_dga::resume(void)
963                  LOCK_VOSF;
964                  PFLAG_SET_ALL;
965                  UNLOCK_VOSF;
966 <                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
966 >                memset(the_buffer_copy, 0, mode.bytes_per_row * mode.y);
967          }
968   #endif
969          
# Line 653 | Line 973 | void driver_dga::resume(void)
973                  // Don't copy fb_save to the temporary frame buffer in VOSF mode
974                  if (!use_vosf)
975   #endif
976 <                memcpy(the_buffer, fb_save, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
976 >                memcpy(the_buffer, fb_save, mode.y * mode.bytes_per_row);
977                  free(fb_save);
978                  fb_save = NULL;
979          }
# Line 675 | Line 995 | const char FBDEVICE_FILE_NAME[] = "/dev/
995  
996   class driver_fbdev : public driver_dga {
997   public:
998 <        driver_fbdev(const video_mode &mode);
998 >        driver_fbdev(X11_monitor_desc &monitor);
999          ~driver_fbdev();
1000   };
1001  
1002   // Open display
1003 < driver_fbdev::driver_fbdev(const video_mode &mode)
1003 > driver_fbdev::driver_fbdev(X11_monitor_desc &m) : driver_dga(m)
1004   {
1005          int width = mode.x, height = mode.y;
1006  
# Line 728 | Line 1048 | driver_fbdev::driver_fbdev(const video_m
1048                  if ((line[0] == '#') || (line[0] == ';') || (line[0] == '\0'))
1049                          continue;
1050                  
1051 <                if ((sscanf(line, "%19s %d %x", &fb_name, &fb_depth, &fb_offset) == 3)
1051 >                if ((sscanf(line, "%19s %d %x", fb_name, &fb_depth, &fb_offset) == 3)
1052                   && (strcmp(fb_name, fb_name) == 0) && (fb_depth == max_depth)) {
1053                          device_found = true;
1054                          break;
# Line 775 | Line 1095 | driver_fbdev::driver_fbdev(const video_m
1095          XGrabPointer(x_display, w, True,
1096                  PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
1097                  GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
1098 +        disable_mouse_accel();
1099          
1100          // Calculate bytes per row
1101          int bytes_per_row = TrivialBytesPerRow(mode.x, mode.depth);
1102          
1103          // Map frame buffer
1104 <        if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
1105 <                if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
1104 >        the_buffer_size = height * bytes_per_row;
1105 >        if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
1106 >                if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
1107                          char str[256];
1108                          sprintf(str, GetString(STR_FBDEV_MMAP_ERR), strerror(errno));
1109                          ErrorAlert(str);
# Line 799 | Line 1121 | driver_fbdev::driver_fbdev(const video_m
1121            // Allocate memory for frame buffer (SIZE is extended to page-boundary)
1122            the_host_buffer = the_buffer;
1123            the_buffer_size = page_extend((height + 2) * bytes_per_row);
1124 <          the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
1124 >          the_buffer_copy = (uint8 *)malloc(the_buffer_size);
1125            the_buffer = (uint8 *)vm_acquire(the_buffer_size);
1126          }
1127   #else
# Line 807 | Line 1129 | driver_fbdev::driver_fbdev(const video_m
1129   #endif
1130   #endif
1131          
1132 <        // Set VideoMonitor
1133 <        VideoModes[0].bytes_per_row = bytes_per_row;
1134 <        VideoModes[0].depth = DepthModeForPixelDepth(fb_depth);
1135 <        VideoMonitor.mode = mode;
814 <        set_mac_frame_buffer(mode.depth, true);
1132 >        // Set frame buffer base
1133 >        const_cast<video_mode *>(&mode)->bytes_per_row = bytes_per_row;
1134 >        const_cast<video_mode *>(&mode)->depth = DepthModeForPixelDepth(fb_depth);
1135 >        set_mac_frame_buffer(monitor, mode.depth, true);
1136  
1137          // Everything went well
1138          init_ok = true;
# Line 820 | Line 1141 | driver_fbdev::driver_fbdev(const video_m
1141   // Close display
1142   driver_fbdev::~driver_fbdev()
1143   {
1144 +        if (!use_vosf) {
1145 +                if (the_buffer != MAP_FAILED) {
1146 +                        // don't free() the screen buffer in driver_base dtor
1147 +                        munmap(the_buffer, the_buffer_size);
1148 +                        the_buffer = NULL;
1149 +                }
1150 +        }
1151 + #ifdef ENABLE_VOSF
1152 +        else {
1153 +                if (the_host_buffer != MAP_FAILED) {
1154 +                        // don't free() the screen buffer in driver_base dtor
1155 +                        munmap(the_host_buffer, the_buffer_size);
1156 +                        the_host_buffer = NULL;
1157 +                }
1158 +        }
1159 + #endif
1160   }
1161   #endif
1162  
# Line 831 | Line 1168 | driver_fbdev::~driver_fbdev()
1168  
1169   class driver_xf86dga : public driver_dga {
1170   public:
1171 <        driver_xf86dga(const video_mode &mode);
1171 >        driver_xf86dga(X11_monitor_desc &monitor);
1172          ~driver_xf86dga();
1173  
1174          void update_palette(void);
# Line 842 | Line 1179 | private:
1179   };
1180  
1181   // Open display
1182 < driver_xf86dga::driver_xf86dga(const video_mode &mode)
1183 < : current_dga_cmap(0)
1182 > driver_xf86dga::driver_xf86dga(X11_monitor_desc &m)
1183 > : driver_dga(m), current_dga_cmap(0)
1184   {
1185          int width = mode.x, height = mode.y;
1186  
# Line 870 | Line 1207 | driver_xf86dga::driver_xf86dga(const vid
1207          XSetWindowAttributes wattr;
1208          wattr.event_mask = eventmask = dga_eventmask;
1209          wattr.override_redirect = True;
1210 +        wattr.colormap = (mode.depth == VDEPTH_1BIT ? DefaultColormap(x_display, screen) : cmap[0]);
1211  
1212          w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
1213 <                InputOutput, vis, CWEventMask | CWOverrideRedirect, &wattr);
1213 >                InputOutput, vis, CWEventMask | CWOverrideRedirect |
1214 >                (color_class == DirectColor ? CWColormap : 0), &wattr);
1215  
1216          // Set window name/class
1217          set_window_name(w, STR_WINDOW_TITLE);
# Line 889 | Line 1228 | driver_xf86dga::driver_xf86dga(const vid
1228          XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1229          XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
1230          XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1231 +        disable_mouse_accel();
1232  
1233          int v_width, v_bank, v_size;
1234          XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size);
# Line 905 | Line 1245 | driver_xf86dga::driver_xf86dga(const vid
1245  
1246          // Init blitting routines
1247          int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, mode.depth);
1248 < #ifdef VIDEO_VOSF
1248 > #if ENABLE_VOSF
1249 >        bool native_byte_order;
1250 > #ifdef WORDS_BIGENDIAN
1251 >        native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
1252 > #else
1253 >        native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
1254 > #endif
1255   #if REAL_ADDRESSING || DIRECT_ADDRESSING
1256          // Screen_blitter_init() returns TRUE if VOSF is mandatory
1257          // i.e. the framebuffer update function is not Blit_Copy_Raw
1258 <        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
1258 >        use_vosf = Screen_blitter_init(&visualInfo, native_byte_order, depth_of_video_mode(mode));
1259          
1260          if (use_vosf) {
1261            // Allocate memory for frame buffer (SIZE is extended to page-boundary)
1262            the_host_buffer = the_buffer;
1263            the_buffer_size = page_extend((height + 2) * bytes_per_row);
1264 <          the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
1264 >          the_buffer_copy = (uint8 *)malloc(the_buffer_size);
1265            the_buffer = (uint8 *)vm_acquire(the_buffer_size);
1266          }
1267   #else
# Line 923 | Line 1269 | driver_xf86dga::driver_xf86dga(const vid
1269   #endif
1270   #endif
1271          
1272 <        // Set VideoMonitor
1272 >        // Set frame buffer base
1273          const_cast<video_mode *>(&mode)->bytes_per_row = bytes_per_row;
1274 <        VideoMonitor.mode = mode;
929 <        set_mac_frame_buffer(mode.depth, true);
1274 >        set_mac_frame_buffer(monitor, mode.depth, true);
1275  
1276          // Everything went well
1277          init_ok = true;
# Line 936 | Line 1281 | driver_xf86dga::driver_xf86dga(const vid
1281   driver_xf86dga::~driver_xf86dga()
1282   {
1283          XF86DGADirectVideo(x_display, screen, 0);
1284 +        if (!use_vosf) {
1285 +                // don't free() the screen buffer in driver_base dtor
1286 +                the_buffer = NULL;
1287 +        }
1288 + #ifdef ENABLE_VOSF
1289 +        else {
1290 +                // don't free() the screen buffer in driver_base dtor
1291 +                the_host_buffer = NULL;
1292 +        }
1293 + #endif
1294   #ifdef ENABLE_XF86_VIDMODE
1295          if (has_vidmode)
1296                  XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
# Line 947 | Line 1302 | void driver_xf86dga::update_palette(void
1302   {
1303          driver_dga::update_palette();
1304          current_dga_cmap ^= 1;
1305 <        if (!IsDirectMode(VideoMonitor.mode) && cmap[current_dga_cmap])
1305 >        if (!IsDirectMode(monitor.get_current_mode()) && cmap[current_dga_cmap])
1306                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1307   }
1308  
# Line 955 | Line 1310 | void driver_xf86dga::update_palette(void
1310   void driver_xf86dga::resume(void)
1311   {
1312          driver_dga::resume();
1313 <        if (!IsDirectMode(VideoMonitor.mode))
1313 >        if (!IsDirectMode(monitor.get_current_mode()))
1314                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1315   }
1316   #endif
# Line 1030 | Line 1385 | static void keycode_init(void)
1385          }
1386   }
1387  
1388 < // Open display for specified mode
1389 < static bool video_open(const video_mode &mode)
1388 > // Open display for current mode
1389 > bool X11_monitor_desc::video_open(void)
1390   {
1391 +        D(bug("video_open()\n"));
1392 +        const video_mode &mode = get_current_mode();
1393 +
1394 +        // Find best available X visual
1395 +        if (!find_visual_for_depth(mode.depth)) {
1396 +                ErrorAlert(STR_NO_XVISUAL_ERR);
1397 +                return false;
1398 +        }
1399 +
1400 +        // Create color maps
1401 +        if (color_class == PseudoColor || color_class == DirectColor) {
1402 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1403 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1404 +        } else {
1405 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone);
1406 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone);
1407 +        }
1408 +
1409 +        // Find pixel format of direct modes
1410 +        if (color_class == DirectColor || color_class == TrueColor) {
1411 +                rshift = gshift = bshift = 0;
1412 +                rloss = gloss = bloss = 8;
1413 +                uint32 mask;
1414 +                for (mask=vis->red_mask; !(mask&1); mask>>=1)
1415 +                        ++rshift;
1416 +                for (; mask&1; mask>>=1)
1417 +                        --rloss;
1418 +                for (mask=vis->green_mask; !(mask&1); mask>>=1)
1419 +                        ++gshift;
1420 +                for (; mask&1; mask>>=1)
1421 +                        --gloss;
1422 +                for (mask=vis->blue_mask; !(mask&1); mask>>=1)
1423 +                        ++bshift;
1424 +                for (; mask&1; mask>>=1)
1425 +                        --bloss;
1426 +        }
1427 +
1428 +        // Preset palette pixel values for CLUT or gamma table
1429 +        if (color_class == DirectColor) {
1430 +                int num = vis->map_entries;
1431 +                for (int i=0; i<num; i++) {
1432 +                        int c = (i * 256) / num;
1433 +                        x_palette[i].pixel = map_rgb(c, c, c);
1434 +                        x_palette[i].flags = DoRed | DoGreen | DoBlue;
1435 +                }
1436 +        } else if (color_class == PseudoColor) {
1437 +                for (int i=0; i<256; i++) {
1438 +                        x_palette[i].pixel = i;
1439 +                        x_palette[i].flags = DoRed | DoGreen | DoBlue;
1440 +                }
1441 +        }
1442 +
1443          // Load gray ramp to color map
1444 <        int num = (vis->c_class == DirectColor ? vis->map_entries : 256);
1444 >        int num = (color_class == DirectColor ? vis->map_entries : 256);
1445          for (int i=0; i<num; i++) {
1446                  int c = (i * 256) / num;
1447 <                palette[i].red = c * 0x0101;
1448 <                palette[i].green = c * 0x0101;
1449 <                palette[i].blue = c * 0x0101;
1450 <                if (vis->c_class == PseudoColor)
1451 <                        palette[i].pixel = i;
1452 <                palette[i].flags = DoRed | DoGreen | DoBlue;
1453 <        }
1047 <        if (cmap[0] && cmap[1]) {
1048 <                XStoreColors(x_display, cmap[0], palette, num);
1049 <                XStoreColors(x_display, cmap[1], palette, num);
1447 >                x_palette[i].red = c * 0x0101;
1448 >                x_palette[i].green = c * 0x0101;
1449 >                x_palette[i].blue = c * 0x0101;
1450 >        }
1451 >        if (color_class == PseudoColor || color_class == DirectColor) {
1452 >                XStoreColors(x_display, cmap[0], x_palette, num);
1453 >                XStoreColors(x_display, cmap[1], x_palette, num);
1454          }
1455  
1456   #ifdef ENABLE_VOSF
1457          // Load gray ramp to 8->16/32 expand map
1458 <        if (!IsDirectMode(mode) && (vis->c_class == TrueColor || vis->c_class == DirectColor))
1458 >        if (!IsDirectMode(mode) && xdepth > 8)
1459                  for (int i=0; i<256; i++)
1460                          ExpandMap[i] = map_rgb(i, i, i);
1461   #endif
# Line 1059 | Line 1463 | static bool video_open(const video_mode
1463          // Create display driver object of requested type
1464          switch (display_type) {
1465                  case DISPLAY_WINDOW:
1466 <                        drv = new driver_window(mode);
1466 >                        drv = new driver_window(*this);
1467                          break;
1468   #ifdef ENABLE_FBDEV_DGA
1469                  case DISPLAY_DGA:
1470 <                        drv = new driver_fbdev(mode);
1470 >                        drv = new driver_fbdev(*this);
1471                          break;
1472   #endif
1473   #ifdef ENABLE_XF86_DGA
1474                  case DISPLAY_DGA:
1475 <                        drv = new driver_xf86dga(mode);
1475 >                        drv = new driver_xf86dga(*this);
1476                          break;
1477   #endif
1478          }
# Line 1082 | Line 1486 | static bool video_open(const video_mode
1486  
1487   #ifdef ENABLE_VOSF
1488          if (use_vosf) {
1489 <                // Initialize the mainBuffer structure
1490 <                if (!video_init_buffer()) {
1489 >                // Initialize the VOSF system
1490 >                if (!video_vosf_init(*this)) {
1491                          ErrorAlert(STR_VOSF_INIT_ERR);
1492                  return false;
1493                  }
1090
1091                // Initialize the handler for SIGSEGV
1092                if (!sigsegv_install_handler(screen_fault_handler)) {
1093                        ErrorAlert("Could not initialize Video on SEGV signals");
1094                        return false;
1095                }
1494          }
1495   #endif
1496          
# Line 1106 | Line 1504 | static bool video_open(const video_mode
1504          // Start redraw/input thread
1505   #ifdef HAVE_PTHREADS
1506          redraw_thread_cancel = false;
1507 <        redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1507 >        Set_pthread_attr(&redraw_thread_attr, 0);
1508 >        redraw_thread_active = (pthread_create(&redraw_thread, &redraw_thread_attr, redraw_func, NULL) == 0);
1509          if (!redraw_thread_active) {
1510                  printf("FATAL: cannot create redraw thread\n");
1511                  return false;
# Line 1143 | Line 1542 | bool VideoInit(bool classic)
1542          // Find screen and root window
1543          screen = XDefaultScreen(x_display);
1544          rootwin = XRootWindow(x_display, screen);
1545 <        
1546 <        // Get screen depth
1547 <        xdepth = DefaultDepth(x_display, screen);
1545 >
1546 >        // Get sorted list of available depths
1547 >        avail_depths = XListDepths(x_display, screen, &num_depths);
1548 >        if (avail_depths == NULL) {
1549 >                ErrorAlert(STR_UNSUPP_DEPTH_ERR);
1550 >                return false;
1551 >        }
1552 >        std::sort(avail_depths, avail_depths + num_depths);
1553          
1554   #ifdef ENABLE_FBDEV_DGA
1555          // Frame buffer name
# Line 1185 | Line 1589 | bool VideoInit(bool classic)
1589          black_pixel = BlackPixel(x_display, screen);
1590          white_pixel = WhitePixel(x_display, screen);
1591  
1188        // Get appropriate visual
1189        int color_class;
1190        switch (xdepth) {
1191                case 1:
1192                        color_class = StaticGray;
1193                        break;
1194                case 8:
1195                        color_class = PseudoColor;
1196                        break;
1197                case 15:
1198                case 16:
1199                case 24:
1200                case 32: // Try DirectColor first, as this will allow gamma correction
1201                        color_class = DirectColor;
1202                        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo))
1203                                color_class = TrueColor;
1204                        break;
1205                default:
1206                        ErrorAlert(STR_UNSUPP_DEPTH_ERR);
1207                        return false;
1208        }
1209        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
1210                ErrorAlert(STR_NO_XVISUAL_ERR);
1211                return false;
1212        }
1213        if (visualInfo.depth != xdepth) {
1214                ErrorAlert(STR_NO_XVISUAL_ERR);
1215                return false;
1216        }
1217        vis = visualInfo.visual;
1218
1219        // Create color maps
1220        if (color_class == PseudoColor || color_class == DirectColor) {
1221                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1222                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1223        }
1224
1225        // Find pixel format of direct modes
1226        if (color_class == DirectColor || color_class == TrueColor) {
1227                rshift = gshift = bshift = 0;
1228                rloss = gloss = bloss = 8;
1229                uint32 mask;
1230                for (mask=vis->red_mask; !(mask&1); mask>>=1)
1231                        ++rshift;
1232                for (; mask&1; mask>>=1)
1233                        --rloss;
1234                for (mask=vis->green_mask; !(mask&1); mask>>=1)
1235                        ++gshift;
1236                for (; mask&1; mask>>=1)
1237                        --gloss;
1238                for (mask=vis->blue_mask; !(mask&1); mask>>=1)
1239                        ++bshift;
1240                for (; mask&1; mask>>=1)
1241                        --bloss;
1242        }
1243
1244        // Preset palette pixel values for gamma table
1245        if (color_class == DirectColor) {
1246                int num = vis->map_entries;
1247                for (int i=0; i<num; i++) {
1248                        int c = (i * 256) / num;
1249                        palette[i].pixel = map_rgb(c, c, c);
1250                }
1251        }
1252
1592          // Get screen mode from preferences
1593          const char *mode_str;
1594          if (classic_mode)
# Line 1284 | Line 1623 | bool VideoInit(bool classic)
1623                  default_height = DisplayHeight(x_display, screen);
1624  
1625          // Mac screen depth follows X depth
1626 <        video_depth default_depth = DepthModeForPixelDepth(xdepth);
1626 >        video_depth default_depth = VDEPTH_1BIT;
1627 >        switch (DefaultDepth(x_display, screen)) {
1628 >                case 8:
1629 >                        default_depth = VDEPTH_8BIT;
1630 >                        break;
1631 >                case 15: case 16:
1632 >                        default_depth = VDEPTH_16BIT;
1633 >                        break;
1634 >                case 24: case 32:
1635 >                        default_depth = VDEPTH_32BIT;
1636 >                        break;
1637 >        }
1638  
1639          // Construct list of supported modes
1640          if (display_type == DISPLAY_WINDOW) {
1641                  if (classic)
1642                          add_mode(512, 342, 0x80, 64, VDEPTH_1BIT);
1643                  else {
1644 <                        if (default_depth != VDEPTH_1BIT) { // 1-bit modes are always available
1645 <                                add_mode(512, 384, 0x80, TrivialBytesPerRow(512, VDEPTH_1BIT), VDEPTH_1BIT);
1646 <                                add_mode(640, 480, 0x81, TrivialBytesPerRow(640, VDEPTH_1BIT), VDEPTH_1BIT);
1297 <                                add_mode(800, 600, 0x82, TrivialBytesPerRow(800, VDEPTH_1BIT), VDEPTH_1BIT);
1298 <                                add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, VDEPTH_1BIT), VDEPTH_1BIT);
1299 <                                add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, VDEPTH_1BIT), VDEPTH_1BIT);
1300 <                                add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, VDEPTH_1BIT), VDEPTH_1BIT);
1301 <                                add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, VDEPTH_1BIT), VDEPTH_1BIT);
1302 <                        }
1303 < #ifdef ENABLE_VOSF
1304 <                        if (default_depth > VDEPTH_8BIT) { // 8-bit modes are also possible on 16/32-bit screens with VOSF blitters
1305 <                                add_mode(512, 384, 0x80, TrivialBytesPerRow(512, VDEPTH_8BIT), VDEPTH_8BIT);
1306 <                                add_mode(640, 480, 0x81, TrivialBytesPerRow(640, VDEPTH_8BIT), VDEPTH_8BIT);
1307 <                                add_mode(800, 600, 0x82, TrivialBytesPerRow(800, VDEPTH_8BIT), VDEPTH_8BIT);
1308 <                                add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, VDEPTH_8BIT), VDEPTH_8BIT);
1309 <                                add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, VDEPTH_8BIT), VDEPTH_8BIT);
1310 <                                add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, VDEPTH_8BIT), VDEPTH_8BIT);
1311 <                                add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, VDEPTH_8BIT), VDEPTH_8BIT);
1644 >                        for (unsigned d=VDEPTH_1BIT; d<=VDEPTH_32BIT; d++) {
1645 >                                if (find_visual_for_depth(video_depth(d)))
1646 >                                        add_window_modes(video_depth(d));
1647                          }
1313 #endif
1314                        add_mode(512, 384, 0x80, TrivialBytesPerRow(512, default_depth), default_depth);
1315                        add_mode(640, 480, 0x81, TrivialBytesPerRow(640, default_depth), default_depth);
1316                        add_mode(800, 600, 0x82, TrivialBytesPerRow(800, default_depth), default_depth);
1317                        add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, default_depth), default_depth);
1318                        add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, default_depth), default_depth);
1319                        add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, default_depth), default_depth);
1320                        add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, default_depth), default_depth);
1648                  }
1649          } else
1650                  add_mode(default_width, default_height, 0x80, TrivialBytesPerRow(default_width, default_depth), default_depth);
1651 +        if (VideoModes.empty()) {
1652 +                ErrorAlert(STR_NO_XVISUAL_ERR);
1653 +                return false;
1654 +        }
1655  
1656 <        // Find requested default mode and open display
1657 <        if (VideoModes.size() == 1)
1658 <                return video_open(VideoModes[0]);
1659 <        else {
1660 <                // Find mode with specified dimensions
1661 <                std::vector<video_mode>::const_iterator i, end = VideoModes.end();
1662 <                for (i = VideoModes.begin(); i != end; ++i) {
1332 <                        if (i->x == default_width && i->y == default_height && i->depth == default_depth)
1333 <                                return video_open(*i);
1656 >        // Find requested default mode with specified dimensions
1657 >        uint32 default_id;
1658 >        std::vector<video_mode>::const_iterator i, end = VideoModes.end();
1659 >        for (i = VideoModes.begin(); i != end; ++i) {
1660 >                if (i->x == default_width && i->y == default_height && i->depth == default_depth) {
1661 >                        default_id = i->resolution_id;
1662 >                        break;
1663                  }
1335                return video_open(VideoModes[0]);
1664          }
1665 +        if (i == end) { // not found, use first available mode
1666 +                default_depth = VideoModes[0].depth;
1667 +                default_id = VideoModes[0].resolution_id;
1668 +        }
1669 +
1670 + #if DEBUG
1671 +        D(bug("Available video modes:\n"));
1672 +        for (i = VideoModes.begin(); i != end; ++i) {
1673 +                int bits = 1 << i->depth;
1674 +                if (bits == 16)
1675 +                        bits = 15;
1676 +                else if (bits == 32)
1677 +                        bits = 24;
1678 +                D(bug(" %dx%d (ID %02x), %d colors\n", i->x, i->y, i->resolution_id, 1 << bits));
1679 +        }
1680 + #endif
1681 +
1682 +        // Create X11_monitor_desc for this (the only) display
1683 +        X11_monitor_desc *monitor = new X11_monitor_desc(VideoModes, default_depth, default_id);
1684 +        VideoMonitors.push_back(monitor);
1685 +
1686 +        // Open display
1687 +        return monitor->video_open();
1688   }
1689  
1690  
# Line 1342 | Line 1693 | bool VideoInit(bool classic)
1693   */
1694  
1695   // Close display
1696 < static void video_close(void)
1696 > void X11_monitor_desc::video_close(void)
1697   {
1698 +        D(bug("video_close()\n"));
1699 +
1700          // Stop redraw thread
1701   #ifdef HAVE_PTHREADS
1702          if (redraw_thread_active) {
# Line 1359 | Line 1712 | static void video_close(void)
1712          // Unlock frame buffer
1713          UNLOCK_FRAME_BUFFER;
1714          XSync(x_display, false);
1715 +        D(bug(" frame buffer unlocked\n"));
1716  
1717   #ifdef ENABLE_VOSF
1364        // Deinitialize VOSF
1718          if (use_vosf) {
1719 <                if (mainBuffer.pageInfo) {
1720 <                        free(mainBuffer.pageInfo);
1368 <                        mainBuffer.pageInfo = NULL;
1369 <                }
1370 <                if (mainBuffer.dirtyPages) {
1371 <                        free(mainBuffer.dirtyPages);
1372 <                        mainBuffer.dirtyPages = NULL;
1373 <                }
1719 >                // Deinitialize VOSF
1720 >                video_vosf_exit();
1721          }
1722   #endif
1723  
1724          // Close display
1725          delete drv;
1726          drv = NULL;
1380 }
1381
1382 void VideoExit(void)
1383 {
1384        // Close display
1385        video_close();
1727  
1728          // Free colormaps
1729          if (cmap[0]) {
# Line 1393 | Line 1734 | void VideoExit(void)
1734                  XFreeColormap(x_display, cmap[1]);
1735                  cmap[1] = 0;
1736          }
1737 + }
1738 +
1739 + void VideoExit(void)
1740 + {
1741 +        // Close displays
1742 +        vector<monitor_desc *>::iterator i, end = VideoMonitors.end();
1743 +        for (i = VideoMonitors.begin(); i != end; ++i)
1744 +                dynamic_cast<X11_monitor_desc *>(*i)->video_close();
1745  
1746   #ifdef ENABLE_XF86_VIDMODE
1747          // Free video mode list
# Line 1409 | Line 1758 | void VideoExit(void)
1758                  fbdev_fd = -1;
1759          }
1760   #endif
1761 +
1762 +        // Free depth list
1763 +        if (avail_depths) {
1764 +                XFree(avail_depths);
1765 +                avail_depths = NULL;
1766 +        }
1767   }
1768  
1769  
# Line 1444 | Line 1799 | void VideoInterrupt(void)
1799   *  Set palette
1800   */
1801  
1802 < void video_set_palette(uint8 *pal)
1802 > void X11_monitor_desc::set_palette(uint8 *pal, int num_in)
1803   {
1804 +        const video_mode &mode = get_current_mode();
1805 +
1806          LOCK_PALETTE;
1807  
1808          // Convert colors to XColor array
1809 <        int num_in = 256, num_out = 256;
1810 <        if (VideoMonitor.mode.depth == VDEPTH_16BIT)
1811 <                num_in = 32;
1812 <        if (IsDirectMode(VideoMonitor.mode)) {
1456 <                // If X is in 565 mode we have to stretch the palette from 32 to 64 entries
1809 >        int num_out = 256;
1810 >        bool stretch = false;
1811 >        if (IsDirectMode(mode)) {
1812 >                // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries
1813                  num_out = vis->map_entries;
1814 +                stretch = true;
1815          }
1816 <        XColor *p = palette;
1816 >        XColor *p = x_palette;
1817          for (int i=0; i<num_out; i++) {
1818 <                int c = (i * num_in) / num_out;
1818 >                int c = (stretch ? (i * num_in) / num_out : i);
1819                  p->red = pal[c*3 + 0] * 0x0101;
1820                  p->green = pal[c*3 + 1] * 0x0101;
1821                  p->blue = pal[c*3 + 2] * 0x0101;
1465                if (vis->c_class == PseudoColor)
1466                        p->pixel = i;
1467                p->flags = DoRed | DoGreen | DoBlue;
1822                  p++;
1823          }
1824  
1825   #ifdef ENABLE_VOSF
1826          // Recalculate pixel color expansion map
1827 <        if (!IsDirectMode(VideoMonitor.mode) && (vis->c_class == TrueColor || vis->c_class == DirectColor)) {
1828 <                for (int i=0; i<256; i++)
1829 <                        ExpandMap[i] = map_rgb(pal[i*3+0], pal[i*3+1], pal[i*3+2]);
1827 >        if (!IsDirectMode(mode) && xdepth > 8) {
1828 >                for (int i=0; i<256; i++) {
1829 >                        int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
1830 >                        ExpandMap[i] = map_rgb(pal[c*3+0], pal[c*3+1], pal[c*3+2]);
1831 >                }
1832  
1833                  // We have to redraw everything because the interpretation of pixel values changed
1834                  LOCK_VOSF;
1835                  PFLAG_SET_ALL;
1836                  UNLOCK_VOSF;
1837 <                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
1837 >                memset(the_buffer_copy, 0, mode.bytes_per_row * mode.y);
1838          }
1839   #endif
1840  
1841          // Tell redraw thread to change palette
1842 <        palette_changed = true;
1842 >        x_palette_changed = true;
1843  
1844          UNLOCK_PALETTE;
1845   }
# Line 1493 | Line 1849 | void video_set_palette(uint8 *pal)
1849   *  Switch video mode
1850   */
1851  
1852 < void video_switch_to_mode(const video_mode &mode)
1852 > void X11_monitor_desc::switch_to_current_mode(void)
1853   {
1854          // Close and reopen display
1855          video_close();
1856 <        video_open(mode);
1856 >        video_open();
1857  
1858          if (drv == NULL) {
1859                  ErrorAlert(STR_OPEN_WINDOW_ERR);
# Line 1507 | Line 1863 | void video_switch_to_mode(const video_mo
1863  
1864  
1865   /*
1866 < *  Translate key event to Mac keycode
1866 > *  Translate key event to Mac keycode, returns -1 if no keycode was found
1867 > *  and -2 if the key was recognized as a hotkey
1868   */
1869  
1870 < static int kc_decode(KeySym ks)
1870 > static int kc_decode(KeySym ks, bool key_down)
1871   {
1872          switch (ks) {
1873                  case XK_A: case XK_a: return 0x00;
# Line 1563 | Line 1920 | static int kc_decode(KeySym ks)
1920                  case XK_period: case XK_greater: return 0x2f;
1921                  case XK_slash: case XK_question: return 0x2c;
1922  
1923 < #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1567 <                case XK_Tab: if (ctrl_down) {drv->suspend(); return -1;} else return 0x30;
1568 < #else
1569 <                case XK_Tab: return 0x30;
1570 < #endif
1923 >                case XK_Tab: if (ctrl_down) {if (key_down) drv->suspend(); return -2;} else return 0x30;
1924                  case XK_Return: return 0x24;
1925                  case XK_space: return 0x31;
1926                  case XK_BackSpace: return 0x33;
# Line 1601 | Line 1954 | static int kc_decode(KeySym ks)
1954                  case XK_Left: return 0x3b;
1955                  case XK_Right: return 0x3c;
1956  
1957 <                case XK_Escape: if (ctrl_down) {quit_full_screen = true; emerg_quit = true; return -1;} else return 0x35;
1957 >                case XK_Escape: if (ctrl_down) {if (key_down) { quit_full_screen = true; emerg_quit = true; } return -2;} else return 0x35;
1958  
1959 <                case XK_F1: if (ctrl_down) {SysMountFirstFloppy(); return -1;} else return 0x7a;
1959 >                case XK_F1: if (ctrl_down) {if (key_down) SysMountFirstFloppy(); return -2;} else return 0x7a;
1960                  case XK_F2: return 0x78;
1961                  case XK_F3: return 0x63;
1962                  case XK_F4: return 0x76;
1963 <                case XK_F5: return 0x60;
1963 >                case XK_F5: if (ctrl_down) {if (key_down) drv->toggle_mouse_grab(); return -2;} else return 0x60;
1964                  case XK_F6: return 0x61;
1965                  case XK_F7: return 0x62;
1966                  case XK_F8: return 0x64;
# Line 1655 | Line 2008 | static int kc_decode(KeySym ks)
2008          return -1;
2009   }
2010  
2011 < static int event2keycode(XKeyEvent &ev)
2011 > static int event2keycode(XKeyEvent &ev, bool key_down)
2012   {
2013          KeySym ks;
1661        int as;
2014          int i = 0;
2015  
2016          do {
2017                  ks = XLookupKeysym(&ev, i++);
2018 <                as = kc_decode(ks);
2019 <                if (as != -1)
2018 >                int as = kc_decode(ks, key_down);
2019 >                if (as >= 0)
2020 >                        return as;
2021 >                if (as == -2)
2022                          return as;
2023          } while (ks != NoSymbol);
2024  
# Line 1683 | Line 2037 | static void handle_events(void)
2037                  XNextEvent(x_display, &event);
2038  
2039                  switch (event.type) {
2040 +
2041                          // Mouse button
2042                          case ButtonPress: {
2043                                  unsigned int button = event.xbutton.button;
# Line 1711 | Line 2066 | static void handle_events(void)
2066                          }
2067  
2068                          // Mouse moved
1714                        case EnterNotify:
2069                          case MotionNotify:
2070 <                                ADBMouseMoved(event.xmotion.x, event.xmotion.y);
2070 >                                drv->mouse_moved(event.xmotion.x, event.xmotion.y);
2071 >                                break;
2072 >
2073 >                        // Mouse entered window
2074 >                        case EnterNotify:
2075 >                                if (event.xcrossing.mode != NotifyGrab && event.xcrossing.mode != NotifyUngrab)
2076 >                                        drv->mouse_moved(event.xmotion.x, event.xmotion.y);
2077                                  break;
2078  
2079                          // Keyboard
2080                          case KeyPress: {
2081 <                                int code;
2081 >                                int code = -1;
2082                                  if (use_keycodes) {
2083 <                                        event2keycode(event.xkey);      // This is called to process the hotkeys
2084 <                                        code = keycode_table[event.xkey.keycode & 0xff];
2083 >                                        if (event2keycode(event.xkey, true) != -2)      // This is called to process the hotkeys
2084 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2085                                  } else
2086 <                                        code = event2keycode(event.xkey);
2087 <                                if (code != -1) {
2086 >                                        code = event2keycode(event.xkey, true);
2087 >                                if (code >= 0) {
2088                                          if (!emul_suspended) {
2089                                                  if (code == 0x39) {     // Caps Lock pressed
2090                                                          if (caps_on) {
# Line 1746 | Line 2106 | static void handle_events(void)
2106                                  break;
2107                          }
2108                          case KeyRelease: {
2109 <                                int code;
2109 >                                int code = -1;
2110                                  if (use_keycodes) {
2111 <                                        event2keycode(event.xkey);      // This is called to process the hotkeys
2112 <                                        code = keycode_table[event.xkey.keycode & 0xff];
2111 >                                        if (event2keycode(event.xkey, false) != -2)     // This is called to process the hotkeys
2112 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2113                                  } else
2114 <                                        code = event2keycode(event.xkey);
2115 <                                if (code != -1 && code != 0x39) {       // Don't propagate Caps Lock releases
2114 >                                        code = event2keycode(event.xkey, false);
2115 >                                if (code >= 0 && code != 0x39) {        // Don't propagate Caps Lock releases
2116                                          ADBKeyUp(code);
2117                                          if (code == 0x36)
2118                                                  ctrl_down = false;
# Line 1763 | Line 2123 | static void handle_events(void)
2123                          // Hidden parts exposed, force complete refresh of window
2124                          case Expose:
2125                                  if (display_type == DISPLAY_WINDOW) {
2126 +                                        const video_mode &mode = VideoMonitors[0]->get_current_mode();
2127   #ifdef ENABLE_VOSF
2128                                          if (use_vosf) {                 // VOSF refresh
2129                                                  LOCK_VOSF;
2130                                                  PFLAG_SET_ALL;
2131                                                  UNLOCK_VOSF;
2132 <                                                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
2132 >                                                memset(the_buffer_copy, 0, mode.bytes_per_row * mode.y);
2133                                          }
2134                                          else
2135   #endif
# Line 1779 | Line 2140 | static void handle_events(void)
2140                                                          updt_box[x1][y1] = true;
2141                                                  nr_boxes = 16 * 16;
2142                                          } else                                  // Static refresh
2143 <                                                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
2143 >                                                memset(the_buffer_copy, 0, mode.bytes_per_row * mode.y);
2144                                  }
2145                                  break;
2146  
# Line 1805 | Line 2166 | static void update_display_dynamic(int t
2166          int y1, y2, y2s, y2a, i, x1, xm, xmo, ymo, yo, yi, yil, xi;
2167          int xil = 0;
2168          int rxm = 0, rxmo = 0;
2169 <        int bytes_per_row = VideoMonitor.mode.bytes_per_row;
2170 <        int bytes_per_pixel = VideoMonitor.mode.bytes_per_row / VideoMonitor.mode.x;
2171 <        int rx = VideoMonitor.mode.bytes_per_row / 16;
2172 <        int ry = VideoMonitor.mode.y / 16;
2169 >        const video_mode &mode = drv->monitor.get_current_mode();
2170 >        int bytes_per_row = mode.bytes_per_row;
2171 >        int bytes_per_pixel = mode.bytes_per_row / mode.x;
2172 >        int rx = mode.bytes_per_row / 16;
2173 >        int ry = mode.y / 16;
2174          int max_box;
2175  
2176          y2s = sm_uptd[ticker % 8];
# Line 1862 | Line 2224 | static void update_display_dynamic(int t
2224                                          i = (yi * bytes_per_row) + xi;
2225                                          for (y2=0; y2 < yil; y2++, i += bytes_per_row)
2226                                                  memcpy(&the_buffer_copy[i], &the_buffer[i], xil);
2227 <                                        if (VideoMonitor.mode.depth == VDEPTH_1BIT) {
2227 >                                        if (mode.depth == VDEPTH_1BIT) {
2228                                                  if (drv->have_shm)
2229                                                          XShmPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0);
2230                                                  else
# Line 1893 | Line 2255 | static void update_display_dynamic(int t
2255   static void update_display_static(driver_window *drv)
2256   {
2257          // Incremental update code
2258 <        int wide = 0, high = 0, x1, x2, y1, y2, i, j;
2259 <        int bytes_per_row = VideoMonitor.mode.bytes_per_row;
2260 <        int bytes_per_pixel = VideoMonitor.mode.bytes_per_row / VideoMonitor.mode.x;
2258 >        unsigned wide = 0, high = 0, x1, x2, y1, y2, i, j;
2259 >        const video_mode &mode = drv->monitor.get_current_mode();
2260 >        int bytes_per_row = mode.bytes_per_row;
2261 >        int bytes_per_pixel = mode.bytes_per_row / mode.x;
2262          uint8 *p, *p2;
2263  
2264          // Check for first line from top and first line from bottom that have changed
2265          y1 = 0;
2266 <        for (j=0; j<VideoMonitor.mode.y; j++) {
2266 >        for (j=0; j<mode.y; j++) {
2267                  if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
2268                          y1 = j;
2269                          break;
2270                  }
2271          }
2272          y2 = y1 - 1;
2273 <        for (j=VideoMonitor.mode.y-1; j>=y1; j--) {
2273 >        for (j=mode.y-1; j>=y1; j--) {
2274                  if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
2275                          y2 = j;
2276                          break;
# Line 1917 | Line 2280 | static void update_display_static(driver
2280  
2281          // Check for first column from left and first column from right that have changed
2282          if (high) {
2283 <                if (VideoMonitor.mode.depth == VDEPTH_1BIT) {
2284 <                        x1 = VideoMonitor.mode.x - 1;
2283 >                if (mode.depth == VDEPTH_1BIT) {
2284 >                        x1 = mode.x - 1;
2285                          for (j=y1; j<=y2; j++) {
2286                                  p = &the_buffer[j * bytes_per_row];
2287                                  p2 = &the_buffer_copy[j * bytes_per_row];
# Line 1936 | Line 2299 | static void update_display_static(driver
2299                                  p2 = &the_buffer_copy[j * bytes_per_row];
2300                                  p += bytes_per_row;
2301                                  p2 += bytes_per_row;
2302 <                                for (i=(VideoMonitor.mode.x>>3); i>(x2>>3); i--) {
2302 >                                for (i=(mode.x>>3); i>(x2>>3); i--) {
2303                                          p--; p2--;
2304                                          if (*p != *p2) {
2305                                                  x2 = (i << 3) + 7;
# Line 1955 | Line 2318 | static void update_display_static(driver
2318                          }
2319  
2320                  } else {
2321 <                        x1 = VideoMonitor.mode.x;
2321 >                        x1 = mode.x;
2322                          for (j=y1; j<=y2; j++) {
2323                                  p = &the_buffer[j * bytes_per_row];
2324                                  p2 = &the_buffer_copy[j * bytes_per_row];
# Line 1973 | Line 2336 | static void update_display_static(driver
2336                                  p2 = &the_buffer_copy[j * bytes_per_row];
2337                                  p += bytes_per_row;
2338                                  p2 += bytes_per_row;
2339 <                                for (i=VideoMonitor.mode.x*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
2339 >                                for (i=mode.x*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
2340                                          p--;
2341                                          p2--;
2342                                          if (*p != *p2) {
# Line 2016 | Line 2379 | static void update_display_static(driver
2379  
2380   static inline void possibly_quit_dga_mode()
2381   {
2382 <        // Quit DGA mode if requested
2382 >        // Quit DGA mode if requested (something terrible has happened and we
2383 >        // want to give control back to the user)
2384          if (quit_full_screen) {
2385                  quit_full_screen = false;
2386                  delete drv;
# Line 2024 | Line 2388 | static inline void possibly_quit_dga_mod
2388          }
2389   }
2390  
2391 + static inline void possibly_ungrab_mouse()
2392 + {
2393 +        // Ungrab mouse if requested (something terrible has happened and we
2394 +        // want to give control back to the user)
2395 +        if (quit_full_screen) {
2396 +                quit_full_screen = false;
2397 +                if (drv)
2398 +                        drv->ungrab_mouse();
2399 +        }
2400 + }
2401 +
2402   static inline void handle_palette_changes(void)
2403   {
2404          LOCK_PALETTE;
2405  
2406 <        if (palette_changed) {
2407 <                palette_changed = false;
2406 >        if (x_palette_changed) {
2407 >                x_palette_changed = false;
2408                  drv->update_palette();
2409          }
2410  
# Line 2040 | Line 2415 | static void video_refresh_dga(void)
2415   {
2416          // Quit DGA mode if requested
2417          possibly_quit_dga_mode();
2043        
2044        // Handle X events
2045        handle_events();
2046        
2047        // Handle palette changes
2048        handle_palette_changes();
2418   }
2419  
2420   #ifdef ENABLE_VOSF
# Line 2055 | Line 2424 | static void video_refresh_dga_vosf(void)
2424          // Quit DGA mode if requested
2425          possibly_quit_dga_mode();
2426          
2058        // Handle X events
2059        handle_events();
2060        
2061        // Handle palette changes
2062        handle_palette_changes();
2063        
2427          // Update display (VOSF variant)
2428          static int tick_counter = 0;
2429          if (++tick_counter >= frame_skip) {
# Line 2076 | Line 2439 | static void video_refresh_dga_vosf(void)
2439  
2440   static void video_refresh_window_vosf(void)
2441   {
2442 <        // Quit DGA mode if requested
2443 <        possibly_quit_dga_mode();
2081 <        
2082 <        // Handle X events
2083 <        handle_events();
2084 <        
2085 <        // Handle palette changes
2086 <        handle_palette_changes();
2442 >        // Ungrab mouse if requested
2443 >        possibly_ungrab_mouse();
2444          
2445          // Update display (VOSF variant)
2446          static int tick_counter = 0;
# Line 2101 | Line 2458 | static void video_refresh_window_vosf(vo
2458  
2459   static void video_refresh_window_static(void)
2460   {
2461 <        // Handle X events
2462 <        handle_events();
2463 <        
2107 <        // Handle_palette changes
2108 <        handle_palette_changes();
2109 <        
2461 >        // Ungrab mouse if requested
2462 >        possibly_ungrab_mouse();
2463 >
2464          // Update display (static variant)
2465          static int tick_counter = 0;
2466          if (++tick_counter >= frame_skip) {
# Line 2117 | Line 2471 | static void video_refresh_window_static(
2471  
2472   static void video_refresh_window_dynamic(void)
2473   {
2474 <        // Handle X events
2475 <        handle_events();
2476 <        
2123 <        // Handle_palette changes
2124 <        handle_palette_changes();
2125 <        
2474 >        // Ungrab mouse if requested
2475 >        possibly_ungrab_mouse();
2476 >
2477          // Update display (dynamic variant)
2478          static int tick_counter = 0;
2479          tick_counter++;
# Line 2158 | Line 2509 | static void VideoRefreshInit(void)
2509          }
2510   }
2511  
2512 + // This function is called on non-threaded platforms from a timer interrupt
2513   void VideoRefresh(void)
2514   {
2515          // We need to check redraw_thread_active to inhibit refreshed during
2516          // mode changes on non-threaded platforms
2517 <        if (redraw_thread_active)
2518 <                video_refresh();
2517 >        if (!redraw_thread_active)
2518 >                return;
2519 >
2520 >        // Handle X events
2521 >        handle_events();
2522 >
2523 >        // Handle palette changes
2524 >        handle_palette_changes();
2525 >
2526 >        // Update display
2527 >        video_refresh();
2528   }
2529  
2530 + const int VIDEO_REFRESH_HZ = 60;
2531 + const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
2532 +
2533   #ifdef HAVE_PTHREADS
2534   static void *redraw_func(void *arg)
2535   {
2536 +        int fd = ConnectionNumber(x_display);
2537 +
2538          uint64 start = GetTicks_usec();
2539          int64 ticks = 0;
2540 <        uint64 next = GetTicks_usec();
2540 >        uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2541 >
2542          while (!redraw_thread_cancel) {
2543 <                video_refresh();
2177 <                next += 16667;
2543 >
2544                  int64 delay = next - GetTicks_usec();
2545 <                if (delay > 0)
2546 <                        Delay_usec(delay);
2547 <                else if (delay < -16667)
2545 >                if (delay < -VIDEO_REFRESH_DELAY) {
2546 >
2547 >                        // We are lagging far behind, so we reset the delay mechanism
2548                          next = GetTicks_usec();
2549 <                ticks++;
2549 >
2550 >                } else if (delay <= 0) {
2551 >
2552 >                        // Delay expired, refresh display
2553 >                        handle_events();
2554 >                        handle_palette_changes();
2555 >                        video_refresh();
2556 >                        next += VIDEO_REFRESH_DELAY;
2557 >                        ticks++;
2558 >
2559 >                } else {
2560 >
2561 >                        // No display refresh pending, check for X events
2562 >                        fd_set readfds;
2563 >                        FD_ZERO(&readfds);
2564 >                        FD_SET(fd, &readfds);
2565 >                        struct timeval timeout;
2566 >                        timeout.tv_sec = 0;
2567 >                        timeout.tv_usec = delay;
2568 >                        if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0)
2569 >                                handle_events();
2570 >                }
2571          }
2572 +
2573          uint64 end = GetTicks_usec();
2574 <        // printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, ticks * 1000000 / (end - start));
2574 >        D(bug("%Ld refreshes in %Ld usec = %f refreshes/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
2575          return NULL;
2576   }
2577   #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines