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.10 by cebix, 1999-10-25T20:22:35Z 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-1999 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 34 | Line 35
35   #include <X11/extensions/XShm.h>
36   #include <sys/ipc.h>
37   #include <sys/shm.h>
37 #include <pthread.h>
38   #include <errno.h>
39  
40 + #include <algorithm>
41 +
42 + #ifdef HAVE_PTHREADS
43 + # include <pthread.h>
44 + #endif
45 +
46 + #ifdef ENABLE_XF86_DGA
47 + # include <X11/extensions/xf86dga.h>
48 + #endif
49 +
50 + #ifdef ENABLE_XF86_VIDMODE
51 + # include <X11/extensions/xf86vmode.h>
52 + #endif
53 +
54 + #ifdef ENABLE_FBDEV_DGA
55 + # include <sys/mman.h>
56 + #endif
57 +
58   #include "cpu_emulation.h"
59   #include "main.h"
60   #include "adb.h"
# Line 45 | Line 63
63   #include "user_strings.h"
64   #include "video.h"
65  
66 < #define DEBUG 1
66 > #define DEBUG 0
67   #include "debug.h"
68  
51 #if ENABLE_XF86_DGA
52 #include <X11/extensions/xf86dga.h>
53 #endif
54
55 #if ENABLE_FBDEV_DGA
56 #include <sys/mman.h>
57 #endif
58
69  
70 + // Supported video modes
71 + static vector<video_mode> VideoModes;
72  
73   // Display types
74   enum {
# Line 64 | Line 76 | enum {
76          DISPLAY_DGA             // DGA fullscreen display
77   };
78  
67
79   // Constants
80   const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
81 < const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
81 >
82 > static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
83 > static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
84  
85  
86   // Global variables
87   static int32 frame_skip;                                                        // Prefs items
88 < static int16 mouse_wheel_mode = 1;
89 < static int16 mouse_wheel_lines = 3;
88 > static int16 mouse_wheel_mode;
89 > static int16 mouse_wheel_lines;
90  
91   static int display_type = DISPLAY_WINDOW;                       // See enum above
92 < static uint8 *the_buffer;                                                       // Mac frame buffer
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 < static volatile bool redraw_thread_cancel = false;      // Flag: Cancel Redraw thread
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
103  
104   static bool has_dga = false;                                            // Flag: Video DGA capable
105 + static bool has_vidmode = false;                                        // Flag: VidMode extension available
106 +
107 + #ifdef ENABLE_VOSF
108 + static bool use_vosf = true;                                            // Flag: VOSF enabled
109 + #else
110 + static const bool use_vosf = false;                                     // VOSF not possible
111 + #endif
112  
113   static bool ctrl_down = false;                                          // Flag: Ctrl key pressed
114   static bool caps_on = false;                                            // Flag: Caps Lock on
# Line 96 | Line 123 | static int keycode_table[256];                                         // X
123  
124   // X11 variables
125   static int screen;                                                                      // Screen number
126 < static int xdepth;                                                                      // Depth of X screen
127 < static int depth;                                                                       // Depth of Mac frame buffer
128 < static Window rootwin, the_win;                                         // Root window and our window
102 < static XVisualInfo visualInfo;
103 < static Visual *vis;
104 < static Colormap cmap[2];                                                        // Two colormaps (DGA) for 8-bit mode
126 > static Window rootwin;                                                          // Root window and our window
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;
108 static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask;
109 static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
132  
133 < static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;        // Mutex to protect palette
134 < static XColor palette[256];                                                     // Color palette for 8-bit mode
135 < static bool palette_changed = false;                            // Flag: Palette changed, redraw thread must set new colors
136 <
115 < // Variables for window mode
116 < static GC the_gc;
117 < static XImage *img = NULL;
118 < static XShmSegmentInfo shminfo;
119 < static XImage *cursor_image, *cursor_mask_image;
120 < static Pixmap cursor_map, cursor_mask_map;
121 < static Cursor mac_cursor;
122 < static GC cursor_gc, cursor_mask_gc;
123 < static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer
124 < static uint8 the_cursor[64];                                            // Cursor image data
125 < static bool have_shm = false;                                           // Flag: SHM extensions available
126 <
127 < // Variables for XF86 DGA mode
128 < static int current_dga_cmap;                                            // Number (0 or 1) of currently installed DGA colormap
129 < static Window suspend_win;                                                      // "Suspend" window
130 < static void *fb_save = NULL;                                            // Saved frame buffer for suspend
131 < static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;   // Mutex to protect frame buffer
133 > static int xdepth;                                                                      // Depth of X screen
134 > static XVisualInfo visualInfo;
135 > static Visual *vis;
136 > static int color_class;
137  
138 < // Variables for fbdev DGA mode
139 < const char FBDEVICE_FILE_NAME[] = "/dev/fb";
140 < static int fbdev_fd;
138 > static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
139 >
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;
147 > #endif
148 >
149 > #ifdef ENABLE_XF86_VIDMODE
150 > static XF86VidModeModeInfo **x_video_modes = NULL;      // Array of all available modes
151 > static int num_x_video_modes;
152 > #endif
153 >
154 > // Mutex to protect palette
155 > #ifdef HAVE_PTHREADS
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
162 > #endif
163 >
164 > // Mutex to protect frame buffer
165 > #ifdef HAVE_PTHREADS
166 > static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
167 > #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock);
168 > #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock);
169 > #else
170 > #define LOCK_FRAME_BUFFER
171 > #define UNLOCK_FRAME_BUFFER
172 > #endif
173 >
174 > // Variables for non-VOSF incremental refresh
175 > static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
176 > static int sm_no_boxes[] = {1,8,32,64,128,300};
177 > static bool updt_box[17][17];
178 > static int nr_boxes;
179 >
180 > // Video refresh function
181 > static void VideoRefreshInit(void);
182 > static void (*video_refresh)(void);
183  
184  
185   // Prototypes
186   static void *redraw_func(void *arg);
140 static int event2keycode(XKeyEvent *ev);
141
187  
188   // From main_unix.cpp
189 + extern char *x_display_name;
190   extern Display *x_display;
191  
192   // From sys_unix.cpp
# Line 148 | Line 194 | extern void SysMountFirstFloppy(void);
194  
195  
196   /*
197 < *  Initialization
197 > *  monitor_desc subclass for X11 display
198   */
199  
200 < // Set VideoMonitor according to video mode
201 < void set_video_monitor(int width, int height, int bytes_per_row, bool native_byte_order)
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 layout = FLAYOUT_DIRECT;
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 <                case 1:
276 <                        layout = FLAYOUT_DIRECT;
277 <                        VideoMonitor.mode = VMODE_1BIT;
278 <                        break;
279 <                case 8:
280 <                        layout = FLAYOUT_DIRECT;
165 <                        VideoMonitor.mode = VMODE_8BIT;
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 <                case 15:
283 <                        layout = FLAYOUT_HOST_555;
284 <                        VideoMonitor.mode = VMODE_16BIT;
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 <                case 16:
291 <                        layout = FLAYOUT_HOST_565;
292 <                        VideoMonitor.mode = VMODE_16BIT;
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 24:
296 <                case 32:
297 <                        layout = FLAYOUT_HOST_888;
178 <                        VideoMonitor.mode = VMODE_32BIT;
295 >                case VDEPTH_32BIT:      // 32-bit requires a 24/32-bit visual
296 >                        min_depth = 24;
297 >                        max_depth = 32;
298                          break;
299          }
300 <        VideoMonitor.x = width;
301 <        VideoMonitor.y = height;
302 <        VideoMonitor.bytes_per_row = bytes_per_row;
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 > {
358 >        video_mode mode;
359 >        mode.x = width;
360 >        mode.y = height;
361 >        mode.resolution_id = resolution_id;
362 >        mode.bytes_per_row = bytes_per_row;
363 >        mode.depth = depth;
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(X11_monitor_desc &monitor, video_depth depth, bool native_byte_order)
381 > {
382 > #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
383 >        int layout = FLAYOUT_DIRECT;
384 >        if (depth == VDEPTH_16BIT)
385 >                layout = (xdepth == 15) ? FLAYOUT_HOST_555 : FLAYOUT_HOST_565;
386 >        else if (depth == VDEPTH_32BIT)
387 >                layout = (xdepth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT;
388          if (native_byte_order)
389                  MacFrameLayout = layout;
390          else
391                  MacFrameLayout = FLAYOUT_DIRECT;
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 = mode.bytes_per_row * mode.y;
398 +        InitFrameBufferMapping();
399 + #else
400 +        monitor.set_mac_frame_base(Host2MacAddr(the_buffer));
401 + #endif
402 +        D(bug("monitor.mac_frame_base = %08x\n", monitor.get_mac_frame_base()));
403 + }
404 +
405 + // Set window name and class
406 + static void set_window_name(Window w, int name)
407 + {
408 +        const char *str = GetString(name);
409 +        XStoreName(x_display, w, str);
410 +        XSetIconName(x_display, w, str);
411 +
412 +        XClassHint *hints;
413 +        hints = XAllocClassHint();
414 +        if (hints) {
415 +                hints->res_name = "BasiliskII";
416 +                hints->res_class = "BasiliskII";
417 +                XSetClassHint(x_display, w, hints);
418 +                XFree(hints);
419 +        }
420 + }
421 +
422 + // Set window input focus flag
423 + static void set_window_focus(Window w)
424 + {
425 +        XWMHints *hints = XAllocWMHints();
426 +        if (hints) {
427 +                hints->input = True;
428 +                hints->initial_state = NormalState;
429 +                hints->flags = InputHint | StateHint;
430 +                XSetWMHints(x_display, w, hints);
431 +                XFree(hints);
432 +        }
433 + }
434 +
435 + // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
436 + static Atom WM_DELETE_WINDOW = (Atom)0;
437 + static void set_window_delete_protocol(Window w)
438 + {
439 +        WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
440 +        XSetWMProtocols(x_display, w, &WM_DELETE_WINDOW, 1);
441 + }
442 +
443 + // Wait until window is mapped/unmapped
444 + void wait_mapped(Window w)
445 + {
446 +        XEvent e;
447 +        do {
448 +                XMaskEvent(x_display, StructureNotifyMask, &e);
449 +        } while ((e.type != MapNotify) || (e.xmap.event != w));
450 + }
451 +
452 + void wait_unmapped(Window w)
453 + {
454 +        XEvent e;
455 +        do {
456 +                XMaskEvent(x_display, StructureNotifyMask, &e);
457 +        } while ((e.type != UnmapNotify) || (e.xmap.event != w));
458   }
459  
460   // Trap SHM errors
# Line 200 | Line 470 | static int error_handler(Display *d, XEr
470                  return old_error_handler(d, e);
471   }
472  
473 < // Init window mode
474 < static bool init_window(int width, int height)
473 >
474 > /*
475 > *  Display "driver" classes
476 > */
477 >
478 > class driver_base {
479 > public:
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;
506 > static void update_display_window_vosf(driver_window *drv);
507 > static void update_display_dynamic(int ticker, driver_window *drv);
508 > static void update_display_static(driver_window *drv);
509 >
510 > class driver_window : public driver_base {
511 >        friend void update_display_window_vosf(driver_window *drv);
512 >        friend void update_display_dynamic(int ticker, driver_window *drv);
513 >        friend void update_display_static(driver_window *drv);
514 >
515 > public:
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
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
536 >
537 > #ifdef ENABLE_VOSF
538 > # include "video_vosf.h"
539 > #endif
540 >
541 > driver_base::driver_base(X11_monitor_desc &m)
542 > : monitor(m), mode(m.get_current_mode()), init_ok(false), w(0)
543   {
544 <        // Set absolute mouse mode
545 <        ADBSetRelMouseMode(false);
544 >        the_buffer = NULL;
545 >        the_buffer_copy = NULL;
546 >        XGetPointerControl(x_display, &orig_accel_numer, &orig_accel_denom, &orig_threshold);
547 > }
548  
549 <        // Read frame skip prefs
550 <        frame_skip = PrefsFindInt32("frameskip");
551 <        if (frame_skip == 0)
552 <                frame_skip = 1;
549 > driver_base::~driver_base()
550 > {
551 >        ungrab_mouse();
552 >        restore_mouse_accel();
553  
554 <        // Create window
555 <        XSetWindowAttributes wattr;
556 <        wattr.event_mask = eventmask = win_eventmask;
557 <        wattr.background_pixel = black_pixel;
558 <        wattr.border_pixel = black_pixel;
219 <        wattr.backing_store = Always;
220 <        wattr.backing_planes = xdepth;
554 >        if (w) {
555 >                XUnmapWindow(x_display, w);
556 >                wait_unmapped(w);
557 >                XDestroyWindow(x_display, w);
558 >        }
559  
560 <        XSync(x_display, false);
223 <        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
224 <                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
225 <                CWBackingStore | CWBackingPlanes, &wattr);
226 <        XSync(x_display, false);
227 <        XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
228 <        XMapRaised(x_display, the_win);
560 >        XFlush(x_display);
561          XSync(x_display, false);
562  
563 <        // Set colormap
564 <        if (depth == 8) {
565 <                XSetWindowColormap(x_display, the_win, cmap[0]);
566 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
563 >        // Free frame buffer(s)
564 >        if (!use_vosf) {
565 >                if (the_buffer) {
566 >                        free(the_buffer);
567 >                        the_buffer = NULL;
568 >                }
569 >                if (the_buffer_copy) {
570 >                        free(the_buffer_copy);
571 >                        the_buffer_copy = NULL;
572 >                }
573          }
574 + #ifdef ENABLE_VOSF
575 +        else {
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_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 +        }
593 + #endif
594 + }
595  
596 <        // Make window unresizable
597 <        XSizeHints *hints;
598 <        if ((hints = XAllocSizeHints()) != NULL) {
599 <                hints->min_width = width;
600 <                hints->max_width = width;
601 <                hints->min_height = height;
602 <                hints->max_height = height;
603 <                hints->flags = PMinSize | PMaxSize;
604 <                XSetWMNormalHints(x_display, the_win, hints);
246 <                XFree((char *)hints);
596 > // Palette has changed
597 > void driver_base::update_palette(void)
598 > {
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], x_palette, num);
604 >                XStoreColors(x_display, cmap[1], x_palette, num);
605          }
606 <        
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(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(mouse_grabbed);
636 >
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 = (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 | CWBorderPixel | CWColormap, &wattr);
647 >        D(bug(" window created\n"));
648 >
649 >        // Set window name/class
650 >        set_window_name(w, STR_WINDOW_TITLE);
651 >
652 >        // Indicate that we want keyboard input
653 >        set_window_focus(w);
654 >
655 >        // Set delete protocol property
656 >        set_window_delete_protocol(w);
657 >
658 >        // Make window unresizable
659 >        {
660 >                XSizeHints *hints = XAllocSizeHints();
661 >                if (hints) {
662 >                        hints->min_width = width;
663 >                        hints->max_width = width;
664 >                        hints->min_height = height;
665 >                        hints->max_height = height;
666 >                        hints->flags = PMinSize | PMaxSize;
667 >                        XSetWMNormalHints(x_display, w, hints);
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
680 >        bool need_msb_image = (mode.depth == VDEPTH_1BIT && XImageByteOrder(x_display) == LSBFirst);
681 >
682          // Try to create and attach SHM image
683 <        have_shm = false;
251 <        if (depth != 1 && XShmQueryExtension(x_display)) {
683 >        if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
684  
685                  // Create SHM image ("height + 2" for safety)
686 <                img = XShmCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
687 <                shminfo.shmid = shmget(IPC_PRIVATE, (height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
688 <                the_buffer = (uint8 *)shmat(shminfo.shmid, 0, 0);
689 <                shminfo.shmaddr = img->data = (char *)the_buffer;
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;
691                  shminfo.readOnly = False;
692  
693                  // Try to attach SHM image, catching errors
# Line 266 | Line 699 | static bool init_window(int width, int h
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)
712          if (!have_shm) {
713 <                int bytes_per_row = width;
714 <                switch (depth) {
715 <                        case 1:
716 <                                bytes_per_row /= 8;
282 <                                break;
283 <                        case 15:
284 <                        case 16:
285 <                                bytes_per_row *= 2;
286 <                                break;
287 <                        case 24:
288 <                        case 32:
289 <                                bytes_per_row *= 4;
290 <                                break;
291 <                }
292 <                the_buffer = (uint8 *)malloc((height + 2) * bytes_per_row);
293 <                img = XCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer, width, height, 32, bytes_per_row);
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 <        // 1-Bit mode is big-endian
297 <        if (depth == 1) {
719 >        if (need_msb_image) {
720                  img->byte_order = MSBFirst;
721                  img->bitmap_bit_order = MSBFirst;
722          }
723  
724 <        // Allocate memory for frame buffer copy
725 <        the_buffer_copy = (uint8 *)malloc((height + 2) * img->bytes_per_line);
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);
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
739 <        the_gc = XCreateGC(x_display, the_win, 0, 0);
740 <        XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
739 >        gc = XCreateGC(x_display, w, 0, 0);
740 >        XSetState(x_display, gc, black_pixel, white_pixel, GXcopy, AllPlanes);
741  
742 <        // Create cursor
743 <        cursor_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)the_cursor, 16, 16, 16, 2);
744 <        cursor_image->byte_order = MSBFirst;
745 <        cursor_image->bitmap_bit_order = MSBFirst;
746 <        cursor_mask_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)the_cursor+32, 16, 16, 16, 2);
747 <        cursor_mask_image->byte_order = MSBFirst;
315 <        cursor_mask_image->bitmap_bit_order = MSBFirst;
316 <        cursor_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
317 <        cursor_mask_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
318 <        cursor_gc = XCreateGC(x_display, cursor_map, 0, 0);
319 <        cursor_mask_gc = XCreateGC(x_display, cursor_mask_map, 0, 0);
320 <        mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, 0, 0);
742 >        // Create no_cursor
743 >        mac_cursor = XCreatePixmapCursor(x_display,
744 >           XCreatePixmap(x_display, w, 1, 1, 1),
745 >           XCreatePixmap(x_display, w, 1, 1, 1),
746 >           &black, &white, 0, 0);
747 >        XDefineCursor(x_display, w, mac_cursor);
748  
749 <        // Set VideoMonitor
749 >        // Init blitting routines
750 >        bool native_byte_order;
751   #ifdef WORDS_BIGENDIAN
752 <        set_video_monitor(width, height, img->bytes_per_line, img->bitmap_bit_order == MSBFirst);
752 >        native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
753   #else
754 <        set_video_monitor(width, height, img->bytes_per_line, img->bitmap_bit_order == LSBFirst);
754 >        native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
755   #endif
756 <        
757 < #if REAL_ADDRESSING
758 <        VideoMonitor.mac_frame_base = (uint32)the_buffer;
759 <        MacFrameLayout = FLAYOUT_DIRECT;
756 > #ifdef ENABLE_VOSF
757 >        Screen_blitter_init(&visualInfo, native_byte_order, depth_of_video_mode(mode));
758 > #endif
759 >
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;
765 > }
766 >
767 > // Close display
768 > driver_window::~driver_window()
769 > {
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 <        VideoMonitor.mac_frame_base = MacFrameBaseMac;
775 >                the_buffer_copy = NULL; // don't free() in driver_base dtor
776   #endif
777 <        return true;
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 > /*
873 > *  DGA display driver base class
874 > */
875 >
876 > class driver_dga : public driver_base {
877 > public:
878 >        driver_dga(X11_monitor_desc &monitor);
879 >        ~driver_dga();
880 >
881 >        void suspend(void);
882 >        void resume(void);
883 >
884 > private:
885 >        Window suspend_win;             // "Suspend" information window
886 >        void *fb_save;                  // Saved frame buffer for suspend/resume
887 > };
888 >
889 > driver_dga::driver_dga(X11_monitor_desc &m)
890 > : driver_base(m), suspend_win(0), fb_save(NULL)
891 > {
892 > }
893 >
894 > driver_dga::~driver_dga()
895 > {
896 >        XUngrabPointer(x_display, CurrentTime);
897 >        XUngrabKeyboard(x_display, CurrentTime);
898 > }
899 >
900 > // Suspend emulation
901 > void driver_dga::suspend(void)
902 > {
903 >        // Release ctrl key
904 >        ADBKeyUp(0x36);
905 >        ctrl_down = false;
906 >
907 >        // Lock frame buffer (this will stop the MacOS thread)
908 >        LOCK_FRAME_BUFFER;
909 >
910 >        // Save frame buffer
911 >        fb_save = malloc(mode.y * mode.bytes_per_row);
912 >        if (fb_save)
913 >                memcpy(fb_save, the_buffer, mode.y * mode.bytes_per_row);
914 >
915 >        // Close full screen display
916 > #ifdef ENABLE_XF86_DGA
917 >        XF86DGADirectVideo(x_display, screen, 0);
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 >
925 >        // Open "suspend" window
926 >        XSetWindowAttributes wattr;
927 >        wattr.event_mask = KeyPressMask;
928 >        wattr.background_pixel = black_pixel;
929 >                
930 >        suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
931 >                InputOutput, vis, CWEventMask | CWBackPixel, &wattr);
932 >        set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
933 >        set_window_focus(suspend_win);
934 >        XMapWindow(x_display, suspend_win);
935 >        emul_suspended = true;
936 > }
937 >
938 > // Resume emulation
939 > void driver_dga::resume(void)
940 > {
941 >        // Close "suspend" window
942 >        XDestroyWindow(x_display, suspend_win);
943 >        XSync(x_display, false);
944 >
945 >        // Reopen full screen display
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, 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);
955 > #endif
956 >        XSync(x_display, false);
957 >        
958 >        // the_buffer already contains the data to restore. i.e. since a temporary
959 >        // frame buffer is used when VOSF is actually used, fb_save is therefore
960 >        // not necessary.
961 > #ifdef ENABLE_VOSF
962 >        if (use_vosf) {
963 >                LOCK_VOSF;
964 >                PFLAG_SET_ALL;
965 >                UNLOCK_VOSF;
966 >                memset(the_buffer_copy, 0, mode.bytes_per_row * mode.y);
967 >        }
968 > #endif
969 >        
970 >        // Restore frame buffer
971 >        if (fb_save) {
972 > #ifdef ENABLE_VOSF
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, mode.y * mode.bytes_per_row);
977 >                free(fb_save);
978 >                fb_save = NULL;
979 >        }
980 >        
981 >        // Unlock frame buffer (and continue MacOS thread)
982 >        UNLOCK_FRAME_BUFFER;
983 >        emul_suspended = false;
984   }
985 + #endif
986 +
987  
988 < // Init fbdev DGA display
989 < static bool init_fbdev_dga(char *in_fb_name)
988 > #ifdef ENABLE_FBDEV_DGA
989 > /*
990 > *  fbdev DGA display driver
991 > */
992 >
993 > const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
994 > const char FBDEVICE_FILE_NAME[] = "/dev/fb";
995 >
996 > class driver_fbdev : public driver_dga {
997 > public:
998 >        driver_fbdev(X11_monitor_desc &monitor);
999 >        ~driver_fbdev();
1000 > };
1001 >
1002 > // Open display
1003 > driver_fbdev::driver_fbdev(X11_monitor_desc &m) : driver_dga(m)
1004   {
1005 < #if ENABLE_FBDEV_DGA
1005 >        int width = mode.x, height = mode.y;
1006 >
1007 >        // Set absolute mouse mode
1008 >        ADBSetRelMouseMode(false);
1009 >        
1010          // Find the maximum depth available
1011          int ndepths, max_depth(0);
1012          int *depths = XListDepths(x_display, screen, &ndepths);
1013          if (depths == NULL) {
1014                  printf("FATAL: Could not determine the maximal depth available\n");
1015 <                return false;
1015 >                return;
1016          } else {
1017                  while (ndepths-- > 0) {
1018                          if (depths[ndepths] > max_depth)
# Line 361 | Line 1029 | static bool init_fbdev_dga(char *in_fb_n
1029                  char str[256];
1030                  sprintf(str, GetString(STR_NO_FBDEVICE_FILE_ERR), fbd_path ? fbd_path : FBDEVICES_FILE_NAME, strerror(errno));
1031                  ErrorAlert(str);
1032 <                return false;
1032 >                return;
1033          }
1034          
1035          int fb_depth;           // supported depth
# Line 380 | Line 1048 | static bool init_fbdev_dga(char *in_fb_n
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)
1052 <                && (strcmp(fb_name, in_fb_name) == 0) && (fb_depth == max_depth)) {
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;
1055                  }
# Line 393 | Line 1061 | static bool init_fbdev_dga(char *in_fb_n
1061          // Frame buffer name not found ? Then, display warning
1062          if (!device_found) {
1063                  char str[256];
1064 <                sprintf(str, GetString(STR_FBDEV_NAME_ERR), in_fb_name, max_depth);
1064 >                sprintf(str, GetString(STR_FBDEV_NAME_ERR), fb_name, max_depth);
1065                  ErrorAlert(str);
1066 <                return false;
1066 >                return;
1067          }
1068          
401        int width = DisplayWidth(x_display, screen);
402        int height = DisplayHeight(x_display, screen);
403        depth = fb_depth; // max_depth
404        
405        // Set relative mouse mode
406        ADBSetRelMouseMode(false);
407        
1069          // Create window
1070          XSetWindowAttributes wattr;
1071 <        wattr.override_redirect = True;
1072 <        wattr.backing_store             = NotUseful;
1073 <        wattr.background_pixel  = white_pixel;
1074 <        wattr.border_pixel              = black_pixel;
414 <        wattr.event_mask                = eventmask = dga_eventmask;
1071 >        wattr.event_mask = eventmask = dga_eventmask;
1072 >        wattr.background_pixel = white_pixel;
1073 >        wattr.override_redirect = True;
1074 >        wattr.colormap = cmap[0];
1075          
1076 <        XSync(x_display, false);
417 <        the_win = XCreateWindow(x_display, rootwin,
1076 >        w = XCreateWindow(x_display, rootwin,
1077                  0, 0, width, height,
1078                  0, xdepth, InputOutput, vis,
1079 <                CWEventMask|CWBackPixel|CWBorderPixel|CWOverrideRedirect|CWBackingStore,
1079 >                CWEventMask | CWBackPixel | CWOverrideRedirect | (fb_depth <= 8 ? CWColormap : 0),
1080                  &wattr);
1081 <        XSync(x_display, false);
1082 <        XMapRaised(x_display, the_win);
1083 <        XSync(x_display, false);
1081 >
1082 >        // Set window name/class
1083 >        set_window_name(w, STR_WINDOW_TITLE);
1084 >
1085 >        // Indicate that we want keyboard input
1086 >        set_window_focus(w);
1087 >
1088 >        // Show window
1089 >        XMapRaised(x_display, w);
1090 >        wait_mapped(w);
1091          
1092          // Grab mouse and keyboard
1093 <        XGrabKeyboard(x_display, the_win, True,
1093 >        XGrabKeyboard(x_display, w, True,
1094                  GrabModeAsync, GrabModeAsync, CurrentTime);
1095 <        XGrabPointer(x_display, the_win, True,
1095 >        XGrabPointer(x_display, w, True,
1096                  PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
1097 <                GrabModeAsync, GrabModeAsync, the_win, None, CurrentTime);
1097 >                GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
1098 >        disable_mouse_accel();
1099          
1100 <        // Set colormap
1101 <        if (depth == 8) {
435 <                XSetWindowColormap(x_display, the_win, cmap[0]);
436 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
437 <        }
1100 >        // Calculate bytes per row
1101 >        int bytes_per_row = TrivialBytesPerRow(mode.x, mode.depth);
1102          
1103 <        // Set VideoMonitor
1104 <        int bytes_per_row = width;
1105 <        switch (depth) {
1106 <                case 1:
443 <                        bytes_per_row = ((width | 7) & ~7) >> 3;
444 <                        break;
445 <                case 15:
446 <                case 16:
447 <                        bytes_per_row *= 2;
448 <                        break;
449 <                case 24:
450 <                case 32:
451 <                        bytes_per_row *= 4;
452 <                        break;
453 <        }
454 <        
455 <        if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
456 <                if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
1103 >        // Map frame buffer
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);
1110 <                        return false;
1110 >                        return;
1111                  }
1112          }
1113          
1114 <        set_video_monitor(width, height, bytes_per_row, true);
1115 < #if REAL_ADDRESSING
1116 <        VideoMonitor.mac_frame_base = (uint32)the_buffer;
1117 <        MacFrameLayout = FLAYOUT_DIRECT;
1114 > #if ENABLE_VOSF
1115 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
1116 >        // Screen_blitter_init() returns TRUE if VOSF is mandatory
1117 >        // i.e. the framebuffer update function is not Blit_Copy_Raw
1118 >        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
1119 >        
1120 >        if (use_vosf) {
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 *)malloc(the_buffer_size);
1125 >          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
1126 >        }
1127   #else
1128 <        VideoMonitor.mac_frame_base = MacFrameBaseMac;
1128 >        use_vosf = false;
1129   #endif
1130 <        return true;
1131 < #else
1132 <        ErrorAlert("Basilisk II has been compiled with fbdev DGA support disabled.");
1133 <        return false;
1130 > #endif
1131 >        
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;
1139 > }
1140 >
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 +
1163 +
1164 + #ifdef ENABLE_XF86_DGA
1165 + /*
1166 + *  XFree86 DGA display driver
1167 + */
1168  
1169 < // Init XF86 DGA display
1170 < static bool init_xf86_dga(int width, int height)
1169 > class driver_xf86dga : public driver_dga {
1170 > public:
1171 >        driver_xf86dga(X11_monitor_desc &monitor);
1172 >        ~driver_xf86dga();
1173 >
1174 >        void update_palette(void);
1175 >        void resume(void);
1176 >
1177 > private:
1178 >        int current_dga_cmap;                                   // Number (0 or 1) of currently installed DGA colormap
1179 > };
1180 >
1181 > // Open display
1182 > driver_xf86dga::driver_xf86dga(X11_monitor_desc &m)
1183 > : driver_dga(m), current_dga_cmap(0)
1184   {
1185 < #if ENABLE_XF86_DGA
1185 >        int width = mode.x, height = mode.y;
1186 >
1187          // Set relative mouse mode
1188          ADBSetRelMouseMode(true);
1189  
1190 + #ifdef ENABLE_XF86_VIDMODE
1191 +        // Switch to best mode
1192 +        if (has_vidmode) {
1193 +                int best = 0;
1194 +                for (int i=1; i<num_x_video_modes; i++) {
1195 +                        if (x_video_modes[i]->hdisplay >= width && x_video_modes[i]->vdisplay >= height &&
1196 +                                x_video_modes[i]->hdisplay <= x_video_modes[best]->hdisplay && x_video_modes[i]->vdisplay <= x_video_modes[best]->vdisplay) {
1197 +                                best = i;
1198 +                        }
1199 +                }
1200 +                XF86VidModeSwitchToMode(x_display, screen, x_video_modes[best]);
1201 +                XF86VidModeSetViewPort(x_display, screen, 0, 0);
1202 +                XSync(x_display, false);
1203 +        }
1204 + #endif
1205 +
1206          // Create window
1207          XSetWindowAttributes wattr;
1208          wattr.event_mask = eventmask = dga_eventmask;
488        wattr.border_pixel = black_pixel;
1209          wattr.override_redirect = True;
1210 +        wattr.colormap = (mode.depth == VDEPTH_1BIT ? DefaultColormap(x_display, screen) : cmap[0]);
1211  
1212 <        XSync(x_display, false);
1213 <        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
1214 <                InputOutput, vis, CWEventMask | CWBorderPixel | CWOverrideRedirect, &wattr);
1215 <        XSync(x_display, false);
1216 <        XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
1217 <        XMapRaised(x_display, the_win);
1218 <        XSync(x_display, false);
1212 >        w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
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);
1218 >
1219 >        // Indicate that we want keyboard input
1220 >        set_window_focus(w);
1221 >
1222 >        // Show window
1223 >        XMapRaised(x_display, w);
1224 >        wait_mapped(w);
1225  
1226          // Establish direct screen connection
1227 <        XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
1227 >        XMoveResizeWindow(x_display, w, 0, 0, width, height);
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 509 | Line 1237 | static bool init_xf86_dga(int width, int
1237          XF86DGASetVidPage(x_display, screen, 0);
1238  
1239          // Set colormap
1240 <        if (depth == 8) {
1241 <                XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
514 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
1240 >        if (!IsDirectMode(mode)) {
1241 >                XSetWindowColormap(x_display, w, cmap[current_dga_cmap = 0]);
1242                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1243          }
1244 +        XSync(x_display, false);
1245  
1246 <        // Set VideoMonitor
1247 <        int bytes_per_row = (v_width + 7) & ~7;
1248 <        switch (depth) {
1249 <                case 1:
1250 <                        bytes_per_row /= 8;
1251 <                        break;
524 <                case 15:
525 <                case 16:
526 <                        bytes_per_row *= 2;
527 <                        break;
528 <                case 24:
529 <                case 32:
530 <                        bytes_per_row *= 4;
531 <                        break;
532 <        }
533 <        set_video_monitor(width, height, bytes_per_row, true);
534 < #if REAL_ADDRESSING
535 <        VideoMonitor.mac_frame_base = (uint32)the_buffer;
536 <        MacFrameLayout = FLAYOUT_DIRECT;
1246 >        // Init blitting routines
1247 >        int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, mode.depth);
1248 > #if ENABLE_VOSF
1249 >        bool native_byte_order;
1250 > #ifdef WORDS_BIGENDIAN
1251 >        native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
1252   #else
1253 <        VideoMonitor.mac_frame_base = MacFrameBaseMac;
1253 >        native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
1254   #endif
1255 <        return true;
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, 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 *)malloc(the_buffer_size);
1265 >          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
1266 >        }
1267   #else
1268 <        ErrorAlert("Basilisk II has been compiled with XF86 DGA support disabled.");
1269 <        return false;
1268 >        use_vosf = false;
1269 > #endif
1270   #endif
1271 +        
1272 +        // Set frame buffer base
1273 +        const_cast<video_mode *>(&mode)->bytes_per_row = bytes_per_row;
1274 +        set_mac_frame_buffer(monitor, mode.depth, true);
1275 +
1276 +        // Everything went well
1277 +        init_ok = true;
1278   }
1279  
1280 + // Close display
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]);
1297 + #endif
1298 + }
1299 +
1300 + // Palette has changed
1301 + void driver_xf86dga::update_palette(void)
1302 + {
1303 +        driver_dga::update_palette();
1304 +        current_dga_cmap ^= 1;
1305 +        if (!IsDirectMode(monitor.get_current_mode()) && cmap[current_dga_cmap])
1306 +                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1307 + }
1308 +
1309 + // Resume emulation
1310 + void driver_xf86dga::resume(void)
1311 + {
1312 +        driver_dga::resume();
1313 +        if (!IsDirectMode(monitor.get_current_mode()))
1314 +                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1315 + }
1316 + #endif
1317 +
1318 +
1319 + /*
1320 + *  Initialization
1321 + */
1322 +
1323   // Init keycode translation table
1324   static void keycode_init(void)
1325   {
# Line 609 | Line 1385 | static void keycode_init(void)
1385          }
1386   }
1387  
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 = (color_class == DirectColor ? vis->map_entries : 256);
1445 +        for (int i=0; i<num; i++) {
1446 +                int c = (i * 256) / 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) && xdepth > 8)
1459 +                for (int i=0; i<256; i++)
1460 +                        ExpandMap[i] = map_rgb(i, i, i);
1461 + #endif
1462 +
1463 +        // Create display driver object of requested type
1464 +        switch (display_type) {
1465 +                case DISPLAY_WINDOW:
1466 +                        drv = new driver_window(*this);
1467 +                        break;
1468 + #ifdef ENABLE_FBDEV_DGA
1469 +                case DISPLAY_DGA:
1470 +                        drv = new driver_fbdev(*this);
1471 +                        break;
1472 + #endif
1473 + #ifdef ENABLE_XF86_DGA
1474 +                case DISPLAY_DGA:
1475 +                        drv = new driver_xf86dga(*this);
1476 +                        break;
1477 + #endif
1478 +        }
1479 +        if (drv == NULL)
1480 +                return false;
1481 +        if (!drv->init_ok) {
1482 +                delete drv;
1483 +                drv = NULL;
1484 +                return false;
1485 +        }
1486 +
1487 + #ifdef ENABLE_VOSF
1488 +        if (use_vosf) {
1489 +                // Initialize the VOSF system
1490 +                if (!video_vosf_init(*this)) {
1491 +                        ErrorAlert(STR_VOSF_INIT_ERR);
1492 +                return false;
1493 +                }
1494 +        }
1495 + #endif
1496 +        
1497 +        // Initialize VideoRefresh function
1498 +        VideoRefreshInit();
1499 +
1500 +        // Lock down frame buffer
1501 +        XSync(x_display, false);
1502 +        LOCK_FRAME_BUFFER;
1503 +
1504 +        // Start redraw/input thread
1505 + #ifdef HAVE_PTHREADS
1506 +        redraw_thread_cancel = false;
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;
1512 +        }
1513 + #else
1514 +        redraw_thread_active = true;
1515 + #endif
1516 +
1517 +        return true;
1518 + }
1519 +
1520   bool VideoInit(bool classic)
1521   {
1522 +        classic_mode = classic;
1523 +
1524 + #ifdef ENABLE_VOSF
1525 +        // Zero the mainBuffer structure
1526 +        mainBuffer.dirtyPages = NULL;
1527 +        mainBuffer.pageInfo = NULL;
1528 + #endif
1529 +        
1530 +        // Check if X server runs on local machine
1531 +        local_X11 = (strncmp(XDisplayName(x_display_name), ":", 1) == 0)
1532 +                 || (strncmp(XDisplayName(x_display_name), "unix:", 5) == 0);
1533 +    
1534          // Init keycode translation
1535          keycode_init();
1536  
1537          // Read prefs
1538 <        mouse_wheel_mode = PrefsFindInt16("mousewheelmode");
1539 <        mouse_wheel_lines = PrefsFindInt16("mousewheellines");
1538 >        frame_skip = PrefsFindInt32("frameskip");
1539 >        mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1540 >        mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1541  
1542          // Find screen and root window
1543          screen = XDefaultScreen(x_display);
1544          rootwin = XRootWindow(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 <        // Get screen depth
626 <        xdepth = DefaultDepth(x_display, screen);
627 <        
628 < #if ENABLE_FBDEV_DGA
1554 > #ifdef ENABLE_FBDEV_DGA
1555          // Frame buffer name
1556          char fb_name[20];
1557          
1558 <        // Could do fbdev dga ?
1558 >        // Could do fbdev DGA?
1559          if ((fbdev_fd = open(FBDEVICE_FILE_NAME, O_RDWR)) != -1)
1560                  has_dga = true;
1561          else
1562                  has_dga = false;
1563   #endif
1564 <        
1565 < #if ENABLE_XF86_DGA
1564 >
1565 > #ifdef ENABLE_XF86_DGA
1566          // DGA available?
1567 <        int event_base, error_base;
1568 <        if (XF86DGAQueryExtension(x_display, &event_base, &error_base)) {
1567 >        int dga_event_base, dga_error_base;
1568 >        if (local_X11 && XF86DGAQueryExtension(x_display, &dga_event_base, &dga_error_base)) {
1569                  int dga_flags = 0;
1570                  XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
1571                  has_dga = dga_flags & XF86DGADirectPresent;
# Line 647 | Line 1573 | bool VideoInit(bool classic)
1573                  has_dga = false;
1574   #endif
1575  
1576 + #ifdef ENABLE_XF86_VIDMODE
1577 +        // VidMode available?
1578 +        int vm_event_base, vm_error_base;
1579 +        has_vidmode = XF86VidModeQueryExtension(x_display, &vm_event_base, &vm_error_base);
1580 +        if (has_vidmode)
1581 +                XF86VidModeGetAllModeLines(x_display, screen, &num_x_video_modes, &x_video_modes);
1582 + #endif
1583 +        
1584          // Find black and white colors
1585          XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:00/00/00", &black);
1586          XAllocColor(x_display, DefaultColormap(x_display, screen), &black);
# Line 655 | Line 1589 | bool VideoInit(bool classic)
1589          black_pixel = BlackPixel(x_display, screen);
1590          white_pixel = WhitePixel(x_display, screen);
1591  
658        // Get appropriate visual
659        int color_class;
660        switch (xdepth) {
661                case 1:
662                        color_class = StaticGray;
663                        break;
664                case 8:
665                        color_class = PseudoColor;
666                        break;
667                case 15:
668                case 16:
669                case 24:
670                case 32:
671                        color_class = TrueColor;
672                        break;
673                default:
674                        ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
675                        return false;
676        }
677        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
678                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
679                return false;
680        }
681        if (visualInfo.depth != xdepth) {
682                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
683                return false;
684        }
685        vis = visualInfo.visual;
686
687        // Mac screen depth is always 1 bit in Classic mode, but follows X depth otherwise
688        classic_mode = classic;
689        if (classic)
690                depth = 1;
691        else
692                depth = xdepth;
693
694        // Create color maps for 8 bit mode
695        if (depth == 8) {
696                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
697                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
698                XInstallColormap(x_display, cmap[0]);
699                XInstallColormap(x_display, cmap[1]);
700        }
701
1592          // Get screen mode from preferences
1593          const char *mode_str;
1594 <        if (classic)
1594 >        if (classic_mode)
1595                  mode_str = "win/512/342";
1596          else
1597                  mode_str = PrefsFindString("screen");
1598  
1599 <        // Determine type and mode
1600 <        int width = 512, height = 384;
1599 >        // Determine display type and default dimensions
1600 >        int default_width = 512, default_height = 384;
1601          display_type = DISPLAY_WINDOW;
1602          if (mode_str) {
1603 <                if (sscanf(mode_str, "win/%d/%d", &width, &height) == 2)
1603 >                if (sscanf(mode_str, "win/%d/%d", &default_width, &default_height) == 2) {
1604                          display_type = DISPLAY_WINDOW;
1605 < #if ENABLE_FBDEV_DGA
1606 <                else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) {
1607 < #else
1608 <                else if (has_dga && sscanf(mode_str, "dga/%d/%d", &width, &height) == 2) {
1605 > #ifdef ENABLE_FBDEV_DGA
1606 >                } else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) {
1607 >                        display_type = DISPLAY_DGA;
1608 >                        default_width = -1; default_height = -1; // use entire screen
1609   #endif
1610 + #ifdef ENABLE_XF86_DGA
1611 +                } else if (has_dga && sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2) {
1612                          display_type = DISPLAY_DGA;
1613 <                        if (width > DisplayWidth(x_display, screen))
1614 <                                width = DisplayWidth(x_display, screen);
723 <                        if (height > DisplayHeight(x_display, screen))
724 <                                height = DisplayHeight(x_display, screen);
725 <                }
726 <                if (width <= 0)
727 <                        width = DisplayWidth(x_display, screen);
728 <                if (height <= 0)
729 <                        height = DisplayHeight(x_display, screen);
1613 > #endif
1614 >                }
1615          }
1616 <
1617 <        // Initialize according to display type
1618 <        switch (display_type) {
1619 <                case DISPLAY_WINDOW:
1620 <                        if (!init_window(width, height))
1621 <                                return false;
1616 >        if (default_width <= 0)
1617 >                default_width = DisplayWidth(x_display, screen);
1618 >        else if (default_width > DisplayWidth(x_display, screen))
1619 >                default_width = DisplayWidth(x_display, screen);
1620 >        if (default_height <= 0)
1621 >                default_height = DisplayHeight(x_display, screen);
1622 >        else if (default_height > DisplayHeight(x_display, screen))
1623 >                default_height = DisplayHeight(x_display, screen);
1624 >
1625 >        // Mac screen depth follows X depth
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 DISPLAY_DGA:
1632 < #if ENABLE_FBDEV_DGA
1633 <                        if (!init_fbdev_dga(fb_name))
1634 < #else
1635 <                        if (!init_xf86_dga(width, height))
743 < #endif
744 <                                return false;
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 <        // Lock down frame buffer
1640 <        pthread_mutex_lock(&frame_buffer_lock);
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 >                        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 >                        }
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 < #if !REAL_ADDRESSING
1657 <        // Set variables for UAE memory mapping
1658 <        MacFrameBaseHost = the_buffer;
1659 <        MacFrameSize = VideoMonitor.bytes_per_row * VideoMonitor.y;
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 >                }
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 <        // No special frame buffer in Classic mode (frame buffer is in Mac RAM)
1671 <        if (classic)
1672 <                MacFrameLayout = FLAYOUT_NONE;
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 <        // Start redraw/input thread
1683 <        XSync(x_display, false);
1684 <        redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1685 <        if (!redraw_thread_active)
1686 <                printf("FATAL: cannot create redraw thread\n");
1687 <        return redraw_thread_active;
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 771 | Line 1692 | bool VideoInit(bool classic)
1692   *  Deinitialization
1693   */
1694  
1695 < void VideoExit(void)
1695 > // Close display
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) {
1703                  redraw_thread_cancel = true;
1704   #ifdef HAVE_PTHREAD_CANCEL
1705                  pthread_cancel(redraw_thread);
1706   #endif
1707                  pthread_join(redraw_thread, NULL);
783                redraw_thread_active = false;
1708          }
1709 + #endif
1710 +        redraw_thread_active = false;
1711  
1712          // Unlock frame buffer
1713 <        pthread_mutex_unlock(&frame_buffer_lock);
1713 >        UNLOCK_FRAME_BUFFER;
1714 >        XSync(x_display, false);
1715 >        D(bug(" frame buffer unlocked\n"));
1716  
1717 <        // Close window and server connection
1718 <        if (x_display != NULL) {
1719 <                XSync(x_display, false);
1717 > #ifdef ENABLE_VOSF
1718 >        if (use_vosf) {
1719 >                // Deinitialize VOSF
1720 >                video_vosf_exit();
1721 >        }
1722 > #endif
1723  
1724 < #if ENABLE_XF86_DGA
1725 <                if (display_type == DISPLAY_DGA) {
1726 <                        XF86DGADirectVideo(x_display, screen, 0);
1727 <                        XUngrabPointer(x_display, CurrentTime);
1728 <                        XUngrabKeyboard(x_display, CurrentTime);
1729 <                }
1724 >        // Close display
1725 >        delete drv;
1726 >        drv = NULL;
1727 >
1728 >        // Free colormaps
1729 >        if (cmap[0]) {
1730 >                XFreeColormap(x_display, cmap[0]);
1731 >                cmap[0] = 0;
1732 >        }
1733 >        if (cmap[1]) {
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
1748 >        if (x_video_modes) {
1749 >                XFree(x_video_modes);
1750 >                x_video_modes = NULL;
1751 >        }
1752   #endif
1753  
1754 < #if ENABLE_FBDEV_DGA
1755 <                if (display_type == DISPLAY_DGA) {
1756 <                        XUngrabPointer(x_display, CurrentTime);
1757 <                        XUngrabKeyboard(x_display, CurrentTime);
1758 <                        close(fbdev_fd);
1759 <                }
1754 > #ifdef ENABLE_FBDEV_DGA
1755 >        // Close framebuffer device
1756 >        if (fbdev_fd >= 0) {
1757 >                close(fbdev_fd);
1758 >                fbdev_fd = -1;
1759 >        }
1760   #endif
808                
809                if (the_buffer_copy) {
810                        free(the_buffer_copy);
811                        the_buffer_copy = NULL;
812                }
1761  
1762 <                XFlush(x_display);
1763 <                XSync(x_display, false);
1764 <                if (depth == 8) {
1765 <                        XFreeColormap(x_display, cmap[0]);
818 <                        XFreeColormap(x_display, cmap[1]);
819 <                }
1762 >        // Free depth list
1763 >        if (avail_depths) {
1764 >                XFree(avail_depths);
1765 >                avail_depths = NULL;
1766          }
1767   }
1768  
# Line 828 | Line 1774 | void VideoExit(void)
1774   void VideoQuitFullScreen(void)
1775   {
1776          D(bug("VideoQuitFullScreen()\n"));
1777 <        if (display_type == DISPLAY_DGA)
832 <                quit_full_screen = true;
1777 >        quit_full_screen = true;
1778   }
1779  
1780  
# Line 845 | Line 1790 | void VideoInterrupt(void)
1790  
1791          // Temporarily give up frame buffer lock (this is the point where
1792          // we are suspended when the user presses Ctrl-Tab)
1793 <        pthread_mutex_unlock(&frame_buffer_lock);
1794 <        pthread_mutex_lock(&frame_buffer_lock);
1793 >        UNLOCK_FRAME_BUFFER;
1794 >        LOCK_FRAME_BUFFER;
1795   }
1796  
1797  
# Line 854 | 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 <        pthread_mutex_lock(&palette_lock);
1804 >        const video_mode &mode = get_current_mode();
1805 >
1806 >        LOCK_PALETTE;
1807  
1808          // Convert colors to XColor array
1809 <        for (int i=0; i<256; i++) {
1810 <                palette[i].pixel = i;
1811 <                palette[i].red = pal[i*3] * 0x0101;
1812 <                palette[i].green = pal[i*3+1] * 0x0101;
1813 <                palette[i].blue = pal[i*3+2] * 0x0101;
1814 <                palette[i].flags = DoRed | DoGreen | DoBlue;
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 = x_palette;
1817 >        for (int i=0; i<num_out; i++) {
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;
1822 >                p++;
1823 >        }
1824 >
1825 > #ifdef ENABLE_VOSF
1826 >        // Recalculate pixel color expansion map
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, 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 <        pthread_mutex_unlock(&palette_lock);
1844 >        UNLOCK_PALETTE;
1845   }
1846  
1847  
1848   /*
1849 < *  Suspend/resume emulator
1849 > *  Switch video mode
1850   */
1851  
1852 < #if ENABLE_XF86_DGA || ENABLE_FBDEV_DGA
882 < static void suspend_emul(void)
1852 > void X11_monitor_desc::switch_to_current_mode(void)
1853   {
1854 <        if (display_type == DISPLAY_DGA) {
1855 <                // Release ctrl key
1856 <                ADBKeyUp(0x36);
887 <                ctrl_down = false;
888 <
889 <                // Lock frame buffer (this will stop the MacOS thread)
890 <                pthread_mutex_lock(&frame_buffer_lock);
891 <
892 <                // Save frame buffer
893 <                fb_save = malloc(VideoMonitor.y * VideoMonitor.bytes_per_row);
894 <                if (fb_save)
895 <                        memcpy(fb_save, the_buffer, VideoMonitor.y * VideoMonitor.bytes_per_row);
896 <
897 <                // Close full screen display
898 < #if ENABLE_XF86_DGA
899 <                XF86DGADirectVideo(x_display, screen, 0);
900 < #endif
901 <                XUngrabPointer(x_display, CurrentTime);
902 <                XUngrabKeyboard(x_display, CurrentTime);
903 <                XUnmapWindow(x_display, the_win);
904 <                XSync(x_display, false);
1854 >        // Close and reopen display
1855 >        video_close();
1856 >        video_open();
1857  
1858 <                // Open "suspend" window
1859 <                XSetWindowAttributes wattr;
1860 <                wattr.event_mask = KeyPressMask;
909 <                wattr.background_pixel = black_pixel;
910 <                wattr.border_pixel = black_pixel;
911 <                wattr.backing_store = Always;
912 <                wattr.backing_planes = xdepth;
913 <                wattr.colormap = DefaultColormap(x_display, screen);
914 <                
915 <                XSync(x_display, false);
916 <                suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
917 <                        InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
918 <                        CWBackingStore | CWBackingPlanes | (xdepth == 8 ? CWColormap : 0), &wattr);
919 <                XSync(x_display, false);
920 <                XStoreName(x_display, suspend_win, GetString(STR_SUSPEND_WINDOW_TITLE));
921 <                XMapRaised(x_display, suspend_win);
922 <                XSync(x_display, false);
923 <                emul_suspended = true;
1858 >        if (drv == NULL) {
1859 >                ErrorAlert(STR_OPEN_WINDOW_ERR);
1860 >                QuitEmulator();
1861          }
1862   }
1863  
927 static void resume_emul(void)
928 {
929        // Close "suspend" window
930        XDestroyWindow(x_display, suspend_win);
931        XSync(x_display, false);
932
933        // Reopen full screen display
934        XMapRaised(x_display, the_win);
935        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
936        XSync(x_display, false);
937        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
938        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
939 #if ENABLE_XF86_DGA
940        XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
941        XF86DGASetViewPort(x_display, screen, 0, 0);
942 #endif
943        XSync(x_display, false);
944
945        // Restore frame buffer
946        if (fb_save) {
947                memcpy(the_buffer, fb_save, VideoMonitor.y * VideoMonitor.bytes_per_row);
948                free(fb_save);
949                fb_save = NULL;
950        }
951        
952        if (depth == 8)
953 #if ENABLE_XF86_DGA
954                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
955 #endif
956
957        // Unlock frame buffer (and continue MacOS thread)
958        pthread_mutex_unlock(&frame_buffer_lock);
959        emul_suspended = false;
960 }
961 #endif
962
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 1018 | 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 ENABLE_XF86_DGA || ENABLE_FBDEV_DGA
1022 <                case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30;
1023 < #else
1024 <                case XK_Tab: return 0x30;
1025 < #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 1056 | 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 1110 | 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;
1116        int as;
2014          int i = 0;
2015  
2016          do {
2017 <                ks = XLookupKeysym(ev, i++);
2018 <                as = kc_decode(ks);
2019 <                if (as != -1)
2017 >                ks = XLookupKeysym(&ev, i++);
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 1133 | Line 2032 | static int event2keycode(XKeyEvent *ev)
2032  
2033   static void handle_events(void)
2034   {
2035 <        XEvent event;
2036 <        for (;;) {
2037 <                if (!XCheckMaskEvent(x_display, eventmask, &event))
1139 <                        break;
2035 >        while (XPending(x_display)) {
2036 >                XEvent event;
2037 >                XNextEvent(x_display, &event);
2038  
2039                  switch (event.type) {
2040 +
2041                          // Mouse button
2042                          case ButtonPress: {
2043 <                                unsigned int button = ((XButtonEvent *)&event)->button;
2043 >                                unsigned int button = event.xbutton.button;
2044                                  if (button < 4)
2045                                          ADBMouseDown(button - 1);
2046                                  else if (button < 6) {  // Wheel mouse
# Line 1160 | Line 2059 | static void handle_events(void)
2059                                  break;
2060                          }
2061                          case ButtonRelease: {
2062 <                                unsigned int button = ((XButtonEvent *)&event)->button;
2062 >                                unsigned int button = event.xbutton.button;
2063                                  if (button < 4)
2064                                          ADBMouseUp(button - 1);
2065                                  break;
2066                          }
2067  
2068                          // Mouse moved
1170                        case EnterNotify:
1171                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1172                                break;
2069                          case MotionNotify:
2070 <                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->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((XKeyEvent *)&event);     // This is called to process the hotkeys
2084 <                                        code = keycode_table[((XKeyEvent *)&event)->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((XKeyEvent *)&event);
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 1197 | Line 2099 | static void handle_events(void)
2099                                                  if (code == 0x36)
2100                                                          ctrl_down = true;
2101                                          } else {
1200 #if ENABLE_XF86_DGA || ENABLE_FBDEV_DGA
2102                                                  if (code == 0x31)
2103 <                                                        resume_emul();  // Space wakes us up
1203 < #endif
2103 >                                                        drv->resume();  // Space wakes us up
2104                                          }
2105                                  }
2106                                  break;
2107                          }
2108                          case KeyRelease: {
2109 <                                int code;
2109 >                                int code = -1;
2110                                  if (use_keycodes) {
2111 <                                        event2keycode((XKeyEvent *)&event);     // This is called to process the hotkeys
2112 <                                        code = keycode_table[((XKeyEvent *)&event)->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((XKeyEvent *)&event);
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 1222 | Line 2122 | static void handle_events(void)
2122  
2123                          // Hidden parts exposed, force complete refresh of window
2124                          case Expose:
2125 <                                if (display_type == DISPLAY_WINDOW)
2126 <                                        memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
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, mode.bytes_per_row * mode.y);
2133 >                                        }
2134 >                                        else
2135 > #endif
2136 >                                        if (frame_skip == 0) {  // Dynamic refresh
2137 >                                                int x1, y1;
2138 >                                                for (y1=0; y1<16; y1++)
2139 >                                                for (x1=0; x1<16; x1++)
2140 >                                                        updt_box[x1][y1] = true;
2141 >                                                nr_boxes = 16 * 16;
2142 >                                        } else                                  // Static refresh
2143 >                                                memset(the_buffer_copy, 0, mode.bytes_per_row * mode.y);
2144 >                                }
2145 >                                break;
2146 >
2147 >                        // Window "close" widget clicked
2148 >                        case ClientMessage:
2149 >                                if (event.xclient.format == 32 && event.xclient.data.l[0] == WM_DELETE_WINDOW) {
2150 >                                        ADBKeyDown(0x7f);       // Power key
2151 >                                        ADBKeyUp(0x7f);
2152 >                                }
2153                                  break;
2154                  }
2155          }
# Line 1234 | Line 2160 | static void handle_events(void)
2160   *  Window display update
2161   */
2162  
2163 < static void update_display(void)
2163 > // Dynamic display update (variable frame rate for each box)
2164 > static void update_display_dynamic(int ticker, driver_window *drv)
2165 > {
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 >        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];
2177 >        y2a = 8;
2178 >        for (i = 0; i < 6; i++)
2179 >                if (ticker % (2 << i))
2180 >                        break;
2181 >        max_box = sm_no_boxes[i];
2182 >
2183 >        if (y2a) {
2184 >                for (y1=0; y1<16; y1++) {
2185 >                        for (y2=y2s; y2 < ry; y2 += y2a) {
2186 >                                i = ((y1 * ry) + y2) * bytes_per_row;
2187 >                                for (x1=0; x1<16; x1++, i += rx) {
2188 >                                        if (updt_box[x1][y1] == false) {
2189 >                                                if (memcmp(&the_buffer_copy[i], &the_buffer[i], rx)) {
2190 >                                                        updt_box[x1][y1] = true;
2191 >                                                        nr_boxes++;
2192 >                                                }
2193 >                                        }
2194 >                                }
2195 >                        }
2196 >                }
2197 >        }
2198 >
2199 >        if ((nr_boxes <= max_box) && (nr_boxes)) {
2200 >                for (y1=0; y1<16; y1++) {
2201 >                        for (x1=0; x1<16; x1++) {
2202 >                                if (updt_box[x1][y1] == true) {
2203 >                                        if (rxm == 0)
2204 >                                                xm = x1;
2205 >                                        rxm += rx;
2206 >                                        updt_box[x1][y1] = false;
2207 >                                }
2208 >                                if (((updt_box[x1+1][y1] == false) || (x1 == 15)) && (rxm)) {
2209 >                                        if ((rxmo != rxm) || (xmo != xm) || (yo != y1 - 1)) {
2210 >                                                if (rxmo) {
2211 >                                                        xi = xmo * rx;
2212 >                                                        yi = ymo * ry;
2213 >                                                        xil = rxmo;
2214 >                                                        yil = (yo - ymo +1) * ry;
2215 >                                                }
2216 >                                                rxmo = rxm;
2217 >                                                xmo = xm;
2218 >                                                ymo = y1;
2219 >                                        }
2220 >                                        rxm = 0;
2221 >                                        yo = y1;
2222 >                                }      
2223 >                                if (xil) {
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 (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
2231 >                                                        XPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil);
2232 >                                        } else {
2233 >                                                if (drv->have_shm)
2234 >                                                        XShmPutImage(x_display, drv->w, drv->gc, drv->img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0);
2235 >                                                else
2236 >                                                        XPutImage(x_display, drv->w, drv->gc, drv->img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil);
2237 >                                        }
2238 >                                        xil = 0;
2239 >                                }
2240 >                                if ((x1 == 15) && (y1 == 15) && (rxmo)) {
2241 >                                        x1--;
2242 >                                        xi = xmo * rx;
2243 >                                        yi = ymo * ry;
2244 >                                        xil = rxmo;
2245 >                                        yil = (yo - ymo +1) * ry;
2246 >                                        rxmo = 0;
2247 >                                }
2248 >                        }
2249 >                }
2250 >                nr_boxes = 0;
2251 >        }
2252 > }
2253 >
2254 > // Static display update (fixed frame rate, but incremental)
2255 > static void update_display_static(driver_window *drv)
2256   {
1239        // In classic mode, copy the frame buffer from Mac RAM
1240        if (classic_mode)
1241                memcpy(the_buffer, Mac2HostAddr(0x3fa700), VideoMonitor.bytes_per_row * VideoMonitor.y);
1242        
2257          // Incremental update code
2258 <        int wide = 0, high = 0, x1, x2, y1, y2, i, j;
2259 <        int bytes_per_row = VideoMonitor.bytes_per_row;
2260 <        int bytes_per_pixel = VideoMonitor.bytes_per_row / VideoMonitor.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.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.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 1265 | Line 2280 | static void update_display(void)
2280  
2281          // Check for first column from left and first column from right that have changed
2282          if (high) {
2283 <                if (depth == 1) {
2284 <                        x1 = VideoMonitor.x;
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 1275 | Line 2290 | static void update_display(void)
2290                                                  x1 = i << 3;
2291                                                  break;
2292                                          }
2293 <                                        p++;
1279 <                                        p2++;
2293 >                                        p++; p2++;
2294                                  }
2295                          }
2296                          x2 = x1;
# Line 1285 | Line 2299 | static void update_display(void)
2299                                  p2 = &the_buffer_copy[j * bytes_per_row];
2300                                  p += bytes_per_row;
2301                                  p2 += bytes_per_row;
2302 <                                for (i=(VideoMonitor.x>>3); i>(x2>>3); i--) {
2303 <                                        p--;
1290 <                                        p2--;
2302 >                                for (i=(mode.x>>3); i>(x2>>3); i--) {
2303 >                                        p--; p2--;
2304                                          if (*p != *p2) {
2305 <                                                x2 = i << 3;
2305 >                                                x2 = (i << 3) + 7;
2306                                                  break;
2307                                          }
2308                                  }
2309                          }
2310 <                        wide = x2 - x1;
2310 >                        wide = x2 - x1 + 1;
2311  
2312                          // Update copy of the_buffer
2313                          if (high && wide) {
2314                                  for (j=y1; j<=y2; j++) {
2315                                          i = j * bytes_per_row + (x1 >> 3);
2316 <                                        memcpy(&the_buffer_copy[i], &the_buffer[i], wide >> 3);
2316 >                                        memcpy(the_buffer_copy + i, the_buffer + i, wide >> 3);
2317                                  }
2318                          }
2319  
2320                  } else {
2321 <                        x1 = VideoMonitor.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];
2325 <                                for (i=0; i<x1; i++) {
2326 <                                        if (memcmp(p, p2, bytes_per_pixel)) {
2327 <                                                x1 = i;
2325 >                                for (i=0; i<x1*bytes_per_pixel; i++) {
2326 >                                        if (*p != *p2) {
2327 >                                                x1 = i / bytes_per_pixel;
2328                                                  break;
2329                                          }
2330 <                                        p += bytes_per_pixel;
1318 <                                        p2 += bytes_per_pixel;
2330 >                                        p++; p2++;
2331                                  }
2332                          }
2333                          x2 = x1;
# Line 1324 | Line 2336 | static void update_display(void)
2336                                  p2 = &the_buffer_copy[j * bytes_per_row];
2337                                  p += bytes_per_row;
2338                                  p2 += bytes_per_row;
2339 <                                for (i=VideoMonitor.x; i>x2; i--) {
2340 <                                        p -= bytes_per_pixel;
2341 <                                        p2 -= bytes_per_pixel;
2342 <                                        if (memcmp(p, p2, bytes_per_pixel)) {
2343 <                                                x2 = i;
2339 >                                for (i=mode.x*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
2340 >                                        p--;
2341 >                                        p2--;
2342 >                                        if (*p != *p2) {
2343 >                                                x2 = i / bytes_per_pixel;
2344                                                  break;
2345                                          }
2346                                  }
# Line 1339 | Line 2351 | static void update_display(void)
2351                          if (high && wide) {
2352                                  for (j=y1; j<=y2; j++) {
2353                                          i = j * bytes_per_row + x1 * bytes_per_pixel;
2354 <                                        memcpy(&the_buffer_copy[i], &the_buffer[i], bytes_per_pixel * wide);
2354 >                                        memcpy(the_buffer_copy + i, the_buffer + i, bytes_per_pixel * wide);
2355                                  }
2356                          }
2357                  }
# Line 1347 | Line 2359 | static void update_display(void)
2359  
2360          // Refresh display
2361          if (high && wide) {
2362 <                if (have_shm)
2363 <                        XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
2362 >                if (drv->have_shm)
2363 >                        XShmPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high, 0);
2364                  else
2365 <                        XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
2365 >                        XPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high);
2366 >        }
2367 > }
2368 >
2369 >
2370 > /*
2371 > *      Screen refresh functions
2372 > */
2373 >
2374 > // We suggest the compiler to inline the next two functions so that it
2375 > // may specialise the code according to the current screen depth and
2376 > // display type. A clever compiler would do that job by itself though...
2377 >
2378 > // NOTE: update_display_vosf is inlined too
2379 >
2380 > static inline void possibly_quit_dga_mode()
2381 > {
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;
2387 >                drv = NULL;
2388          }
2389 + }
2390  
2391 <        // Has the Mac started? (cursor data is not valid otherwise)
2392 <        if (HasMacStarted()) {
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 <                // Set new cursor image if it was changed
2403 <                if (memcmp(the_cursor, Mac2HostAddr(0x844), 64)) {
2404 <                        memcpy(the_cursor, Mac2HostAddr(0x844), 64);
2405 <                        memcpy(cursor_image->data, the_cursor, 32);
2406 <                        memcpy(cursor_mask_image->data, the_cursor+32, 32);
2407 <                        XFreeCursor(x_display, mac_cursor);
2408 <                        XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
2409 <                        XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
2410 <                        mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, ReadMacInt8(0x885), ReadMacInt8(0x887));
2411 <                        XDefineCursor(x_display, the_win, mac_cursor);
2402 > static inline void handle_palette_changes(void)
2403 > {
2404 >        LOCK_PALETTE;
2405 >
2406 >        if (x_palette_changed) {
2407 >                x_palette_changed = false;
2408 >                drv->update_palette();
2409 >        }
2410 >
2411 >        UNLOCK_PALETTE;
2412 > }
2413 >
2414 > static void video_refresh_dga(void)
2415 > {
2416 >        // Quit DGA mode if requested
2417 >        possibly_quit_dga_mode();
2418 > }
2419 >
2420 > #ifdef ENABLE_VOSF
2421 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
2422 > static void video_refresh_dga_vosf(void)
2423 > {
2424 >        // Quit DGA mode if requested
2425 >        possibly_quit_dga_mode();
2426 >        
2427 >        // Update display (VOSF variant)
2428 >        static int tick_counter = 0;
2429 >        if (++tick_counter >= frame_skip) {
2430 >                tick_counter = 0;
2431 >                if (mainBuffer.dirty) {
2432 >                        LOCK_VOSF;
2433 >                        update_display_dga_vosf();
2434 >                        UNLOCK_VOSF;
2435                  }
2436          }
2437   }
2438 + #endif
2439 +
2440 + static void video_refresh_window_vosf(void)
2441 + {
2442 +        // Ungrab mouse if requested
2443 +        possibly_ungrab_mouse();
2444 +        
2445 +        // Update display (VOSF variant)
2446 +        static int tick_counter = 0;
2447 +        if (++tick_counter >= frame_skip) {
2448 +                tick_counter = 0;
2449 +                if (mainBuffer.dirty) {
2450 +                        LOCK_VOSF;
2451 +                        update_display_window_vosf(static_cast<driver_window *>(drv));
2452 +                        UNLOCK_VOSF;
2453 +                        XSync(x_display, false); // Let the server catch up
2454 +                }
2455 +        }
2456 + }
2457 + #endif // def ENABLE_VOSF
2458 +
2459 + static void video_refresh_window_static(void)
2460 + {
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) {
2467 +                tick_counter = 0;
2468 +                update_display_static(static_cast<driver_window *>(drv));
2469 +        }
2470 + }
2471 +
2472 + static void video_refresh_window_dynamic(void)
2473 + {
2474 +        // Ungrab mouse if requested
2475 +        possibly_ungrab_mouse();
2476 +
2477 +        // Update display (dynamic variant)
2478 +        static int tick_counter = 0;
2479 +        tick_counter++;
2480 +        update_display_dynamic(tick_counter, static_cast<driver_window *>(drv));
2481 + }
2482  
2483  
2484   /*
2485   *  Thread for screen refresh, input handling etc.
2486   */
2487  
2488 + static void VideoRefreshInit(void)
2489 + {
2490 +        // TODO: set up specialised 8bpp VideoRefresh handlers ?
2491 +        if (display_type == DISPLAY_DGA) {
2492 + #if ENABLE_VOSF && (REAL_ADDRESSING || DIRECT_ADDRESSING)
2493 +                if (use_vosf)
2494 +                        video_refresh = video_refresh_dga_vosf;
2495 +                else
2496 + #endif
2497 +                        video_refresh = video_refresh_dga;
2498 +        }
2499 +        else {
2500 + #ifdef ENABLE_VOSF
2501 +                if (use_vosf)
2502 +                        video_refresh = video_refresh_window_vosf;
2503 +                else
2504 + #endif
2505 +                if (frame_skip == 0)
2506 +                        video_refresh = video_refresh_window_dynamic;
2507 +                else
2508 +                        video_refresh = video_refresh_window_static;
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 +                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 tick_counter = 0;
2536 >        int fd = ConnectionNumber(x_display);
2537 >
2538 >        uint64 start = GetTicks_usec();
2539 >        int64 ticks = 0;
2540 >        uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2541  
2542          while (!redraw_thread_cancel) {
2543  
2544 <                // Wait
2545 < #ifdef HAVE_NANOSLEEP
1386 <                struct timespec req = {0, 16666667};
1387 <                nanosleep(&req, NULL);
1388 < #else
1389 <                usleep(16667);
1390 < #endif
2544 >                int64 delay = next - GetTicks_usec();
2545 >                if (delay < -VIDEO_REFRESH_DELAY) {
2546  
2547 < #if ENABLE_XF86_DGA
2548 <                // Quit DGA mode if requested
1394 <                if (quit_full_screen) {
1395 <                        quit_full_screen = false;
1396 <                        if (display_type == DISPLAY_DGA) {
1397 <                                XF86DGADirectVideo(x_display, screen, 0);
1398 <                                XUngrabPointer(x_display, CurrentTime);
1399 <                                XUngrabKeyboard(x_display, CurrentTime);
1400 <                                XUnmapWindow(x_display, the_win);
1401 <                                XSync(x_display, false);
1402 <                        }
1403 <                }
1404 < #endif
2547 >                        // We are lagging far behind, so we reset the delay mechanism
2548 >                        next = GetTicks_usec();
2549  
2550 < #if ENABLE_FBDEV_DGA
1407 <                // Quit DGA mode if requested
1408 <                if (quit_full_screen) {
1409 <                        quit_full_screen = false;
1410 <                        if (display_type == DISPLAY_DGA) {
1411 <                                XUngrabPointer(x_display, CurrentTime);
1412 <                                XUngrabKeyboard(x_display, CurrentTime);
1413 <                                XUnmapWindow(x_display, the_win);
1414 <                                XSync(x_display, false);
1415 <                        }
1416 <                }
1417 < #endif
1418 <                // Handle X events
1419 <                handle_events();
2550 >                } else if (delay <= 0) {
2551  
2552 <                // Handle palette changes
2553 <                pthread_mutex_lock(&palette_lock);
2554 <                if (palette_changed) {
2555 <                        palette_changed = false;
2556 <                        if (depth == 8) {
2557 <                                XStoreColors(x_display, cmap[0], palette, 256);
1427 <                                XStoreColors(x_display, cmap[1], palette, 256);
1428 <                                
1429 < #if ENABLE_XF86_DGA
1430 <                                if (display_type == DISPLAY_DGA) {
1431 <                                        current_dga_cmap ^= 1;
1432 <                                        XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1433 <                                }
1434 < #endif
1435 <                        }
1436 <                }
1437 <                pthread_mutex_unlock(&palette_lock);
2552 >                        // Delay expired, refresh display
2553 >                        handle_events();
2554 >                        handle_palette_changes();
2555 >                        video_refresh();
2556 >                        next += VIDEO_REFRESH_DELAY;
2557 >                        ticks++;
2558  
2559 <                // In window mode, update display and mouse pointer
2560 <                if (display_type == DISPLAY_WINDOW) {
2561 <                        tick_counter++;
2562 <                        if (tick_counter >= frame_skip) {
2563 <                                tick_counter = 0;
2564 <                                update_display();
2565 <                        }
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 +        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