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

Comparing SheepShaver/src/Unix/video_x.cpp (file contents):
Revision 1.2 by gbeauche, 2002-04-21T11:47:18Z vs.
Revision 1.45 by gbeauche, 2005-06-24T22:31:28Z

# Line 1 | Line 1
1   /*
2   *  video_x.cpp - Video/graphics emulation, X11 specific stuff
3   *
4 < *  SheepShaver (C) 1997-2002 Marc Hellwig and Christian Bauer
4 > *  SheepShaver (C) 1997-2005 Marc Hellwig and 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 18 | Line 18
18   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   */
20  
21 + /*
22 + *  NOTES:
23 + *    The Ctrl key works like a qualifier for special actions:
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"
31 +
32   #include <X11/Xlib.h>
33   #include <X11/Xutil.h>
34   #include <X11/keysym.h>
35   #include <X11/extensions/XShm.h>
36   #include <sys/ipc.h>
37   #include <sys/shm.h>
38 + #include <errno.h>
39   #include <pthread.h>
40  
41 < #include "sysdeps.h"
41 > #include <algorithm>
42 >
43 > #ifdef ENABLE_FBDEV_DGA
44 > # include <linux/fb.h>
45 > # include <sys/ioctl.h>
46 > #endif
47 >
48 > #ifdef ENABLE_XF86_DGA
49 > # include <X11/extensions/xf86dga.h>
50 > #endif
51 >
52 > #ifdef ENABLE_XF86_VIDMODE
53 > # include <X11/extensions/xf86vmode.h>
54 > #endif
55 >
56 > #ifdef ENABLE_FBDEV_DGA
57 > # include <sys/mman.h>
58 > #endif
59 >
60   #include "main.h"
61   #include "adb.h"
62   #include "prefs.h"
# Line 34 | Line 64
64   #include "about_window.h"
65   #include "video.h"
66   #include "video_defs.h"
67 + #include "video_blit.h"
68  
69   #define DEBUG 0
70   #include "debug.h"
71  
72 < #ifdef ENABLE_XF86_DGA
73 < #include <X11/extensions/xf86dga.h>
72 > #ifndef NO_STD_NAMESPACE
73 > using std::sort;
74   #endif
75  
45 #ifdef ENABLE_XF86_VIDMODE
46 #include <X11/extensions/xf86vmode.h>
47 #endif
76  
77 + // Constants
78 + const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
79 + static const bool hw_mac_cursor_accl = true;    // Flag: Enable MacOS to X11 copy of cursor?
80  
81   // Global variables
82   static int32 frame_skip;
83 + static int16 mouse_wheel_mode;
84 + static int16 mouse_wheel_lines;
85   static bool redraw_thread_active = false;       // Flag: Redraw thread installed
86 + static pthread_attr_t redraw_thread_attr;       // Redraw thread attributes
87 + static volatile bool redraw_thread_cancel;      // Flag: Cancel Redraw thread
88   static pthread_t redraw_thread;                         // Redraw thread
89  
90 + static bool local_X11;                                          // Flag: X server running on local machine?
91   static volatile bool thread_stop_req = false;
92   static volatile bool thread_stop_ack = false;   // Acknowledge for thread_stop_req
93  
94   static bool has_dga = false;                            // Flag: Video DGA capable
95   static bool has_vidmode = false;                        // Flag: VidMode extension available
96  
97 + #ifdef ENABLE_VOSF
98 + static bool use_vosf = true;                            // Flag: VOSF enabled
99 + #else
100 + static const bool use_vosf = false;                     // VOSF not possible
101 + #endif
102 +
103   static bool palette_changed = false;            // Flag: Palette changed, redraw thread must update palette
104   static bool ctrl_down = false;                          // Flag: Ctrl key pressed
105 + static bool caps_on = false;                            // Flag: Caps Lock on
106   static bool quit_full_screen = false;           // Flag: DGA close requested from redraw thread
107   static volatile bool quit_full_screen_ack = false;      // Acknowledge for quit_full_screen
108   static bool emerg_quit = false;                         // Flag: Ctrl-Esc pressed, emergency quit requested from MacOS thread
# Line 67 | Line 110 | static bool emerg_quit = false;                                // Fl
110   static bool emul_suspended = false;                     // Flag: emulator suspended
111   static Window suspend_win;                                      // "Suspend" window
112   static void *fb_save = NULL;                            // Saved frame buffer for suspend
113 + static bool use_keycodes = false;                       // Flag: Use keycodes rather than keysyms
114 + static int keycode_table[256];                          // X keycode -> Mac keycode translation table
115  
116   // X11 variables
117   static int screen;                                                      // Screen number
118   static int xdepth;                                                      // Depth of X screen
119   static int depth;                                                       // Depth of Mac frame buffer
120   static Window rootwin, the_win;                         // Root window and our window
121 + static int num_depths = 0;                                      // Number of available X depths
122 + static int *avail_depths = NULL;                        // List of available X depths
123 + static VisualFormat visualFormat;
124   static XVisualInfo visualInfo;
125   static Visual *vis;
126 + static int color_class;
127 + static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
128   static Colormap cmap[2];                                        // Two colormaps (DGA) for 8-bit mode
129 + static XColor x_palette[256];                           // Color palette to be used as CLUT and gamma table
130 + static int orig_accel_numer, orig_accel_denom, orig_threshold;  // Original mouse acceleration
131 +
132   static XColor black, white;
133   static unsigned long black_pixel, white_pixel;
134   static int eventmask;
135 < static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask;
136 < static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
135 > static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
136 > static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
137  
138   // Variables for window mode
139   static GC the_gc;
# Line 92 | Line 145 | static Cursor mac_cursor;
145   static GC cursor_gc, cursor_mask_gc;
146   static bool cursor_changed = false;                     // Flag: Cursor changed, window_func must update cursor
147   static bool have_shm = false;                           // Flag: SHM present and usable
148 < static uint8 *the_buffer;                                       // Pointer to Mac frame buffer
148 > static uint8 *the_buffer = NULL;                        // Pointer to Mac frame buffer
149   static uint8 *the_buffer_copy = NULL;           // Copy of Mac frame buffer
150 + static uint32 the_buffer_size;                          // Size of allocated the_buffer
151  
152   // Variables for DGA mode
153 < static char *dga_screen_base;
100 < static int dga_fb_width;
153 > static bool is_fbdev_dga_mode = false;          // Flag: Use FBDev DGA mode?
154   static int current_dga_cmap;
155  
156 + #ifdef ENABLE_FBDEV_DGA
157 + static int fb_dev_fd = -1;                                              // Handle to fb device name
158 + static struct fb_fix_screeninfo fb_finfo;               // Fixed info
159 + static struct fb_var_screeninfo fb_vinfo;               // Variable info
160 + static struct fb_var_screeninfo fb_orig_vinfo;  // Variable info to restore later
161 + static struct fb_cmap fb_oldcmap;                               // Colormap to restore later
162 + #endif
163 +
164   #ifdef ENABLE_XF86_VIDMODE
165   // Variables for XF86 VidMode support
166   static XF86VidModeModeInfo **x_video_modes;             // Array of all available modes
167   static int num_x_video_modes;
168   #endif
169  
170 + // Mutex to protect palette
171 + #ifdef HAVE_SPINLOCKS
172 + static spinlock_t x_palette_lock = SPIN_LOCK_UNLOCKED;
173 + #define LOCK_PALETTE spin_lock(&x_palette_lock)
174 + #define UNLOCK_PALETTE spin_unlock(&x_palette_lock)
175 + #elif defined(HAVE_PTHREADS)
176 + static pthread_mutex_t x_palette_lock = PTHREAD_MUTEX_INITIALIZER;
177 + #define LOCK_PALETTE pthread_mutex_lock(&x_palette_lock)
178 + #define UNLOCK_PALETTE pthread_mutex_unlock(&x_palette_lock)
179 + #else
180 + #define LOCK_PALETTE
181 + #define UNLOCK_PALETTE
182 + #endif
183 +
184 + // Mutex to protect frame buffer
185 + #ifdef HAVE_SPINLOCKS
186 + static spinlock_t frame_buffer_lock = SPIN_LOCK_UNLOCKED;
187 + #define LOCK_FRAME_BUFFER spin_lock(&frame_buffer_lock)
188 + #define UNLOCK_FRAME_BUFFER spin_unlock(&frame_buffer_lock)
189 + #elif defined(HAVE_PTHREADS)
190 + static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
191 + #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock);
192 + #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock);
193 + #else
194 + #define LOCK_FRAME_BUFFER
195 + #define UNLOCK_FRAME_BUFFER
196 + #endif
197 +
198  
199   // Prototypes
200   static void *redraw_func(void *arg);
201  
202  
203 < // From main_linux.cpp
203 > // From main_unix.cpp
204 > extern char *x_display_name;
205   extern Display *x_display;
206  
207   // From sys_unix.cpp
208   extern void SysMountFirstFloppy(void);
209  
210 + // From clip_unix.cpp
211 + extern void ClipboardSelectionClear(XSelectionClearEvent *);
212 + extern void ClipboardSelectionRequest(XSelectionRequestEvent *);
213 +
214 +
215 + // Video acceleration through SIGSEGV
216 + #ifdef ENABLE_VOSF
217 + # include "video_vosf.h"
218 + #endif
219 +
220 +
221 + /*
222 + *  Utility functions
223 + */
224 +
225 + // Get current video mode
226 + static inline int get_current_mode(void)
227 + {
228 +        return VModes[cur_mode].viAppleMode;
229 + }
230 +
231 + // Find palette size for given color depth
232 + static int palette_size(int mode)
233 + {
234 +        switch (mode) {
235 +        case APPLE_1_BIT: return 2;
236 +        case APPLE_2_BIT: return 4;
237 +        case APPLE_4_BIT: return 16;
238 +        case APPLE_8_BIT: return 256;
239 +        case APPLE_16_BIT: return 32;
240 +        case APPLE_32_BIT: return 256;
241 +        default: return 0;
242 +        }
243 + }
244 +
245 + // Return bits per pixel for requested depth
246 + static inline int bytes_per_pixel(int depth)
247 + {
248 +        int bpp;
249 +        switch (depth) {
250 +        case 8:
251 +                bpp = 1;
252 +                break;
253 +        case 15: case 16:
254 +                bpp = 2;
255 +                break;
256 +        case 24: case 32:
257 +                bpp = 4;
258 +                break;
259 +        default:
260 +                abort();
261 +        }
262 +        return bpp;
263 + }
264 +
265 + // Map video_mode depth ID to numerical depth value
266 + static inline int depth_of_video_mode(int mode)
267 + {
268 +        int depth;
269 +        switch (mode) {
270 +        case APPLE_1_BIT:
271 +                depth = 1;
272 +                break;
273 +        case APPLE_2_BIT:
274 +                depth = 2;
275 +                break;
276 +        case APPLE_4_BIT:
277 +                depth = 4;
278 +                break;
279 +        case APPLE_8_BIT:
280 +                depth = 8;
281 +                break;
282 +        case APPLE_16_BIT:
283 +                depth = 16;
284 +                break;
285 +        case APPLE_32_BIT:
286 +                depth = 32;
287 +                break;
288 +        default:
289 +                abort();
290 +        }
291 +        return depth;
292 + }
293 +
294 + // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
295 + static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
296 + {
297 +        return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
298 + }
299 +
300 +
301 + // Do we have a visual for handling the specified Mac depth? If so, set the
302 + // global variables "xdepth", "visualInfo", "vis" and "color_class".
303 + static bool find_visual_for_depth(int depth)
304 + {
305 +        D(bug("have_visual_for_depth(%d)\n", depth_of_video_mode(depth)));
306 +
307 +        // 1-bit works always and uses default visual
308 +        if (depth == APPLE_1_BIT) {
309 +                vis = DefaultVisual(x_display, screen);
310 +                visualInfo.visualid = XVisualIDFromVisual(vis);
311 +                int num = 0;
312 +                XVisualInfo *vi = XGetVisualInfo(x_display, VisualIDMask, &visualInfo, &num);
313 +                visualInfo = vi[0];
314 +                XFree(vi);
315 +                xdepth = visualInfo.depth;
316 +                color_class = visualInfo.c_class;
317 +                D(bug(" found visual ID 0x%02x, depth %d\n", visualInfo.visualid, xdepth));
318 +                return true;
319 +        }
320 +
321 +        // Calculate minimum and maximum supported X depth
322 +        int min_depth = 1, max_depth = 32;
323 +        switch (depth) {
324 + #ifdef ENABLE_VOSF
325 +                case APPLE_2_BIT:
326 +                case APPLE_4_BIT:       // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit
327 +                case APPLE_8_BIT:
328 +                        min_depth = 8;
329 +                        max_depth = 32;
330 +                        break;
331 + #else
332 +                case APPLE_2_BIT:
333 +                case APPLE_4_BIT:       // 2/4-bit requires VOSF blitters
334 +                        return false;
335 +                case APPLE_8_BIT:       // 8-bit without VOSF requires an 8-bit visual
336 +                        min_depth = 8;
337 +                        max_depth = 8;
338 +                        break;
339 + #endif
340 +                case APPLE_16_BIT:      // 16-bit requires a 15/16-bit visual
341 +                        min_depth = 15;
342 +                        max_depth = 16;
343 +                        break;
344 +                case APPLE_32_BIT:      // 32-bit requires a 24/32-bit visual
345 +                        min_depth = 24;
346 +                        max_depth = 32;
347 +                        break;
348 +        }
349 +        D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth));
350 +
351 +        // Try to find a visual for one of the color depths
352 +        bool visual_found = false;
353 +        for (int i=0; i<num_depths && !visual_found; i++) {
354 +
355 +                xdepth = avail_depths[i];
356 +                D(bug(" trying to find visual for depth %d\n", xdepth));
357 +                if (xdepth < min_depth || xdepth > max_depth)
358 +                        continue;
359 +
360 +                // Determine best color class for this depth
361 +                switch (xdepth) {
362 +                        case 1: // Try StaticGray or StaticColor
363 +                                if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo)
364 +                                 || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo))
365 +                                        visual_found = true;
366 +                                break;
367 +                        case 8: // Need PseudoColor
368 +                                if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo))
369 +                                        visual_found = true;
370 +                                break;
371 +                        case 15:
372 +                        case 16:
373 +                        case 24:
374 +                        case 32: // Try DirectColor first, as this will allow gamma correction
375 +                                if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo)
376 +                                 || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo))
377 +                                        visual_found = true;
378 +                                break;
379 +                        default:
380 +                                D(bug("  not a supported depth\n"));
381 +                                break;
382 +                }
383 +        }
384 +        if (!visual_found)
385 +                return false;
386 +
387 +        // Visual was found
388 +        vis = visualInfo.visual;
389 +        color_class = visualInfo.c_class;
390 +        D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth));
391 + #if DEBUG
392 +        switch (color_class) {
393 +                case StaticGray: D(bug("StaticGray\n")); break;
394 +                case GrayScale: D(bug("GrayScale\n")); break;
395 +                case StaticColor: D(bug("StaticColor\n")); break;
396 +                case PseudoColor: D(bug("PseudoColor\n")); break;
397 +                case TrueColor: D(bug("TrueColor\n")); break;
398 +                case DirectColor: D(bug("DirectColor\n")); break;
399 +        }
400 + #endif
401 +        return true;
402 + }
403 +
404  
405   /*
406   *  Open display (window or fullscreen)
407   */
408  
409 + // Set window name and class
410 + static void set_window_name(Window w, int name)
411 + {
412 +        const char *str = GetString(name);
413 +        XStoreName(x_display, w, str);
414 +        XSetIconName(x_display, w, str);
415 +
416 +        XClassHint *hints;
417 +        hints = XAllocClassHint();
418 +        if (hints) {
419 +                hints->res_name = "SheepShaver";
420 +                hints->res_class = "SheepShaver";
421 +                XSetClassHint(x_display, w, hints);
422 +                XFree(hints);
423 +        }
424 + }
425 +
426 + // Set window input focus flag
427 + static void set_window_focus(Window w)
428 + {
429 +        XWMHints *hints = XAllocWMHints();
430 +        if (hints) {
431 +                hints->input = True;
432 +                hints->initial_state = NormalState;
433 +                hints->flags = InputHint | StateHint;
434 +                XSetWMHints(x_display, w, hints);
435 +                XFree(hints);
436 +        }
437 + }
438 +
439 + // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
440 + static Atom WM_DELETE_WINDOW = (Atom)0;
441 + static void set_window_delete_protocol(Window w)
442 + {
443 +        WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
444 +        XSetWMProtocols(x_display, w, &WM_DELETE_WINDOW, 1);
445 + }
446 +
447 + // Wait until window is mapped/unmapped
448 + static void wait_mapped(Window w)
449 + {
450 +        XEvent e;
451 +        do {
452 +                XMaskEvent(x_display, StructureNotifyMask, &e);
453 +        } while ((e.type != MapNotify) || (e.xmap.event != w));
454 + }
455 +
456 + static void wait_unmapped(Window w)
457 + {
458 +        XEvent e;
459 +        do {
460 +                XMaskEvent(x_display, StructureNotifyMask, &e);
461 +        } while ((e.type != UnmapNotify) || (e.xmap.event != w));
462 + }
463 +
464 + // Disable mouse acceleration
465 + static void disable_mouse_accel(void)
466 + {
467 +        XChangePointerControl(x_display, True, False, 1, 1, 0);
468 + }
469 +
470 + // Restore mouse acceleration to original value
471 + static void restore_mouse_accel(void)
472 + {
473 +        XChangePointerControl(x_display, True, True, orig_accel_numer, orig_accel_denom, orig_threshold);
474 + }
475 +
476   // Trap SHM errors
477   static bool shm_error = false;
478   static int (*old_error_handler)(Display *, XErrorEvent *);
# Line 138 | Line 489 | static int error_handler(Display *d, XEr
489   // Open window
490   static bool open_window(int width, int height)
491   {
492 +        int aligned_width = (width + 15) & ~15;
493 +        int aligned_height = (height + 15) & ~15;
494 +
495          // Set absolute mouse mode
496          ADBSetRelMouseMode(false);
497  
144        // Read frame skip prefs
145        frame_skip = PrefsFindInt32("frameskip");
146        if (frame_skip == 0)
147                frame_skip = 1;
148
498          // Create window
499          XSetWindowAttributes wattr;
500          wattr.event_mask = eventmask = win_eventmask;
501 <        wattr.background_pixel = black_pixel;
502 <        wattr.border_pixel = black_pixel;
501 >        wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
502 >        wattr.border_pixel = 0;
503          wattr.backing_store = NotUseful;
504 <
156 <        XSync(x_display, false);
504 >        wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
505          the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
506 <                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWBackingStore, &wattr);
159 <        XSync(x_display, false);
160 <        XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
161 <        XMapRaised(x_display, the_win);
162 <        XSync(x_display, false);
506 >                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWBackingStore | CWColormap, &wattr);
507  
508 <        // Set colormap
509 <        if (depth == 8) {
510 <                XSetWindowColormap(x_display, the_win, cmap[0]);
511 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
512 <        }
508 >        // Set window name/class
509 >        set_window_name(the_win, STR_WINDOW_TITLE);
510 >
511 >        // Indicate that we want keyboard input
512 >        set_window_focus(the_win);
513 >
514 >        // Set delete protocol property
515 >        set_window_delete_protocol(the_win);
516  
517          // Make window unresizable
518          XSizeHints *hints;
# Line 179 | Line 526 | static bool open_window(int width, int h
526                  XFree((char *)hints);
527          }
528  
529 +        // Show window
530 +        XMapWindow(x_display, the_win);
531 +        wait_mapped(the_win);
532 +
533 +        // 1-bit mode is big-endian; if the X server is little-endian, we can't
534 +        // use SHM because that doesn't allow changing the image byte order
535 +        bool need_msb_image = (depth == 1 && XImageByteOrder(x_display) == LSBFirst);
536 +
537          // Try to create and attach SHM image
538          have_shm = false;
539 <        if (depth != 1 && XShmQueryExtension(x_display)) {
539 >        if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
540  
541                  // Create SHM image ("height + 2" for safety)
542 <                img = XShmCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
543 <                shminfo.shmid = shmget(IPC_PRIVATE, (height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
544 <                screen_base = (uint32)shmat(shminfo.shmid, 0, 0);
545 <                the_buffer = (uint8 *)screen_base;
546 <                shminfo.shmaddr = img->data = (char *)screen_base;
542 >                img = XShmCreateImage(x_display, vis, depth == 1 ? 1 : xdepth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
543 >                shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
544 >                D(bug(" shm image created\n"));
545 >                the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
546 >                shminfo.shmaddr = img->data = (char *)the_buffer_copy;
547                  shminfo.readOnly = False;
548  
549                  // Try to attach SHM image, catching errors
# Line 205 | Line 560 | static bool open_window(int width, int h
560                          have_shm = true;
561                          shmctl(shminfo.shmid, IPC_RMID, 0);
562                  }
563 +                D(bug(" shm image attached\n"));
564          }
565  
566          // Create normal X image if SHM doesn't work ("height + 2" for safety)
567          if (!have_shm) {
568 <                int bytes_per_row = width;
569 <                switch (depth) {
570 <                        case 1:
571 <                                bytes_per_row /= 8;
216 <                                break;
217 <                        case 15:
218 <                        case 16:
219 <                                bytes_per_row *= 2;
220 <                                break;
221 <                        case 24:
222 <                        case 32:
223 <                                bytes_per_row *= 4;
224 <                                break;
225 <                }
226 <                screen_base = (uint32)malloc((height + 2) * bytes_per_row);
227 <                the_buffer = (uint8 *)screen_base;
228 <                img = XCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)screen_base, width, height, 32, bytes_per_row);
568 >                int bytes_per_row = depth == 1 ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth));
569 >                the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
570 >                img = XCreateImage(x_display, vis, depth == 1 ? 1 : xdepth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
571 >                D(bug(" X image created\n"));
572          }
573  
574          // 1-Bit mode is big-endian
575 <    if (depth == 1) {
575 >    if (need_msb_image) {
576          img->byte_order = MSBFirst;
577          img->bitmap_bit_order = MSBFirst;
578      }
579  
580 <        // Allocate memory for frame buffer copy
581 <        the_buffer_copy = (uint8 *)malloc((height + 2) * img->bytes_per_line);
580 > #ifdef ENABLE_VOSF
581 >        use_vosf = true;
582 >        // Allocate memory for frame buffer (SIZE is extended to page-boundary)
583 >        the_host_buffer = the_buffer_copy;
584 >        the_buffer_size = page_extend((aligned_height + 2) * img->bytes_per_line);
585 >        the_buffer = (uint8 *)vm_acquire(the_buffer_size);
586 >        the_buffer_copy = (uint8 *)malloc(the_buffer_size);
587 >        D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
588 > #else
589 >        // Allocate memory for frame buffer
590 >        the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
591 >        D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
592 > #endif
593 >        screen_base = Host2MacAddr(the_buffer);
594  
595          // Create GC
596          the_gc = XCreateGC(x_display, the_win, 0, 0);
597 <        XSetForeground(x_display, the_gc, black_pixel);
597 >        XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
598  
599          // Create cursor
600 <        cursor_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 4, 16, 16, 16, 2);
601 <        cursor_image->byte_order = MSBFirst;
602 <        cursor_image->bitmap_bit_order = MSBFirst;
603 <        cursor_mask_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 36, 16, 16, 16, 2);
604 <        cursor_mask_image->byte_order = MSBFirst;
605 <        cursor_mask_image->bitmap_bit_order = MSBFirst;
606 <        cursor_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
607 <        cursor_mask_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
608 <        cursor_gc = XCreateGC(x_display, cursor_map, 0, 0);
609 <        cursor_mask_gc = XCreateGC(x_display, cursor_mask_map, 0, 0);
610 <        mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, 0, 0);
611 <        cursor_changed = false;
600 >        if (hw_mac_cursor_accl) {
601 >                cursor_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 4, 16, 16, 16, 2);
602 >                cursor_image->byte_order = MSBFirst;
603 >                cursor_image->bitmap_bit_order = MSBFirst;
604 >                cursor_mask_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 36, 16, 16, 16, 2);
605 >                cursor_mask_image->byte_order = MSBFirst;
606 >                cursor_mask_image->bitmap_bit_order = MSBFirst;
607 >                cursor_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
608 >                cursor_mask_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
609 >                cursor_gc = XCreateGC(x_display, cursor_map, 0, 0);
610 >                cursor_mask_gc = XCreateGC(x_display, cursor_mask_map, 0, 0);
611 >                mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, 0, 0);
612 >                cursor_changed = false;
613 >        }
614 >
615 >        // Create no_cursor
616 >        else {
617 >                mac_cursor = XCreatePixmapCursor(x_display,
618 >                        XCreatePixmap(x_display, the_win, 1, 1, 1),
619 >                        XCreatePixmap(x_display, the_win, 1, 1, 1),
620 >                        &black, &white, 0, 0);
621 >                XDefineCursor(x_display, the_win, mac_cursor);
622 >        }
623 >
624 >        // Init blitting routines
625 >        bool native_byte_order;
626 > #ifdef WORDS_BIGENDIAN
627 >        native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
628 > #else
629 >        native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
630 > #endif
631 > #ifdef ENABLE_VOSF
632 >        Screen_blitter_init(visualFormat, native_byte_order, depth);
633 > #endif
634  
635          // Set bytes per row
259        VModes[cur_mode].viRowBytes = img->bytes_per_line;
636          XSync(x_display, false);
637          return true;
638   }
639  
640 < // Open DGA display (!! should use X11 VidMode extensions to set mode)
641 < static bool open_dga(int width, int height)
640 > // Open FBDev DGA display
641 > static bool open_fbdev_dga(int width, int height)
642   {
643 + #ifdef ENABLE_FBDEV_DGA
644 + #ifdef ENABLE_XF86_VIDMODE
645 +        // Switch to best mode
646 +        if (has_vidmode) {
647 +                int best = -1;
648 +                for (int i = 0; i < num_x_video_modes; i++) {
649 +                        if (x_video_modes[i]->hdisplay == width && x_video_modes[i]->vdisplay == height) {
650 +                                best = i;
651 +                                break;
652 +                        }
653 +                };
654 +                assert(best != -1);
655 +                XF86VidModeSwitchToMode(x_display, screen, x_video_modes[best]);
656 +                XF86VidModeSetViewPort(x_display, screen, 0, 0);
657 +                D(bug("[fbdev] VideoMode %d: %d x %d @ %d\n", best,
658 +                          x_video_modes[best]->hdisplay, x_video_modes[best]->vdisplay,
659 +                          1000 * x_video_modes[best]->dotclock / (x_video_modes[best]->htotal * x_video_modes[best]->vtotal)));
660 +        }
661 + #endif
662 +
663 +        if (ioctl(fb_dev_fd, FBIOGET_FSCREENINFO, &fb_finfo) != 0) {
664 +                D(bug("[fbdev] Can't get FSCREENINFO: %s\n", strerror(errno)));
665 +                return false;
666 +        }
667 +        D(bug("[fbdev] Device ID: %s\n", fb_finfo.id));
668 +        D(bug("[fbdev] smem_start: %p [%d bytes]\n", fb_finfo.smem_start, fb_finfo.smem_len));
669 +
670 +        int fb_type = fb_finfo.type;
671 +        const char *fb_type_str = NULL;
672 +        switch (fb_type) {
673 +        case FB_TYPE_PACKED_PIXELS:                     fb_type_str = "Packed Pixels";                  break;
674 +        case FB_TYPE_PLANES:                            fb_type_str = "Non interleaved planes"; break;
675 +        case FB_TYPE_INTERLEAVED_PLANES:        fb_type_str = "Interleaved planes";             break;
676 +        case FB_TYPE_TEXT:                                      fb_type_str = "Text/attributes";                break;
677 +        case FB_TYPE_VGA_PLANES:                        fb_type_str = "EGA/VGA planes";                 break;
678 +        default:                                                        fb_type_str = "<unknown>";                              break;
679 +        }
680 +        D(bug("[fbdev] type: %s\n", fb_type_str));
681 +
682 +        if (fb_type != FB_TYPE_PACKED_PIXELS) {
683 +                D(bug("[fbdev] type '%s' not supported\n", fb_type_str));
684 +                return false;
685 +        }
686 +
687 +        int fb_visual = fb_finfo.visual;
688 +        const char *fb_visual_str;
689 +        switch (fb_visual) {
690 +        case FB_VISUAL_MONO01:                          fb_visual_str = "Monochrome 1=Black 0=White";   break;
691 +        case FB_VISUAL_MONO10:                          fb_visual_str = "Monochrome 1=While 0=Black";   break;
692 +        case FB_VISUAL_TRUECOLOR:                       fb_visual_str = "True color";                                   break;
693 +        case FB_VISUAL_PSEUDOCOLOR:                     fb_visual_str = "Pseudo color (like atari)";    break;
694 +        case FB_VISUAL_DIRECTCOLOR:                     fb_visual_str = "Direct color";                                 break;
695 +        case FB_VISUAL_STATIC_PSEUDOCOLOR:      fb_visual_str = "Pseudo color readonly";                break;
696 +        default:                                                        fb_visual_str = "<unknown>";                                    break;
697 +        }
698 +        D(bug("[fbdev] visual: %s\n", fb_visual_str));
699 +
700 +        if (fb_visual != FB_VISUAL_TRUECOLOR && fb_visual != FB_VISUAL_DIRECTCOLOR) {
701 +                D(bug("[fbdev] visual '%s' not supported\n", fb_visual_str));
702 +                return false;
703 +        }
704 +        
705 +        // Map frame buffer
706 +        the_buffer = (uint8 *)mmap(NULL, fb_finfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fb_dev_fd, 0);
707 +        if (the_buffer == MAP_FAILED) {
708 +                D(bug("[fbdev] Can't mmap /dev/fb0: %s\n", strerror(errno)));
709 +                return false;
710 +        }
711 +
712 +        // Set absolute mouse mode
713 +        ADBSetRelMouseMode(false);
714 +
715 +        // Create window
716 +        XSetWindowAttributes wattr;
717 +        wattr.event_mask = eventmask = dga_eventmask;
718 +        wattr.override_redirect = True;
719 +        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
720 +                                                        InputOutput, DefaultVisual(x_display, screen),
721 +                                                        CWEventMask | CWOverrideRedirect, &wattr);
722 +
723 +        // Show window
724 +        XMapRaised(x_display, the_win);
725 +        wait_mapped(the_win);
726 +
727 +        // Grab mouse and keyboard
728 +        XGrabKeyboard(x_display, the_win, True,
729 +                                  GrabModeAsync, GrabModeAsync, CurrentTime);
730 +        XGrabPointer(x_display, the_win, True,
731 +                                 PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
732 +                                 GrabModeAsync, GrabModeAsync, the_win, None, CurrentTime);
733 +        disable_mouse_accel();
734 +
735 +        // Create no_cursor
736 +        mac_cursor = XCreatePixmapCursor(x_display,
737 +                                                                         XCreatePixmap(x_display, the_win, 1, 1, 1),
738 +                                                                         XCreatePixmap(x_display, the_win, 1, 1, 1),
739 +                                                                         &black, &white, 0, 0);
740 +        XDefineCursor(x_display, the_win, mac_cursor);
741 +
742 +        // Init blitting routines
743 +        int bytes_per_row = TrivialBytesPerRow((width + 7) & ~7, DepthModeForPixelDepth(depth));
744 + #if ENABLE_VOSF
745 +        // Extract current screen color masks (we are in True Color mode)
746 +        VisualFormat visualFormat;
747 +        visualFormat.depth = xdepth = DefaultDepth(x_display, screen);
748 +        XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo);
749 +        assert(visualFormat.depth == visualInfo.depth);
750 +        visualFormat.Rmask = visualInfo.red_mask;
751 +        visualFormat.Gmask = visualInfo.green_mask;
752 +        visualFormat.Bmask = visualInfo.blue_mask;
753 +        D(bug("[fbdev] %d bpp, (%08x,%08x,%08x)\n",
754 +                  visualFormat.depth,
755 +                  visualFormat.Rmask, visualFormat.Gmask, visualFormat.Bmask));
756 +        D(bug("[fbdev] Mac depth %d bpp\n", depth));
757 +
758 +        // Screen_blitter_init() returns TRUE if VOSF is mandatory
759 +        // i.e. the framebuffer update function is not Blit_Copy_Raw
760 + #ifdef WORDS_BIGENDIAN
761 +        const bool native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
762 + #else
763 +        const bool native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
764 + #endif
765 +        Screen_blitter_init(visualFormat, native_byte_order, depth);
766 +        
767 +        // Allocate memory for frame buffer (SIZE is extended to page-boundary)
768 +        use_vosf = true;
769 +        the_host_buffer = the_buffer;
770 +        the_buffer_size = page_extend((height + 2) * bytes_per_row);
771 +        the_buffer_copy = (uint8 *)malloc(the_buffer_size);
772 +        the_buffer = (uint8 *)vm_acquire(the_buffer_size);
773 +        D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
774 + #endif
775 +
776 +        // Set frame buffer base
777 +        D(bug("the_buffer = %p, use_vosf = %d\n", the_buffer, use_vosf));
778 +        screen_base = Host2MacAddr(the_buffer);
779 +        VModes[cur_mode].viRowBytes = bytes_per_row;
780 +        return true;
781 + #else
782 +        ErrorAlert("SheepShaver has been compiled with DGA support disabled.");
783 +        return false;
784 + #endif
785 + }
786 +
787 + // Open XF86 DGA display (!! should use X11 VidMode extensions to set mode)
788 + static bool open_xf86_dga(int width, int height)
789 + {
790 +        if (is_fbdev_dga_mode)
791 +                return false;
792 +
793   #ifdef ENABLE_XF86_DGA
794          // Set relative mouse mode
795          ADBSetRelMouseMode(true);
796  
797 +        // Create window
798 +        XSetWindowAttributes wattr;
799 +        wattr.event_mask = eventmask = dga_eventmask;
800 +        wattr.override_redirect = True;
801 +        wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
802 +        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
803 +                InputOutput, vis, CWEventMask | CWOverrideRedirect |
804 +                (color_class == DirectColor ? CWColormap : 0), &wattr);
805 +
806 +        // Show window
807 +        XMapRaised(x_display, the_win);
808 +        wait_mapped(the_win);
809 +
810   #ifdef ENABLE_XF86_VIDMODE
811          // Switch to best mode
812          if (has_vidmode) {
# Line 284 | Line 823 | static bool open_dga(int width, int heig
823   #endif
824  
825          // Establish direct screen connection
826 +        XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
827 +        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
828          XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
829          XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
830 +
831 +        int v_width, v_bank, v_size;
832 +        XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size);
833          XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
834          XF86DGASetViewPort(x_display, screen, 0, 0);
835          XF86DGASetVidPage(x_display, screen, 0);
292        screen_base = (uint32)dga_screen_base;
836  
837          // Set colormap
838 <        if (depth == 8)
838 >        if (!IsDirectMode(get_current_mode())) {
839 >                XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
840                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
841 +        }
842 +        XSync(x_display, false);
843  
844 <        // Set bytes per row
845 <        int bytes_per_row = (dga_fb_width + 7) & ~7;
846 <        switch (depth) {
847 <                case 15:
848 <                case 16:
849 <                        bytes_per_row *= 2;
850 <                        break;
851 <                case 24:
852 <                case 32:
853 <                        bytes_per_row *= 4;
854 <                        break;
844 >        // Init blitting routines
845 >        int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, DepthModeForPixelDepth(depth));
846 > #if ENABLE_VOSF
847 >        bool native_byte_order;
848 > #ifdef WORDS_BIGENDIAN
849 >        native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
850 > #else
851 >        native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
852 > #endif
853 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
854 >        // Screen_blitter_init() returns TRUE if VOSF is mandatory
855 >        // i.e. the framebuffer update function is not Blit_Copy_Raw
856 >        use_vosf = Screen_blitter_init(visualFormat, native_byte_order, depth);
857 >        
858 >        if (use_vosf) {
859 >          // Allocate memory for frame buffer (SIZE is extended to page-boundary)
860 >          the_host_buffer = the_buffer;
861 >          the_buffer_size = page_extend((height + 2) * bytes_per_row);
862 >          the_buffer_copy = (uint8 *)malloc(the_buffer_size);
863 >          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
864 >          D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
865          }
866 + #else
867 +        use_vosf = false;
868 + #endif
869 + #endif
870 +
871 +        // Set frame buffer base
872 +        D(bug("the_buffer = %p, use_vosf = %d\n", the_buffer, use_vosf));
873 +        screen_base = Host2MacAddr(the_buffer);
874          VModes[cur_mode].viRowBytes = bytes_per_row;
311        XSync(x_display, false);
875          return true;
876   #else
877          ErrorAlert("SheepShaver has been compiled with DGA support disabled.");
# Line 316 | Line 879 | static bool open_dga(int width, int heig
879   #endif
880   }
881  
882 < static bool open_display(void)
882 > // Open DGA display
883 > static bool open_dga(int width, int height)
884   {
885 <        display_type = VModes[cur_mode].viType;
886 <        switch (VModes[cur_mode].viAppleMode) {
887 <                case APPLE_1_BIT:
888 <                        depth = 1;
889 <                        break;
890 <                case APPLE_2_BIT:
891 <                        depth = 2;
892 <                        break;
329 <                case APPLE_4_BIT:
330 <                        depth = 4;
331 <                        break;
332 <                case APPLE_8_BIT:
333 <                        depth = 8;
334 <                        break;
335 <                case APPLE_16_BIT:
336 <                        depth = xdepth == 15 ? 15 : 16;
337 <                        break;
338 <                case APPLE_32_BIT:
339 <                        depth = 32;
340 <                        break;
885 >        bool display_open;
886 >
887 >        display_open = open_xf86_dga(width, height);
888 > #ifdef ENABLE_FBDEV_DGA
889 >        // Try to fallback to FBDev DGA mode
890 >        if (!display_open) {
891 >                is_fbdev_dga_mode = true;
892 >                display_open = open_fbdev_dga(width, height);
893          }
894 <        if (display_type == DIS_SCREEN)
895 <                return open_dga(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
896 <        else if (display_type == DIS_WINDOW)
897 <                return open_window(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
898 <        else
894 > #endif
895 >
896 >        // Common DGA display initialization
897 >        if (display_open) {
898 >
899 >                // Fake image to get display bounds in the refresh function
900 >                if ((img = (XImage *)malloc(sizeof(*img))) == NULL)
901 >                        return false;
902 >                img->width = DisplayWidth(x_display, screen);
903 >                img->height = DisplayHeight(x_display, screen);
904 >                img->depth = is_fbdev_dga_mode ? xdepth : depth;
905 >                img->bytes_per_line = TrivialBytesPerRow(img->width, DepthModeForPixelDepth(img->depth));
906 >        }
907 >
908 >        return display_open;
909 > }
910 >
911 > static bool open_display(void)
912 > {
913 >        D(bug("open_display()\n"));
914 >        const VideoInfo &mode = VModes[cur_mode];
915 >
916 >        // Get original mouse acceleration
917 >        XGetPointerControl(x_display, &orig_accel_numer, &orig_accel_denom, &orig_threshold);
918 >
919 >        // Find best available X visual
920 >        if (!find_visual_for_depth(mode.viAppleMode)) {
921 >                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
922                  return false;
923 +        }
924 +
925 +        // Build up visualFormat structure
926 +        visualFormat.fullscreen = (display_type == DIS_SCREEN);
927 +        visualFormat.depth = visualInfo.depth;
928 +        visualFormat.Rmask = visualInfo.red_mask;
929 +        visualFormat.Gmask = visualInfo.green_mask;
930 +        visualFormat.Bmask = visualInfo.blue_mask;
931 +
932 +        // Create color maps
933 +        if (color_class == PseudoColor || color_class == DirectColor) {
934 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
935 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
936 +        } else {
937 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone);
938 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone);
939 +        }
940 +
941 +        // Find pixel format of direct modes
942 +        if (color_class == DirectColor || color_class == TrueColor) {
943 +                rshift = gshift = bshift = 0;
944 +                rloss = gloss = bloss = 8;
945 +                uint32 mask;
946 +                for (mask=vis->red_mask; !(mask&1); mask>>=1)
947 +                        ++rshift;
948 +                for (; mask&1; mask>>=1)
949 +                        --rloss;
950 +                for (mask=vis->green_mask; !(mask&1); mask>>=1)
951 +                        ++gshift;
952 +                for (; mask&1; mask>>=1)
953 +                        --gloss;
954 +                for (mask=vis->blue_mask; !(mask&1); mask>>=1)
955 +                        ++bshift;
956 +                for (; mask&1; mask>>=1)
957 +                        --bloss;
958 +        }
959 +
960 +        // Preset palette pixel values for CLUT or gamma table
961 +        if (color_class == DirectColor) {
962 +                int num = vis->map_entries;
963 +                for (int i=0; i<num; i++) {
964 +                        int c = (i * 256) / num;
965 +                        x_palette[i].pixel = map_rgb(c, c, c);
966 +                        x_palette[i].flags = DoRed | DoGreen | DoBlue;
967 +                }
968 +        } else if (color_class == PseudoColor) {
969 +                for (int i=0; i<256; i++) {
970 +                        x_palette[i].pixel = i;
971 +                        x_palette[i].flags = DoRed | DoGreen | DoBlue;
972 +                }
973 +        }
974 +
975 +        // Load gray ramp to color map
976 +        int num = (color_class == DirectColor ? vis->map_entries : 256);
977 +        for (int i=0; i<num; i++) {
978 +                int c = (i * 256) / num;
979 +                x_palette[i].red = c * 0x0101;
980 +                x_palette[i].green = c * 0x0101;
981 +                x_palette[i].blue = c * 0x0101;
982 +        }
983 +        if (color_class == PseudoColor || color_class == DirectColor) {
984 +                XStoreColors(x_display, cmap[0], x_palette, num);
985 +                XStoreColors(x_display, cmap[1], x_palette, num);
986 +        }
987 +
988 + #ifdef ENABLE_VOSF
989 +        // Load gray ramp to 8->16/32 expand map
990 +        if (!IsDirectMode(get_current_mode()) && xdepth > 8)
991 +                for (int i=0; i<256; i++)
992 +                        ExpandMap[i] = map_rgb(i, i, i);
993 + #endif
994 +
995 +        // Create display of requested type
996 +        display_type = mode.viType;
997 +        depth = depth_of_video_mode(mode.viAppleMode);
998 +
999 +        bool display_open;
1000 +        switch (display_type) {
1001 +        case DIS_SCREEN:
1002 +                display_open = open_dga(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
1003 +                break;
1004 +        case DIS_WINDOW:
1005 +                display_open = open_window(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
1006 +                break;
1007 +        default:
1008 +                display_open = false;
1009 +                break;
1010 +        }
1011 +
1012 + #ifdef ENABLE_VOSF
1013 +        if (use_vosf) {
1014 +                // Initialize the VOSF system
1015 +                LOCK_VOSF;
1016 +                if (!video_vosf_init()) {
1017 +                        ErrorAlert(GetString(STR_VOSF_INIT_ERR));
1018 +                        UNLOCK_VOSF;
1019 +                        return false;
1020 +                }
1021 +                UNLOCK_VOSF;
1022 +        }
1023 + #endif
1024 +
1025 +        // Zero screen buffers, viRowBytes is initialized at this stage
1026 +        if (display_open) {
1027 +                memset(the_buffer, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1028 +                memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1029 +        }
1030 +        return display_open;
1031   }
1032  
1033  
# Line 355 | Line 1038 | static bool open_display(void)
1038   // Close window
1039   static void close_window(void)
1040   {
1041 <        // Close window
1042 <        XDestroyWindow(x_display, the_win);
1043 <
1044 <        // Close frame buffer copy
1045 <        if (the_buffer_copy) {
1046 <                free(the_buffer_copy);
1047 <                the_buffer_copy = NULL;
1041 >        if (have_shm) {
1042 >                XShmDetach(x_display, &shminfo);
1043 > #ifdef ENABLE_VOSF
1044 >                the_host_buffer = NULL; // don't free() in driver_base dtor
1045 > #else
1046 >                the_buffer_copy = NULL; // don't free() in driver_base dtor
1047 > #endif
1048          }
1049 +        if (img) {
1050 +                if (!have_shm)
1051 +                        img->data = NULL;
1052 +                XDestroyImage(img);
1053 +        }
1054 +        if (have_shm) {
1055 +                shmdt(shminfo.shmaddr);
1056 +                shmctl(shminfo.shmid, IPC_RMID, 0);
1057 +        }
1058 +        if (the_gc)
1059 +                XFreeGC(x_display, the_gc);
1060 +
1061 +        XFlush(x_display);
1062 +        XSync(x_display, false);
1063   }
1064  
1065 < // Close DGA mode
1066 < static void close_dga(void)
1065 > // Close FBDev mode
1066 > static void close_fbdev_dga(void)
1067 > {
1068 > #ifdef ENABLE_FBDEV_DGA
1069 >        uint8 *fb_base;
1070 >        if (!use_vosf)
1071 >                fb_base = the_buffer;
1072 > #ifdef ENABLE_VOSF
1073 >        else
1074 >                fb_base = the_host_buffer;
1075 > #endif
1076 >        munmap(fb_base, fb_finfo.smem_len);
1077 > #endif
1078 > }
1079 >
1080 > // Close XF86 DGA mode
1081 > static void close_xf86_dga(void)
1082   {
1083   #ifdef ENABLE_XF86_DGA
1084          XF86DGADirectVideo(x_display, screen, 0);
1085 + #endif
1086 + }
1087 +
1088 + // Close DGA mode
1089 + static void close_dga(void)
1090 + {
1091 +        if (is_fbdev_dga_mode)
1092 +                close_fbdev_dga();
1093 +        else
1094 +                close_xf86_dga();
1095 +
1096          XUngrabPointer(x_display, CurrentTime);
1097          XUngrabKeyboard(x_display, CurrentTime);
375 #endif
1098  
1099   #ifdef ENABLE_XF86_VIDMODE
1100          if (has_vidmode)
1101                  XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1102   #endif
1103 +
1104 +        // Release fake image (it's not a normal XImage!)
1105 +        free(img);
1106 +        img = NULL;
1107 +
1108 +        if (!use_vosf) {
1109 +                // don't free() the screen buffer in driver_base dtor
1110 +                the_buffer = NULL;
1111 +        }
1112 + #ifdef ENABLE_VOSF
1113 +        else {
1114 +                // don't free() the screen buffer in driver_base dtor
1115 +                the_host_buffer = NULL;
1116 +        }
1117 + #endif
1118   }
1119  
1120   static void close_display(void)
# Line 386 | Line 1123 | static void close_display(void)
1123                  close_dga();
1124          else if (display_type == DIS_WINDOW)
1125                  close_window();
1126 +
1127 +        // Close window
1128 +        if (the_win) {
1129 +                XUnmapWindow(x_display, the_win);
1130 +                wait_unmapped(the_win);
1131 +                XDestroyWindow(x_display, the_win);
1132 +        }
1133 +
1134 +        // Free colormaps
1135 +        if (cmap[0]) {
1136 +                XFreeColormap(x_display, cmap[0]);
1137 +                cmap[0] = 0;
1138 +        }
1139 +        if (cmap[1]) {
1140 +                XFreeColormap(x_display, cmap[1]);
1141 +                cmap[1] = 0;
1142 +        }
1143 +
1144 + #ifdef ENABLE_VOSF
1145 +        if (use_vosf) {
1146 +                // Deinitialize VOSF
1147 +                video_vosf_exit();
1148 +        }
1149 + #endif
1150 +
1151 +        // Free frame buffer(s)
1152 +        if (!use_vosf) {
1153 +                if (the_buffer_copy) {
1154 +                        free(the_buffer_copy);
1155 +                        the_buffer_copy = NULL;
1156 +                }
1157 +        }
1158 + #ifdef ENABLE_VOSF
1159 +        else {
1160 +                // the_buffer shall always be mapped through vm_acquire() so that we can vm_protect() it at will
1161 +                if (the_buffer != VM_MAP_FAILED) {
1162 +                        D(bug(" releasing the_buffer at %p (%d bytes)\n", the_buffer, the_buffer_size));
1163 +                        vm_release(the_buffer, the_buffer_size);
1164 +                        the_buffer = NULL;
1165 +                }
1166 +                if (the_host_buffer) {
1167 +                        D(bug(" freeing the_host_buffer at %p\n", the_host_buffer));
1168 +                        free(the_host_buffer);
1169 +                        the_host_buffer = NULL;
1170 +                }
1171 +                if (the_buffer_copy) {
1172 +                        D(bug(" freeing the_buffer_copy at %p\n", the_buffer_copy));
1173 +                        free(the_buffer_copy);
1174 +                        the_buffer_copy = NULL;
1175 +                }
1176 +        }
1177 + #endif
1178 +
1179 +        // Restore mouse acceleration
1180 +        restore_mouse_accel();
1181   }
1182  
1183  
# Line 393 | Line 1185 | static void close_display(void)
1185   *  Initialization
1186   */
1187  
1188 < static void add_mode(VideoInfo *&p, uint32 allow, uint32 test, long apple_mode, long apple_id, int type)
1188 > // Init keycode translation table
1189 > static void keycode_init(void)
1190 > {
1191 >        bool use_kc = PrefsFindBool("keycodes");
1192 >        if (use_kc) {
1193 >
1194 >                // Get keycode file path from preferences
1195 >                const char *kc_path = PrefsFindString("keycodefile");
1196 >
1197 >                // Open keycode table
1198 >                FILE *f = fopen(kc_path ? kc_path : KEYCODE_FILE_NAME, "r");
1199 >                if (f == NULL) {
1200 >                        char str[256];
1201 >                        sprintf(str, GetString(STR_KEYCODE_FILE_WARN), kc_path ? kc_path : KEYCODE_FILE_NAME, strerror(errno));
1202 >                        WarningAlert(str);
1203 >                        return;
1204 >                }
1205 >
1206 >                // Default translation table
1207 >                for (int i=0; i<256; i++)
1208 >                        keycode_table[i] = -1;
1209 >
1210 >                // Search for server vendor string, then read keycodes
1211 >                const char *vendor = ServerVendor(x_display);
1212 >                // Force use of MacX mappings on MacOS X with Apple's X server
1213 >                int dummy;
1214 >                if (XQueryExtension(x_display, "Apple-DRI", &dummy, &dummy, &dummy))
1215 >                        vendor = "MacX";
1216 >                bool vendor_found = false;
1217 >                char line[256];
1218 >                while (fgets(line, 255, f)) {
1219 >                        // Read line
1220 >                        int len = strlen(line);
1221 >                        if (len == 0)
1222 >                                continue;
1223 >                        line[len-1] = 0;
1224 >
1225 >                        // Comments begin with "#" or ";"
1226 >                        if (line[0] == '#' || line[0] == ';' || line[0] == 0)
1227 >                                continue;
1228 >
1229 >                        if (vendor_found) {
1230 >                                // Read keycode
1231 >                                int x_code, mac_code;
1232 >                                if (sscanf(line, "%d %d", &x_code, &mac_code) == 2)
1233 >                                        keycode_table[x_code & 0xff] = mac_code;
1234 >                                else
1235 >                                        break;
1236 >                        } else {
1237 >                                // Search for vendor string
1238 >                                if (strstr(vendor, line) == vendor)
1239 >                                        vendor_found = true;
1240 >                        }
1241 >                }
1242 >
1243 >                // Keycode file completely read
1244 >                fclose(f);
1245 >                use_keycodes = vendor_found;
1246 >
1247 >                // Vendor not found? Then display warning
1248 >                if (!vendor_found) {
1249 >                        char str[256];
1250 >                        sprintf(str, GetString(STR_KEYCODE_VENDOR_WARN), vendor, kc_path ? kc_path : KEYCODE_FILE_NAME);
1251 >                        WarningAlert(str);
1252 >                        return;
1253 >                }
1254 >        }
1255 > }
1256 >
1257 > // Find Apple mode matching best specified dimensions
1258 > static int find_apple_resolution(int xsize, int ysize)
1259 > {
1260 >        int apple_id;
1261 >        if (xsize < 800)
1262 >                apple_id = APPLE_640x480;
1263 >        else if (xsize < 1024)
1264 >                apple_id = APPLE_800x600;
1265 >        else if (xsize < 1152)
1266 >                apple_id = APPLE_1024x768;
1267 >        else if (xsize < 1280) {
1268 >                if (ysize < 900)
1269 >                        apple_id = APPLE_1152x768;
1270 >                else
1271 >                        apple_id = APPLE_1152x900;
1272 >        }
1273 >        else if (xsize < 1600)
1274 >                apple_id = APPLE_1280x1024;
1275 >        else
1276 >                apple_id = APPLE_1600x1200;
1277 >        return apple_id;
1278 > }
1279 >
1280 > // Find mode in list of supported modes
1281 > static int find_mode(int apple_mode, int apple_id, int type)
1282 > {
1283 >        for (VideoInfo *p = VModes; p->viType != DIS_INVALID; p++) {
1284 >                if (p->viType == type && p->viAppleID == apple_id && p->viAppleMode == apple_mode)
1285 >                        return p - VModes;
1286 >        }
1287 >        return -1;
1288 > }
1289 >
1290 > // Add custom video mode
1291 > static void add_custom_mode(VideoInfo *&p, int type, uint32 x, uint32 y, int apple_mode, int apple_id)
1292 > {
1293 >        p->viType = type;
1294 >        p->viXsize = x;
1295 >        p->viYsize = y;
1296 >        p->viRowBytes = TrivialBytesPerRow(p->viXsize, apple_mode);
1297 >        p->viAppleMode = apple_mode;
1298 >        p->viAppleID = apple_id;
1299 >        p++;
1300 > }
1301 >
1302 > // Add mode to list of supported modes
1303 > static void add_mode(VideoInfo *&p, uint32 allow, uint32 test, int apple_mode, int apple_id, int type)
1304   {
1305          if (allow & test) {
1306 <                p->viType = type;
1306 >                uint32 x = 0, y = 0;
1307                  switch (apple_id) {
1308                          case APPLE_W_640x480:
1309                          case APPLE_640x480:
1310 <                                p->viXsize = 640;
1311 <                                p->viYsize = 480;
1310 >                                x = 640;
1311 >                                y = 480;
1312                                  break;
1313                          case APPLE_W_800x600:
1314                          case APPLE_800x600:
1315 <                                p->viXsize = 800;
1316 <                                p->viYsize = 600;
1315 >                                x = 800;
1316 >                                y = 600;
1317                                  break;
1318                          case APPLE_1024x768:
1319 <                                p->viXsize = 1024;
1320 <                                p->viYsize = 768;
1319 >                                x = 1024;
1320 >                                y = 768;
1321 >                                break;
1322 >                        case APPLE_1152x768:
1323 >                                x = 1152;
1324 >                                y = 768;
1325                                  break;
1326                          case APPLE_1152x900:
1327 <                                p->viXsize = 1152;
1328 <                                p->viYsize = 900;
1327 >                                x = 1152;
1328 >                                y = 900;
1329                                  break;
1330                          case APPLE_1280x1024:
1331 <                                p->viXsize = 1280;
1332 <                                p->viYsize = 1024;
1331 >                                x = 1280;
1332 >                                y = 1024;
1333                                  break;
1334                          case APPLE_1600x1200:
1335 <                                p->viXsize = 1600;
1336 <                                p->viYsize = 1200;
1335 >                                x = 1600;
1336 >                                y = 1200;
1337                                  break;
1338                  }
1339 <                switch (apple_mode) {
429 <                        case APPLE_8_BIT:
430 <                                p->viRowBytes = p->viXsize;
431 <                                break;
432 <                        case APPLE_16_BIT:
433 <                                p->viRowBytes = p->viXsize * 2;
434 <                                break;
435 <                        case APPLE_32_BIT:
436 <                                p->viRowBytes = p->viXsize * 4;
437 <                                break;
438 <                }
439 <                p->viAppleMode = apple_mode;
440 <                p->viAppleID = apple_id;
441 <                p++;
1339 >                add_custom_mode(p, type, x, y, apple_mode, apple_id);
1340          }
1341   }
1342  
1343 + // Add standard list of windowed modes for given color depth
1344 + static void add_window_modes(VideoInfo *&p, int window_modes, int mode)
1345 + {
1346 +        add_mode(p, window_modes, 1, mode, APPLE_W_640x480, DIS_WINDOW);
1347 +        add_mode(p, window_modes, 2, mode, APPLE_W_800x600, DIS_WINDOW);
1348 + }
1349 +
1350   static bool has_mode(int x, int y)
1351   {
1352   #ifdef ENABLE_XF86_VIDMODE
1353 <        for (int i=0; i<num_x_video_modes; i++)
1354 <                if (x_video_modes[i]->hdisplay >= x && x_video_modes[i]->vdisplay >= y)
1355 <                        return true;
1356 <        return false;
1357 < #else
1358 <        return DisplayWidth(x_display, screen) >= x && DisplayHeight(x_display, screen) >= y;
1353 >        if (has_vidmode) {
1354 >                for (int i=0; i<num_x_video_modes; i++)
1355 >                        if (x_video_modes[i]->hdisplay == x && x_video_modes[i]->vdisplay == y)
1356 >                                return true;
1357 >                return false;
1358 >        }
1359   #endif
1360 +        return DisplayWidth(x_display, screen) >= x && DisplayHeight(x_display, screen) >= y;
1361   }
1362  
1363   bool VideoInit(void)
1364   {
1365 + #ifdef ENABLE_VOSF
1366 +        // Zero the mainBuffer structure
1367 +        mainBuffer.dirtyPages = NULL;
1368 +        mainBuffer.pageInfo = NULL;
1369 + #endif
1370 +        
1371 +        // Check if X server runs on local machine
1372 +        local_X11 = (strncmp(XDisplayName(x_display_name), ":", 1) == 0)
1373 +                 || (strncmp(XDisplayName(x_display_name), "unix:", 5) == 0);
1374 +    
1375 +        // Init keycode translation
1376 +        keycode_init();
1377 +
1378 +        // Read frame skip prefs
1379 +        frame_skip = PrefsFindInt32("frameskip");
1380 +        if (frame_skip == 0)
1381 +                frame_skip = 1;
1382 +
1383 +        // Read mouse wheel prefs
1384 +        mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1385 +        mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1386 +
1387          // Init variables
1388          private_data = NULL;
461        cur_mode = 0;   // Window 640x480
1389          video_activated = true;
1390  
1391          // Find screen and root window
1392          screen = XDefaultScreen(x_display);
1393          rootwin = XRootWindow(x_display, screen);
1394  
1395 +        // Get sorted list of available depths
1396 +        avail_depths = XListDepths(x_display, screen, &num_depths);
1397 +        if (avail_depths == NULL) {
1398 +                ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
1399 +                return false;
1400 +        }
1401 +        sort(avail_depths, avail_depths + num_depths);
1402 +        
1403          // Get screen depth
1404          xdepth = DefaultDepth(x_display, screen);
1405  
1406   #ifdef ENABLE_XF86_DGA
1407          // DGA available?
1408      int event_base, error_base;
1409 <    if (XF86DGAQueryExtension(x_display, &event_base, &error_base)) {
1409 >    is_fbdev_dga_mode = false;
1410 >    if (local_X11 && XF86DGAQueryExtension(x_display, &event_base, &error_base)) {
1411                  int dga_flags = 0;
1412                  XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
1413                  has_dga = dga_flags & XF86DGADirectPresent;
1414 + #if defined(__linux__)
1415 +                // Check r/w permission on /dev/mem for DGA mode to work
1416 +                if (has_dga && access("/dev/mem", R_OK | W_OK) != 0)
1417 +                        has_dga = false;
1418 + #endif
1419          } else
1420                  has_dga = false;
1421   #endif
# Line 483 | Line 1424 | bool VideoInit(void)
1424          // VidMode available?
1425          int vm_event_base, vm_error_base;
1426          has_vidmode = XF86VidModeQueryExtension(x_display, &vm_event_base, &vm_error_base);
1427 <        if (has_vidmode)
1427 >        if (has_vidmode) {
1428 >                int vm_major_version, vm_minor_version;
1429 >                XF86VidModeQueryVersion(x_display, &vm_major_version, &vm_minor_version);
1430 >                D(bug("VidMode extension %d.%d available\n", vm_major_version, vm_minor_version));
1431                  XF86VidModeGetAllModeLines(x_display, screen, &num_x_video_modes, &x_video_modes);
1432 +        }
1433 + #endif
1434 +
1435 + #ifdef ENABLE_FBDEV_DGA
1436 +        // FBDev available?
1437 +        bool has_fbdev_dga = false;
1438 +        if (local_X11) {
1439 +                if ((fb_dev_fd = open("/dev/fb0", O_RDWR)) > 0) {
1440 +                        if (ioctl(fb_dev_fd, FBIOGET_VSCREENINFO, &fb_vinfo) != 0)
1441 +                                close(fb_dev_fd);
1442 +                        else {
1443 +                                has_fbdev_dga = true;
1444 +                                if (!has_dga) {
1445 +                                        // Fallback to FBDev DGA mode if XF86 DGA is not possible
1446 +                                        has_dga = true;
1447 +                                        is_fbdev_dga_mode = true;
1448 +                                }
1449 +                                fb_orig_vinfo = fb_vinfo;
1450 +                                D(bug("Frame buffer device initial resolution: %dx%dx%d\n", fb_vinfo.xres, fb_vinfo.yres, fb_vinfo.bits_per_pixel));
1451 +                        }
1452 +                }
1453 +        }
1454   #endif
1455  
1456          // Find black and white colors
# Line 495 | Line 1461 | bool VideoInit(void)
1461          black_pixel = BlackPixel(x_display, screen);
1462          white_pixel = WhitePixel(x_display, screen);
1463  
498        // Get appropriate visual
499        int color_class;
500        switch (xdepth) {
501 #if 0
502                case 1:
503                        color_class = StaticGray;
504                        break;
505 #endif
506                case 8:
507                        color_class = PseudoColor;
508                        break;
509                case 15:
510                case 16:
511                case 24:
512                case 32:
513                        color_class = TrueColor;
514                        break;
515                default:
516                        ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
517                        return false;
518        }
519        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
520                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
521                return false;
522        }
523        if (visualInfo.depth != xdepth) {
524                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
525                return false;
526        }
527        vis = visualInfo.visual;
528
1464          // Mac screen depth follows X depth (for now)
1465 <        depth = xdepth;
1466 <
1467 <        // Create color maps for 8 bit mode
1468 <        if (depth == 8) {
1469 <                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1470 <                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1471 <                XInstallColormap(x_display, cmap[0]);
1472 <                XInstallColormap(x_display, cmap[1]);
1465 >        int default_mode = APPLE_8_BIT;
1466 >        switch (DefaultDepth(x_display, screen)) {
1467 >        case 1:
1468 >                default_mode = APPLE_1_BIT;
1469 >                break;
1470 >        case 8:
1471 >                default_mode = APPLE_8_BIT;
1472 >                break;
1473 >        case 15: case 16:
1474 >                default_mode = APPLE_16_BIT;
1475 >                break;
1476 >        case 24: case 32:
1477 >                default_mode = APPLE_32_BIT;
1478 >                break;
1479 >        }
1480 >
1481 >        // Get screen mode from preferences
1482 >        const char *mode_str = PrefsFindString("screen");
1483 >        int default_width = 640, default_height = 480;
1484 >        if (mode_str) {
1485 >                display_type = DIS_INVALID;
1486 >                if (sscanf(mode_str, "win/%d/%d", &default_width, &default_height) == 2)
1487 >                        display_type = DIS_WINDOW;
1488 > #ifdef ENABLE_XF86_DGA
1489 >                else if (has_dga && sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2)
1490 >                        display_type = DIS_SCREEN;
1491 > #endif
1492 > #ifdef ENABLE_FBDEV_DGA
1493 >                else if (has_fbdev_dga && sscanf(mode_str, "fbdev/%d/%d", &default_width, &default_height) == 2) {
1494 >                        is_fbdev_dga_mode = true;
1495 >                        display_type = DIS_SCREEN;
1496 >                }
1497 > #endif
1498 >                if (display_type == DIS_INVALID) {
1499 >                        D(bug("Invalid screen mode specified, defaulting to old modes selection\n"));
1500 >                        mode_str = NULL;
1501 >                }
1502 >                else {
1503 >                        if (default_width <= 0)
1504 >                                default_width = DisplayWidth(x_display, screen);
1505 >                        else if (default_width > DisplayWidth(x_display, screen))
1506 >                                default_width = DisplayWidth(x_display, screen);
1507 >                        if (default_height <= 0)
1508 >                                default_height = DisplayHeight(x_display, screen);
1509 >                        else if (default_height > DisplayHeight(x_display, screen))
1510 >                                default_height = DisplayHeight(x_display, screen);
1511 >                }
1512          }
1513  
1514          // Construct video mode table
541        int mode = APPLE_8_BIT;
542        int bpr_mult = 8;
543        switch (depth) {
544                case 1:
545                        mode = APPLE_1_BIT;
546                        bpr_mult = 1;
547                        break;
548                case 8:
549                        mode = APPLE_8_BIT;
550                        bpr_mult = 8;
551                        break;
552                case 15:
553                case 16:
554                        mode = APPLE_16_BIT;
555                        bpr_mult = 16;
556                        break;
557                case 24:
558                case 32:
559                        mode = APPLE_32_BIT;
560                        bpr_mult = 32;
561                        break;
562        }
563
1515          uint32 window_modes = PrefsFindInt32("windowmodes");
1516          uint32 screen_modes = PrefsFindInt32("screenmodes");
1517          if (!has_dga)
1518                  screen_modes = 0;
1519 <        if (window_modes == 0 && screen_modes == 0)
1519 >        if (mode_str)
1520 >                window_modes = screen_modes = 0;
1521 >        else if (window_modes == 0 && screen_modes == 0)
1522                  window_modes |= 3;      // Allow at least 640x480 and 800x600 window modes
1523  
1524          VideoInfo *p = VModes;
1525 <        add_mode(p, window_modes, 1, mode, APPLE_W_640x480, DIS_WINDOW);
1526 <        add_mode(p, window_modes, 2, mode, APPLE_W_800x600, DIS_WINDOW);
1527 <        if (has_vidmode) {
1525 >        if (mode_str) {
1526 >                if (display_type == DIS_WINDOW) {
1527 >                        for (unsigned int d = APPLE_1_BIT; d <= APPLE_32_BIT; d++) {
1528 >                                if (find_visual_for_depth(d)) {
1529 >                                        if (default_width > 640 && default_height > 480)
1530 >                                                add_mode(p, 3, 1, d, APPLE_W_640x480, DIS_WINDOW);
1531 >                                        if (default_width > 800 && default_height > 600)
1532 >                                                add_mode(p, 3, 2, d, APPLE_W_800x600, DIS_WINDOW);
1533 >                                        add_custom_mode(p, display_type, default_width, default_height, d, APPLE_CUSTOM);
1534 >                                }
1535 >                        }
1536 > #ifdef ENABLE_VOSF
1537 >                } else if (display_type == DIS_SCREEN && is_fbdev_dga_mode) {
1538 >                        for (unsigned int d = APPLE_1_BIT; d <= default_mode; d++)
1539 >                                if (find_visual_for_depth(d))
1540 >                                        add_custom_mode(p, display_type, default_width, default_height, d, APPLE_CUSTOM);
1541 > #endif
1542 >                } else
1543 >                        add_custom_mode(p, display_type, default_width, default_height, default_mode, APPLE_CUSTOM);
1544 >
1545 >                // Add extra VidMode capable modes
1546 >                if (display_type == DIS_SCREEN) {
1547 >                        struct {
1548 >                                int w;
1549 >                                int h;
1550 >                                int apple_id;
1551 >                        }
1552 >                        video_modes[] = {
1553 >                                {  640,  480, APPLE_640x480   },
1554 >                                {  800,  600, APPLE_800x600   },
1555 >                                { 1024,  768, APPLE_1024x768  },
1556 >                                { 1152,  768, APPLE_1152x768  },
1557 >                                { 1152,  900, APPLE_1152x900  },
1558 >                                { 1280, 1024, APPLE_1280x1024 },
1559 >                                { 1600, 1200, APPLE_1600x1200 },
1560 >                                { 0, }
1561 >                        };
1562 >
1563 >                        for (int i = 0; video_modes[i].w != 0; i++) {
1564 >                                const int w = video_modes[i].w;
1565 >                                const int h = video_modes[i].h;
1566 >                                if (w >= default_width || h >= default_height)
1567 >                                        continue;
1568 >                                if (has_mode(w, h)) {
1569 > #ifdef ENABLE_VOSF
1570 >                                        if (is_fbdev_dga_mode) {
1571 >                                                for (unsigned int d = APPLE_1_BIT; d <= default_mode; d++)
1572 >                                                        if (find_visual_for_depth(d))
1573 >                                                                add_custom_mode(p, display_type, w, h, d, video_modes[i].apple_id);
1574 >                                        } else
1575 > #endif
1576 >                                                add_custom_mode(p, display_type, w, h, default_mode, video_modes[i].apple_id);
1577 >                                }
1578 >                        }
1579 >                }
1580 >        } else if (window_modes) {
1581 >                for (unsigned int d = APPLE_1_BIT; d <= APPLE_32_BIT; d++)
1582 >                        if (find_visual_for_depth(d))
1583 >                                add_window_modes(p, window_modes, d);
1584 >        } else if (has_vidmode) {
1585                  if (has_mode(640, 480))
1586 <                        add_mode(p, screen_modes, 1, mode, APPLE_640x480, DIS_SCREEN);
1586 >                        add_mode(p, screen_modes, 1, default_mode, APPLE_640x480, DIS_SCREEN);
1587                  if (has_mode(800, 600))
1588 <                        add_mode(p, screen_modes, 2, mode, APPLE_800x600, DIS_SCREEN);
1588 >                        add_mode(p, screen_modes, 2, default_mode, APPLE_800x600, DIS_SCREEN);
1589                  if (has_mode(1024, 768))
1590 <                        add_mode(p, screen_modes, 4, mode, APPLE_1024x768, DIS_SCREEN);
1590 >                        add_mode(p, screen_modes, 4, default_mode, APPLE_1024x768, DIS_SCREEN);
1591 >                if (has_mode(1152, 768))
1592 >                        add_mode(p, screen_modes, 64, default_mode, APPLE_1152x768, DIS_SCREEN);
1593                  if (has_mode(1152, 900))
1594 <                        add_mode(p, screen_modes, 8, mode, APPLE_1152x900, DIS_SCREEN);
1594 >                        add_mode(p, screen_modes, 8, default_mode, APPLE_1152x900, DIS_SCREEN);
1595                  if (has_mode(1280, 1024))
1596 <                        add_mode(p, screen_modes, 16, mode, APPLE_1280x1024, DIS_SCREEN);
1596 >                        add_mode(p, screen_modes, 16, default_mode, APPLE_1280x1024, DIS_SCREEN);
1597                  if (has_mode(1600, 1200))
1598 <                        add_mode(p, screen_modes, 32, mode, APPLE_1600x1200, DIS_SCREEN);
1598 >                        add_mode(p, screen_modes, 32, default_mode, APPLE_1600x1200, DIS_SCREEN);
1599          } else if (screen_modes) {
1600                  int xsize = DisplayWidth(x_display, screen);
1601                  int ysize = DisplayHeight(x_display, screen);
1602 <                int apple_id;
591 <                if (xsize < 800)
592 <                        apple_id = APPLE_640x480;
593 <                else if (xsize < 1024)
594 <                        apple_id = APPLE_800x600;
595 <                else if (xsize < 1152)
596 <                        apple_id = APPLE_1024x768;
597 <                else if (xsize < 1280)
598 <                        apple_id = APPLE_1152x900;
599 <                else if (xsize < 1600)
600 <                        apple_id = APPLE_1280x1024;
601 <                else
602 <                        apple_id = APPLE_1600x1200;
1602 >                int apple_id = find_apple_resolution(xsize, ysize);
1603                  p->viType = DIS_SCREEN;
1604                  p->viRowBytes = 0;
1605                  p->viXsize = xsize;
1606                  p->viYsize = ysize;
1607 <                p->viAppleMode = mode;
1607 >                p->viAppleMode = default_mode;
1608                  p->viAppleID = apple_id;
1609                  p++;
1610          }
# Line 614 | Line 1614 | bool VideoInit(void)
1614          p->viAppleMode = 0;
1615          p->viAppleID = 0;
1616  
1617 < #ifdef ENABLE_XF86_DGA
1617 >        // Find default mode (window 640x480)
1618 >        cur_mode = -1;
1619          if (has_dga && screen_modes) {
1620 <                int v_bank, v_size;
1621 <                XF86DGAGetVideo(x_display, screen, &dga_screen_base, &dga_fb_width, &v_bank, &v_size);
1622 <                D(bug("DGA screen_base %p, v_width %d\n", dga_screen_base, dga_fb_width));
1620 >                int screen_width = DisplayWidth(x_display, screen);
1621 >                int screen_height = DisplayHeight(x_display, screen);
1622 >                int apple_id = find_apple_resolution(screen_width, screen_height);
1623 >                if (apple_id != -1)
1624 >                        cur_mode = find_mode(default_mode, apple_id, DIS_SCREEN);
1625 >        } else if (has_dga && mode_str)
1626 >                cur_mode = find_mode(default_mode, APPLE_CUSTOM, DIS_SCREEN);
1627 >
1628 >        if (cur_mode == -1) {
1629 >                // pick up first windowed mode available
1630 >                for (VideoInfo *p = VModes; p->viType != DIS_INVALID; p++) {
1631 >                        if (p->viType == DIS_WINDOW && p->viAppleMode == default_mode) {
1632 >                                cur_mode = p - VModes;
1633 >                                break;
1634 >                        }
1635 >                }
1636 >        }
1637 >        assert(cur_mode != -1);
1638 >
1639 > #if DEBUG
1640 >        D(bug("Available video modes:\n"));
1641 >        for (p = VModes; p->viType != DIS_INVALID; p++) {
1642 >                int bits = depth_of_video_mode(p->viAppleMode);
1643 >                D(bug(" %dx%d (ID %02x), %d colors\n", p->viXsize, p->viYsize, p->viAppleID, 1 << bits));
1644          }
1645   #endif
1646  
1647          // Open window/screen
1648 <        if (!open_display())
1648 >        if (!open_display()) {
1649 >                ErrorAlert(GetString(STR_OPEN_WINDOW_ERR));
1650                  return false;
1651 +        }
1652  
1653   #if 0
1654          // Ignore errors from now on
1655          XSetErrorHandler(ignore_errors);
1656   #endif
1657  
1658 +        // Lock down frame buffer
1659 +        XSync(x_display, false);
1660 +        LOCK_FRAME_BUFFER;
1661 +
1662          // Start periodic thread
1663          XSync(x_display, false);
1664 <        redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1664 >        Set_pthread_attr(&redraw_thread_attr, 0);
1665 >        redraw_thread_cancel = false;
1666 >        redraw_thread_active = (pthread_create(&redraw_thread, &redraw_thread_attr, redraw_func, NULL) == 0);
1667          D(bug("Redraw thread installed (%ld)\n", redraw_thread));
1668          return true;
1669   }
# Line 647 | Line 1677 | void VideoExit(void)
1677   {
1678          // Stop redraw thread
1679          if (redraw_thread_active) {
1680 +                redraw_thread_cancel = true;
1681                  pthread_cancel(redraw_thread);
1682                  pthread_join(redraw_thread, NULL);
1683                  redraw_thread_active = false;
1684          }
1685  
1686 +        // Unlock frame buffer
1687 +        UNLOCK_FRAME_BUFFER;
1688 +        XSync(x_display, false);
1689 +        D(bug(" frame buffer unlocked\n"));
1690 +
1691 + #ifdef ENABLE_VOSF
1692 +        if (use_vosf) {
1693 +                // Deinitialize VOSF
1694 +                video_vosf_exit();
1695 +        }
1696 + #endif
1697 +
1698          // Close window and server connection
1699          if (x_display != NULL) {
1700                  XSync(x_display, false);
1701                  close_display();
1702                  XFlush(x_display);
1703                  XSync(x_display, false);
661                if (depth == 8) {
662                        XFreeColormap(x_display, cmap[0]);
663                        XFreeColormap(x_display, cmap[1]);
664                }
1704          }
1705 +
1706 + #ifdef ENABLE_FBDEV_DGA
1707 +        // Close framebuffer device
1708 +        if (fb_dev_fd >= 0) {
1709 +                close(fb_dev_fd);
1710 +                fb_dev_fd = -1;
1711 +        }
1712 + #endif
1713   }
1714  
1715  
# Line 670 | Line 1717 | void VideoExit(void)
1717   *  Suspend/resume emulator
1718   */
1719  
673 extern void PauseEmulator(void);
674 extern void ResumeEmulator(void);
675
1720   static void suspend_emul(void)
1721   {
1722          if (display_type == DIS_SCREEN) {
# Line 680 | Line 1724 | static void suspend_emul(void)
1724                  ADBKeyUp(0x36);
1725                  ctrl_down = false;
1726  
1727 <                // Pause MacOS thread
1728 <                PauseEmulator();
685 <                emul_suspended = true;
1727 >                // Lock frame buffer (this will stop the MacOS thread)
1728 >                LOCK_FRAME_BUFFER;
1729  
1730                  // Save frame buffer
1731                  fb_save = malloc(VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1732                  if (fb_save)
1733 <                        memcpy(fb_save, (void *)screen_base, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1733 >                        Mac2Host_memcpy(fb_save, screen_base, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1734  
1735                  // Close full screen display
1736 + #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1737   #ifdef ENABLE_XF86_DGA
1738 <                XF86DGADirectVideo(x_display, screen, 0);
1738 >                if (!is_fbdev_dga_mode)
1739 >                        XF86DGADirectVideo(x_display, screen, 0);
1740 > #endif
1741                  XUngrabPointer(x_display, CurrentTime);
1742                  XUngrabKeyboard(x_display, CurrentTime);
1743   #endif
1744 +                restore_mouse_accel();
1745 +                XUnmapWindow(x_display, the_win);
1746 +                wait_unmapped(the_win);
1747                  XSync(x_display, false);
1748  
1749                  // Open "suspend" window
1750                  XSetWindowAttributes wattr;
1751                  wattr.event_mask = KeyPressMask;
1752 <                wattr.background_pixel = black_pixel;
704 <                wattr.border_pixel = black_pixel;
1752 >                wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
1753                  wattr.backing_store = Always;
1754 <                wattr.backing_planes = xdepth;
1755 <                wattr.colormap = DefaultColormap(x_display, screen);
708 <                XSync(x_display, false);
1754 >                wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
1755 >
1756                  suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1757 <                        InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
1758 <                        CWBackingStore | CWBackingPlanes | (xdepth == 8 ? CWColormap : 0), &wattr);
1759 <                XSync(x_display, false);
1760 <                XStoreName(x_display, suspend_win, GetString(STR_SUSPEND_WINDOW_TITLE));
1761 <                XMapRaised(x_display, suspend_win);
715 <                XSync(x_display, false);
1757 >                                                                        InputOutput, vis, CWEventMask | CWBackPixel | CWBackingStore | CWColormap, &wattr);
1758 >                set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
1759 >                set_window_focus(suspend_win);
1760 >                XMapWindow(x_display, suspend_win);
1761 >                emul_suspended = true;
1762          }
1763   }
1764  
# Line 723 | Line 1769 | static void resume_emul(void)
1769          XSync(x_display, false);
1770  
1771          // Reopen full screen display
1772 <        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1773 <        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1774 <        XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1775 <        XF86DGASetViewPort(x_display, screen, 0, 0);
1772 >        XMapRaised(x_display, the_win);
1773 >        wait_mapped(the_win);
1774 >        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1775 >        Window w = is_fbdev_dga_mode ? the_win : rootwin;
1776 >        XGrabKeyboard(x_display, w, True, GrabModeAsync, GrabModeAsync, CurrentTime);
1777 >        XGrabPointer(x_display, w, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, is_fbdev_dga_mode ? w : None, None, CurrentTime);
1778 >        disable_mouse_accel();
1779 > #ifdef ENABLE_XF86_DGA
1780 >        if (!is_fbdev_dga_mode) {
1781 >                XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1782 >                XF86DGASetViewPort(x_display, screen, 0, 0);
1783 >        }
1784 > #endif
1785          XSync(x_display, false);
1786  
1787 +        // the_buffer already contains the data to restore. i.e. since a temporary
1788 +        // frame buffer is used when VOSF is actually used, fb_save is therefore
1789 +        // not necessary.
1790 + #ifdef ENABLE_VOSF
1791 +        if (use_vosf) {
1792 +                LOCK_VOSF;
1793 +                PFLAG_SET_ALL;
1794 +                memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1795 +                UNLOCK_VOSF;
1796 +        }
1797 + #endif
1798 +        
1799          // Restore frame buffer
1800          if (fb_save) {
1801 <                memcpy((void *)screen_base, fb_save, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1801 > #ifdef ENABLE_VOSF
1802 >                // Don't copy fb_save to the temporary frame buffer in VOSF mode
1803 >                if (!use_vosf)
1804 > #endif
1805 >                Host2Mac_memcpy(screen_base, fb_save, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1806                  free(fb_save);
1807                  fb_save = NULL;
1808          }
738        if (depth == 8)
739                palette_changed = true;
1809  
1810 <        // Resume MacOS thread
1810 >        // Unlock frame buffer (and continue MacOS thread)
1811 >        UNLOCK_FRAME_BUFFER;
1812          emul_suspended = false;
743        ResumeEmulator();
1813   }
1814  
1815  
# Line 904 | Line 1973 | static int kc_decode(KeySym ks)
1973          return -1;
1974   }
1975  
1976 < static int event2keycode(XKeyEvent *ev)
1976 > static int event2keycode(XKeyEvent &ev, bool key_down)
1977   {
1978          KeySym ks;
910        int as;
1979          int i = 0;
1980  
1981          do {
1982 <                ks = XLookupKeysym(ev, i++);
1983 <                as = kc_decode(ks);
1984 <                if (as != -1)
1982 >                ks = XLookupKeysym(&ev, i++);
1983 >                int as = kc_decode(ks);
1984 >                if (as >= 0)
1985 >                        return as;
1986 >                if (as == -2)
1987                          return as;
1988          } while (ks != NoSymbol);
1989  
# Line 926 | Line 1996 | static void handle_events(void)
1996          for (;;) {
1997                  XEvent event;
1998  
1999 <                if (!XCheckMaskEvent(x_display, eventmask, &event))
1999 >                XDisplayLock();
2000 >                if (!XCheckMaskEvent(x_display, eventmask, &event)) {
2001 >                        // Handle clipboard events
2002 >                        if (XCheckTypedEvent(x_display, SelectionRequest, &event))
2003 >                                ClipboardSelectionRequest(&event.xselectionrequest);
2004 >                        else if (XCheckTypedEvent(x_display, SelectionClear, &event))
2005 >                                ClipboardSelectionClear(&event.xselectionclear);
2006 >
2007 >                        // Window "close" widget clicked
2008 >                        else if (XCheckTypedEvent(x_display, ClientMessage, &event)) {
2009 >                                if (event.xclient.format == 32 && event.xclient.data.l[0] == WM_DELETE_WINDOW) {
2010 >                                        ADBKeyDown(0x7f);       // Power key
2011 >                                        ADBKeyUp(0x7f);
2012 >                                }
2013 >                        }
2014 >
2015 >                        XDisplayUnlock();
2016                          break;
2017 +                }
2018 +                XDisplayUnlock();
2019  
2020                  switch (event.type) {
2021                          // Mouse button
# Line 935 | Line 2023 | static void handle_events(void)
2023                                  unsigned int button = ((XButtonEvent *)&event)->button;
2024                                  if (button < 4)
2025                                          ADBMouseDown(button - 1);
2026 +                                else if (button < 6) {  // Wheel mouse
2027 +                                        if (mouse_wheel_mode == 0) {
2028 +                                                int key = (button == 5) ? 0x79 : 0x74;  // Page up/down
2029 +                                                ADBKeyDown(key);
2030 +                                                ADBKeyUp(key);
2031 +                                        } else {
2032 +                                                int key = (button == 5) ? 0x3d : 0x3e;  // Cursor up/down
2033 +                                                for(int i=0; i<mouse_wheel_lines; i++) {
2034 +                                                        ADBKeyDown(key);
2035 +                                                        ADBKeyUp(key);
2036 +                                                }
2037 +                                        }
2038 +                                }
2039                                  break;
2040                          }
2041                          case ButtonRelease: {
# Line 944 | Line 2045 | static void handle_events(void)
2045                                  break;
2046                          }
2047  
2048 <                        // Mouse moved
2048 >                        // Mouse entered window
2049                          case EnterNotify:
2050 <                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
2050 >                                if (event.xcrossing.mode != NotifyGrab && event.xcrossing.mode != NotifyUngrab)
2051 >                                        ADBMouseMoved(event.xmotion.x, event.xmotion.y);
2052                                  break;
2053 +
2054 +                        // Mouse moved
2055                          case MotionNotify:
2056 <                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
2056 >                                ADBMouseMoved(event.xmotion.x, event.xmotion.y);
2057                                  break;
2058  
2059                          // Keyboard
2060                          case KeyPress: {
2061 <                                int code;
2062 <                                if ((code = event2keycode((XKeyEvent *)&event)) != -1) {
2061 >                                int code = -1;
2062 >                                if (use_keycodes) {
2063 >                                        if (event2keycode(event.xkey, true) != -2)      // This is called to process the hotkeys
2064 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2065 >                                } else
2066 >                                        code = event2keycode(event.xkey, true);
2067 >                                if (code >= 0) {
2068                                          if (!emul_suspended) {
2069 <                                                ADBKeyDown(code);
2069 >                                                if (code == 0x39) {     // Caps Lock pressed
2070 >                                                        if (caps_on) {
2071 >                                                                ADBKeyUp(code);
2072 >                                                                caps_on = false;
2073 >                                                        } else {
2074 >                                                                ADBKeyDown(code);
2075 >                                                                caps_on = true;
2076 >                                                        }
2077 >                                                } else
2078 >                                                        ADBKeyDown(code);
2079                                                  if (code == 0x36)
2080                                                          ctrl_down = true;
2081                                          } else {
# Line 968 | Line 2086 | static void handle_events(void)
2086                                  break;
2087                          }
2088                          case KeyRelease: {
2089 <                                int code;
2090 <                                if ((code = event2keycode((XKeyEvent *)&event)) != -1) {
2089 >                                int code = -1;
2090 >                                if (use_keycodes) {
2091 >                                        if (event2keycode(event.xkey, false) != -2)     // This is called to process the hotkeys
2092 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2093 >                                } else
2094 >                                        code = event2keycode(event.xkey, false);
2095 >                                if (code >= 0 && code != 0x39) {        // Don't propagate Caps Lock releases
2096                                          ADBKeyUp(code);
2097                                          if (code == 0x36)
2098                                                  ctrl_down = false;
# Line 979 | Line 2102 | static void handle_events(void)
2102  
2103                          // Hidden parts exposed, force complete refresh
2104                          case Expose:
2105 <                                memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
2105 > #ifdef ENABLE_VOSF
2106 >                                if (use_vosf) {                 // VOSF refresh
2107 >                                        LOCK_VOSF;
2108 >                                        PFLAG_SET_ALL;
2109 >                                        memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
2110 >                                        UNLOCK_VOSF;
2111 >                                }
2112 >                                else
2113 > #endif
2114 >                                        memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
2115                                  break;
2116                  }
2117          }
# Line 995 | Line 2127 | void VideoVBL(void)
2127          if (emerg_quit)
2128                  QuitEmulator();
2129  
2130 +        // Temporarily give up frame buffer lock (this is the point where
2131 +        // we are suspended when the user presses Ctrl-Tab)
2132 +        UNLOCK_FRAME_BUFFER;
2133 +        LOCK_FRAME_BUFFER;
2134 +
2135          // Execute video VBL
2136          if (private_data != NULL && private_data->interruptsEnabled)
2137                  VSLDoInterruptService(private_data->vslServiceID);
# Line 1002 | Line 2139 | void VideoVBL(void)
2139  
2140  
2141   /*
1005 *  Install graphics acceleration
1006 */
1007
1008 #if 0
1009 // Rectangle blitting
1010 static void accl_bitblt(accl_params *p)
1011 {
1012        D(bug("accl_bitblt\n"));
1013
1014        // Get blitting parameters
1015        int16 src_X = p->src_rect[1] - p->src_bounds[1];
1016        int16 src_Y = p->src_rect[0] - p->src_bounds[0];
1017        int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1018        int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1019        int16 width = p->dest_rect[3] - p->dest_rect[1] - 1;
1020        int16 height = p->dest_rect[2] - p->dest_rect[0] - 1;
1021        D(bug(" src X %d, src Y %d, dest X %d, dest Y %d\n", src_X, src_Y, dest_X, dest_Y));
1022        D(bug(" width %d, height %d\n", width, height));
1023
1024        // And perform the blit
1025        bitblt_hook(src_X, src_Y, dest_X, dest_Y, width, height);
1026 }
1027
1028 static bool accl_bitblt_hook(accl_params *p)
1029 {
1030        D(bug("accl_draw_hook %p\n", p));
1031
1032        // Check if we can accelerate this bitblt
1033        if (p->src_base_addr == screen_base && p->dest_base_addr == screen_base &&
1034                display_type == DIS_SCREEN && bitblt_hook != NULL &&
1035                ((uint32 *)p)[0x18 >> 2] + ((uint32 *)p)[0x128 >> 2] == 0 &&
1036                ((uint32 *)p)[0x130 >> 2] == 0 &&
1037                p->transfer_mode == 0 &&
1038                p->src_row_bytes > 0 && ((uint32 *)p)[0x15c >> 2] > 0) {
1039
1040                // Yes, set function pointer
1041                p->draw_proc = accl_bitblt;
1042                return true;
1043        }
1044        return false;
1045 }
1046
1047 // Rectangle filling/inversion
1048 static void accl_fillrect8(accl_params *p)
1049 {
1050        D(bug("accl_fillrect8\n"));
1051
1052        // Get filling parameters
1053        int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1054        int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1055        int16 dest_X_max = p->dest_rect[3] - p->dest_bounds[1] - 1;
1056        int16 dest_Y_max = p->dest_rect[2] - p->dest_bounds[0] - 1;
1057        uint8 color = p->pen_mode == 8 ? p->fore_pen : p->back_pen;
1058        D(bug(" dest X %d, dest Y %d\n", dest_X, dest_Y));
1059        D(bug(" dest X max %d, dest Y max %d\n", dest_X_max, dest_Y_max));
1060
1061        // And perform the fill
1062        fillrect8_hook(dest_X, dest_Y, dest_X_max, dest_Y_max, color);
1063 }
1064
1065 static void accl_fillrect32(accl_params *p)
1066 {
1067        D(bug("accl_fillrect32\n"));
1068
1069        // Get filling parameters
1070        int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1071        int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1072        int16 dest_X_max = p->dest_rect[3] - p->dest_bounds[1] - 1;
1073        int16 dest_Y_max = p->dest_rect[2] - p->dest_bounds[0] - 1;
1074        uint32 color = p->pen_mode == 8 ? p->fore_pen : p->back_pen;
1075        D(bug(" dest X %d, dest Y %d\n", dest_X, dest_Y));
1076        D(bug(" dest X max %d, dest Y max %d\n", dest_X_max, dest_Y_max));
1077
1078        // And perform the fill
1079        fillrect32_hook(dest_X, dest_Y, dest_X_max, dest_Y_max, color);
1080 }
1081
1082 static void accl_invrect(accl_params *p)
1083 {
1084        D(bug("accl_invrect\n"));
1085
1086        // Get inversion parameters
1087        int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1088        int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1089        int16 dest_X_max = p->dest_rect[3] - p->dest_bounds[1] - 1;
1090        int16 dest_Y_max = p->dest_rect[2] - p->dest_bounds[0] - 1;
1091        D(bug(" dest X %d, dest Y %d\n", dest_X, dest_Y));
1092        D(bug(" dest X max %d, dest Y max %d\n", dest_X_max, dest_Y_max));
1093
1094        //!!?? pen_mode == 14
1095
1096        // And perform the inversion
1097        invrect_hook(dest_X, dest_Y, dest_X_max, dest_Y_max);
1098 }
1099
1100 static bool accl_fillrect_hook(accl_params *p)
1101 {
1102        D(bug("accl_fillrect_hook %p\n", p));
1103
1104        // Check if we can accelerate this fillrect
1105        if (p->dest_base_addr == screen_base && ((uint32 *)p)[0x284 >> 2] != 0 && display_type == DIS_SCREEN) {
1106                if (p->transfer_mode == 8) {
1107                        // Fill
1108                        if (p->dest_pixel_size == 8 && fillrect8_hook != NULL) {
1109                                p->draw_proc = accl_fillrect8;
1110                                return true;
1111                        } else if (p->dest_pixel_size == 32 && fillrect32_hook != NULL) {
1112                                p->draw_proc = accl_fillrect32;
1113                                return true;
1114                        }
1115                } else if (p->transfer_mode == 10 && invrect_hook != NULL) {
1116                        // Invert
1117                        p->draw_proc = accl_invrect;
1118                        return true;
1119                }
1120        }
1121        return false;
1122 }
1123
1124 // Wait for graphics operation to finish
1125 static bool accl_sync_hook(void *arg)
1126 {
1127        D(bug("accl_sync_hook %p\n", arg));
1128        if (sync_hook != NULL)
1129                sync_hook();
1130        return true;
1131 }
1132
1133 static struct accl_hook_info bitblt_hook_info = {accl_bitblt_hook, accl_sync_hook, ACCL_BITBLT};
1134 static struct accl_hook_info fillrect_hook_info = {accl_fillrect_hook, accl_sync_hook, ACCL_FILLRECT};
1135 #endif
1136
1137 void VideoInstallAccel(void)
1138 {
1139        // Install acceleration hooks
1140        if (PrefsFindBool("gfxaccel")) {
1141                D(bug("Video: Installing acceleration hooks\n"));
1142 //!!    NQDMisc(6, &bitblt_hook_info);
1143 //              NQDMisc(6, &fillrect_hook_info);
1144        }
1145 }
1146
1147
1148 /*
2142   *  Change video mode
2143   */
2144  
# Line 1203 | Line 2196 | int16 video_mode_change(VidLocals *csSav
2196  
2197   void video_set_palette(void)
2198   {
2199 +        LOCK_PALETTE;
2200 +
2201 +        // Convert colors to XColor array
2202 +        int mode = get_current_mode();
2203 +        int num_in = palette_size(mode);
2204 +        int num_out = 256;
2205 +        bool stretch = false;
2206 +        if (IsDirectMode(mode)) {
2207 +                // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries
2208 +                num_out = vis->map_entries;
2209 +                stretch = true;
2210 +        }
2211 +        XColor *p = x_palette;
2212 +        for (int i=0; i<num_out; i++) {
2213 +                int c = (stretch ? (i * num_in) / num_out : i);
2214 +                p->red = mac_pal[c].red * 0x0101;
2215 +                p->green = mac_pal[c].green * 0x0101;
2216 +                p->blue = mac_pal[c].blue * 0x0101;
2217 +                p++;
2218 +        }
2219 +
2220 + #ifdef ENABLE_VOSF
2221 +        // Recalculate pixel color expansion map
2222 +        if (!IsDirectMode(mode) && xdepth > 8) {
2223 +                for (int i=0; i<256; i++) {
2224 +                        int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
2225 +                        ExpandMap[i] = map_rgb(mac_pal[c].red, mac_pal[c].green, mac_pal[c].blue);
2226 +                }
2227 +
2228 +                // We have to redraw everything because the interpretation of pixel values changed
2229 +                LOCK_VOSF;
2230 +                PFLAG_SET_ALL;
2231 +                if (display_type == DIS_SCREEN)
2232 +                        PFLAG_SET_VERY_DIRTY;
2233 +                UNLOCK_VOSF;
2234 +        }
2235 + #endif
2236 +
2237 +        // Tell redraw thread to change palette
2238          palette_changed = true;
2239 +
2240 +        UNLOCK_PALETTE;
2241 + }
2242 +
2243 +
2244 + /*
2245 + *  Can we set the MacOS cursor image into the window?
2246 + */
2247 +
2248 + bool video_can_change_cursor(void)
2249 + {
2250 +        return hw_mac_cursor_accl && (display_type != DIS_SCREEN);
2251   }
2252  
2253  
# Line 1330 | Line 2374 | static void update_display(void)
2374  
2375          // Refresh display
2376          if (high && wide) {
2377 +                XDisplayLock();
2378                  if (have_shm)
2379                          XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
2380                  else
2381                          XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
2382 +                XDisplayUnlock();
2383 +        }
2384 + }
2385 +
2386 + const int VIDEO_REFRESH_HZ = 60;
2387 + const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
2388 +
2389 + static void handle_palette_changes(void)
2390 + {
2391 +        LOCK_PALETTE;
2392 +
2393 +        if (palette_changed && !emul_suspended) {
2394 +                palette_changed = false;
2395 +
2396 +                int mode = get_current_mode();
2397 +                if (color_class == PseudoColor || color_class == DirectColor) {
2398 +                        int num = vis->map_entries;
2399 +                        bool set_clut = true;
2400 +                        if (!IsDirectMode(mode) && color_class == DirectColor) {
2401 +                                if (display_type == DIS_WINDOW)
2402 +                                        set_clut = false; // Indexed mode on true color screen, don't set CLUT
2403 +                        }
2404 +
2405 +                        if (set_clut) {
2406 +                                XDisplayLock();
2407 +                                XStoreColors(x_display, cmap[0], x_palette, num);
2408 +                                XStoreColors(x_display, cmap[1], x_palette, num);
2409 +                                XSync(x_display, false);
2410 +                                XDisplayUnlock();
2411 +                        }
2412 +                }
2413 +
2414 + #ifdef ENABLE_XF86_DGA
2415 +                if (display_type == DIS_SCREEN && !is_fbdev_dga_mode) {
2416 +                        current_dga_cmap ^= 1;
2417 +                        if (!IsDirectMode(mode) && cmap[current_dga_cmap])
2418 +                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
2419 +                }
2420 + #endif
2421          }
2422 +
2423 +        UNLOCK_PALETTE;
2424   }
2425  
2426   static void *redraw_func(void *arg)
2427   {
2428 <        int tick_counter = 0;
1343 <        struct timespec req = {0, 16666667};
2428 >        int fd = ConnectionNumber(x_display);
2429  
2430 <        for (;;) {
2430 >        uint64 start = GetTicks_usec();
2431 >        int64 ticks = 0;
2432 >        uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2433  
2434 <                // Wait
1348 <                nanosleep(&req, NULL);
2434 >        while (!redraw_thread_cancel) {
2435  
2436                  // Pause if requested (during video mode switches)
2437                  while (thread_stop_req)
2438                          thread_stop_ack = true;
2439  
2440 <                // Handle X11 events
2441 <                handle_events();
2440 >                int64 delay = next - GetTicks_usec();
2441 >                if (delay < -VIDEO_REFRESH_DELAY) {
2442 >
2443 >                        // We are lagging far behind, so we reset the delay mechanism
2444 >                        next = GetTicks_usec();
2445 >
2446 >                } else if (delay <= 0) {
2447 >
2448 >                        // Delay expired, refresh display
2449 >                        next += VIDEO_REFRESH_DELAY;
2450 >                        ticks++;
2451 >
2452 >                        // Handle X11 events
2453 >                        handle_events();
2454  
2455 <                // Quit DGA mode if requested
2456 <                if (quit_full_screen) {
2457 <                        quit_full_screen = false;
2458 <                        if (display_type == DIS_SCREEN) {
2455 >                        // Quit DGA mode if requested
2456 >                        if (quit_full_screen) {
2457 >                                quit_full_screen = false;
2458 >                                if (display_type == DIS_SCREEN) {
2459 >                                        XDisplayLock();
2460 > #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
2461   #ifdef ENABLE_XF86_DGA
2462 <                                XF86DGADirectVideo(x_display, screen, 0);
2463 <                                XUngrabPointer(x_display, CurrentTime);
1364 <                                XUngrabKeyboard(x_display, CurrentTime);
2462 >                                        if (!is_fbdev_dga_mode)
2463 >                                                XF86DGADirectVideo(x_display, screen, 0);
2464   #endif
2465 <                                XSync(x_display, false);
2466 <                                quit_full_screen_ack = true;
2467 <                                return NULL;
2465 >                                        XUngrabPointer(x_display, CurrentTime);
2466 >                                        XUngrabKeyboard(x_display, CurrentTime);
2467 >                                        XUnmapWindow(x_display, the_win);
2468 >                                        wait_unmapped(the_win);
2469 >                                        XDestroyWindow(x_display, the_win);
2470 > #endif
2471 >                                        XSync(x_display, false);
2472 >                                        XDisplayUnlock();
2473 >                                        quit_full_screen_ack = true;
2474 >                                        return NULL;
2475 >                                }
2476                          }
1370                }
2477  
2478 <                // Refresh display and set cursor image in window mode
2479 <                if (display_type == DIS_WINDOW) {
2480 <                        tick_counter++;
2481 <                        if (tick_counter >= frame_skip) {
2482 <                                tick_counter = 0;
2483 <
2484 <                                // Update display
2485 <                                update_display();
2486 <
2487 <                                // Set new cursor image if it was changed
2488 <                                if (cursor_changed) {
2489 <                                        cursor_changed = false;
2490 <                                        memcpy(cursor_image->data, MacCursor + 4, 32);
2491 <                                        memcpy(cursor_mask_image->data, MacCursor + 36, 32);
2492 <                                        XFreeCursor(x_display, mac_cursor);
2493 <                                        XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
2494 <                                        XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
2495 <                                        mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, MacCursor[2], MacCursor[3]);
2496 <                                        XDefineCursor(x_display, the_win, mac_cursor);
2478 >                        // Refresh display and set cursor image in window mode
2479 >                        static int tick_counter = 0;
2480 >                        if (display_type == DIS_WINDOW) {
2481 >                                tick_counter++;
2482 >                                if (tick_counter >= frame_skip) {
2483 >                                        tick_counter = 0;
2484 >
2485 >                                        // Update display
2486 > #ifdef ENABLE_VOSF
2487 >                                        if (use_vosf) {
2488 >                                                XDisplayLock();
2489 >                                                if (mainBuffer.dirty) {
2490 >                                                        LOCK_VOSF;
2491 >                                                        update_display_window_vosf();
2492 >                                                        UNLOCK_VOSF;
2493 >                                                        XSync(x_display, false); // Let the server catch up
2494 >                                                }
2495 >                                                XDisplayUnlock();
2496 >                                        }
2497 >                                        else
2498 > #endif
2499 >                                                update_display();
2500 >
2501 >                                        // Set new cursor image if it was changed
2502 >                                        if (hw_mac_cursor_accl && cursor_changed) {
2503 >                                                cursor_changed = false;
2504 >                                                uint8 *x_data = (uint8 *)cursor_image->data;
2505 >                                                uint8 *x_mask = (uint8 *)cursor_mask_image->data;
2506 >                                                for (int i = 0; i < 32; i++) {
2507 >                                                        x_mask[i] = MacCursor[4 + i] | MacCursor[36 + i];
2508 >                                                        x_data[i] = MacCursor[4 + i];
2509 >                                                }
2510 >                                                XDisplayLock();
2511 >                                                XFreeCursor(x_display, mac_cursor);
2512 >                                                XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
2513 >                                                XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
2514 >                                                mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, MacCursor[2], MacCursor[3]);
2515 >                                                XDefineCursor(x_display, the_win, mac_cursor);
2516 >                                                XDisplayUnlock();
2517 >                                        }
2518                                  }
2519                          }
2520 <                }
2521 <
2522 <                // Set new palette if it was changed
2523 <                if (palette_changed && !emul_suspended) {
2524 <                        palette_changed = false;
2525 <                        XColor c[256];
2526 <                        for (int i=0; i<256; i++) {
2527 <                                c[i].pixel = i;
2528 <                                c[i].red = mac_pal[i].red * 0x0101;
2529 <                                c[i].green = mac_pal[i].green * 0x0101;
1403 <                                c[i].blue = mac_pal[i].blue * 0x0101;
1404 <                                c[i].flags = DoRed | DoGreen | DoBlue;
1405 <                        }
1406 <                        if (depth == 8) {
1407 <                                XStoreColors(x_display, cmap[0], c, 256);
1408 <                                XStoreColors(x_display, cmap[1], c, 256);
1409 < #ifdef ENABLE_XF86_DGA
1410 <                                if (display_type == DIS_SCREEN) {
1411 <                                        current_dga_cmap ^= 1;
1412 <                                        XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
2520 > #ifdef ENABLE_VOSF
2521 >                        else if (use_vosf) {
2522 >                                // Update display (VOSF variant)
2523 >                                if (++tick_counter >= frame_skip) {
2524 >                                        tick_counter = 0;
2525 >                                        if (mainBuffer.dirty) {
2526 >                                                LOCK_VOSF;
2527 >                                                update_display_dga_vosf();
2528 >                                                UNLOCK_VOSF;
2529 >                                        }
2530                                  }
1414 #endif
2531                          }
2532 + #endif
2533 +
2534 +                        // Set new palette if it was changed
2535 +                        handle_palette_changes();
2536 +
2537 +                } else {
2538 +
2539 +                        // No display refresh pending, check for X events
2540 +                        fd_set readfds;
2541 +                        FD_ZERO(&readfds);
2542 +                        FD_SET(fd, &readfds);
2543 +                        struct timeval timeout;
2544 +                        timeout.tv_sec = 0;
2545 +                        timeout.tv_usec = delay;
2546 +                        if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0)
2547 +                                handle_events();
2548                  }
2549          }
2550          return NULL;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines