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.3 by gbeauche, 2003-05-22T22:12:05Z vs.
Revision 1.15 by gbeauche, 2004-04-13T22:22:21Z

# 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-2004 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 + #include "sysdeps.h"
22 +
23   #include <X11/Xlib.h>
24   #include <X11/Xutil.h>
25   #include <X11/keysym.h>
26   #include <X11/extensions/XShm.h>
27   #include <sys/ipc.h>
28   #include <sys/shm.h>
29 + #include <errno.h>
30   #include <pthread.h>
31  
32 < #include "sysdeps.h"
32 > #include <algorithm>
33 >
34 > #ifdef ENABLE_XF86_DGA
35 > # include <X11/extensions/xf86dga.h>
36 > #endif
37 >
38 > #ifdef ENABLE_XF86_VIDMODE
39 > # include <X11/extensions/xf86vmode.h>
40 > #endif
41 >
42   #include "main.h"
43   #include "adb.h"
44   #include "prefs.h"
# Line 38 | Line 50
50   #define DEBUG 0
51   #include "debug.h"
52  
53 < #ifdef ENABLE_XF86_DGA
54 < #include <X11/extensions/xf86dga.h>
53 > #ifndef NO_STD_NAMESPACE
54 > using std::sort;
55   #endif
56  
45 #ifdef ENABLE_XF86_VIDMODE
46 #include <X11/extensions/xf86vmode.h>
47 #endif
57  
58 + // Constants
59 + const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
60  
61   // Global variables
62   static int32 frame_skip;
63 + static int16 mouse_wheel_mode;
64 + static int16 mouse_wheel_lines;
65   static bool redraw_thread_active = false;       // Flag: Redraw thread installed
66 + static pthread_attr_t redraw_thread_attr;       // Redraw thread attributes
67   static pthread_t redraw_thread;                         // Redraw thread
68  
69 + static bool local_X11;                                          // Flag: X server running on local machine?
70   static volatile bool thread_stop_req = false;
71   static volatile bool thread_stop_ack = false;   // Acknowledge for thread_stop_req
72  
# Line 73 | Line 88 | static bool emerg_quit = false;                                // Fl
88   static bool emul_suspended = false;                     // Flag: emulator suspended
89   static Window suspend_win;                                      // "Suspend" window
90   static void *fb_save = NULL;                            // Saved frame buffer for suspend
91 + static bool use_keycodes = false;                       // Flag: Use keycodes rather than keysyms
92 + static int keycode_table[256];                          // X keycode -> Mac keycode translation table
93  
94   // X11 variables
95   static int screen;                                                      // Screen number
96   static int xdepth;                                                      // Depth of X screen
97   static int depth;                                                       // Depth of Mac frame buffer
98   static Window rootwin, the_win;                         // Root window and our window
99 + static int num_depths = 0;                                      // Number of available X depths
100 + static int *avail_depths = NULL;                        // List of available X depths
101   static XVisualInfo visualInfo;
102   static Visual *vis;
103 + static int color_class;
104 + static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
105   static Colormap cmap[2];                                        // Two colormaps (DGA) for 8-bit mode
106 + static XColor x_palette[256];                           // Color palette to be used as CLUT and gamma table
107 +
108   static XColor black, white;
109   static unsigned long black_pixel, white_pixel;
110   static int eventmask;
111 < static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask;
112 < static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
111 > static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
112 > static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
113  
114   // Variables for window mode
115   static GC the_gc;
# Line 103 | Line 126 | static uint8 *the_buffer_copy = NULL;          /
126   static uint32 the_buffer_size;                          // Size of allocated the_buffer
127  
128   // Variables for DGA mode
106 static char *dga_screen_base;
107 static int dga_fb_width;
129   static int current_dga_cmap;
130  
131   #ifdef ENABLE_XF86_VIDMODE
# Line 113 | Line 134 | static XF86VidModeModeInfo **x_video_mod
134   static int num_x_video_modes;
135   #endif
136  
137 + // Mutex to protect palette
138 + #ifdef HAVE_SPINLOCKS
139 + static spinlock_t x_palette_lock = SPIN_LOCK_UNLOCKED;
140 + #define LOCK_PALETTE spin_lock(&x_palette_lock)
141 + #define UNLOCK_PALETTE spin_unlock(&x_palette_lock)
142 + #elif defined(HAVE_PTHREADS)
143 + static pthread_mutex_t x_palette_lock = PTHREAD_MUTEX_INITIALIZER;
144 + #define LOCK_PALETTE pthread_mutex_lock(&x_palette_lock)
145 + #define UNLOCK_PALETTE pthread_mutex_unlock(&x_palette_lock)
146 + #else
147 + #define LOCK_PALETTE
148 + #define UNLOCK_PALETTE
149 + #endif
150 +
151  
152   // Prototypes
153   static void *redraw_func(void *arg);
154  
155  
156 < // From main_linux.cpp
156 > // From main_unix.cpp
157 > extern char *x_display_name;
158   extern Display *x_display;
159  
160   // From sys_unix.cpp
161   extern void SysMountFirstFloppy(void);
162  
163 + // From clip_unix.cpp
164 + extern void ClipboardSelectionClear(XSelectionClearEvent *);
165 + extern void ClipboardSelectionRequest(XSelectionRequestEvent *);
166 +
167  
168   // Video acceleration through SIGSEGV
169   #ifdef ENABLE_VOSF
# Line 132 | Line 172 | extern void SysMountFirstFloppy(void);
172  
173  
174   /*
175 + *  Utility functions
176 + */
177 +
178 + // Get current video mode
179 + static inline int get_current_mode(void)
180 + {
181 +        return VModes[cur_mode].viAppleMode;
182 + }
183 +
184 + // Find palette size for given color depth
185 + static int palette_size(int mode)
186 + {
187 +        switch (mode) {
188 +        case APPLE_1_BIT: return 2;
189 +        case APPLE_2_BIT: return 4;
190 +        case APPLE_4_BIT: return 16;
191 +        case APPLE_8_BIT: return 256;
192 +        case APPLE_16_BIT: return 32;
193 +        case APPLE_32_BIT: return 256;
194 +        default: return 0;
195 +        }
196 + }
197 +
198 + // Map video_mode depth ID to numerical depth value
199 + static inline int depth_of_video_mode(int mode)
200 + {
201 +        int depth = -1;
202 +        switch (mode) {
203 +        case APPLE_1_BIT:
204 +                depth = 1;
205 +                break;
206 +        case APPLE_2_BIT:
207 +                depth = 2;
208 +                break;
209 +        case APPLE_4_BIT:
210 +                depth = 4;
211 +                break;
212 +        case APPLE_8_BIT:
213 +                depth = 8;
214 +                break;
215 +        case APPLE_16_BIT:
216 +                depth = 16;
217 +                break;
218 +        case APPLE_32_BIT:
219 +                depth = 32;
220 +                break;
221 +        default:
222 +                abort();
223 +        }
224 +        return depth;
225 + }
226 +
227 + // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
228 + static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
229 + {
230 +        return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
231 + }
232 +
233 +
234 + // Do we have a visual for handling the specified Mac depth? If so, set the
235 + // global variables "xdepth", "visualInfo", "vis" and "color_class".
236 + static bool find_visual_for_depth(int depth)
237 + {
238 +        D(bug("have_visual_for_depth(%d)\n", depth_of_video_mode(depth)));
239 +
240 +        // 1-bit works always and uses default visual
241 +        if (depth == APPLE_1_BIT) {
242 +                vis = DefaultVisual(x_display, screen);
243 +                visualInfo.visualid = XVisualIDFromVisual(vis);
244 +                int num = 0;
245 +                XVisualInfo *vi = XGetVisualInfo(x_display, VisualIDMask, &visualInfo, &num);
246 +                visualInfo = vi[0];
247 +                XFree(vi);
248 +                xdepth = visualInfo.depth;
249 +                color_class = visualInfo.c_class;
250 +                D(bug(" found visual ID 0x%02x, depth %d\n", visualInfo.visualid, xdepth));
251 +                return true;
252 +        }
253 +
254 +        // Calculate minimum and maximum supported X depth
255 +        int min_depth = 1, max_depth = 32;
256 +        switch (depth) {
257 + #ifdef ENABLE_VOSF
258 +                case APPLE_2_BIT:
259 +                case APPLE_4_BIT:       // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit
260 +                case APPLE_8_BIT:
261 +                        min_depth = 8;
262 +                        max_depth = 32;
263 +                        break;
264 + #else
265 +                case APPLE_2_BIT:
266 +                case APPLE_4_BIT:       // 2/4-bit requires VOSF blitters
267 +                        return false;
268 +                case APPLE_8_BIT:       // 8-bit without VOSF requires an 8-bit visual
269 +                        min_depth = 8;
270 +                        max_depth = 8;
271 +                        break;
272 + #endif
273 +                case APPLE_16_BIT:      // 16-bit requires a 15/16-bit visual
274 +                        min_depth = 15;
275 +                        max_depth = 16;
276 +                        break;
277 +                case APPLE_32_BIT:      // 32-bit requires a 24/32-bit visual
278 +                        min_depth = 24;
279 +                        max_depth = 32;
280 +                        break;
281 +        }
282 +        D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth));
283 +
284 +        // Try to find a visual for one of the color depths
285 +        bool visual_found = false;
286 +        for (int i=0; i<num_depths && !visual_found; i++) {
287 +
288 +                xdepth = avail_depths[i];
289 +                D(bug(" trying to find visual for depth %d\n", xdepth));
290 +                if (xdepth < min_depth || xdepth > max_depth)
291 +                        continue;
292 +
293 +                // Determine best color class for this depth
294 +                switch (xdepth) {
295 +                        case 1: // Try StaticGray or StaticColor
296 +                                if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo)
297 +                                 || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo))
298 +                                        visual_found = true;
299 +                                break;
300 +                        case 8: // Need PseudoColor
301 +                                if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo))
302 +                                        visual_found = true;
303 +                                break;
304 +                        case 15:
305 +                        case 16:
306 +                        case 24:
307 +                        case 32: // Try DirectColor first, as this will allow gamma correction
308 +                                if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo)
309 +                                 || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo))
310 +                                        visual_found = true;
311 +                                break;
312 +                        default:
313 +                                D(bug("  not a supported depth\n"));
314 +                                break;
315 +                }
316 +        }
317 +        if (!visual_found)
318 +                return false;
319 +
320 +        // Visual was found
321 +        vis = visualInfo.visual;
322 +        color_class = visualInfo.c_class;
323 +        D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth));
324 + #if DEBUG
325 +        switch (color_class) {
326 +                case StaticGray: D(bug("StaticGray\n")); break;
327 +                case GrayScale: D(bug("GrayScale\n")); break;
328 +                case StaticColor: D(bug("StaticColor\n")); break;
329 +                case PseudoColor: D(bug("PseudoColor\n")); break;
330 +                case TrueColor: D(bug("TrueColor\n")); break;
331 +                case DirectColor: D(bug("DirectColor\n")); break;
332 +        }
333 + #endif
334 +        return true;
335 + }
336 +
337 +
338 + /*
339   *  Open display (window or fullscreen)
340   */
341  
342 + // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
343 + static Atom WM_DELETE_WINDOW = (Atom)0;
344 + static void set_window_delete_protocol(Window w)
345 + {
346 +        WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
347 +        XSetWMProtocols(x_display, w, &WM_DELETE_WINDOW, 1);
348 + }
349 +
350 + // Wait until window is mapped/unmapped
351 + static void wait_mapped(Window w)
352 + {
353 +        XEvent e;
354 +        do {
355 +                XMaskEvent(x_display, StructureNotifyMask, &e);
356 +        } while ((e.type != MapNotify) || (e.xmap.event != w));
357 + }
358 +
359 + static void wait_unmapped(Window w)
360 + {
361 +        XEvent e;
362 +        do {
363 +                XMaskEvent(x_display, StructureNotifyMask, &e);
364 +        } while ((e.type != UnmapNotify) || (e.xmap.event != w));
365 + }
366 +
367   // Trap SHM errors
368   static bool shm_error = false;
369   static int (*old_error_handler)(Display *, XErrorEvent *);
# Line 157 | Line 386 | static bool open_window(int width, int h
386          // Set absolute mouse mode
387          ADBSetRelMouseMode(false);
388  
160        // Read frame skip prefs
161        frame_skip = PrefsFindInt32("frameskip");
162        if (frame_skip == 0)
163                frame_skip = 1;
164
389          // Create window
390          XSetWindowAttributes wattr;
391          wattr.event_mask = eventmask = win_eventmask;
392 <        wattr.background_pixel = black_pixel;
393 <        wattr.border_pixel = black_pixel;
392 >        wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
393 >        wattr.border_pixel = 0;
394          wattr.backing_store = NotUseful;
395 <
172 <        XSync(x_display, false);
395 >        wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
396          the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
397 <                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWBackingStore, &wattr);
398 <        XSync(x_display, false);
397 >                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWBackingStore | CWColormap, &wattr);
398 >
399 >        // Set window name
400          XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
177        XMapRaised(x_display, the_win);
178        XSync(x_display, false);
401  
402 <        // Set colormap
403 <        if (depth == 8) {
182 <                XSetWindowColormap(x_display, the_win, cmap[0]);
183 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
184 <        }
402 >        // Set delete protocol property
403 >        set_window_delete_protocol(the_win);
404  
405          // Make window unresizable
406          XSizeHints *hints;
# Line 195 | Line 414 | static bool open_window(int width, int h
414                  XFree((char *)hints);
415          }
416  
417 +        // Show window
418 +        XMapWindow(x_display, the_win);
419 +        wait_mapped(the_win);
420 +
421 +        // 1-bit mode is big-endian; if the X server is little-endian, we can't
422 +        // use SHM because that doesn't allow changing the image byte order
423 +        bool need_msb_image = (depth == 1 && XImageByteOrder(x_display) == LSBFirst);
424 +
425          // Try to create and attach SHM image
426          have_shm = false;
427 <        if (depth != 1 && XShmQueryExtension(x_display)) {
427 >        if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
428  
429                  // Create SHM image ("height + 2" for safety)
430 <                img = XShmCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
431 <                shminfo.shmid = shmget(IPC_PRIVATE, (height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
430 >                img = XShmCreateImage(x_display, vis, depth == 1 ? 1 : xdepth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
431 >                shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
432 >                D(bug(" shm image created\n"));
433                  the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
434                  shminfo.shmaddr = img->data = (char *)the_buffer_copy;
435                  shminfo.readOnly = False;
# Line 220 | Line 448 | static bool open_window(int width, int h
448                          have_shm = true;
449                          shmctl(shminfo.shmid, IPC_RMID, 0);
450                  }
451 +                D(bug(" shm image attached\n"));
452          }
453  
454          // Create normal X image if SHM doesn't work ("height + 2" for safety)
455          if (!have_shm) {
456 <                int bytes_per_row = aligned_width;
228 <                switch (depth) {
229 <                        case 1:
230 <                                bytes_per_row /= 8;
231 <                                break;
232 <                        case 15:
233 <                        case 16:
234 <                                bytes_per_row *= 2;
235 <                                break;
236 <                        case 24:
237 <                        case 32:
238 <                                bytes_per_row *= 4;
239 <                                break;
240 <                }
456 >                int bytes_per_row = depth == 1 ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth));
457                  the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
458                  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);
459 +                D(bug(" X image created\n"));
460          }
461  
462          // 1-Bit mode is big-endian
463 <    if (depth == 1) {
463 >    if (need_msb_image) {
464          img->byte_order = MSBFirst;
465          img->bitmap_bit_order = MSBFirst;
466      }
# Line 265 | Line 482 | static bool open_window(int width, int h
482  
483          // Create GC
484          the_gc = XCreateGC(x_display, the_win, 0, 0);
485 <        XSetForeground(x_display, the_gc, black_pixel);
485 >        XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
486  
487          // Create cursor
488          cursor_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 4, 16, 16, 16, 2);
# Line 293 | Line 510 | static bool open_window(int width, int h
510   #endif
511  
512          // Set bytes per row
296        VModes[cur_mode].viRowBytes = img->bytes_per_line;
513          XSync(x_display, false);
514          return true;
515   }
# Line 305 | Line 521 | static bool open_dga(int width, int heig
521          // Set relative mouse mode
522          ADBSetRelMouseMode(true);
523  
524 +        // Create window
525 +        XSetWindowAttributes wattr;
526 +        wattr.event_mask = eventmask = dga_eventmask;
527 +        wattr.override_redirect = True;
528 +        wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
529 +        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
530 +                InputOutput, vis, CWEventMask | CWOverrideRedirect |
531 +                (color_class == DirectColor ? CWColormap : 0), &wattr);
532 +
533 +        // Show window
534 +        XMapRaised(x_display, the_win);
535 +        wait_mapped(the_win);
536 +
537   #ifdef ENABLE_XF86_VIDMODE
538          // Switch to best mode
539          if (has_vidmode) {
# Line 321 | Line 550 | static bool open_dga(int width, int heig
550   #endif
551  
552          // Establish direct screen connection
553 +        XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
554 +        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
555          XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
556          XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
557 +
558 +        int v_width, v_bank, v_size;
559 +        XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size);
560          XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
561          XF86DGASetViewPort(x_display, screen, 0, 0);
562          XF86DGASetVidPage(x_display, screen, 0);
563  
564          // Set colormap
565 <        if (depth == 8)
565 >        if (!IsDirectMode(get_current_mode())) {
566 >                XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
567                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
333
334        // Set bytes per row
335        int bytes_per_row = (dga_fb_width + 7) & ~7;
336        switch (depth) {
337                case 15:
338                case 16:
339                        bytes_per_row *= 2;
340                        break;
341                case 24:
342                case 32:
343                        bytes_per_row *= 4;
344                        break;
568          }
569 +        XSync(x_display, false);
570  
571 +        // Init blitting routines
572 +        int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, DepthModeForPixelDepth(depth));
573   #if ENABLE_VOSF
574          bool native_byte_order;
575   #ifdef WORDS_BIGENDIAN
# Line 362 | Line 588 | static bool open_dga(int width, int heig
588            the_buffer_size = page_extend((height + 2) * bytes_per_row);
589            the_buffer_copy = (uint8 *)malloc(the_buffer_size);
590            the_buffer = (uint8 *)vm_acquire(the_buffer_size);
591 +          D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
592          }
593   #else
594          use_vosf = false;
368        the_buffer = dga_screen_base;
595   #endif
596   #endif
371        screen_base = (uint32)the_buffer;
597  
598 +        // Set frame buffer base
599 +        D(bug("the_buffer = %p, use_vosf = %d\n", the_buffer, use_vosf));
600 +        screen_base = (uint32)the_buffer;
601          VModes[cur_mode].viRowBytes = bytes_per_row;
374        XSync(x_display, false);
602          return true;
603   #else
604          ErrorAlert("SheepShaver has been compiled with DGA support disabled.");
# Line 381 | Line 608 | static bool open_dga(int width, int heig
608  
609   static bool open_display(void)
610   {
611 <        display_type = VModes[cur_mode].viType;
612 <        switch (VModes[cur_mode].viAppleMode) {
613 <                case APPLE_1_BIT:
614 <                        depth = 1;
615 <                        break;
616 <                case APPLE_2_BIT:
617 <                        depth = 2;
391 <                        break;
392 <                case APPLE_4_BIT:
393 <                        depth = 4;
394 <                        break;
395 <                case APPLE_8_BIT:
396 <                        depth = 8;
397 <                        break;
398 <                case APPLE_16_BIT:
399 <                        depth = xdepth == 15 ? 15 : 16;
400 <                        break;
401 <                case APPLE_32_BIT:
402 <                        depth = 32;
403 <                        break;
611 >        D(bug("open_display()\n"));
612 >        const VideoInfo &mode = VModes[cur_mode];
613 >
614 >        // Find best available X visual
615 >        if (!find_visual_for_depth(mode.viAppleMode)) {
616 >                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
617 >                return false;
618          }
619  
620 +        // Create color maps
621 +        if (color_class == PseudoColor || color_class == DirectColor) {
622 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
623 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
624 +        } else {
625 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone);
626 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone);
627 +        }
628 +
629 +        // Find pixel format of direct modes
630 +        if (color_class == DirectColor || color_class == TrueColor) {
631 +                rshift = gshift = bshift = 0;
632 +                rloss = gloss = bloss = 8;
633 +                uint32 mask;
634 +                for (mask=vis->red_mask; !(mask&1); mask>>=1)
635 +                        ++rshift;
636 +                for (; mask&1; mask>>=1)
637 +                        --rloss;
638 +                for (mask=vis->green_mask; !(mask&1); mask>>=1)
639 +                        ++gshift;
640 +                for (; mask&1; mask>>=1)
641 +                        --gloss;
642 +                for (mask=vis->blue_mask; !(mask&1); mask>>=1)
643 +                        ++bshift;
644 +                for (; mask&1; mask>>=1)
645 +                        --bloss;
646 +        }
647 +
648 +        // Preset palette pixel values for CLUT or gamma table
649 +        if (color_class == DirectColor) {
650 +                int num = vis->map_entries;
651 +                for (int i=0; i<num; i++) {
652 +                        int c = (i * 256) / num;
653 +                        x_palette[i].pixel = map_rgb(c, c, c);
654 +                        x_palette[i].flags = DoRed | DoGreen | DoBlue;
655 +                }
656 +        } else if (color_class == PseudoColor) {
657 +                for (int i=0; i<256; i++) {
658 +                        x_palette[i].pixel = i;
659 +                        x_palette[i].flags = DoRed | DoGreen | DoBlue;
660 +                }
661 +        }
662 +
663 +        // Load gray ramp to color map
664 +        int num = (color_class == DirectColor ? vis->map_entries : 256);
665 +        for (int i=0; i<num; i++) {
666 +                int c = (i * 256) / num;
667 +                x_palette[i].red = c * 0x0101;
668 +                x_palette[i].green = c * 0x0101;
669 +                x_palette[i].blue = c * 0x0101;
670 +        }
671 +        if (color_class == PseudoColor || color_class == DirectColor) {
672 +                XStoreColors(x_display, cmap[0], x_palette, num);
673 +                XStoreColors(x_display, cmap[1], x_palette, num);
674 +        }
675 +
676 + #ifdef ENABLE_VOSF
677 +        // Load gray ramp to 8->16/32 expand map
678 +        if (!IsDirectMode(get_current_mode()) && xdepth > 8)
679 +                for (int i=0; i<256; i++)
680 +                        ExpandMap[i] = map_rgb(i, i, i);
681 + #endif
682 +
683 +        // Create display of requested type
684 +        display_type = mode.viType;
685 +        depth = depth_of_video_mode(mode.viAppleMode);
686 +
687          bool display_open = false;
688          if (display_type == DIS_SCREEN)
689                  display_open = open_dga(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
# Line 450 | Line 731 | static void close_window(void)
731          if (the_gc)
732                  XFreeGC(x_display, the_gc);
733  
734 <        // Close window
735 <        XDestroyWindow(x_display, the_win);
734 >        XFlush(x_display);
735 >        XSync(x_display, false);
736   }
737  
738   // Close DGA mode
# Line 487 | Line 768 | static void close_display(void)
768          else if (display_type == DIS_WINDOW)
769                  close_window();
770  
771 +        // Close window
772 +        if (the_win) {
773 +                XUnmapWindow(x_display, the_win);
774 +                wait_unmapped(the_win);
775 +                XDestroyWindow(x_display, the_win);
776 +        }
777 +
778 +        // Free colormaps
779 +        if (cmap[0]) {
780 +                XFreeColormap(x_display, cmap[0]);
781 +                cmap[0] = 0;
782 +        }
783 +        if (cmap[1]) {
784 +                XFreeColormap(x_display, cmap[1]);
785 +                cmap[1] = 0;
786 +        }
787 +
788   #ifdef ENABLE_VOSF
789          if (use_vosf) {
790                  // Deinitialize VOSF
# Line 528 | Line 826 | static void close_display(void)
826   *  Initialization
827   */
828  
829 < static void add_mode(VideoInfo *&p, uint32 allow, uint32 test, long apple_mode, long apple_id, int type)
829 > // Init keycode translation table
830 > static void keycode_init(void)
831 > {
832 >        bool use_kc = PrefsFindBool("keycodes");
833 >        if (use_kc) {
834 >
835 >                // Get keycode file path from preferences
836 >                const char *kc_path = PrefsFindString("keycodefile");
837 >
838 >                // Open keycode table
839 >                FILE *f = fopen(kc_path ? kc_path : KEYCODE_FILE_NAME, "r");
840 >                if (f == NULL) {
841 >                        char str[256];
842 >                        sprintf(str, GetString(STR_KEYCODE_FILE_WARN), kc_path ? kc_path : KEYCODE_FILE_NAME, strerror(errno));
843 >                        WarningAlert(str);
844 >                        return;
845 >                }
846 >
847 >                // Default translation table
848 >                for (int i=0; i<256; i++)
849 >                        keycode_table[i] = -1;
850 >
851 >                // Search for server vendor string, then read keycodes
852 >                const char *vendor = ServerVendor(x_display);
853 >                bool vendor_found = false;
854 >                char line[256];
855 >                while (fgets(line, 255, f)) {
856 >                        // Read line
857 >                        int len = strlen(line);
858 >                        if (len == 0)
859 >                                continue;
860 >                        line[len-1] = 0;
861 >
862 >                        // Comments begin with "#" or ";"
863 >                        if (line[0] == '#' || line[0] == ';' || line[0] == 0)
864 >                                continue;
865 >
866 >                        if (vendor_found) {
867 >                                // Read keycode
868 >                                int x_code, mac_code;
869 >                                if (sscanf(line, "%d %d", &x_code, &mac_code) == 2)
870 >                                        keycode_table[x_code & 0xff] = mac_code;
871 >                                else
872 >                                        break;
873 >                        } else {
874 >                                // Search for vendor string
875 >                                if (strstr(vendor, line) == vendor)
876 >                                        vendor_found = true;
877 >                        }
878 >                }
879 >
880 >                // Keycode file completely read
881 >                fclose(f);
882 >                use_keycodes = vendor_found;
883 >
884 >                // Vendor not found? Then display warning
885 >                if (!vendor_found) {
886 >                        char str[256];
887 >                        sprintf(str, GetString(STR_KEYCODE_VENDOR_WARN), vendor, kc_path ? kc_path : KEYCODE_FILE_NAME);
888 >                        WarningAlert(str);
889 >                        return;
890 >                }
891 >        }
892 > }
893 >
894 > // Find Apple mode matching best specified dimensions
895 > static int find_apple_resolution(int xsize, int ysize)
896 > {
897 >        int apple_id;
898 >        if (xsize < 800)
899 >                apple_id = APPLE_640x480;
900 >        else if (xsize < 1024)
901 >                apple_id = APPLE_800x600;
902 >        else if (xsize < 1152)
903 >                apple_id = APPLE_1024x768;
904 >        else if (xsize < 1280) {
905 >                if (ysize < 900)
906 >                        apple_id = APPLE_1152x768;
907 >                else
908 >                        apple_id = APPLE_1152x900;
909 >        }
910 >        else if (xsize < 1600)
911 >                apple_id = APPLE_1280x1024;
912 >        else
913 >                apple_id = APPLE_1600x1200;
914 >        return apple_id;
915 > }
916 >
917 > // Find mode in list of supported modes
918 > static int find_mode(int apple_mode, int apple_id, int type)
919 > {
920 >        for (VideoInfo *p = VModes; p->viType != DIS_INVALID; p++) {
921 >                if (p->viType == type && p->viAppleID == apple_id && p->viAppleMode == apple_mode)
922 >                        return p - VModes;
923 >        }
924 >        return -1;
925 > }
926 >
927 > // Add mode to list of supported modes
928 > static void add_mode(VideoInfo *&p, uint32 allow, uint32 test, int apple_mode, int apple_id, int type)
929   {
930          if (allow & test) {
931                  p->viType = type;
# Line 547 | Line 944 | static void add_mode(VideoInfo *&p, uint
944                                  p->viXsize = 1024;
945                                  p->viYsize = 768;
946                                  break;
947 +                        case APPLE_1152x768:
948 +                                p->viXsize = 1152;
949 +                                p->viYsize = 768;
950 +                                break;
951                          case APPLE_1152x900:
952                                  p->viXsize = 1152;
953                                  p->viYsize = 900;
# Line 560 | Line 961 | static void add_mode(VideoInfo *&p, uint
961                                  p->viYsize = 1200;
962                                  break;
963                  }
964 <                switch (apple_mode) {
564 <                        case APPLE_8_BIT:
565 <                                p->viRowBytes = p->viXsize;
566 <                                break;
567 <                        case APPLE_16_BIT:
568 <                                p->viRowBytes = p->viXsize * 2;
569 <                                break;
570 <                        case APPLE_32_BIT:
571 <                                p->viRowBytes = p->viXsize * 4;
572 <                                break;
573 <                }
964 >                p->viRowBytes = TrivialBytesPerRow(p->viXsize, apple_mode);
965                  p->viAppleMode = apple_mode;
966                  p->viAppleID = apple_id;
967                  p++;
968          }
969   }
970  
971 + // Add standard list of windowed modes for given color depth
972 + static void add_window_modes(VideoInfo *&p, int window_modes, int mode)
973 + {
974 +        add_mode(p, window_modes, 1, mode, APPLE_W_640x480, DIS_WINDOW);
975 +        add_mode(p, window_modes, 2, mode, APPLE_W_800x600, DIS_WINDOW);
976 + }
977 +
978   static bool has_mode(int x, int y)
979   {
980   #ifdef ENABLE_XF86_VIDMODE
# Line 597 | Line 995 | bool VideoInit(void)
995          mainBuffer.pageInfo = NULL;
996   #endif
997          
998 +        // Check if X server runs on local machine
999 +        local_X11 = (strncmp(XDisplayName(x_display_name), ":", 1) == 0)
1000 +                 || (strncmp(XDisplayName(x_display_name), "unix:", 5) == 0);
1001 +    
1002 +        // Init keycode translation
1003 +        keycode_init();
1004 +
1005 +        // Read frame skip prefs
1006 +        frame_skip = PrefsFindInt32("frameskip");
1007 +        if (frame_skip == 0)
1008 +                frame_skip = 1;
1009 +
1010 +        // Read mouse wheel prefs
1011 +        mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1012 +        mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1013 +
1014          // Init variables
1015          private_data = NULL;
602        cur_mode = 0;   // Window 640x480
1016          video_activated = true;
1017  
1018          // Find screen and root window
1019          screen = XDefaultScreen(x_display);
1020          rootwin = XRootWindow(x_display, screen);
1021  
1022 +        // Get sorted list of available depths
1023 +        avail_depths = XListDepths(x_display, screen, &num_depths);
1024 +        if (avail_depths == NULL) {
1025 +                ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
1026 +                return false;
1027 +        }
1028 +        sort(avail_depths, avail_depths + num_depths);
1029 +        
1030          // Get screen depth
1031          xdepth = DefaultDepth(x_display, screen);
1032  
1033   #ifdef ENABLE_XF86_DGA
1034          // DGA available?
1035      int event_base, error_base;
1036 <    if (XF86DGAQueryExtension(x_display, &event_base, &error_base)) {
1036 >    if (local_X11 && XF86DGAQueryExtension(x_display, &event_base, &error_base)) {
1037                  int dga_flags = 0;
1038                  XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
1039                  has_dga = dga_flags & XF86DGADirectPresent;
# Line 636 | Line 1057 | bool VideoInit(void)
1057          black_pixel = BlackPixel(x_display, screen);
1058          white_pixel = WhitePixel(x_display, screen);
1059  
639        // Get appropriate visual
640        int color_class;
641        switch (xdepth) {
642 #if 0
643                case 1:
644                        color_class = StaticGray;
645                        break;
646 #endif
647                case 8:
648                        color_class = PseudoColor;
649                        break;
650                case 15:
651                case 16:
652                case 24:
653                case 32:
654                        color_class = TrueColor;
655                        break;
656                default:
657                        ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
658                        return false;
659        }
660        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
661                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
662                return false;
663        }
664        if (visualInfo.depth != xdepth) {
665                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
666                return false;
667        }
668        vis = visualInfo.visual;
669
1060          // Mac screen depth follows X depth (for now)
1061 <        depth = xdepth;
1062 <
1063 <        // Create color maps for 8 bit mode
1064 <        if (depth == 8) {
1065 <                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1066 <                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1067 <                XInstallColormap(x_display, cmap[0]);
1068 <                XInstallColormap(x_display, cmap[1]);
1061 >        int default_mode = APPLE_8_BIT;
1062 >        switch (DefaultDepth(x_display, screen)) {
1063 >        case 1:
1064 >                default_mode = APPLE_1_BIT;
1065 >                break;
1066 >        case 8:
1067 >                default_mode = APPLE_8_BIT;
1068 >                break;
1069 >        case 15: case 16:
1070 >                default_mode = APPLE_16_BIT;
1071 >                break;
1072 >        case 24: case 32:
1073 >                default_mode = APPLE_32_BIT;
1074 >                break;
1075          }
1076  
1077          // Construct video mode table
682        int mode = APPLE_8_BIT;
683        int bpr_mult = 8;
684        switch (depth) {
685                case 1:
686                        mode = APPLE_1_BIT;
687                        bpr_mult = 1;
688                        break;
689                case 8:
690                        mode = APPLE_8_BIT;
691                        bpr_mult = 8;
692                        break;
693                case 15:
694                case 16:
695                        mode = APPLE_16_BIT;
696                        bpr_mult = 16;
697                        break;
698                case 24:
699                case 32:
700                        mode = APPLE_32_BIT;
701                        bpr_mult = 32;
702                        break;
703        }
704
1078          uint32 window_modes = PrefsFindInt32("windowmodes");
1079          uint32 screen_modes = PrefsFindInt32("screenmodes");
1080          if (!has_dga)
# Line 710 | Line 1083 | bool VideoInit(void)
1083                  window_modes |= 3;      // Allow at least 640x480 and 800x600 window modes
1084  
1085          VideoInfo *p = VModes;
1086 <        add_mode(p, window_modes, 1, mode, APPLE_W_640x480, DIS_WINDOW);
1087 <        add_mode(p, window_modes, 2, mode, APPLE_W_800x600, DIS_WINDOW);
1086 >        for (unsigned int d = APPLE_1_BIT; d <= APPLE_32_BIT; d++)
1087 >                if (find_visual_for_depth(d))
1088 >                        add_window_modes(p, window_modes, d);
1089 >
1090          if (has_vidmode) {
1091                  if (has_mode(640, 480))
1092 <                        add_mode(p, screen_modes, 1, mode, APPLE_640x480, DIS_SCREEN);
1092 >                        add_mode(p, screen_modes, 1, default_mode, APPLE_640x480, DIS_SCREEN);
1093                  if (has_mode(800, 600))
1094 <                        add_mode(p, screen_modes, 2, mode, APPLE_800x600, DIS_SCREEN);
1094 >                        add_mode(p, screen_modes, 2, default_mode, APPLE_800x600, DIS_SCREEN);
1095                  if (has_mode(1024, 768))
1096 <                        add_mode(p, screen_modes, 4, mode, APPLE_1024x768, DIS_SCREEN);
1096 >                        add_mode(p, screen_modes, 4, default_mode, APPLE_1024x768, DIS_SCREEN);
1097 >                if (has_mode(1152, 768))
1098 >                        add_mode(p, screen_modes, 64, default_mode, APPLE_1152x768, DIS_SCREEN);
1099                  if (has_mode(1152, 900))
1100 <                        add_mode(p, screen_modes, 8, mode, APPLE_1152x900, DIS_SCREEN);
1100 >                        add_mode(p, screen_modes, 8, default_mode, APPLE_1152x900, DIS_SCREEN);
1101                  if (has_mode(1280, 1024))
1102 <                        add_mode(p, screen_modes, 16, mode, APPLE_1280x1024, DIS_SCREEN);
1102 >                        add_mode(p, screen_modes, 16, default_mode, APPLE_1280x1024, DIS_SCREEN);
1103                  if (has_mode(1600, 1200))
1104 <                        add_mode(p, screen_modes, 32, mode, APPLE_1600x1200, DIS_SCREEN);
1104 >                        add_mode(p, screen_modes, 32, default_mode, APPLE_1600x1200, DIS_SCREEN);
1105          } else if (screen_modes) {
1106                  int xsize = DisplayWidth(x_display, screen);
1107                  int ysize = DisplayHeight(x_display, screen);
1108 <                int apple_id;
732 <                if (xsize < 800)
733 <                        apple_id = APPLE_640x480;
734 <                else if (xsize < 1024)
735 <                        apple_id = APPLE_800x600;
736 <                else if (xsize < 1152)
737 <                        apple_id = APPLE_1024x768;
738 <                else if (xsize < 1280)
739 <                        apple_id = APPLE_1152x900;
740 <                else if (xsize < 1600)
741 <                        apple_id = APPLE_1280x1024;
742 <                else
743 <                        apple_id = APPLE_1600x1200;
1108 >                int apple_id = find_apple_resolution(xsize, ysize);
1109                  p->viType = DIS_SCREEN;
1110                  p->viRowBytes = 0;
1111                  p->viXsize = xsize;
1112                  p->viYsize = ysize;
1113 <                p->viAppleMode = mode;
1113 >                p->viAppleMode = default_mode;
1114                  p->viAppleID = apple_id;
1115                  p++;
1116          }
# Line 755 | Line 1120 | bool VideoInit(void)
1120          p->viAppleMode = 0;
1121          p->viAppleID = 0;
1122  
1123 < #ifdef ENABLE_XF86_DGA
1123 >        // Find default mode (window 640x480)
1124 >        cur_mode = -1;
1125          if (has_dga && screen_modes) {
1126 <                int v_bank, v_size;
1127 <                XF86DGAGetVideo(x_display, screen, &dga_screen_base, &dga_fb_width, &v_bank, &v_size);
1128 <                D(bug("DGA screen_base %p, v_width %d\n", dga_screen_base, dga_fb_width));
1126 >                int screen_width = DisplayWidth(x_display, screen);
1127 >                int screen_height = DisplayHeight(x_display, screen);
1128 >                int apple_id = find_apple_resolution(screen_width, screen_height);
1129 >                if (apple_id != -1)
1130 >                        cur_mode = find_mode(default_mode, apple_id, DIS_SCREEN);
1131 >        }
1132 >        if (cur_mode == -1)
1133 >                cur_mode = find_mode(default_mode, APPLE_W_640x480, DIS_WINDOW);
1134 >        assert(cur_mode != -1);
1135 >
1136 > #if DEBUG
1137 >        D(bug("Available video modes:\n"));
1138 >        for (p = VModes; p->viType != DIS_INVALID; p++) {
1139 >                int bits = depth_of_video_mode(p->viAppleMode);
1140 >                D(bug(" %dx%d (ID %02x), %d colors\n", p->viXsize, p->viYsize, p->viAppleID, 1 << bits));
1141          }
1142   #endif
1143  
# Line 774 | Line 1152 | bool VideoInit(void)
1152  
1153          // Start periodic thread
1154          XSync(x_display, false);
1155 <        redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1155 >        Set_pthread_attr(&redraw_thread_attr, 0);
1156 >        redraw_thread_active = (pthread_create(&redraw_thread, &redraw_thread_attr, redraw_func, NULL) == 0);
1157          D(bug("Redraw thread installed (%ld)\n", redraw_thread));
1158          return true;
1159   }
# Line 806 | Line 1185 | void VideoExit(void)
1185                  close_display();
1186                  XFlush(x_display);
1187                  XSync(x_display, false);
809                if (depth == 8) {
810                        XFreeColormap(x_display, cmap[0]);
811                        XFreeColormap(x_display, cmap[1]);
812                }
1188          }
1189   }
1190  
# Line 873 | Line 1248 | static void resume_emul(void)
1248          // Reopen full screen display
1249          XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1250          XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1251 + #ifdef ENABLE_XF86_DGA
1252          XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1253          XF86DGASetViewPort(x_display, screen, 0, 0);
1254 + #endif
1255          XSync(x_display, false);
1256  
1257          // the_buffer already contains the data to restore. i.e. since a temporary
# Line 1068 | Line 1445 | static int kc_decode(KeySym ks)
1445          return -1;
1446   }
1447  
1448 < static int event2keycode(XKeyEvent *ev)
1448 > static int event2keycode(XKeyEvent &ev)
1449   {
1450          KeySym ks;
1451          int as;
1452          int i = 0;
1453  
1454          do {
1455 <                ks = XLookupKeysym(ev, i++);
1455 >                ks = XLookupKeysym(&ev, i++);
1456                  as = kc_decode(ks);
1457                  if (as != -1)
1458                          return as;
# Line 1090 | Line 1467 | static void handle_events(void)
1467          for (;;) {
1468                  XEvent event;
1469  
1470 <                if (!XCheckMaskEvent(x_display, eventmask, &event))
1470 >                XDisplayLock();
1471 >                if (!XCheckMaskEvent(x_display, eventmask, &event)) {
1472 >                        // Handle clipboard events
1473 >                        if (XCheckTypedEvent(x_display, SelectionRequest, &event))
1474 >                                ClipboardSelectionRequest(&event.xselectionrequest);
1475 >                        else if (XCheckTypedEvent(x_display, SelectionClear, &event))
1476 >                                ClipboardSelectionClear(&event.xselectionclear);
1477 >
1478 >                        // Window "close" widget clicked
1479 >                        else if (XCheckTypedEvent(x_display, ClientMessage, &event)) {
1480 >                                if (event.xclient.format == 32 && event.xclient.data.l[0] == WM_DELETE_WINDOW) {
1481 >                                        ADBKeyDown(0x7f);       // Power key
1482 >                                        ADBKeyUp(0x7f);
1483 >                                }
1484 >                        }
1485 >
1486 >                        XDisplayUnlock();
1487                          break;
1488 +                }
1489 +                XDisplayUnlock();
1490  
1491                  switch (event.type) {
1492                          // Mouse button
# Line 1099 | Line 1494 | static void handle_events(void)
1494                                  unsigned int button = ((XButtonEvent *)&event)->button;
1495                                  if (button < 4)
1496                                          ADBMouseDown(button - 1);
1497 +                                else if (button < 6) {  // Wheel mouse
1498 +                                        if (mouse_wheel_mode == 0) {
1499 +                                                int key = (button == 5) ? 0x79 : 0x74;  // Page up/down
1500 +                                                ADBKeyDown(key);
1501 +                                                ADBKeyUp(key);
1502 +                                        } else {
1503 +                                                int key = (button == 5) ? 0x3d : 0x3e;  // Cursor up/down
1504 +                                                for(int i=0; i<mouse_wheel_lines; i++) {
1505 +                                                        ADBKeyDown(key);
1506 +                                                        ADBKeyUp(key);
1507 +                                                }
1508 +                                        }
1509 +                                }
1510                                  break;
1511                          }
1512                          case ButtonRelease: {
# Line 1108 | Line 1516 | static void handle_events(void)
1516                                  break;
1517                          }
1518  
1519 <                        // Mouse moved
1519 >                        // Mouse entered window
1520                          case EnterNotify:
1521 <                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1521 >                                if (event.xcrossing.mode != NotifyGrab && event.xcrossing.mode != NotifyUngrab)
1522 >                                        ADBMouseMoved(event.xmotion.x, event.xmotion.y);
1523                                  break;
1524 +
1525 +                        // Mouse moved
1526                          case MotionNotify:
1527 <                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1527 >                                ADBMouseMoved(event.xmotion.x, event.xmotion.y);
1528                                  break;
1529  
1530                          // Keyboard
1531                          case KeyPress: {
1532 <                                int code;
1533 <                                if ((code = event2keycode((XKeyEvent *)&event)) != -1) {
1532 >                                int code = event2keycode(event.xkey);
1533 >                                if (use_keycodes && code != -1)
1534 >                                        code = keycode_table[event.xkey.keycode & 0xff];
1535 >                                if (code != -1) {
1536                                          if (!emul_suspended) {
1537                                                  ADBKeyDown(code);
1538                                                  if (code == 0x36)
# Line 1132 | Line 1545 | static void handle_events(void)
1545                                  break;
1546                          }
1547                          case KeyRelease: {
1548 <                                int code;
1549 <                                if ((code = event2keycode((XKeyEvent *)&event)) != -1) {
1548 >                                int code = event2keycode(event.xkey);
1549 >                                if (use_keycodes && code != 1)
1550 >                                        code = keycode_table[event.xkey.keycode & 0xff];
1551 >                                if (code != -1) {
1552                                          ADBKeyUp(code);
1553                                          if (code == 0x36)
1554                                                  ctrl_down = false;
# Line 1374 | Line 1789 | int16 video_mode_change(VidLocals *csSav
1789  
1790   void video_set_palette(void)
1791   {
1792 +        LOCK_PALETTE;
1793 +
1794 +        // Convert colors to XColor array
1795 +        int mode = get_current_mode();
1796 +        int num_in = palette_size(mode);
1797 +        int num_out = 256;
1798 +        bool stretch = false;
1799 +        if (IsDirectMode(mode)) {
1800 +                // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries
1801 +                num_out = vis->map_entries;
1802 +                stretch = true;
1803 +        }
1804 +        XColor *p = x_palette;
1805 +        for (int i=0; i<num_out; i++) {
1806 +                int c = (stretch ? (i * num_in) / num_out : i);
1807 +                p->red = mac_pal[c].red * 0x0101;
1808 +                p->green = mac_pal[c].green * 0x0101;
1809 +                p->blue = mac_pal[c].blue * 0x0101;
1810 +                p++;
1811 +        }
1812 +
1813 + #ifdef ENABLE_VOSF
1814 +        // Recalculate pixel color expansion map
1815 +        if (!IsDirectMode(mode) && xdepth > 8) {
1816 +                for (int i=0; i<256; i++) {
1817 +                        int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
1818 +                        ExpandMap[i] = map_rgb(mac_pal[c].red, mac_pal[c].green, mac_pal[c].blue);
1819 +                }
1820 +
1821 +                // We have to redraw everything because the interpretation of pixel values changed
1822 +                LOCK_VOSF;
1823 +                PFLAG_SET_ALL;
1824 +                UNLOCK_VOSF;
1825 +                memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1826 +        }
1827 + #endif
1828 +
1829 +        // Tell redraw thread to change palette
1830          palette_changed = true;
1831 +
1832 +        UNLOCK_PALETTE;
1833   }
1834  
1835  
# Line 1501 | Line 1956 | static void update_display(void)
1956  
1957          // Refresh display
1958          if (high && wide) {
1959 +                XDisplayLock();
1960                  if (have_shm)
1961                          XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
1962                  else
1963                          XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
1964 +                XDisplayUnlock();
1965 +        }
1966 + }
1967 +
1968 + const int VIDEO_REFRESH_HZ = 60;
1969 + const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
1970 +
1971 + static void handle_palette_changes(void)
1972 + {
1973 +        LOCK_PALETTE;
1974 +
1975 +        if (palette_changed && !emul_suspended) {
1976 +                palette_changed = false;
1977 +
1978 +                int mode = get_current_mode();
1979 +                if (color_class == PseudoColor || color_class == DirectColor) {
1980 +                        int num = vis->map_entries;
1981 +                        bool set_clut = true;
1982 +                        if (!IsDirectMode(mode) && color_class == DirectColor) {
1983 +                                if (display_type == DIS_WINDOW)
1984 +                                        set_clut = false; // Indexed mode on true color screen, don't set CLUT
1985 +                        }
1986 +
1987 +                        if (set_clut) {
1988 +                                XDisplayLock();
1989 +                                XStoreColors(x_display, cmap[0], x_palette, num);
1990 +                                XStoreColors(x_display, cmap[1], x_palette, num);
1991 +                                XSync(x_display, false);
1992 +                                XDisplayUnlock();
1993 +                        }
1994 +                }
1995 +
1996 + #ifdef ENABLE_XF86_DGA
1997 +                if (display_type == DIS_SCREEN) {
1998 +                        current_dga_cmap ^= 1;
1999 +                        if (!IsDirectMode(mode) && cmap[current_dga_cmap])
2000 +                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
2001 +                }
2002 + #endif
2003          }
2004 +
2005 +        UNLOCK_PALETTE;
2006   }
2007  
2008   static void *redraw_func(void *arg)
2009   {
2010 <        int tick_counter = 0;
1514 <        struct timespec req = {0, 16666667};
2010 >        int fd = ConnectionNumber(x_display);
2011  
2012 <        for (;;) {
2012 >        uint64 start = GetTicks_usec();
2013 >        int64 ticks = 0;
2014 >        uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2015  
2016 <                // Wait
1519 <                nanosleep(&req, NULL);
2016 >        for (;;) {
2017  
2018                  // Pause if requested (during video mode switches)
2019                  while (thread_stop_req)
2020                          thread_stop_ack = true;
2021  
2022 <                // Handle X11 events
2023 <                handle_events();
2022 >                int64 delay = next - GetTicks_usec();
2023 >                if (delay < -VIDEO_REFRESH_DELAY) {
2024 >
2025 >                        // We are lagging far behind, so we reset the delay mechanism
2026 >                        next = GetTicks_usec();
2027 >
2028 >                } else if (delay <= 0) {
2029 >
2030 >                        // Delay expired, refresh display
2031 >                        next += VIDEO_REFRESH_DELAY;
2032 >                        ticks++;
2033  
2034 <                // Quit DGA mode if requested
2035 <                if (quit_full_screen) {
2036 <                        quit_full_screen = false;
2037 <                        if (display_type == DIS_SCREEN) {
2034 >                        // Handle X11 events
2035 >                        handle_events();
2036 >
2037 >                        // Quit DGA mode if requested
2038 >                        if (quit_full_screen) {
2039 >                                quit_full_screen = false;
2040 >                                if (display_type == DIS_SCREEN) {
2041 >                                        XDisplayLock();
2042   #ifdef ENABLE_XF86_DGA
2043 <                                XF86DGADirectVideo(x_display, screen, 0);
2044 <                                XUngrabPointer(x_display, CurrentTime);
2045 <                                XUngrabKeyboard(x_display, CurrentTime);
2046 < #endif
2047 <                                XSync(x_display, false);
2048 <                                quit_full_screen_ack = true;
2049 <                                return NULL;
2043 >                                        XF86DGADirectVideo(x_display, screen, 0);
2044 >                                        XUngrabPointer(x_display, CurrentTime);
2045 >                                        XUngrabKeyboard(x_display, CurrentTime);
2046 >                                        XUnmapWindow(x_display, the_win);
2047 >                                        wait_unmapped(the_win);
2048 >                                        XDestroyWindow(x_display, the_win);
2049 > #endif
2050 >                                        XSync(x_display, false);
2051 >                                        XDisplayUnlock();
2052 >                                        quit_full_screen_ack = true;
2053 >                                        return NULL;
2054 >                                }
2055                          }
1541                }
2056  
2057 <                // Refresh display and set cursor image in window mode
2058 <                if (display_type == DIS_WINDOW) {
2059 <                        tick_counter++;
2060 <                        if (tick_counter >= frame_skip) {
2061 <                                tick_counter = 0;
2057 >                        // Refresh display and set cursor image in window mode
2058 >                        static int tick_counter = 0;
2059 >                        if (display_type == DIS_WINDOW) {
2060 >                                tick_counter++;
2061 >                                if (tick_counter >= frame_skip) {
2062 >                                        tick_counter = 0;
2063  
2064 <                                // Update display
2064 >                                        // Update display
2065   #ifdef ENABLE_VOSF
2066 <                                if (use_vosf) {
2067 <                                        if (mainBuffer.dirty) {
2068 <                                                LOCK_VOSF;
2069 <                                                update_display_window_vosf();
2070 <                                                UNLOCK_VOSF;
2071 <                                                XSync(x_display, false); // Let the server catch up
2066 >                                        if (use_vosf) {
2067 >                                                XDisplayLock();
2068 >                                                if (mainBuffer.dirty) {
2069 >                                                        LOCK_VOSF;
2070 >                                                        update_display_window_vosf();
2071 >                                                        UNLOCK_VOSF;
2072 >                                                        XSync(x_display, false); // Let the server catch up
2073 >                                                }
2074 >                                                XDisplayUnlock();
2075                                          }
2076 <                                }
1559 <                                else
2076 >                                        else
2077   #endif
2078 <                                        update_display();
2078 >                                                update_display();
2079  
2080 <                                // Set new cursor image if it was changed
2081 <                                if (cursor_changed) {
2082 <                                        cursor_changed = false;
2083 <                                        memcpy(cursor_image->data, MacCursor + 4, 32);
2084 <                                        memcpy(cursor_mask_image->data, MacCursor + 36, 32);
2085 <                                        XFreeCursor(x_display, mac_cursor);
2086 <                                        XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
2087 <                                        XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
2088 <                                        mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, MacCursor[2], MacCursor[3]);
2089 <                                        XDefineCursor(x_display, the_win, mac_cursor);
2080 >                                        // Set new cursor image if it was changed
2081 >                                        if (cursor_changed) {
2082 >                                                cursor_changed = false;
2083 >                                                memcpy(cursor_image->data, MacCursor + 4, 32);
2084 >                                                memcpy(cursor_mask_image->data, MacCursor + 36, 32);
2085 >                                                XDisplayLock();
2086 >                                                XFreeCursor(x_display, mac_cursor);
2087 >                                                XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
2088 >                                                XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
2089 >                                                mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, MacCursor[2], MacCursor[3]);
2090 >                                                XDefineCursor(x_display, the_win, mac_cursor);
2091 >                                                XDisplayUnlock();
2092 >                                        }
2093                                  }
2094                          }
1575                }
2095   #ifdef ENABLE_VOSF
2096 <                else if (use_vosf) {
2097 <                        // Update display (VOSF variant)
2098 <                        static int tick_counter = 0;
2099 <                        if (++tick_counter >= frame_skip) {
2100 <                                tick_counter = 0;
2101 <                                if (mainBuffer.dirty) {
2102 <                                        LOCK_VOSF;
2103 <                                        update_display_dga_vosf();
2104 <                                        UNLOCK_VOSF;
2096 >                        else if (use_vosf) {
2097 >                                // Update display (VOSF variant)
2098 >                                if (++tick_counter >= frame_skip) {
2099 >                                        tick_counter = 0;
2100 >                                        if (mainBuffer.dirty) {
2101 >                                                LOCK_VOSF;
2102 >                                                update_display_dga_vosf();
2103 >                                                UNLOCK_VOSF;
2104 >                                        }
2105                                  }
2106                          }
1588                }
2107   #endif
2108  
2109 <                // Set new palette if it was changed
2110 <                if (palette_changed && !emul_suspended) {
2111 <                        palette_changed = false;
2112 <                        XColor c[256];
2113 <                        for (int i=0; i<256; i++) {
2114 <                                c[i].pixel = i;
2115 <                                c[i].red = mac_pal[i].red * 0x0101;
2116 <                                c[i].green = mac_pal[i].green * 0x0101;
2117 <                                c[i].blue = mac_pal[i].blue * 0x0101;
2118 <                                c[i].flags = DoRed | DoGreen | DoBlue;
2119 <                        }
2120 <                        if (depth == 8) {
2121 <                                XStoreColors(x_display, cmap[0], c, 256);
2122 <                                XStoreColors(x_display, cmap[1], c, 256);
1605 < #ifdef ENABLE_XF86_DGA
1606 <                                if (display_type == DIS_SCREEN) {
1607 <                                        current_dga_cmap ^= 1;
1608 <                                        XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1609 <                                }
1610 < #endif
1611 <                        }
2109 >                        // Set new palette if it was changed
2110 >                        handle_palette_changes();
2111 >
2112 >                } else {
2113 >
2114 >                        // No display refresh pending, check for X events
2115 >                        fd_set readfds;
2116 >                        FD_ZERO(&readfds);
2117 >                        FD_SET(fd, &readfds);
2118 >                        struct timeval timeout;
2119 >                        timeout.tv_sec = 0;
2120 >                        timeout.tv_usec = delay;
2121 >                        if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0)
2122 >                                handle_events();
2123                  }
2124          }
2125          return NULL;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines