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

Comparing BasiliskII/src/Unix/video_x.cpp (file contents):
Revision 1.46 by cebix, 2001-06-30T22:23:44Z vs.
Revision 1.58 by cebix, 2001-07-10T15:50:57Z

# Line 24 | Line 24
24   *      Ctrl-Tab = suspend DGA mode
25   *      Ctrl-Esc = emergency quit
26   *      Ctrl-F1 = mount floppy
27 + *      Ctrl-F5 = grab mouse (in windowed mode)
28   */
29  
30   #include "sysdeps.h"
# Line 36 | Line 37
37   #include <sys/shm.h>
38   #include <errno.h>
39  
40 + #include <algorithm>
41 +
42 + #ifndef NO_STD_NAMESPACE
43 + using std::sort;
44 + #endif
45 +
46   #ifdef HAVE_PTHREADS
47   # include <pthread.h>
48   #endif
# Line 86 | Line 93 | static int display_type = DISPLAY_WINDOW
93   static bool local_X11;                                                          // Flag: X server running on local machine?
94   static uint8 *the_buffer = NULL;                                        // Mac frame buffer (where MacOS draws into)
95   static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer (for refreshed modes)
96 + static uint32 the_buffer_size;                                          // Size of allocated the_buffer
97  
98   static bool redraw_thread_active = false;                       // Flag: Redraw thread installed
99   #ifdef HAVE_PTHREADS
# Line 115 | Line 123 | static int keycode_table[256];                                         // X
123  
124   // X11 variables
125   static int screen;                                                                      // Screen number
118 static int xdepth;                                                                      // Depth of X screen
126   static Window rootwin;                                                          // Root window and our window
127 < static XVisualInfo visualInfo;
128 < static Visual *vis;
122 < static Colormap cmap[2] = {0, 0};                                       // Colormaps for indexed modes (DGA needs two of them)
127 > static int num_depths = 0;                                                      // Number of available X depths
128 > static int *avail_depths = NULL;                                        // List of available X depths
129   static XColor black, white;
130   static unsigned long black_pixel, white_pixel;
131   static int eventmask;
132  
133 < static XColor palette[256];                                                     // Color palette for indexed modes
133 > static int xdepth;                                                                      // Depth of X screen
134 > static XVisualInfo visualInfo;
135 > static Visual *vis;
136 > static int color_class;
137 >
138 > static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
139 >
140 > static Colormap cmap[2] = {0, 0};                                       // Colormaps for indexed modes (DGA needs two of them)
141 >
142 > static XColor palette[256];                                                     // Color palette to be used as CLUT and gamma table
143   static bool palette_changed = false;                            // Flag: Palette changed, redraw thread must set new colors
144  
145   #ifdef ENABLE_FBDEV_DGA
# Line 183 | Line 198 | extern void SysMountFirstFloppy(void);
198   *  Utility functions
199   */
200  
201 + // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
202 + static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
203 + {
204 +        return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
205 + }
206 +
207 + // Do we have a visual for handling the specified Mac depth? If so, set the
208 + // global variables "xdepth", "visualInfo", "vis" and "color_class".
209 + static bool find_visual_for_depth(video_depth depth)
210 + {
211 +        D(bug("have_visual_for_depth(%d)\n", 1 << depth));
212 +
213 +        // Calculate minimum and maximum supported X depth
214 +        int min_depth = 1, max_depth = 32;
215 +        switch (depth) {
216 +                case VDEPTH_1BIT:       // 1-bit works always and uses default visual
217 +                        min_depth = max_depth = DefaultDepth(x_display, screen);
218 +                        break;
219 + #ifdef ENABLE_VOSF
220 +                case VDEPTH_2BIT:
221 +                case VDEPTH_4BIT:       // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit
222 +                case VDEPTH_8BIT:
223 +                        min_depth = 8;
224 +                        max_depth = 32;
225 +                        break;
226 + #else
227 +                case VDEPTH_2BIT:
228 +                case VDEPTH_4BIT:       // 2/4-bit requires VOSF blitters
229 +                        return false;
230 +                case VDEPTH_8BIT:       // 8-bit without VOSF requires an 8-bit visual
231 +                        min_depth = 8;
232 +                        max_depth = 8;
233 +                        break;
234 + #endif
235 +                case VDEPTH_16BIT:      // 16-bit requires a 15/16-bit visual
236 +                        min_depth = 15;
237 +                        max_depth = 16;
238 +                        break;
239 +                case VDEPTH_32BIT:      // 32-bit requires a 24/32-bit visual
240 +                        min_depth = 24;
241 +                        max_depth = 32;
242 +                        break;
243 +        }
244 +        D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth));
245 +
246 +        // Try to find a visual for one of the color depths
247 +        bool visual_found = false;
248 +        for (int i=0; i<num_depths && !visual_found; i++) {
249 +
250 +                xdepth = avail_depths[i];
251 +                D(bug(" trying to find visual for depth %d\n", xdepth));
252 +                if (xdepth < min_depth || xdepth > max_depth)
253 +                        continue;
254 +
255 +                // Determine best color class for this depth
256 +                switch (xdepth) {
257 +                        case 1: // Try StaticGray or StaticColor
258 +                                if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo)
259 +                                 || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo))
260 +                                        visual_found = true;
261 +                                break;
262 +                        case 8: // Need PseudoColor
263 +                                if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo))
264 +                                        visual_found = true;
265 +                                break;
266 +                        case 15:
267 +                        case 16:
268 +                        case 24:
269 +                        case 32: // Try DirectColor first, as this will allow gamma correction
270 +                                if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo)
271 +                                 || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo))
272 +                                        visual_found = true;
273 +                                break;
274 +                        default:
275 +                                D(bug("  not a supported depth\n"));
276 +                                break;
277 +                }
278 +        }
279 +        if (!visual_found)
280 +                return false;
281 +
282 +        // Visual was found
283 +        vis = visualInfo.visual;
284 +        color_class = visualInfo.c_class;
285 +        D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth));
286 + #if DEBUG
287 +        switch (color_class) {
288 +                case StaticGray: D(bug("StaticGray\n")); break;
289 +                case GrayScale: D(bug("GrayScale\n")); break;
290 +                case StaticColor: D(bug("StaticColor\n")); break;
291 +                case PseudoColor: D(bug("PseudoColor\n")); break;
292 +                case TrueColor: D(bug("TrueColor\n")); break;
293 +                case DirectColor: D(bug("DirectColor\n")); break;
294 +        }
295 + #endif
296 + }
297 +
298   // Add mode to list of supported modes
299   static void add_mode(uint32 width, uint32 height, uint32 resolution_id, uint32 bytes_per_row, video_depth depth)
300   {
# Line 195 | Line 307 | static void add_mode(uint32 width, uint3
307          VideoModes.push_back(mode);
308   }
309  
310 + // Add standard list of windowed modes for given color depth
311 + static void add_window_modes(video_depth depth)
312 + {
313 +        add_mode(512, 384, 0x80, TrivialBytesPerRow(512, depth), depth);
314 +        add_mode(640, 480, 0x81, TrivialBytesPerRow(640, depth), depth);
315 +        add_mode(800, 600, 0x82, TrivialBytesPerRow(800, depth), depth);
316 +        add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, depth), depth);
317 +        add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, depth), depth);
318 +        add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, depth), depth);
319 +        add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, depth), depth);
320 + }
321 +
322   // Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac)
323   static void set_mac_frame_buffer(video_depth depth, bool native_byte_order)
324   {
# Line 203 | Line 327 | static void set_mac_frame_buffer(video_d
327          if (depth == VDEPTH_16BIT)
328                  layout = (xdepth == 15) ? FLAYOUT_HOST_555 : FLAYOUT_HOST_565;
329          else if (depth == VDEPTH_32BIT)
330 <                layour = (xdepth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT;
330 >                layout = (xdepth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT;
331          if (native_byte_order)
332                  MacFrameLayout = layout;
333          else
# Line 216 | Line 340 | static void set_mac_frame_buffer(video_d
340          InitFrameBufferMapping();
341   #else
342          VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
219        D(bug("Host frame buffer = %p, ", the_buffer));
343   #endif
344          D(bug("VideoMonitor.mac_frame_base = %08x\n", VideoMonitor.mac_frame_base));
345   }
# Line 302 | Line 425 | public:
425          virtual void update_palette(void);
426          virtual void suspend(void) {}
427          virtual void resume(void) {}
428 +        virtual void toggle_mouse_grab(void) {}
429 +        virtual void mouse_moved(int x, int y) { ADBMouseMoved(x, y); }
430 +
431 +        void disable_mouse_accel(void);
432 +        void restore_mouse_accel(void);
433 +
434 +        virtual void grab_mouse(void) {}
435 +        virtual void ungrab_mouse(void) {}
436  
437   public:
438          bool init_ok;   // Initialization succeeded (we can't use exceptions because of -fomit-frame-pointer)
439          Window w;               // The window we draw into
440 +
441 +        int orig_accel_numer, orig_accel_denom, orig_threshold; // Original mouse acceleration
442   };
443  
444   class driver_window;
# Line 322 | Line 455 | public:
455          driver_window(const video_mode &mode);
456          ~driver_window();
457  
458 +        void toggle_mouse_grab(void);
459 +        void mouse_moved(int x, int y);
460 +
461 +        void grab_mouse(void);
462 +        void ungrab_mouse(void);
463 +
464   private:
465          GC gc;
466          XImage *img;
467 <        bool have_shm;                          // Flag: SHM extensions available
467 >        bool have_shm;                                  // Flag: SHM extensions available
468          XShmSegmentInfo shminfo;
469          Cursor mac_cursor;
470 +        bool mouse_grabbed;                             // Flag: mouse pointer grabbed, using relative mouse mode
471 +        int mouse_last_x, mouse_last_y; // Last mouse position (for relative mode)
472   };
473  
474   static driver_base *drv = NULL; // Pointer to currently used driver object
# Line 341 | Line 482 | driver_base::driver_base()
482   {
483          the_buffer = NULL;
484          the_buffer_copy = NULL;
485 +        XGetPointerControl(x_display, &orig_accel_numer, &orig_accel_denom, &orig_threshold);
486   }
487  
488   driver_base::~driver_base()
489   {
490 +        ungrab_mouse();
491 +        restore_mouse_accel();
492 +
493          if (w) {
494                  XUnmapWindow(x_display, w);
495                  wait_unmapped(w);
# Line 367 | Line 512 | driver_base::~driver_base()
512          }
513   #ifdef ENABLE_VOSF
514          else {
515 <                if (the_buffer != (uint8 *)VM_MAP_FAILED) {
516 <                        vm_release(the_buffer, the_buffer_size);
515 >                if (the_host_buffer) {
516 >                        free(the_host_buffer);
517 >                        the_host_buffer = NULL;
518 >                }
519 >                if (the_buffer) {
520 >                        free(the_buffer);
521                          the_buffer = NULL;
522                  }
523 <                if (the_buffer_copy != (uint8 *)VM_MAP_FAILED) {
524 <                        vm_release(the_buffer_copy, the_buffer_size);
523 >                if (the_buffer_copy) {
524 >                        free(the_buffer_copy);
525                          the_buffer_copy = NULL;
526                  }
527          }
# Line 382 | Line 531 | driver_base::~driver_base()
531   // Palette has changed
532   void driver_base::update_palette(void)
533   {
534 <        if (cmap[0] && cmap[1]) {
535 <                int num = 256;
536 <                if (vis->c_class == DirectColor && VideoMonitor.mode.depth == VDEPTH_16BIT)
537 <                        num = vis->map_entries;
534 >        if (color_class == PseudoColor || color_class == DirectColor) {
535 >                int num = vis->map_entries;
536 >                if (!IsDirectMode(VideoMonitor.mode) && color_class == DirectColor)
537 >                        return; // Indexed mode on true color screen, don't set CLUT
538                  XStoreColors(x_display, cmap[0], palette, num);
539                  XStoreColors(x_display, cmap[1], palette, num);
540          }
541          XSync(x_display, false);
542   }
543  
544 + // Disable mouse acceleration
545 + void driver_base::disable_mouse_accel(void)
546 + {
547 +        XChangePointerControl(x_display, True, False, 1, 1, 0);
548 + }
549 +
550 + // Restore mouse acceleration to original value
551 + void driver_base::restore_mouse_accel(void)
552 + {
553 +        XChangePointerControl(x_display, True, True, orig_accel_numer, orig_accel_denom, orig_threshold);
554 + }
555 +
556  
557   /*
558   *  Windowed display driver
# Line 399 | Line 560 | void driver_base::update_palette(void)
560  
561   // Open display
562   driver_window::driver_window(const video_mode &mode)
563 < : gc(0), img(NULL), have_shm(false), mac_cursor(0)
563 > : gc(0), img(NULL), have_shm(false), mouse_grabbed(false), mac_cursor(0)
564   {
565          int width = mode.x, height = mode.y;
566          int aligned_width = (width + 15) & ~15;
567          int aligned_height = (height + 15) & ~15;
568  
569          // Set absolute mouse mode
570 <        ADBSetRelMouseMode(false);
570 >        ADBSetRelMouseMode(mouse_grabbed);
571  
572 <        // Create window
572 >        // Create window (setting backround_pixel, border_pixel and colormap is
573 >        // mandatory when using a non-default visual; in 1-bit mode we use the
574 >        // default visual, so we can also use the default colormap)
575          XSetWindowAttributes wattr;
576          wattr.event_mask = eventmask = win_eventmask;
577 <        wattr.background_pixel = black_pixel;
578 <        wattr.colormap = cmap[0];
577 >        wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
578 >        wattr.border_pixel = 0;
579 >        wattr.colormap = (mode.depth == VDEPTH_1BIT ? DefaultColormap(x_display, screen) : cmap[0]);
580          w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
581 <                InputOutput, vis, CWEventMask | CWBackPixel | ((mode.depth == VDEPTH_1BIT || cmap[0] == 0) ? 0 : CWColormap), &wattr);
581 >                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWColormap, &wattr);
582  
583          // Set window name/class
584          set_window_name(w, STR_WINDOW_TITLE);
# Line 443 | Line 607 | driver_window::driver_window(const video
607          XMapWindow(x_display, w);
608          wait_mapped(w);
609  
610 +        // 1-bit mode is big-endian; if the X server is little-endian, we can't
611 +        // use SHM because that doesn't allow changing the image byte order
612 +        bool need_msb_image = (mode.depth == VDEPTH_1BIT && XImageByteOrder(x_display) == LSBFirst);
613 +
614          // Try to create and attach SHM image
615 <        if (local_X11 && XShmQueryExtension(x_display)) {
615 >        if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
616  
617                  // Create SHM image ("height + 2" for safety)
618                  img = XShmCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
# Line 462 | Line 630 | driver_window::driver_window(const video
630                  if (shm_error) {
631                          shmdt(shminfo.shmaddr);
632                          XDestroyImage(img);
633 +                        img = NULL;
634                          shminfo.shmid = -1;
635                  } else {
636                          have_shm = true;
# Line 471 | Line 640 | driver_window::driver_window(const video
640          
641          // Create normal X image if SHM doesn't work ("height + 2" for safety)
642          if (!have_shm) {
643 <                int bytes_per_row = TrivialBytesPerRow(aligned_width, mode.depth);
643 >                int bytes_per_row = (mode.depth == VDEPTH_1BIT ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth)));
644                  the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
645                  img = XCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
646          }
647  
648 <        // 1-Bit mode is big-endian
480 <        if (mode.depth == VDEPTH_1BIT) {
648 >        if (need_msb_image) {
649                  img->byte_order = MSBFirst;
650                  img->bitmap_bit_order = MSBFirst;
651          }
652  
653   #ifdef ENABLE_VOSF
654 +        use_vosf = true;
655          // Allocate memory for frame buffer (SIZE is extended to page-boundary)
656          the_host_buffer = the_buffer_copy;
657          the_buffer_size = page_extend((aligned_height + 2) * img->bytes_per_line);
658          the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
659          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
660 +        D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
661   #else
662          // Allocate memory for frame buffer
663          the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
664 +        D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
665   #endif
666  
667          // Create GC
# Line 512 | Line 683 | driver_window::driver_window(const video
683          native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
684   #endif
685   #ifdef ENABLE_VOSF
686 <        Screen_blitter_init(&visualInfo, native_byte_order);
686 >        Screen_blitter_init(&visualInfo, native_byte_order, mode.depth);
687   #endif
688  
689          // Set VideoMonitor
# Line 526 | Line 697 | driver_window::driver_window(const video
697   // Close display
698   driver_window::~driver_window()
699   {
529        if (img)
530                XDestroyImage(img);
700          if (have_shm) {
701                  XShmDetach(x_display, &shminfo);
702 + #ifdef ENABLE_VOSF
703 +                the_host_buffer = NULL; // don't free() in driver_base dtor
704 + #else
705                  the_buffer_copy = NULL; // don't free() in driver_base dtor
706 + #endif
707 +        }
708 + #ifdef ENABLE_VOSF
709 +        if (use_vosf) {
710 +                // don't free() memory mapped buffers in driver_base dtor
711 +                if (the_buffer != VM_MAP_FAILED) {
712 +                        vm_release(the_buffer, the_buffer_size);
713 +                        the_buffer = NULL;
714 +                }
715 +                if (the_buffer_copy != VM_MAP_FAILED) {
716 +                        vm_release(the_buffer_copy, the_buffer_size);
717 +                        the_buffer_copy = NULL;
718 +                }
719 +        }
720 + #endif
721 +        if (img)
722 +                XDestroyImage(img);
723 +        if (have_shm) {
724 +                shmdt(shminfo.shmaddr);
725 +                shmctl(shminfo.shmid, IPC_RMID, 0);
726          }
727          if (gc)
728                  XFreeGC(x_display, gc);
729   }
730  
731 + // Toggle mouse grab
732 + void driver_window::toggle_mouse_grab(void)
733 + {
734 +        if (mouse_grabbed)
735 +                ungrab_mouse();
736 +        else
737 +                grab_mouse();
738 + }
739 +
740 + // Grab mouse, switch to relative mouse mode
741 + void driver_window::grab_mouse(void)
742 + {
743 +        int result;
744 +        for (int i=0; i<10; i++) {
745 +                result = XGrabPointer(x_display, w, True, 0,
746 +                        GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
747 +                if (result != AlreadyGrabbed)
748 +                        break;
749 +                Delay_usec(100000);
750 +        }
751 +        if (result == GrabSuccess) {
752 +                XStoreName(x_display, w, GetString(STR_WINDOW_TITLE_GRABBED));
753 +                ADBSetRelMouseMode(mouse_grabbed = true);
754 +                disable_mouse_accel();
755 +        }
756 + }
757 +
758 + // Ungrab mouse, switch to absolute mouse mode
759 + void driver_window::ungrab_mouse(void)
760 + {
761 +        if (mouse_grabbed) {
762 +                XUngrabPointer(x_display, CurrentTime);
763 +                XStoreName(x_display, w, GetString(STR_WINDOW_TITLE));
764 +                ADBSetRelMouseMode(mouse_grabbed = false);
765 +                restore_mouse_accel();
766 +        }
767 + }
768 +
769 + // Mouse moved
770 + void driver_window::mouse_moved(int x, int y)
771 + {
772 +        if (!mouse_grabbed) {
773 +                mouse_last_x = x; mouse_last_y = y;
774 +                ADBMouseMoved(x, y);
775 +                return;
776 +        }
777 +
778 +        // Warped mouse motion (this code is taken from SDL)
779 +
780 +        // Post first mouse event
781 +        int width = VideoMonitor.mode.x, height = VideoMonitor.mode.y;
782 +        int delta_x = x - mouse_last_x, delta_y = y - mouse_last_y;
783 +        mouse_last_x = x; mouse_last_y = y;
784 +        ADBMouseMoved(delta_x, delta_y);
785 +
786 +        // Only warp the pointer when it has reached the edge
787 +        const int MOUSE_FUDGE_FACTOR = 8;
788 +        if (x < MOUSE_FUDGE_FACTOR || x > (width - MOUSE_FUDGE_FACTOR)
789 +         || y < MOUSE_FUDGE_FACTOR || y > (height - MOUSE_FUDGE_FACTOR)) {
790 +                XEvent event;
791 +                while (XCheckTypedEvent(x_display, MotionNotify, &event)) {
792 +                        delta_x = x - mouse_last_x; delta_y = y - mouse_last_y;
793 +                        mouse_last_x = x; mouse_last_y = y;
794 +                        ADBMouseMoved(delta_x, delta_y);
795 +                }
796 +                mouse_last_x = width/2;
797 +                mouse_last_y = height/2;
798 +                XWarpPointer(x_display, None, w, 0, 0, 0, 0, mouse_last_x, mouse_last_y);
799 +                for (int i=0; i<10; i++) {
800 +                        XMaskEvent(x_display, PointerMotionMask, &event);
801 +                        if (event.xmotion.x > (mouse_last_x - MOUSE_FUDGE_FACTOR)
802 +                         && event.xmotion.x < (mouse_last_x + MOUSE_FUDGE_FACTOR)
803 +                         && event.xmotion.y > (mouse_last_y - MOUSE_FUDGE_FACTOR)
804 +                         && event.xmotion.y < (mouse_last_y + MOUSE_FUDGE_FACTOR))
805 +                                break;
806 +                }
807 +        }
808 + }
809 +
810  
811   #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
812   /*
# Line 587 | Line 858 | void driver_dga::suspend(void)
858   #endif
859          XUngrabPointer(x_display, CurrentTime);
860          XUngrabKeyboard(x_display, CurrentTime);
861 +        restore_mouse_accel();
862          XUnmapWindow(x_display, w);
863          wait_unmapped(w);
864  
# Line 614 | Line 886 | void driver_dga::resume(void)
886          XMapRaised(x_display, w);
887          wait_mapped(w);
888          XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
889 <        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
890 <        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
889 >        XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
890 >        XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
891 >        disable_mouse_accel();
892   #ifdef ENABLE_XF86_DGA
893          XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
894          XF86DGASetViewPort(x_display, screen, 0, 0);
# Line 762 | Line 1035 | driver_fbdev::driver_fbdev(const video_m
1035          XGrabPointer(x_display, w, True,
1036                  PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
1037                  GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
1038 +        disable_mouse_accel();
1039          
1040          // Calculate bytes per row
1041          int bytes_per_row = TrivialBytesPerRow(mode.x, mode.depth);
1042          
1043          // Map frame buffer
1044 <        if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
1045 <                if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
1044 >        the_buffer_size = height * bytes_per_row;
1045 >        if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
1046 >                if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
1047                          char str[256];
1048                          sprintf(str, GetString(STR_FBDEV_MMAP_ERR), strerror(errno));
1049                          ErrorAlert(str);
# Line 780 | Line 1055 | driver_fbdev::driver_fbdev(const video_m
1055   #if REAL_ADDRESSING || DIRECT_ADDRESSING
1056          // Screen_blitter_init() returns TRUE if VOSF is mandatory
1057          // i.e. the framebuffer update function is not Blit_Copy_Raw
1058 <        use_vosf = Screen_blitter_init(&visualInfo, true);
1058 >        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
1059          
1060          if (use_vosf) {
1061            // Allocate memory for frame buffer (SIZE is extended to page-boundary)
# Line 807 | Line 1082 | driver_fbdev::driver_fbdev(const video_m
1082   // Close display
1083   driver_fbdev::~driver_fbdev()
1084   {
1085 +        if (!use_vosf) {
1086 +                if (the_buffer != MAP_FAILED) {
1087 +                        // don't free() the screen buffer in driver_base dtor
1088 +                        munmap(the_buffer, the_buffer_size);
1089 +                        the_buffer = NULL;
1090 +                }
1091 +        }
1092 + #ifdef ENABLE_VOSF
1093 +        else {
1094 +                if (the_host_buffer != MAP_FAILED) {
1095 +                        // don't free() the screen buffer in driver_base dtor
1096 +                        munmap(the_host_buffer, the_buffer_size);
1097 +                        the_host_buffer = NULL;
1098 +                }
1099 +                if (the_buffer_copy != VM_MAP_FAILED) {
1100 +                        vm_release(the_buffer_copy, the_buffer_size);
1101 +                        the_buffer_copy = NULL;
1102 +                }
1103 +                if (the_buffer != VM_MAP_FAILED) {
1104 +                        vm_release(the_buffer, the_buffer_size);
1105 +                        the_buffer = NULL;
1106 +                }
1107 +        }
1108 + #endif
1109   }
1110   #endif
1111  
# Line 876 | Line 1175 | driver_xf86dga::driver_xf86dga(const vid
1175          XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1176          XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
1177          XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1178 +        disable_mouse_accel();
1179  
1180          int v_width, v_bank, v_size;
1181          XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size);
# Line 892 | Line 1192 | driver_xf86dga::driver_xf86dga(const vid
1192  
1193          // Init blitting routines
1194          int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, mode.depth);
1195 < #ifdef VIDEO_VOSF
1195 > #if VIDEO_VOSF
1196   #if REAL_ADDRESSING || DIRECT_ADDRESSING
1197          // Screen_blitter_init() returns TRUE if VOSF is mandatory
1198          // i.e. the framebuffer update function is not Blit_Copy_Raw
1199 <        use_vosf = Screen_blitter_init(&visualInfo, true);
1199 >        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
1200          
1201          if (use_vosf) {
1202            // Allocate memory for frame buffer (SIZE is extended to page-boundary)
# Line 923 | Line 1223 | driver_xf86dga::driver_xf86dga(const vid
1223   driver_xf86dga::~driver_xf86dga()
1224   {
1225          XF86DGADirectVideo(x_display, screen, 0);
1226 +        if (!use_vosf) {
1227 +                // don't free() the screen buffer in driver_base dtor
1228 +                the_buffer = NULL;
1229 +        }
1230 + #ifdef ENABLE_VOSF
1231 +        else {
1232 +                // don't free() the screen buffer in driver_base dtor
1233 +                the_host_buffer = NULL;
1234 +                
1235 +                if (the_buffer_copy != VM_MAP_FAILED) {
1236 +                        vm_release(the_buffer_copy, the_buffer_size);
1237 +                        the_buffer_copy = NULL;
1238 +                }
1239 +                if (the_buffer != VM_MAP_FAILED) {
1240 +                        vm_release(the_buffer, the_buffer_size);
1241 +                        the_buffer = NULL;
1242 +                }
1243 +        }
1244 + #endif
1245   #ifdef ENABLE_XF86_VIDMODE
1246          if (has_vidmode)
1247                  XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
# Line 1020 | Line 1339 | static void keycode_init(void)
1339   // Open display for specified mode
1340   static bool video_open(const video_mode &mode)
1341   {
1342 +        // Find best available X visual
1343 +        if (!find_visual_for_depth(mode.depth)) {
1344 +                ErrorAlert(STR_NO_XVISUAL_ERR);
1345 +                return false;
1346 +        }
1347 +
1348 +        // Create color maps
1349 +        if (color_class == PseudoColor || color_class == DirectColor) {
1350 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1351 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1352 +        } else {
1353 +                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone);
1354 +                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone);
1355 +        }
1356 +
1357 +        // Find pixel format of direct modes
1358 +        if (color_class == DirectColor || color_class == TrueColor) {
1359 +                rshift = gshift = bshift = 0;
1360 +                rloss = gloss = bloss = 8;
1361 +                uint32 mask;
1362 +                for (mask=vis->red_mask; !(mask&1); mask>>=1)
1363 +                        ++rshift;
1364 +                for (; mask&1; mask>>=1)
1365 +                        --rloss;
1366 +                for (mask=vis->green_mask; !(mask&1); mask>>=1)
1367 +                        ++gshift;
1368 +                for (; mask&1; mask>>=1)
1369 +                        --gloss;
1370 +                for (mask=vis->blue_mask; !(mask&1); mask>>=1)
1371 +                        ++bshift;
1372 +                for (; mask&1; mask>>=1)
1373 +                        --bloss;
1374 +        }
1375 +
1376 +        // Preset palette pixel values for CLUT or gamma table
1377 +        if (color_class == DirectColor) {
1378 +                int num = vis->map_entries;
1379 +                for (int i=0; i<num; i++) {
1380 +                        int c = (i * 256) / num;
1381 +                        palette[i].pixel = map_rgb(c, c, c);
1382 +                        palette[i].flags = DoRed | DoGreen | DoBlue;
1383 +                }
1384 +        } else if (color_class == PseudoColor) {
1385 +                for (int i=0; i<256; i++) {
1386 +                        palette[i].pixel = i;
1387 +                        palette[i].flags = DoRed | DoGreen | DoBlue;
1388 +                }
1389 +        }
1390 +
1391 +        // Load gray ramp to color map
1392 +        int num = (color_class == DirectColor ? vis->map_entries : 256);
1393 +        for (int i=0; i<num; i++) {
1394 +                int c = (i * 256) / num;
1395 +                palette[i].red = c * 0x0101;
1396 +                palette[i].green = c * 0x0101;
1397 +                palette[i].blue = c * 0x0101;
1398 +        }
1399 +        if (color_class == PseudoColor || color_class == DirectColor) {
1400 +                XStoreColors(x_display, cmap[0], palette, num);
1401 +                XStoreColors(x_display, cmap[1], palette, num);
1402 +        }
1403 +
1404 + #ifdef ENABLE_VOSF
1405 +        // Load gray ramp to 8->16/32 expand map
1406 +        if (!IsDirectMode(mode) && xdepth > 8)
1407 +                for (int i=0; i<256; i++)
1408 +                        ExpandMap[i] = map_rgb(i, i, i);
1409 + #endif
1410 +
1411          // Create display driver object of requested type
1412          switch (display_type) {
1413                  case DISPLAY_WINDOW:
# Line 1046 | Line 1434 | static bool video_open(const video_mode
1434  
1435   #ifdef ENABLE_VOSF
1436          if (use_vosf) {
1437 <                // Initialize the mainBuffer structure
1438 <                if (!video_init_buffer()) {
1437 >                // Initialize the VOSF system
1438 >                if (!video_vosf_init()) {
1439                          ErrorAlert(STR_VOSF_INIT_ERR);
1440                  return false;
1441                  }
1054
1055                // Initialize the handler for SIGSEGV
1056                if (!sigsegv_install_handler(screen_fault_handler)) {
1057                        ErrorAlert("Could not initialize Video on SEGV signals");
1058                        return false;
1059                }
1442          }
1443   #endif
1444          
# Line 1107 | Line 1489 | bool VideoInit(bool classic)
1489          // Find screen and root window
1490          screen = XDefaultScreen(x_display);
1491          rootwin = XRootWindow(x_display, screen);
1492 <        
1493 <        // Get screen depth
1494 <        xdepth = DefaultDepth(x_display, screen);
1492 >
1493 >        // Get sorted list of available depths
1494 >        avail_depths = XListDepths(x_display, screen, &num_depths);
1495 >        if (avail_depths == NULL) {
1496 >                ErrorAlert(STR_UNSUPP_DEPTH_ERR);
1497 >                return false;
1498 >        }
1499 >        sort(avail_depths, avail_depths + num_depths);
1500          
1501   #ifdef ENABLE_FBDEV_DGA
1502          // Frame buffer name
# Line 1149 | Line 1536 | bool VideoInit(bool classic)
1536          black_pixel = BlackPixel(x_display, screen);
1537          white_pixel = WhitePixel(x_display, screen);
1538  
1152        // Get appropriate visual
1153        int color_class;
1154        switch (xdepth) {
1155                case 1:
1156                        color_class = StaticGray;
1157                        break;
1158                case 8:
1159                        color_class = PseudoColor;
1160                        break;
1161                case 15:
1162                case 16:
1163                case 24:
1164                case 32: // Try DirectColor first, as this will allow gamma correction
1165                        color_class = DirectColor;
1166                        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo))
1167                                color_class = TrueColor;
1168                        break;
1169                default:
1170                        ErrorAlert(STR_UNSUPP_DEPTH_ERR);
1171                        return false;
1172        }
1173        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
1174                ErrorAlert(STR_NO_XVISUAL_ERR);
1175                return false;
1176        }
1177        if (visualInfo.depth != xdepth) {
1178                ErrorAlert(STR_NO_XVISUAL_ERR);
1179                return false;
1180        }
1181        vis = visualInfo.visual;
1182
1183        // Create color maps
1184        if (color_class == PseudoColor || color_class == DirectColor) {
1185                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1186                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1187
1188                // Preset pixel members for gamma table
1189                if (color_class == DirectColor) {
1190                        int num = vis->map_entries;
1191                        uint32 rmask = vis->red_mask, gmask = vis->green_mask, bmask = vis->blue_mask;
1192                        uint32 mask;
1193                        int rloss = 8, rshift = 0;
1194                        for (mask=rmask; !(mask&1); mask>>=1)
1195                                ++rshift;
1196                        for (; mask&1; mask>>=1)
1197                                --rloss;
1198                        int gloss = 8, gshift = 0;
1199                        for (mask=gmask; !(mask&1); mask>>=1)
1200                                ++gshift;
1201                        for (; mask&1; mask>>=1)
1202                                --gloss;
1203                        int bloss = 8, bshift = 0;
1204                        for (mask=bmask; !(mask&1); mask>>=1)
1205                                ++bshift;
1206                        for (; mask&1; mask>>=1)
1207                                --bloss;
1208                        for (int i=0; i<num; i++) {
1209                                int c = (i * 256) / num;
1210                                palette[i].pixel = ((c >> rloss) << rshift) | ((c >> gloss) << gshift) | ((c >> bloss) << bshift);
1211                        }
1212                }
1213        }
1214
1539          // Get screen mode from preferences
1540          const char *mode_str;
1541          if (classic_mode)
# Line 1245 | Line 1569 | bool VideoInit(bool classic)
1569          else if (default_height > DisplayHeight(x_display, screen))
1570                  default_height = DisplayHeight(x_display, screen);
1571  
1572 <        // Mac screen depth is always 1 bit in Classic mode, but follows X depth otherwise
1573 <        int depth = (classic_mode ? 1 : xdepth);
1574 <        video_depth depth_mode = DepthModeForPixelDepth(depth);
1572 >        // Mac screen depth follows X depth
1573 >        video_depth default_depth = VDEPTH_1BIT;
1574 >        switch (DefaultDepth(x_display, screen)) {
1575 >                case 8:
1576 >                        default_depth = VDEPTH_8BIT;
1577 >                        break;
1578 >                case 15: case 16:
1579 >                        default_depth = VDEPTH_16BIT;
1580 >                        break;
1581 >                case 24: case 32:
1582 >                        default_depth = VDEPTH_32BIT;
1583 >                        break;
1584 >        }
1585  
1586          // Construct list of supported modes
1587          if (display_type == DISPLAY_WINDOW) {
1588                  if (classic)
1589 <                        add_mode(512, 342, 0x80, 64, depth_mode);
1589 >                        add_mode(512, 342, 0x80, 64, VDEPTH_1BIT);
1590                  else {
1591 <                        add_mode(512, 384, 0x80, TrivialBytesPerRow(512, depth_mode), depth_mode);
1592 <                        add_mode(640, 480, 0x81, TrivialBytesPerRow(640, depth_mode), depth_mode);
1593 <                        add_mode(800, 600, 0x82, TrivialBytesPerRow(800, depth_mode), depth_mode);
1594 <                        add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, depth_mode), depth_mode);
1261 <                        add_mode(1280, 1024, 0x84, TrivialBytesPerRow(1280, depth_mode), depth_mode);
1591 >                        for (unsigned d=VDEPTH_1BIT; d<=VDEPTH_32BIT; d++) {
1592 >                                if (find_visual_for_depth(video_depth(d)))
1593 >                                        add_window_modes(video_depth(d));
1594 >                        }
1595                  }
1596          } else
1597 <                add_mode(default_width, default_height, 0x80, TrivialBytesPerRow(default_width, depth_mode), depth_mode);
1597 >                add_mode(default_width, default_height, 0x80, TrivialBytesPerRow(default_width, default_depth), default_depth);
1598 >        if (VideoModes.empty()) {
1599 >                ErrorAlert(STR_NO_XVISUAL_ERR);
1600 >                return false;
1601 >        }
1602 >        video_init_depth_list();
1603 >
1604 > #if DEBUG
1605 >        D(bug("Available video modes:\n"));
1606 >        vector<video_mode>::const_iterator i = VideoModes.begin(), end = VideoModes.end();
1607 >        while (i != end) {
1608 >                int bits = 1 << i->depth;
1609 >                if (bits == 16)
1610 >                        bits = 15;
1611 >                else if (bits == 32)
1612 >                        bits = 24;
1613 >                D(bug(" %dx%d (ID %02x), %d colors\n", i->x, i->y, i->resolution_id, 1 << bits));
1614 >                ++i;
1615 >        }
1616 > #endif
1617  
1618          // Find requested default mode and open display
1619          if (VideoModes.size() == 1)
1620                  return video_open(VideoModes[0]);
1621          else {
1622                  // Find mode with specified dimensions
1623 <                std::vector<video_mode>::const_iterator i = VideoModes.begin(), end = VideoModes.end();
1624 <                while (i != end) {
1625 <                        if (i->x == default_width && i->y == default_height)
1623 >                std::vector<video_mode>::const_iterator i, end = VideoModes.end();
1624 >                for (i = VideoModes.begin(); i != end; ++i) {
1625 >                        if (i->x == default_width && i->y == default_height && i->depth == default_depth)
1626                                  return video_open(*i);
1275                        ++i;
1627                  }
1628                  return video_open(VideoModes[0]);
1629          }
# Line 1303 | Line 1654 | static void video_close(void)
1654          XSync(x_display, false);
1655  
1656   #ifdef ENABLE_VOSF
1306        // Deinitialize VOSF
1657          if (use_vosf) {
1658 <                if (mainBuffer.pageInfo) {
1659 <                        free(mainBuffer.pageInfo);
1310 <                        mainBuffer.pageInfo = NULL;
1311 <                }
1312 <                if (mainBuffer.dirtyPages) {
1313 <                        free(mainBuffer.dirtyPages);
1314 <                        mainBuffer.dirtyPages = NULL;
1315 <                }
1658 >                // Deinitialize VOSF
1659 >                video_vosf_exit();
1660          }
1661   #endif
1662  
1663          // Close display
1664          delete drv;
1665          drv = NULL;
1322 }
1323
1324 void VideoExit(void)
1325 {
1326        // Close display
1327        video_close();
1666  
1667          // Free colormaps
1668          if (cmap[0]) {
# Line 1335 | Line 1673 | void VideoExit(void)
1673                  XFreeColormap(x_display, cmap[1]);
1674                  cmap[1] = 0;
1675          }
1676 + }
1677 +
1678 + void VideoExit(void)
1679 + {
1680 +        // Close display
1681 +        video_close();
1682  
1683   #ifdef ENABLE_XF86_VIDMODE
1684          // Free video mode list
# Line 1351 | Line 1695 | void VideoExit(void)
1695                  fbdev_fd = -1;
1696          }
1697   #endif
1698 +
1699 +        // Free depth list
1700 +        if (avail_depths) {
1701 +                XFree(avail_depths);
1702 +                avail_depths = NULL;
1703 +        }
1704   }
1705  
1706  
# Line 1386 | Line 1736 | void VideoInterrupt(void)
1736   *  Set palette
1737   */
1738  
1739 < void video_set_palette(uint8 *pal)
1739 > void video_set_palette(uint8 *pal, int num_in)
1740   {
1741          LOCK_PALETTE;
1742  
1743          // Convert colors to XColor array
1744 <        int num_in = 256, num_out = 256;
1745 <        if (VideoMonitor.mode.depth == VDEPTH_16BIT) {
1746 <                num_in = 32;
1747 <                // If X is in 565 mode we have to stretch the palette from 32 to 64 entries
1748 <                if (vis->c_class == DirectColor)
1749 <                        num_out = vis->map_entries;
1744 >        int num_out = 256;
1745 >        bool stretch = false;
1746 >        if (IsDirectMode(VideoMonitor.mode)) {
1747 >                // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries
1748 >                num_out = vis->map_entries;
1749 >                stretch = true;
1750          }
1751          XColor *p = palette;
1752          for (int i=0; i<num_out; i++) {
1753 <                int c = (i * num_in) / num_out;
1753 >                int c = (stretch ? (i * num_in) / num_out : i);
1754                  p->red = pal[c*3 + 0] * 0x0101;
1755                  p->green = pal[c*3 + 1] * 0x0101;
1756                  p->blue = pal[c*3 + 2] * 0x0101;
1407                if (!IsDirectMode(VideoMonitor.mode))
1408                        p->pixel = i;
1409                p->flags = DoRed | DoGreen | DoBlue;
1757                  p++;
1758          }
1759  
1760 + #ifdef ENABLE_VOSF
1761 +        // Recalculate pixel color expansion map
1762 +        if (!IsDirectMode(VideoMonitor.mode) && xdepth > 8) {
1763 +                for (int i=0; i<256; i++) {
1764 +                        int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
1765 +                        ExpandMap[i] = map_rgb(pal[c*3+0], pal[c*3+1], pal[c*3+2]);
1766 +                }
1767 +
1768 +                // We have to redraw everything because the interpretation of pixel values changed
1769 +                LOCK_VOSF;
1770 +                PFLAG_SET_ALL;
1771 +                UNLOCK_VOSF;
1772 +                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
1773 +        }
1774 + #endif
1775 +
1776          // Tell redraw thread to change palette
1777          palette_changed = true;
1778  
# Line 1435 | Line 1798 | void video_switch_to_mode(const video_mo
1798  
1799  
1800   /*
1801 < *  Translate key event to Mac keycode
1801 > *  Translate key event to Mac keycode, returns -1 if no keycode was found
1802 > *  and -2 if the key was recognized as a hotkey
1803   */
1804  
1805 < static int kc_decode(KeySym ks)
1805 > static int kc_decode(KeySym ks, bool key_down)
1806   {
1807          switch (ks) {
1808                  case XK_A: case XK_a: return 0x00;
# Line 1491 | Line 1855 | static int kc_decode(KeySym ks)
1855                  case XK_period: case XK_greater: return 0x2f;
1856                  case XK_slash: case XK_question: return 0x2c;
1857  
1858 < #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1495 <                case XK_Tab: if (ctrl_down) {drv->suspend(); return -1;} else return 0x30;
1496 < #else
1497 <                case XK_Tab: return 0x30;
1498 < #endif
1858 >                case XK_Tab: if (ctrl_down) {if (key_down) drv->suspend(); return -2;} else return 0x30;
1859                  case XK_Return: return 0x24;
1860                  case XK_space: return 0x31;
1861                  case XK_BackSpace: return 0x33;
# Line 1529 | Line 1889 | static int kc_decode(KeySym ks)
1889                  case XK_Left: return 0x3b;
1890                  case XK_Right: return 0x3c;
1891  
1892 <                case XK_Escape: if (ctrl_down) {quit_full_screen = true; emerg_quit = true; return -1;} else return 0x35;
1892 >                case XK_Escape: if (ctrl_down) {if (key_down) { quit_full_screen = true; emerg_quit = true; } return -2;} else return 0x35;
1893  
1894 <                case XK_F1: if (ctrl_down) {SysMountFirstFloppy(); return -1;} else return 0x7a;
1894 >                case XK_F1: if (ctrl_down) {if (key_down) SysMountFirstFloppy(); return -2;} else return 0x7a;
1895                  case XK_F2: return 0x78;
1896                  case XK_F3: return 0x63;
1897                  case XK_F4: return 0x76;
1898 <                case XK_F5: return 0x60;
1898 >                case XK_F5: if (ctrl_down) {if (key_down) drv->toggle_mouse_grab(); return -2;} else return 0x60;
1899                  case XK_F6: return 0x61;
1900                  case XK_F7: return 0x62;
1901                  case XK_F8: return 0x64;
# Line 1583 | Line 1943 | static int kc_decode(KeySym ks)
1943          return -1;
1944   }
1945  
1946 < static int event2keycode(XKeyEvent &ev)
1946 > static int event2keycode(XKeyEvent &ev, bool key_down)
1947   {
1948          KeySym ks;
1589        int as;
1949          int i = 0;
1950  
1951          do {
1952                  ks = XLookupKeysym(&ev, i++);
1953 <                as = kc_decode(ks);
1954 <                if (as != -1)
1953 >                int as = kc_decode(ks, key_down);
1954 >                if (as >= 0)
1955 >                        return as;
1956 >                if (as == -2)
1957                          return as;
1958          } while (ks != NoSymbol);
1959  
# Line 1611 | Line 1972 | static void handle_events(void)
1972                  XNextEvent(x_display, &event);
1973  
1974                  switch (event.type) {
1975 +
1976                          // Mouse button
1977                          case ButtonPress: {
1978                                  unsigned int button = event.xbutton.button;
# Line 1639 | Line 2001 | static void handle_events(void)
2001                          }
2002  
2003                          // Mouse moved
1642                        case EnterNotify:
2004                          case MotionNotify:
2005 <                                ADBMouseMoved(event.xmotion.x, event.xmotion.y);
2005 >                                drv->mouse_moved(event.xmotion.x, event.xmotion.y);
2006 >                                break;
2007 >
2008 >                        // Mouse entered window
2009 >                        case EnterNotify:
2010 >                                if (event.xcrossing.mode != NotifyGrab && event.xcrossing.mode != NotifyUngrab)
2011 >                                        drv->mouse_moved(event.xmotion.x, event.xmotion.y);
2012                                  break;
2013  
2014                          // Keyboard
2015                          case KeyPress: {
2016 <                                int code;
2016 >                                int code = -1;
2017                                  if (use_keycodes) {
2018 <                                        event2keycode(event.xkey);      // This is called to process the hotkeys
2019 <                                        code = keycode_table[event.xkey.keycode & 0xff];
2018 >                                        if (event2keycode(event.xkey, true) != -2)      // This is called to process the hotkeys
2019 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2020                                  } else
2021 <                                        code = event2keycode(event.xkey);
2022 <                                if (code != -1) {
2021 >                                        code = event2keycode(event.xkey, true);
2022 >                                if (code >= 0) {
2023                                          if (!emul_suspended) {
2024                                                  if (code == 0x39) {     // Caps Lock pressed
2025                                                          if (caps_on) {
# Line 1674 | Line 2041 | static void handle_events(void)
2041                                  break;
2042                          }
2043                          case KeyRelease: {
2044 <                                int code;
2044 >                                int code = -1;
2045                                  if (use_keycodes) {
2046 <                                        event2keycode(event.xkey);      // This is called to process the hotkeys
2047 <                                        code = keycode_table[event.xkey.keycode & 0xff];
2046 >                                        if (event2keycode(event.xkey, false) != -2)     // This is called to process the hotkeys
2047 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2048                                  } else
2049 <                                        code = event2keycode(event.xkey);
2050 <                                if (code != -1 && code != 0x39) {       // Don't propagate Caps Lock releases
2049 >                                        code = event2keycode(event.xkey, false);
2050 >                                if (code >= 0 && code != 0x39) {        // Don't propagate Caps Lock releases
2051                                          ADBKeyUp(code);
2052                                          if (code == 0x36)
2053                                                  ctrl_down = false;
# Line 1944 | Line 2311 | static void update_display_static(driver
2311  
2312   static inline void possibly_quit_dga_mode()
2313   {
2314 <        // Quit DGA mode if requested
2314 >        // Quit DGA mode if requested (something terrible has happened and we
2315 >        // want to give control back to the user)
2316          if (quit_full_screen) {
2317                  quit_full_screen = false;
2318                  delete drv;
# Line 1952 | Line 2320 | static inline void possibly_quit_dga_mod
2320          }
2321   }
2322  
2323 + static inline void possibly_ungrab_mouse()
2324 + {
2325 +        // Ungrab mouse if requested (something terrible has happened and we
2326 +        // want to give control back to the user)
2327 +        if (quit_full_screen) {
2328 +                quit_full_screen = false;
2329 +                if (drv)
2330 +                        drv->ungrab_mouse();
2331 +        }
2332 + }
2333 +
2334   static inline void handle_palette_changes(void)
2335   {
2336          LOCK_PALETTE;
# Line 1968 | Line 2347 | static void video_refresh_dga(void)
2347   {
2348          // Quit DGA mode if requested
2349          possibly_quit_dga_mode();
1971        
1972        // Handle X events
1973        handle_events();
1974        
1975        // Handle palette changes
1976        handle_palette_changes();
2350   }
2351  
2352   #ifdef ENABLE_VOSF
# Line 1983 | Line 2356 | static void video_refresh_dga_vosf(void)
2356          // Quit DGA mode if requested
2357          possibly_quit_dga_mode();
2358          
1986        // Handle X events
1987        handle_events();
1988        
1989        // Handle palette changes
1990        handle_palette_changes();
1991        
2359          // Update display (VOSF variant)
2360          static int tick_counter = 0;
2361          if (++tick_counter >= frame_skip) {
# Line 2004 | Line 2371 | static void video_refresh_dga_vosf(void)
2371  
2372   static void video_refresh_window_vosf(void)
2373   {
2374 <        // Quit DGA mode if requested
2375 <        possibly_quit_dga_mode();
2009 <        
2010 <        // Handle X events
2011 <        handle_events();
2012 <        
2013 <        // Handle palette changes
2014 <        handle_palette_changes();
2374 >        // Ungrab mouse if requested
2375 >        possibly_ungrab_mouse();
2376          
2377          // Update display (VOSF variant)
2378          static int tick_counter = 0;
# Line 2029 | Line 2390 | static void video_refresh_window_vosf(vo
2390  
2391   static void video_refresh_window_static(void)
2392   {
2393 <        // Handle X events
2394 <        handle_events();
2395 <        
2035 <        // Handle_palette changes
2036 <        handle_palette_changes();
2037 <        
2393 >        // Ungrab mouse if requested
2394 >        possibly_ungrab_mouse();
2395 >
2396          // Update display (static variant)
2397          static int tick_counter = 0;
2398          if (++tick_counter >= frame_skip) {
# Line 2045 | Line 2403 | static void video_refresh_window_static(
2403  
2404   static void video_refresh_window_dynamic(void)
2405   {
2406 <        // Handle X events
2407 <        handle_events();
2408 <        
2051 <        // Handle_palette changes
2052 <        handle_palette_changes();
2053 <        
2406 >        // Ungrab mouse if requested
2407 >        possibly_ungrab_mouse();
2408 >
2409          // Update display (dynamic variant)
2410          static int tick_counter = 0;
2411          tick_counter++;
# Line 2086 | Line 2441 | static void VideoRefreshInit(void)
2441          }
2442   }
2443  
2444 + // This function is called on non-threaded platforms from a timer interrupt
2445   void VideoRefresh(void)
2446   {
2447          // We need to check redraw_thread_active to inhibit refreshed during
2448          // mode changes on non-threaded platforms
2449 <        if (redraw_thread_active)
2450 <                video_refresh();
2449 >        if (!redraw_thread_active)
2450 >                return;
2451 >
2452 >        // Handle X events
2453 >        handle_events();
2454 >
2455 >        // Handle palette changes
2456 >        handle_palette_changes();
2457 >
2458 >        // Update display
2459 >        video_refresh();
2460   }
2461  
2462 + const int VIDEO_REFRESH_HZ = 60;
2463 + const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
2464 +
2465   #ifdef HAVE_PTHREADS
2466   static void *redraw_func(void *arg)
2467   {
2468 +        int fd = ConnectionNumber(x_display);
2469 +
2470          uint64 start = GetTicks_usec();
2471          int64 ticks = 0;
2472 <        uint64 next = GetTicks_usec();
2472 >        uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2473 >
2474          while (!redraw_thread_cancel) {
2475 <                video_refresh();
2105 <                next += 16667;
2475 >
2476                  int64 delay = next - GetTicks_usec();
2477 <                if (delay > 0)
2478 <                        Delay_usec(delay);
2479 <                else if (delay < -16667)
2477 >                if (delay < -VIDEO_REFRESH_DELAY) {
2478 >
2479 >                        // We are lagging far behind, so we reset the delay mechanism
2480                          next = GetTicks_usec();
2481 <                ticks++;
2481 >
2482 >                } else if (delay <= 0) {
2483 >
2484 >                        // Delay expired, refresh display
2485 >                        handle_events();
2486 >                        handle_palette_changes();
2487 >                        video_refresh();
2488 >                        next += VIDEO_REFRESH_DELAY;
2489 >                        ticks++;
2490 >
2491 >                } else {
2492 >
2493 >                        // No display refresh pending, check for X events
2494 >                        fd_set readfds;
2495 >                        FD_ZERO(&readfds);
2496 >                        FD_SET(fd, &readfds);
2497 >                        struct timeval timeout;
2498 >                        timeout.tv_sec = 0;
2499 >                        timeout.tv_usec = delay;
2500 >                        if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0)
2501 >                                handle_events();
2502 >                }
2503          }
2504 +
2505          uint64 end = GetTicks_usec();
2506 <        // printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, ticks * 1000000 / (end - start));
2506 >        D(bug("%Ld refreshes in %Ld usec = %f refreshes/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
2507          return NULL;
2508   }
2509   #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines