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.6 by gbeauche, 2003-11-21T17:01:33Z vs.
Revision 1.42 by gbeauche, 2005-05-12T11:20:00Z

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines