ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/video_x.cpp
Revision: 1.40
Committed: 2005-03-28T16:19:28Z (19 years, 7 months ago) by gbeauche
Branch: MAIN
Changes since 1.39: +46 -27 lines
Log Message:
Only support True Color frame buffers. Make it possible to run-time switch
depth in FBDev DGA fullscreen mode.

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * video_x.cpp - Video/graphics emulation, X11 specific stuff
3     *
4 gbeauche 1.35 * SheepShaver (C) 1997-2005 Marc Hellwig and Christian Bauer
5 cebix 1.1 *
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
8     * the Free Software Foundation; either version 2 of the License, or
9     * (at your option) any later version.
10     *
11     * This program is distributed in the hope that it will be useful,
12     * but WITHOUT ANY WARRANTY; without even the implied warranty of
13     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14     * GNU General Public License for more details.
15     *
16     * You should have received a copy of the GNU General Public License
17     * along with this program; if not, write to the Free Software
18     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19     */
20    
21 gbeauche 1.38 /*
22     * NOTES:
23     * The Ctrl key works like a qualifier for special actions:
24     * Ctrl-Tab = suspend DGA mode
25     * Ctrl-Esc = emergency quit
26     * Ctrl-F1 = mount floppy
27     * Ctrl-F5 = grab mouse (in windowed mode)
28     */
29    
30 gbeauche 1.6 #include "sysdeps.h"
31    
32 cebix 1.1 #include <X11/Xlib.h>
33     #include <X11/Xutil.h>
34     #include <X11/keysym.h>
35     #include <X11/extensions/XShm.h>
36     #include <sys/ipc.h>
37     #include <sys/shm.h>
38 gbeauche 1.6 #include <errno.h>
39 gbeauche 1.7 #include <pthread.h>
40 gbeauche 1.6
41 gbeauche 1.13 #include <algorithm>
42    
43 gbeauche 1.38 #ifdef ENABLE_FBDEV_DGA
44     # include <linux/fb.h>
45     # include <sys/ioctl.h>
46     #endif
47    
48 gbeauche 1.6 #ifdef ENABLE_XF86_DGA
49 gbeauche 1.15 # include <X11/extensions/xf86dga.h>
50 gbeauche 1.6 #endif
51    
52     #ifdef ENABLE_XF86_VIDMODE
53     # include <X11/extensions/xf86vmode.h>
54     #endif
55 cebix 1.1
56     #include "main.h"
57     #include "adb.h"
58     #include "prefs.h"
59     #include "user_strings.h"
60     #include "about_window.h"
61     #include "video.h"
62     #include "video_defs.h"
63 gbeauche 1.30 #include "video_blit.h"
64 cebix 1.1
65     #define DEBUG 0
66     #include "debug.h"
67    
68 gbeauche 1.13 #ifndef NO_STD_NAMESPACE
69     using std::sort;
70     #endif
71    
72 cebix 1.1
73 gbeauche 1.6 // Constants
74     const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
75 gbeauche 1.22 static const bool hw_mac_cursor_accl = true; // Flag: Enable MacOS to X11 copy of cursor?
76 cebix 1.1
77     // Global variables
78     static int32 frame_skip;
79 gbeauche 1.8 static int16 mouse_wheel_mode;
80     static int16 mouse_wheel_lines;
81 cebix 1.1 static bool redraw_thread_active = false; // Flag: Redraw thread installed
82 gbeauche 1.15 static pthread_attr_t redraw_thread_attr; // Redraw thread attributes
83 gbeauche 1.28 static volatile bool redraw_thread_cancel; // Flag: Cancel Redraw thread
84 cebix 1.1 static pthread_t redraw_thread; // Redraw thread
85    
86 gbeauche 1.4 static bool local_X11; // Flag: X server running on local machine?
87 cebix 1.1 static volatile bool thread_stop_req = false;
88     static volatile bool thread_stop_ack = false; // Acknowledge for thread_stop_req
89    
90     static bool has_dga = false; // Flag: Video DGA capable
91     static bool has_vidmode = false; // Flag: VidMode extension available
92    
93 gbeauche 1.3 #ifdef ENABLE_VOSF
94     static bool use_vosf = true; // Flag: VOSF enabled
95     #else
96     static const bool use_vosf = false; // VOSF not possible
97     #endif
98    
99 cebix 1.1 static bool palette_changed = false; // Flag: Palette changed, redraw thread must update palette
100     static bool ctrl_down = false; // Flag: Ctrl key pressed
101 gbeauche 1.27 static bool caps_on = false; // Flag: Caps Lock on
102 cebix 1.1 static bool quit_full_screen = false; // Flag: DGA close requested from redraw thread
103     static volatile bool quit_full_screen_ack = false; // Acknowledge for quit_full_screen
104     static bool emerg_quit = false; // Flag: Ctrl-Esc pressed, emergency quit requested from MacOS thread
105    
106     static bool emul_suspended = false; // Flag: emulator suspended
107     static Window suspend_win; // "Suspend" window
108     static void *fb_save = NULL; // Saved frame buffer for suspend
109 gbeauche 1.6 static bool use_keycodes = false; // Flag: Use keycodes rather than keysyms
110     static int keycode_table[256]; // X keycode -> Mac keycode translation table
111 cebix 1.1
112     // X11 variables
113     static int screen; // Screen number
114     static int xdepth; // Depth of X screen
115     static int depth; // Depth of Mac frame buffer
116     static Window rootwin, the_win; // Root window and our window
117 gbeauche 1.13 static int num_depths = 0; // Number of available X depths
118     static int *avail_depths = NULL; // List of available X depths
119 gbeauche 1.30 static VisualFormat visualFormat;
120 cebix 1.1 static XVisualInfo visualInfo;
121     static Visual *vis;
122 gbeauche 1.13 static int color_class;
123     static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
124 cebix 1.1 static Colormap cmap[2]; // Two colormaps (DGA) for 8-bit mode
125 gbeauche 1.13 static XColor x_palette[256]; // Color palette to be used as CLUT and gamma table
126 gbeauche 1.38 static int orig_accel_numer, orig_accel_denom, orig_threshold; // Original mouse acceleration
127 gbeauche 1.13
128 cebix 1.1 static XColor black, white;
129     static unsigned long black_pixel, white_pixel;
130     static int eventmask;
131 gbeauche 1.13 static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
132     static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
133 cebix 1.1
134     // Variables for window mode
135     static GC the_gc;
136     static XImage *img = NULL;
137     static XShmSegmentInfo shminfo;
138     static XImage *cursor_image, *cursor_mask_image;
139     static Pixmap cursor_map, cursor_mask_map;
140     static Cursor mac_cursor;
141     static GC cursor_gc, cursor_mask_gc;
142     static bool cursor_changed = false; // Flag: Cursor changed, window_func must update cursor
143     static bool have_shm = false; // Flag: SHM present and usable
144 gbeauche 1.3 static uint8 *the_buffer = NULL; // Pointer to Mac frame buffer
145 cebix 1.1 static uint8 *the_buffer_copy = NULL; // Copy of Mac frame buffer
146 gbeauche 1.3 static uint32 the_buffer_size; // Size of allocated the_buffer
147 cebix 1.1
148     // Variables for DGA mode
149 gbeauche 1.38 static bool is_fbdev_dga_mode = false; // Flag: Use FBDev DGA mode?
150 cebix 1.1 static int current_dga_cmap;
151    
152 gbeauche 1.38 #ifdef ENABLE_FBDEV_DGA
153     static int fb_dev_fd = -1; // Handle to fb device name
154     static struct fb_fix_screeninfo fb_finfo; // Fixed info
155     static struct fb_var_screeninfo fb_vinfo; // Variable info
156     static struct fb_var_screeninfo fb_orig_vinfo; // Variable info to restore later
157     static struct fb_cmap fb_oldcmap; // Colormap to restore later
158     #endif
159    
160 cebix 1.1 #ifdef ENABLE_XF86_VIDMODE
161     // Variables for XF86 VidMode support
162     static XF86VidModeModeInfo **x_video_modes; // Array of all available modes
163     static int num_x_video_modes;
164     #endif
165    
166 gbeauche 1.13 // Mutex to protect palette
167     #ifdef HAVE_SPINLOCKS
168     static spinlock_t x_palette_lock = SPIN_LOCK_UNLOCKED;
169     #define LOCK_PALETTE spin_lock(&x_palette_lock)
170     #define UNLOCK_PALETTE spin_unlock(&x_palette_lock)
171     #elif defined(HAVE_PTHREADS)
172     static pthread_mutex_t x_palette_lock = PTHREAD_MUTEX_INITIALIZER;
173     #define LOCK_PALETTE pthread_mutex_lock(&x_palette_lock)
174     #define UNLOCK_PALETTE pthread_mutex_unlock(&x_palette_lock)
175     #else
176     #define LOCK_PALETTE
177     #define UNLOCK_PALETTE
178     #endif
179    
180 gbeauche 1.38 // Mutex to protect frame buffer
181     #ifdef HAVE_SPINLOCKS
182     static spinlock_t frame_buffer_lock = SPIN_LOCK_UNLOCKED;
183     #define LOCK_FRAME_BUFFER spin_lock(&frame_buffer_lock)
184     #define UNLOCK_FRAME_BUFFER spin_unlock(&frame_buffer_lock)
185     #elif defined(HAVE_PTHREADS)
186     static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
187     #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock);
188     #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock);
189     #else
190     #define LOCK_FRAME_BUFFER
191     #define UNLOCK_FRAME_BUFFER
192     #endif
193    
194 cebix 1.1
195     // Prototypes
196     static void *redraw_func(void *arg);
197    
198    
199 gbeauche 1.4 // From main_unix.cpp
200     extern char *x_display_name;
201 cebix 1.1 extern Display *x_display;
202    
203     // From sys_unix.cpp
204     extern void SysMountFirstFloppy(void);
205    
206 gbeauche 1.9 // From clip_unix.cpp
207     extern void ClipboardSelectionClear(XSelectionClearEvent *);
208     extern void ClipboardSelectionRequest(XSelectionRequestEvent *);
209    
210 cebix 1.1
211 gbeauche 1.3 // Video acceleration through SIGSEGV
212     #ifdef ENABLE_VOSF
213     # include "video_vosf.h"
214     #endif
215    
216    
217 cebix 1.1 /*
218 gbeauche 1.13 * Utility functions
219     */
220    
221     // Get current video mode
222     static inline int get_current_mode(void)
223     {
224     return VModes[cur_mode].viAppleMode;
225     }
226    
227     // Find palette size for given color depth
228     static int palette_size(int mode)
229     {
230     switch (mode) {
231     case APPLE_1_BIT: return 2;
232     case APPLE_2_BIT: return 4;
233     case APPLE_4_BIT: return 16;
234     case APPLE_8_BIT: return 256;
235     case APPLE_16_BIT: return 32;
236     case APPLE_32_BIT: return 256;
237     default: return 0;
238     }
239     }
240    
241 gbeauche 1.16 // Return bits per pixel for requested depth
242     static inline int bytes_per_pixel(int depth)
243     {
244     int bpp;
245     switch (depth) {
246     case 8:
247     bpp = 1;
248     break;
249     case 15: case 16:
250     bpp = 2;
251     break;
252     case 24: case 32:
253     bpp = 4;
254     break;
255     default:
256     abort();
257     }
258     return bpp;
259     }
260    
261 gbeauche 1.13 // Map video_mode depth ID to numerical depth value
262     static inline int depth_of_video_mode(int mode)
263     {
264 gbeauche 1.16 int depth;
265 gbeauche 1.13 switch (mode) {
266     case APPLE_1_BIT:
267     depth = 1;
268     break;
269     case APPLE_2_BIT:
270     depth = 2;
271     break;
272     case APPLE_4_BIT:
273     depth = 4;
274     break;
275     case APPLE_8_BIT:
276     depth = 8;
277     break;
278     case APPLE_16_BIT:
279     depth = 16;
280     break;
281     case APPLE_32_BIT:
282     depth = 32;
283     break;
284     default:
285     abort();
286     }
287     return depth;
288     }
289    
290     // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
291     static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
292     {
293     return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
294     }
295    
296    
297     // Do we have a visual for handling the specified Mac depth? If so, set the
298     // global variables "xdepth", "visualInfo", "vis" and "color_class".
299     static bool find_visual_for_depth(int depth)
300     {
301     D(bug("have_visual_for_depth(%d)\n", depth_of_video_mode(depth)));
302    
303     // 1-bit works always and uses default visual
304     if (depth == APPLE_1_BIT) {
305     vis = DefaultVisual(x_display, screen);
306     visualInfo.visualid = XVisualIDFromVisual(vis);
307     int num = 0;
308     XVisualInfo *vi = XGetVisualInfo(x_display, VisualIDMask, &visualInfo, &num);
309     visualInfo = vi[0];
310     XFree(vi);
311     xdepth = visualInfo.depth;
312     color_class = visualInfo.c_class;
313     D(bug(" found visual ID 0x%02x, depth %d\n", visualInfo.visualid, xdepth));
314     return true;
315     }
316    
317     // Calculate minimum and maximum supported X depth
318     int min_depth = 1, max_depth = 32;
319     switch (depth) {
320     #ifdef ENABLE_VOSF
321     case APPLE_2_BIT:
322     case APPLE_4_BIT: // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit
323     case APPLE_8_BIT:
324     min_depth = 8;
325     max_depth = 32;
326     break;
327     #else
328     case APPLE_2_BIT:
329     case APPLE_4_BIT: // 2/4-bit requires VOSF blitters
330     return false;
331     case APPLE_8_BIT: // 8-bit without VOSF requires an 8-bit visual
332     min_depth = 8;
333     max_depth = 8;
334     break;
335     #endif
336     case APPLE_16_BIT: // 16-bit requires a 15/16-bit visual
337     min_depth = 15;
338     max_depth = 16;
339     break;
340     case APPLE_32_BIT: // 32-bit requires a 24/32-bit visual
341     min_depth = 24;
342     max_depth = 32;
343     break;
344     }
345     D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth));
346    
347     // Try to find a visual for one of the color depths
348     bool visual_found = false;
349     for (int i=0; i<num_depths && !visual_found; i++) {
350    
351     xdepth = avail_depths[i];
352     D(bug(" trying to find visual for depth %d\n", xdepth));
353     if (xdepth < min_depth || xdepth > max_depth)
354     continue;
355    
356     // Determine best color class for this depth
357     switch (xdepth) {
358     case 1: // Try StaticGray or StaticColor
359     if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo)
360     || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo))
361     visual_found = true;
362     break;
363     case 8: // Need PseudoColor
364     if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo))
365     visual_found = true;
366     break;
367     case 15:
368     case 16:
369     case 24:
370     case 32: // Try DirectColor first, as this will allow gamma correction
371     if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo)
372     || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo))
373     visual_found = true;
374     break;
375     default:
376     D(bug(" not a supported depth\n"));
377     break;
378     }
379     }
380     if (!visual_found)
381     return false;
382    
383     // Visual was found
384     vis = visualInfo.visual;
385     color_class = visualInfo.c_class;
386     D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth));
387     #if DEBUG
388     switch (color_class) {
389     case StaticGray: D(bug("StaticGray\n")); break;
390     case GrayScale: D(bug("GrayScale\n")); break;
391     case StaticColor: D(bug("StaticColor\n")); break;
392     case PseudoColor: D(bug("PseudoColor\n")); break;
393     case TrueColor: D(bug("TrueColor\n")); break;
394     case DirectColor: D(bug("DirectColor\n")); break;
395     }
396     #endif
397     return true;
398     }
399    
400    
401     /*
402 cebix 1.1 * Open display (window or fullscreen)
403     */
404    
405 gbeauche 1.38 // Set window name and class
406     static void set_window_name(Window w, int name)
407     {
408     const char *str = GetString(name);
409     XStoreName(x_display, w, str);
410     XSetIconName(x_display, w, str);
411    
412     XClassHint *hints;
413     hints = XAllocClassHint();
414     if (hints) {
415     hints->res_name = "SheepShaver";
416     hints->res_class = "SheepShaver";
417     XSetClassHint(x_display, w, hints);
418     XFree(hints);
419     }
420     }
421    
422     // Set window input focus flag
423     static void set_window_focus(Window w)
424     {
425     XWMHints *hints = XAllocWMHints();
426     if (hints) {
427     hints->input = True;
428     hints->initial_state = NormalState;
429     hints->flags = InputHint | StateHint;
430     XSetWMHints(x_display, w, hints);
431     XFree(hints);
432     }
433     }
434    
435 gbeauche 1.14 // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
436     static Atom WM_DELETE_WINDOW = (Atom)0;
437     static void set_window_delete_protocol(Window w)
438     {
439     WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
440     XSetWMProtocols(x_display, w, &WM_DELETE_WINDOW, 1);
441     }
442    
443 gbeauche 1.13 // Wait until window is mapped/unmapped
444 gbeauche 1.15 static void wait_mapped(Window w)
445 gbeauche 1.13 {
446     XEvent e;
447     do {
448     XMaskEvent(x_display, StructureNotifyMask, &e);
449     } while ((e.type != MapNotify) || (e.xmap.event != w));
450     }
451    
452 gbeauche 1.15 static void wait_unmapped(Window w)
453 gbeauche 1.13 {
454     XEvent e;
455     do {
456     XMaskEvent(x_display, StructureNotifyMask, &e);
457     } while ((e.type != UnmapNotify) || (e.xmap.event != w));
458     }
459    
460 gbeauche 1.38 // Disable mouse acceleration
461     static void disable_mouse_accel(void)
462     {
463     XChangePointerControl(x_display, True, False, 1, 1, 0);
464     }
465    
466     // Restore mouse acceleration to original value
467     static void restore_mouse_accel(void)
468     {
469     XChangePointerControl(x_display, True, True, orig_accel_numer, orig_accel_denom, orig_threshold);
470     }
471    
472 cebix 1.1 // Trap SHM errors
473     static bool shm_error = false;
474     static int (*old_error_handler)(Display *, XErrorEvent *);
475    
476     static int error_handler(Display *d, XErrorEvent *e)
477     {
478     if (e->error_code == BadAccess) {
479     shm_error = true;
480     return 0;
481     } else
482     return old_error_handler(d, e);
483     }
484    
485     // Open window
486     static bool open_window(int width, int height)
487     {
488 gbeauche 1.3 int aligned_width = (width + 15) & ~15;
489     int aligned_height = (height + 15) & ~15;
490    
491 cebix 1.1 // Set absolute mouse mode
492     ADBSetRelMouseMode(false);
493    
494     // Create window
495     XSetWindowAttributes wattr;
496     wattr.event_mask = eventmask = win_eventmask;
497 gbeauche 1.13 wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
498     wattr.border_pixel = 0;
499 cebix 1.1 wattr.backing_store = NotUseful;
500 gbeauche 1.13 wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
501     the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
502     InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWBackingStore | CWColormap, &wattr);
503 cebix 1.1
504 gbeauche 1.38 // Set window name/class
505     set_window_name(the_win, STR_WINDOW_TITLE);
506    
507     // Indicate that we want keyboard input
508     set_window_focus(the_win);
509 cebix 1.1
510 gbeauche 1.14 // Set delete protocol property
511     set_window_delete_protocol(the_win);
512    
513 cebix 1.1 // Make window unresizable
514     XSizeHints *hints;
515     if ((hints = XAllocSizeHints()) != NULL) {
516     hints->min_width = width;
517     hints->max_width = width;
518     hints->min_height = height;
519     hints->max_height = height;
520     hints->flags = PMinSize | PMaxSize;
521     XSetWMNormalHints(x_display, the_win, hints);
522     XFree((char *)hints);
523     }
524    
525 gbeauche 1.13 // Show window
526     XMapWindow(x_display, the_win);
527     wait_mapped(the_win);
528    
529 gbeauche 1.5 // 1-bit mode is big-endian; if the X server is little-endian, we can't
530     // use SHM because that doesn't allow changing the image byte order
531     bool need_msb_image = (depth == 1 && XImageByteOrder(x_display) == LSBFirst);
532    
533 cebix 1.1 // Try to create and attach SHM image
534     have_shm = false;
535 gbeauche 1.5 if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
536 cebix 1.1
537     // Create SHM image ("height + 2" for safety)
538 gbeauche 1.5 img = XShmCreateImage(x_display, vis, depth == 1 ? 1 : xdepth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
539 gbeauche 1.13 shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
540     D(bug(" shm image created\n"));
541 gbeauche 1.3 the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
542     shminfo.shmaddr = img->data = (char *)the_buffer_copy;
543 cebix 1.1 shminfo.readOnly = False;
544    
545     // Try to attach SHM image, catching errors
546     shm_error = false;
547     old_error_handler = XSetErrorHandler(error_handler);
548     XShmAttach(x_display, &shminfo);
549     XSync(x_display, false);
550     XSetErrorHandler(old_error_handler);
551     if (shm_error) {
552     shmdt(shminfo.shmaddr);
553     XDestroyImage(img);
554     shminfo.shmid = -1;
555     } else {
556     have_shm = true;
557     shmctl(shminfo.shmid, IPC_RMID, 0);
558     }
559 gbeauche 1.13 D(bug(" shm image attached\n"));
560 cebix 1.1 }
561    
562     // Create normal X image if SHM doesn't work ("height + 2" for safety)
563     if (!have_shm) {
564 gbeauche 1.13 int bytes_per_row = depth == 1 ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth));
565 gbeauche 1.3 the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
566     img = XCreateImage(x_display, vis, depth == 1 ? 1 : xdepth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
567 gbeauche 1.13 D(bug(" X image created\n"));
568 cebix 1.1 }
569    
570     // 1-Bit mode is big-endian
571 gbeauche 1.13 if (need_msb_image) {
572 cebix 1.1 img->byte_order = MSBFirst;
573     img->bitmap_bit_order = MSBFirst;
574     }
575    
576 gbeauche 1.3 #ifdef ENABLE_VOSF
577     use_vosf = true;
578     // Allocate memory for frame buffer (SIZE is extended to page-boundary)
579     the_host_buffer = the_buffer_copy;
580 gbeauche 1.40 the_buffer_size = page_extend((aligned_height + 2) * (the_host_buffer_row_bytes = img->bytes_per_line));
581 gbeauche 1.3 the_buffer = (uint8 *)vm_acquire(the_buffer_size);
582     the_buffer_copy = (uint8 *)malloc(the_buffer_size);
583     D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
584     #else
585     // Allocate memory for frame buffer
586     the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
587     D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
588     #endif
589 gbeauche 1.33 screen_base = Host2MacAddr(the_buffer);
590 cebix 1.1
591     // Create GC
592     the_gc = XCreateGC(x_display, the_win, 0, 0);
593 gbeauche 1.13 XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
594 cebix 1.1
595     // Create cursor
596 gbeauche 1.22 if (hw_mac_cursor_accl) {
597 gbeauche 1.21 cursor_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 4, 16, 16, 16, 2);
598     cursor_image->byte_order = MSBFirst;
599     cursor_image->bitmap_bit_order = MSBFirst;
600     cursor_mask_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 36, 16, 16, 16, 2);
601     cursor_mask_image->byte_order = MSBFirst;
602     cursor_mask_image->bitmap_bit_order = MSBFirst;
603     cursor_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
604     cursor_mask_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
605     cursor_gc = XCreateGC(x_display, cursor_map, 0, 0);
606     cursor_mask_gc = XCreateGC(x_display, cursor_mask_map, 0, 0);
607     mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, 0, 0);
608     cursor_changed = false;
609     }
610    
611     // Create no_cursor
612     else {
613     mac_cursor = XCreatePixmapCursor(x_display,
614     XCreatePixmap(x_display, the_win, 1, 1, 1),
615     XCreatePixmap(x_display, the_win, 1, 1, 1),
616     &black, &white, 0, 0);
617     XDefineCursor(x_display, the_win, mac_cursor);
618     }
619 cebix 1.1
620 gbeauche 1.3 // Init blitting routines
621     bool native_byte_order;
622     #ifdef WORDS_BIGENDIAN
623     native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
624     #else
625     native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
626     #endif
627     #ifdef ENABLE_VOSF
628 gbeauche 1.30 Screen_blitter_init(visualFormat, native_byte_order, depth);
629 gbeauche 1.3 #endif
630    
631 cebix 1.1 // Set bytes per row
632     XSync(x_display, false);
633     return true;
634     }
635    
636 gbeauche 1.38 // Open FBDev display
637     static bool open_fbdev(int width, int height)
638     {
639     #ifdef ENABLE_FBDEV_DGA
640     if (ioctl(fb_dev_fd, FBIOGET_FSCREENINFO, &fb_finfo) != 0) {
641     D(bug("[fbdev] Can't get FSCREENINFO: %s\n", strerror(errno)));
642     return false;
643     }
644     D(bug("[fbdev] Device ID: %s\n", fb_finfo.id));
645     D(bug("[fbdev] smem_start: %p [%d bytes]\n", fb_finfo.smem_start, fb_finfo.smem_len));
646 gbeauche 1.40
647 gbeauche 1.38 int fb_type = fb_finfo.type;
648     const char *fb_type_str = NULL;
649     switch (fb_type) {
650     case FB_TYPE_PACKED_PIXELS: fb_type_str = "Packed Pixels"; break;
651     case FB_TYPE_PLANES: fb_type_str = "Non interleaved planes"; break;
652     case FB_TYPE_INTERLEAVED_PLANES: fb_type_str = "Interleaved planes"; break;
653     case FB_TYPE_TEXT: fb_type_str = "Text/attributes"; break;
654     case FB_TYPE_VGA_PLANES: fb_type_str = "EGA/VGA planes"; break;
655     default: fb_type_str = "<unknown>"; break;
656     }
657     D(bug("[fbdev] type: %s\n", fb_type_str));
658 gbeauche 1.40
659     if (fb_type != FB_TYPE_PACKED_PIXELS) {
660     D(bug("[fbdev] type '%s' not supported\n", fb_type_str));
661     return false;
662     }
663    
664 gbeauche 1.38 int fb_visual = fb_finfo.visual;
665     const char *fb_visual_str;
666     switch (fb_visual) {
667     case FB_VISUAL_MONO01: fb_visual_str = "Monochrome 1=Black 0=White"; break;
668     case FB_VISUAL_MONO10: fb_visual_str = "Monochrome 1=While 0=Black"; break;
669     case FB_VISUAL_TRUECOLOR: fb_visual_str = "True color"; break;
670     case FB_VISUAL_PSEUDOCOLOR: fb_visual_str = "Pseudo color (like atari)"; break;
671     case FB_VISUAL_DIRECTCOLOR: fb_visual_str = "Direct color"; break;
672     case FB_VISUAL_STATIC_PSEUDOCOLOR: fb_visual_str = "Pseudo color readonly"; break;
673     default: fb_visual_str = "<unknown>"; break;
674     }
675     D(bug("[fbdev] visual: %s\n", fb_visual_str));
676    
677 gbeauche 1.40 if (fb_visual != FB_VISUAL_TRUECOLOR) {
678     D(bug("[fbdev] visual '%s' not supported\n", fb_visual_str));
679 gbeauche 1.38 return false;
680     }
681    
682     // Map frame buffer
683     the_buffer = (uint8 *)mmap(NULL, fb_finfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fb_dev_fd, 0);
684     if (the_buffer == MAP_FAILED) {
685     D(bug("[fbdev] Can't mmap /dev/fb0: %s\n", strerror(errno)));
686     return false;
687     }
688    
689     // Set absolute mouse mode
690     ADBSetRelMouseMode(false);
691    
692     // Create window
693     XSetWindowAttributes wattr;
694     wattr.event_mask = eventmask = dga_eventmask;
695     wattr.override_redirect = True;
696     the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
697 gbeauche 1.40 InputOutput, DefaultVisual(x_display, screen),
698     CWEventMask | CWOverrideRedirect, &wattr);
699 gbeauche 1.38
700     // Show window
701     XMapRaised(x_display, the_win);
702     wait_mapped(the_win);
703    
704     // Grab mouse and keyboard
705     XGrabKeyboard(x_display, the_win, True,
706     GrabModeAsync, GrabModeAsync, CurrentTime);
707     XGrabPointer(x_display, the_win, True,
708     PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
709     GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
710     disable_mouse_accel();
711    
712     // Create no_cursor
713     mac_cursor = XCreatePixmapCursor(x_display,
714     XCreatePixmap(x_display, the_win, 1, 1, 1),
715     XCreatePixmap(x_display, the_win, 1, 1, 1),
716     &black, &white, 0, 0);
717     XDefineCursor(x_display, the_win, mac_cursor);
718    
719     // Init blitting routines
720     #if ENABLE_VOSF
721 gbeauche 1.40 // Extract current screen color masks (we are in True Color mode)
722     VisualFormat visualFormat;
723     visualFormat.depth = xdepth = DefaultDepth(x_display, screen);
724     XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo);
725     assert(visualFormat.depth == visualInfo.depth);
726     visualFormat.Rmask = visualInfo.red_mask;
727     visualFormat.Gmask = visualInfo.green_mask;
728     visualFormat.Bmask = visualInfo.blue_mask;
729     D(bug("[fbdev] %d bpp, (%08x,%08x,%08x)\n",
730     visualFormat.depth,
731     visualFormat.Rmask, visualFormat.Gmask, visualFormat.Bmask));
732     D(bug("[fbdev] Mac depth %d bpp\n", depth));
733    
734     // Screen_blitter_init() returns TRUE if VOSF is mandatory
735     // i.e. the framebuffer update function is not Blit_Copy_Raw
736 gbeauche 1.38 #ifdef WORDS_BIGENDIAN
737 gbeauche 1.40 const bool native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
738 gbeauche 1.38 #else
739 gbeauche 1.40 const bool native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
740 gbeauche 1.38 #endif
741 gbeauche 1.40 Screen_blitter_init(visualFormat, native_byte_order, depth);
742 gbeauche 1.38
743 gbeauche 1.40 // Allocate memory for frame buffer (SIZE is extended to page-boundary)
744     the_host_buffer = the_buffer;
745     the_host_buffer_row_bytes = TrivialBytesPerRow((width + 7) & ~7, DepthModeForPixelDepth(visualFormat.depth));
746     the_buffer_size = page_extend((height + 2) * the_host_buffer_row_bytes);
747     the_buffer_copy = (uint8 *)malloc(the_buffer_size);
748     the_buffer = (uint8 *)vm_acquire(the_buffer_size);
749     D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
750 gbeauche 1.38 #endif
751    
752     // Set frame buffer base
753     D(bug("the_buffer = %p, use_vosf = %d\n", the_buffer, use_vosf));
754     screen_base = Host2MacAddr(the_buffer);
755 gbeauche 1.40 VModes[cur_mode].viRowBytes = TrivialBytesPerRow((width + 7) & ~7, DepthModeForPixelDepth(depth));
756 gbeauche 1.38 return true;
757     #else
758     ErrorAlert("SheepShaver has been compiled with DGA support disabled.");
759     return false;
760     #endif
761     }
762    
763 cebix 1.1 // Open DGA display (!! should use X11 VidMode extensions to set mode)
764     static bool open_dga(int width, int height)
765     {
766 gbeauche 1.38 if (is_fbdev_dga_mode)
767     return false;
768    
769 cebix 1.1 #ifdef ENABLE_XF86_DGA
770     // Set relative mouse mode
771     ADBSetRelMouseMode(true);
772    
773 gbeauche 1.15 // Create window
774     XSetWindowAttributes wattr;
775     wattr.event_mask = eventmask = dga_eventmask;
776     wattr.override_redirect = True;
777     wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
778     the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
779     InputOutput, vis, CWEventMask | CWOverrideRedirect |
780     (color_class == DirectColor ? CWColormap : 0), &wattr);
781    
782     // Show window
783     XMapRaised(x_display, the_win);
784     wait_mapped(the_win);
785    
786 cebix 1.1 #ifdef ENABLE_XF86_VIDMODE
787     // Switch to best mode
788     if (has_vidmode) {
789     int best = 0;
790     for (int i=1; i<num_x_video_modes; i++) {
791     if (x_video_modes[i]->hdisplay >= width && x_video_modes[i]->vdisplay >= height &&
792     x_video_modes[i]->hdisplay <= x_video_modes[best]->hdisplay && x_video_modes[i]->vdisplay <= x_video_modes[best]->vdisplay) {
793     best = i;
794     }
795     }
796     XF86VidModeSwitchToMode(x_display, screen, x_video_modes[best]);
797     XF86VidModeSetViewPort(x_display, screen, 0, 0);
798     }
799     #endif
800    
801     // Establish direct screen connection
802 gbeauche 1.15 XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
803     XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
804 cebix 1.1 XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
805     XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
806 gbeauche 1.15
807     int v_width, v_bank, v_size;
808     XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size);
809 cebix 1.1 XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
810     XF86DGASetViewPort(x_display, screen, 0, 0);
811     XF86DGASetVidPage(x_display, screen, 0);
812    
813     // Set colormap
814 gbeauche 1.15 if (!IsDirectMode(get_current_mode())) {
815     XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
816 cebix 1.1 XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
817 gbeauche 1.15 }
818     XSync(x_display, false);
819 cebix 1.1
820 gbeauche 1.15 // Init blitting routines
821     int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, DepthModeForPixelDepth(depth));
822 gbeauche 1.3 #if ENABLE_VOSF
823     bool native_byte_order;
824     #ifdef WORDS_BIGENDIAN
825     native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
826     #else
827     native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
828     #endif
829     #if REAL_ADDRESSING || DIRECT_ADDRESSING
830     // Screen_blitter_init() returns TRUE if VOSF is mandatory
831     // i.e. the framebuffer update function is not Blit_Copy_Raw
832 gbeauche 1.30 use_vosf = Screen_blitter_init(visualFormat, native_byte_order, depth);
833 gbeauche 1.3
834     if (use_vosf) {
835     // Allocate memory for frame buffer (SIZE is extended to page-boundary)
836     the_host_buffer = the_buffer;
837 gbeauche 1.40 the_buffer_size = page_extend((height + 2) * (the_host_buffer_row_bytes = bytes_per_row));
838 gbeauche 1.3 the_buffer_copy = (uint8 *)malloc(the_buffer_size);
839     the_buffer = (uint8 *)vm_acquire(the_buffer_size);
840 gbeauche 1.15 D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
841 gbeauche 1.3 }
842     #else
843     use_vosf = false;
844     #endif
845     #endif
846 gbeauche 1.15
847     // Set frame buffer base
848     D(bug("the_buffer = %p, use_vosf = %d\n", the_buffer, use_vosf));
849 gbeauche 1.33 screen_base = Host2MacAddr(the_buffer);
850 cebix 1.1 VModes[cur_mode].viRowBytes = bytes_per_row;
851     return true;
852     #else
853     ErrorAlert("SheepShaver has been compiled with DGA support disabled.");
854     return false;
855     #endif
856     }
857    
858     static bool open_display(void)
859     {
860 gbeauche 1.13 D(bug("open_display()\n"));
861     const VideoInfo &mode = VModes[cur_mode];
862    
863 gbeauche 1.38 // Get original mouse acceleration
864     XGetPointerControl(x_display, &orig_accel_numer, &orig_accel_denom, &orig_threshold);
865    
866 gbeauche 1.13 // Find best available X visual
867     if (!find_visual_for_depth(mode.viAppleMode)) {
868     ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
869     return false;
870     }
871    
872 gbeauche 1.30 // Build up visualFormat structure
873 gbeauche 1.40 visualFormat.fullscreen = (display_type == DIS_SCREEN);
874 gbeauche 1.30 visualFormat.depth = visualInfo.depth;
875     visualFormat.Rmask = visualInfo.red_mask;
876     visualFormat.Gmask = visualInfo.green_mask;
877     visualFormat.Bmask = visualInfo.blue_mask;
878    
879 gbeauche 1.13 // Create color maps
880     if (color_class == PseudoColor || color_class == DirectColor) {
881     cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
882     cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
883     } else {
884     cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone);
885     cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone);
886     }
887    
888     // Find pixel format of direct modes
889     if (color_class == DirectColor || color_class == TrueColor) {
890     rshift = gshift = bshift = 0;
891     rloss = gloss = bloss = 8;
892     uint32 mask;
893     for (mask=vis->red_mask; !(mask&1); mask>>=1)
894     ++rshift;
895     for (; mask&1; mask>>=1)
896     --rloss;
897     for (mask=vis->green_mask; !(mask&1); mask>>=1)
898     ++gshift;
899     for (; mask&1; mask>>=1)
900     --gloss;
901     for (mask=vis->blue_mask; !(mask&1); mask>>=1)
902     ++bshift;
903     for (; mask&1; mask>>=1)
904     --bloss;
905     }
906    
907     // Preset palette pixel values for CLUT or gamma table
908     if (color_class == DirectColor) {
909     int num = vis->map_entries;
910     for (int i=0; i<num; i++) {
911     int c = (i * 256) / num;
912     x_palette[i].pixel = map_rgb(c, c, c);
913     x_palette[i].flags = DoRed | DoGreen | DoBlue;
914     }
915     } else if (color_class == PseudoColor) {
916     for (int i=0; i<256; i++) {
917     x_palette[i].pixel = i;
918     x_palette[i].flags = DoRed | DoGreen | DoBlue;
919     }
920     }
921    
922     // Load gray ramp to color map
923     int num = (color_class == DirectColor ? vis->map_entries : 256);
924     for (int i=0; i<num; i++) {
925     int c = (i * 256) / num;
926     x_palette[i].red = c * 0x0101;
927     x_palette[i].green = c * 0x0101;
928     x_palette[i].blue = c * 0x0101;
929     }
930     if (color_class == PseudoColor || color_class == DirectColor) {
931     XStoreColors(x_display, cmap[0], x_palette, num);
932     XStoreColors(x_display, cmap[1], x_palette, num);
933 cebix 1.1 }
934 gbeauche 1.3
935 gbeauche 1.13 #ifdef ENABLE_VOSF
936     // Load gray ramp to 8->16/32 expand map
937     if (!IsDirectMode(get_current_mode()) && xdepth > 8)
938     for (int i=0; i<256; i++)
939     ExpandMap[i] = map_rgb(i, i, i);
940     #endif
941    
942     // Create display of requested type
943     display_type = mode.viType;
944     depth = depth_of_video_mode(mode.viAppleMode);
945    
946 gbeauche 1.3 bool display_open = false;
947 gbeauche 1.38 if (display_type == DIS_SCREEN) {
948 gbeauche 1.3 display_open = open_dga(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
949 gbeauche 1.38 #ifdef ENABLE_FBDEV_DGA
950     // Try to fallback to FBDev DGA mode
951     if (!display_open) {
952     is_fbdev_dga_mode = true;
953     display_open = open_fbdev(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
954     }
955     #endif
956    
957     }
958 cebix 1.1 else if (display_type == DIS_WINDOW)
959 gbeauche 1.3 display_open = open_window(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
960    
961     #ifdef ENABLE_VOSF
962     if (use_vosf) {
963     // Initialize the VOSF system
964     if (!video_vosf_init()) {
965     ErrorAlert(GetString(STR_VOSF_INIT_ERR));
966     return false;
967     }
968     }
969     #endif
970    
971     return display_open;
972 cebix 1.1 }
973    
974    
975     /*
976     * Close display
977     */
978    
979     // Close window
980     static void close_window(void)
981     {
982 gbeauche 1.3 if (have_shm) {
983     XShmDetach(x_display, &shminfo);
984     #ifdef ENABLE_VOSF
985     the_host_buffer = NULL; // don't free() in driver_base dtor
986     #else
987     the_buffer_copy = NULL; // don't free() in driver_base dtor
988     #endif
989     }
990     if (img) {
991     if (!have_shm)
992     img->data = NULL;
993     XDestroyImage(img);
994     }
995     if (have_shm) {
996     shmdt(shminfo.shmaddr);
997     shmctl(shminfo.shmid, IPC_RMID, 0);
998     }
999     if (the_gc)
1000     XFreeGC(x_display, the_gc);
1001    
1002 gbeauche 1.13 XFlush(x_display);
1003     XSync(x_display, false);
1004 cebix 1.1 }
1005    
1006 gbeauche 1.38 // Close FBDev mode
1007     static void close_fbdev(void)
1008     {
1009     #ifdef ENABLE_FBDEV_DGA
1010     XUngrabPointer(x_display, CurrentTime);
1011     XUngrabKeyboard(x_display, CurrentTime);
1012    
1013     uint8 *fb_base;
1014     if (!use_vosf) {
1015     // don't free() the screen buffer in driver_base dtor
1016     fb_base = the_buffer;
1017     the_buffer = NULL;
1018     }
1019     #ifdef ENABLE_VOSF
1020     else {
1021     // don't free() the screen buffer in driver_base dtor
1022     fb_base = the_host_buffer;
1023     the_host_buffer = NULL;
1024     }
1025     #endif
1026     munmap(fb_base, fb_finfo.smem_len);
1027     #endif
1028     }
1029    
1030 cebix 1.1 // Close DGA mode
1031     static void close_dga(void)
1032     {
1033 gbeauche 1.38 if (is_fbdev_dga_mode)
1034     return;
1035    
1036 cebix 1.1 #ifdef ENABLE_XF86_DGA
1037     XF86DGADirectVideo(x_display, screen, 0);
1038     XUngrabPointer(x_display, CurrentTime);
1039     XUngrabKeyboard(x_display, CurrentTime);
1040     #endif
1041    
1042     #ifdef ENABLE_XF86_VIDMODE
1043     if (has_vidmode)
1044     XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1045     #endif
1046 gbeauche 1.3
1047     if (!use_vosf) {
1048     // don't free() the screen buffer in driver_base dtor
1049     the_buffer = NULL;
1050     }
1051     #ifdef ENABLE_VOSF
1052     else {
1053     // don't free() the screen buffer in driver_base dtor
1054     the_host_buffer = NULL;
1055     }
1056     #endif
1057 cebix 1.1 }
1058    
1059     static void close_display(void)
1060     {
1061 gbeauche 1.38 if (display_type == DIS_SCREEN) {
1062     if (is_fbdev_dga_mode)
1063     close_fbdev();
1064     else
1065     close_dga();
1066     }
1067 cebix 1.1 else if (display_type == DIS_WINDOW)
1068     close_window();
1069 gbeauche 1.3
1070 gbeauche 1.15 // Close window
1071     if (the_win) {
1072     XUnmapWindow(x_display, the_win);
1073     wait_unmapped(the_win);
1074     XDestroyWindow(x_display, the_win);
1075     }
1076    
1077 gbeauche 1.13 // Free colormaps
1078     if (cmap[0]) {
1079     XFreeColormap(x_display, cmap[0]);
1080     cmap[0] = 0;
1081     }
1082     if (cmap[1]) {
1083     XFreeColormap(x_display, cmap[1]);
1084     cmap[1] = 0;
1085     }
1086    
1087 gbeauche 1.3 #ifdef ENABLE_VOSF
1088     if (use_vosf) {
1089     // Deinitialize VOSF
1090     video_vosf_exit();
1091     }
1092     #endif
1093    
1094     // Free frame buffer(s)
1095     if (!use_vosf) {
1096     if (the_buffer_copy) {
1097     free(the_buffer_copy);
1098     the_buffer_copy = NULL;
1099     }
1100     }
1101     #ifdef ENABLE_VOSF
1102     else {
1103     // the_buffer shall always be mapped through vm_acquire() so that we can vm_protect() it at will
1104     if (the_buffer != VM_MAP_FAILED) {
1105     D(bug(" releasing the_buffer at %p (%d bytes)\n", the_buffer, the_buffer_size));
1106     vm_release(the_buffer, the_buffer_size);
1107     the_buffer = NULL;
1108     }
1109     if (the_host_buffer) {
1110     D(bug(" freeing the_host_buffer at %p\n", the_host_buffer));
1111     free(the_host_buffer);
1112     the_host_buffer = NULL;
1113     }
1114     if (the_buffer_copy) {
1115     D(bug(" freeing the_buffer_copy at %p\n", the_buffer_copy));
1116     free(the_buffer_copy);
1117     the_buffer_copy = NULL;
1118     }
1119     }
1120     #endif
1121 gbeauche 1.38
1122     // Restore mouse acceleration
1123     restore_mouse_accel();
1124 cebix 1.1 }
1125    
1126    
1127     /*
1128     * Initialization
1129     */
1130    
1131 gbeauche 1.6 // Init keycode translation table
1132     static void keycode_init(void)
1133     {
1134     bool use_kc = PrefsFindBool("keycodes");
1135     if (use_kc) {
1136    
1137     // Get keycode file path from preferences
1138     const char *kc_path = PrefsFindString("keycodefile");
1139    
1140     // Open keycode table
1141     FILE *f = fopen(kc_path ? kc_path : KEYCODE_FILE_NAME, "r");
1142     if (f == NULL) {
1143     char str[256];
1144     sprintf(str, GetString(STR_KEYCODE_FILE_WARN), kc_path ? kc_path : KEYCODE_FILE_NAME, strerror(errno));
1145     WarningAlert(str);
1146     return;
1147     }
1148    
1149     // Default translation table
1150     for (int i=0; i<256; i++)
1151     keycode_table[i] = -1;
1152    
1153     // Search for server vendor string, then read keycodes
1154     const char *vendor = ServerVendor(x_display);
1155 gbeauche 1.29 // Force use of MacX mappings on MacOS X with Apple's X server
1156     int dummy;
1157     if (XQueryExtension(x_display, "Apple-DRI", &dummy, &dummy, &dummy))
1158     vendor = "MacX";
1159 gbeauche 1.6 bool vendor_found = false;
1160     char line[256];
1161     while (fgets(line, 255, f)) {
1162     // Read line
1163     int len = strlen(line);
1164     if (len == 0)
1165     continue;
1166     line[len-1] = 0;
1167    
1168     // Comments begin with "#" or ";"
1169     if (line[0] == '#' || line[0] == ';' || line[0] == 0)
1170     continue;
1171    
1172     if (vendor_found) {
1173     // Read keycode
1174     int x_code, mac_code;
1175     if (sscanf(line, "%d %d", &x_code, &mac_code) == 2)
1176     keycode_table[x_code & 0xff] = mac_code;
1177     else
1178     break;
1179     } else {
1180     // Search for vendor string
1181     if (strstr(vendor, line) == vendor)
1182     vendor_found = true;
1183     }
1184     }
1185    
1186     // Keycode file completely read
1187     fclose(f);
1188     use_keycodes = vendor_found;
1189    
1190     // Vendor not found? Then display warning
1191     if (!vendor_found) {
1192     char str[256];
1193     sprintf(str, GetString(STR_KEYCODE_VENDOR_WARN), vendor, kc_path ? kc_path : KEYCODE_FILE_NAME);
1194     WarningAlert(str);
1195     return;
1196     }
1197     }
1198     }
1199    
1200 gbeauche 1.15 // Find Apple mode matching best specified dimensions
1201     static int find_apple_resolution(int xsize, int ysize)
1202     {
1203     int apple_id;
1204     if (xsize < 800)
1205     apple_id = APPLE_640x480;
1206     else if (xsize < 1024)
1207     apple_id = APPLE_800x600;
1208     else if (xsize < 1152)
1209     apple_id = APPLE_1024x768;
1210     else if (xsize < 1280) {
1211     if (ysize < 900)
1212     apple_id = APPLE_1152x768;
1213     else
1214     apple_id = APPLE_1152x900;
1215     }
1216     else if (xsize < 1600)
1217     apple_id = APPLE_1280x1024;
1218     else
1219     apple_id = APPLE_1600x1200;
1220     return apple_id;
1221     }
1222    
1223     // Find mode in list of supported modes
1224     static int find_mode(int apple_mode, int apple_id, int type)
1225     {
1226     for (VideoInfo *p = VModes; p->viType != DIS_INVALID; p++) {
1227     if (p->viType == type && p->viAppleID == apple_id && p->viAppleMode == apple_mode)
1228     return p - VModes;
1229     }
1230     return -1;
1231     }
1232    
1233 gbeauche 1.36 // Add custom video mode
1234     static void add_custom_mode(VideoInfo *&p, int type, uint32 x, uint32 y, int apple_mode, int apple_id)
1235     {
1236     p->viType = type;
1237     p->viXsize = x;
1238     p->viYsize = y;
1239     p->viRowBytes = TrivialBytesPerRow(p->viXsize, apple_mode);
1240     p->viAppleMode = apple_mode;
1241     p->viAppleID = apple_id;
1242     p++;
1243     }
1244    
1245 gbeauche 1.13 // Add mode to list of supported modes
1246     static void add_mode(VideoInfo *&p, uint32 allow, uint32 test, int apple_mode, int apple_id, int type)
1247 cebix 1.1 {
1248     if (allow & test) {
1249 gbeauche 1.36 uint32 x = 0, y = 0;
1250 cebix 1.1 switch (apple_id) {
1251     case APPLE_W_640x480:
1252     case APPLE_640x480:
1253 gbeauche 1.36 x = 640;
1254     y = 480;
1255 cebix 1.1 break;
1256     case APPLE_W_800x600:
1257     case APPLE_800x600:
1258 gbeauche 1.36 x = 800;
1259     y = 600;
1260 cebix 1.1 break;
1261     case APPLE_1024x768:
1262 gbeauche 1.36 x = 1024;
1263     y = 768;
1264 cebix 1.1 break;
1265 gbeauche 1.15 case APPLE_1152x768:
1266 gbeauche 1.36 x = 1152;
1267     y = 768;
1268 gbeauche 1.15 break;
1269 cebix 1.1 case APPLE_1152x900:
1270 gbeauche 1.36 x = 1152;
1271     y = 900;
1272 cebix 1.1 break;
1273     case APPLE_1280x1024:
1274 gbeauche 1.36 x = 1280;
1275     y = 1024;
1276 cebix 1.1 break;
1277     case APPLE_1600x1200:
1278 gbeauche 1.36 x = 1600;
1279     y = 1200;
1280 cebix 1.1 break;
1281     }
1282 gbeauche 1.36 add_custom_mode(p, type, x, y, apple_mode, apple_id);
1283 cebix 1.1 }
1284     }
1285    
1286 gbeauche 1.13 // Add standard list of windowed modes for given color depth
1287     static void add_window_modes(VideoInfo *&p, int window_modes, int mode)
1288     {
1289     add_mode(p, window_modes, 1, mode, APPLE_W_640x480, DIS_WINDOW);
1290     add_mode(p, window_modes, 2, mode, APPLE_W_800x600, DIS_WINDOW);
1291     }
1292    
1293 cebix 1.1 static bool has_mode(int x, int y)
1294     {
1295     #ifdef ENABLE_XF86_VIDMODE
1296     for (int i=0; i<num_x_video_modes; i++)
1297     if (x_video_modes[i]->hdisplay >= x && x_video_modes[i]->vdisplay >= y)
1298     return true;
1299     return false;
1300     #else
1301     return DisplayWidth(x_display, screen) >= x && DisplayHeight(x_display, screen) >= y;
1302     #endif
1303     }
1304    
1305     bool VideoInit(void)
1306     {
1307 gbeauche 1.3 #ifdef ENABLE_VOSF
1308     // Zero the mainBuffer structure
1309     mainBuffer.dirtyPages = NULL;
1310     mainBuffer.pageInfo = NULL;
1311     #endif
1312    
1313 gbeauche 1.4 // Check if X server runs on local machine
1314     local_X11 = (strncmp(XDisplayName(x_display_name), ":", 1) == 0)
1315     || (strncmp(XDisplayName(x_display_name), "unix:", 5) == 0);
1316    
1317 gbeauche 1.6 // Init keycode translation
1318     keycode_init();
1319    
1320 gbeauche 1.8 // Read frame skip prefs
1321     frame_skip = PrefsFindInt32("frameskip");
1322     if (frame_skip == 0)
1323     frame_skip = 1;
1324    
1325     // Read mouse wheel prefs
1326     mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1327     mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1328    
1329 cebix 1.1 // Init variables
1330     private_data = NULL;
1331     video_activated = true;
1332    
1333     // Find screen and root window
1334     screen = XDefaultScreen(x_display);
1335     rootwin = XRootWindow(x_display, screen);
1336    
1337 gbeauche 1.13 // Get sorted list of available depths
1338     avail_depths = XListDepths(x_display, screen, &num_depths);
1339     if (avail_depths == NULL) {
1340     ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
1341     return false;
1342     }
1343     sort(avail_depths, avail_depths + num_depths);
1344    
1345 cebix 1.1 // Get screen depth
1346     xdepth = DefaultDepth(x_display, screen);
1347    
1348     #ifdef ENABLE_XF86_DGA
1349     // DGA available?
1350     int event_base, error_base;
1351 gbeauche 1.38 is_fbdev_dga_mode = false;
1352 gbeauche 1.4 if (local_X11 && XF86DGAQueryExtension(x_display, &event_base, &error_base)) {
1353 cebix 1.1 int dga_flags = 0;
1354     XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
1355     has_dga = dga_flags & XF86DGADirectPresent;
1356 gbeauche 1.38 #if defined(__linux__)
1357     // Check r/w permission on /dev/mem for DGA mode to work
1358     if (has_dga && access("/dev/mem", R_OK | W_OK) != 0)
1359     has_dga = false;
1360     #endif
1361 cebix 1.1 } else
1362     has_dga = false;
1363     #endif
1364    
1365     #ifdef ENABLE_XF86_VIDMODE
1366     // VidMode available?
1367     int vm_event_base, vm_error_base;
1368     has_vidmode = XF86VidModeQueryExtension(x_display, &vm_event_base, &vm_error_base);
1369     if (has_vidmode)
1370     XF86VidModeGetAllModeLines(x_display, screen, &num_x_video_modes, &x_video_modes);
1371     #endif
1372    
1373 gbeauche 1.38 #ifdef ENABLE_FBDEV_DGA
1374     // FBDev available?
1375 gbeauche 1.39 bool has_fbdev_dga = false;
1376     if (local_X11) {
1377 gbeauche 1.38 if ((fb_dev_fd = open("/dev/fb0", O_RDWR)) > 0) {
1378     if (ioctl(fb_dev_fd, FBIOGET_VSCREENINFO, &fb_vinfo) != 0)
1379     close(fb_dev_fd);
1380     else {
1381 gbeauche 1.39 has_fbdev_dga = true;
1382     if (!has_dga) {
1383     // Fallback to FBDev DGA mode if XF86 DGA is not possible
1384     has_dga = true;
1385     is_fbdev_dga_mode = true;
1386     }
1387 gbeauche 1.38 fb_orig_vinfo = fb_vinfo;
1388     D(bug("Frame buffer device initial resolution: %dx%dx%d\n", fb_vinfo.xres, fb_vinfo.yres, fb_vinfo.bits_per_pixel));
1389     }
1390     }
1391     }
1392     #endif
1393    
1394 cebix 1.1 // Find black and white colors
1395     XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:00/00/00", &black);
1396     XAllocColor(x_display, DefaultColormap(x_display, screen), &black);
1397     XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:ff/ff/ff", &white);
1398     XAllocColor(x_display, DefaultColormap(x_display, screen), &white);
1399     black_pixel = BlackPixel(x_display, screen);
1400     white_pixel = WhitePixel(x_display, screen);
1401    
1402     // Mac screen depth follows X depth (for now)
1403 gbeauche 1.13 int default_mode = APPLE_8_BIT;
1404     switch (DefaultDepth(x_display, screen)) {
1405     case 1:
1406     default_mode = APPLE_1_BIT;
1407     break;
1408     case 8:
1409     default_mode = APPLE_8_BIT;
1410     break;
1411     case 15: case 16:
1412     default_mode = APPLE_16_BIT;
1413     break;
1414     case 24: case 32:
1415     default_mode = APPLE_32_BIT;
1416     break;
1417 cebix 1.1 }
1418    
1419 gbeauche 1.37 // Get screen mode from preferences
1420     const char *mode_str = PrefsFindString("screen");
1421     int default_width = 640, default_height = 480;
1422     if (mode_str) {
1423     display_type = DIS_INVALID;
1424     if (sscanf(mode_str, "win/%d/%d", &default_width, &default_height) == 2)
1425     display_type = DIS_WINDOW;
1426     #ifdef ENABLE_XF86_DGA
1427     else if (has_dga && sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2)
1428     display_type = DIS_SCREEN;
1429     #endif
1430 gbeauche 1.39 #ifdef ENABLE_FBDEV_DGA
1431     else if (has_fbdev_dga && sscanf(mode_str, "fbdev/%d/%d", &default_width, &default_height) == 2) {
1432     is_fbdev_dga_mode = true;
1433     display_type = DIS_SCREEN;
1434     }
1435     #endif
1436 gbeauche 1.37 if (display_type == DIS_INVALID) {
1437     D(bug("Invalid screen mode specified, defaulting to old modes selection\n"));
1438     mode_str = NULL;
1439     }
1440     else {
1441     if (default_width <= 0)
1442     default_width = DisplayWidth(x_display, screen);
1443     else if (default_width > DisplayWidth(x_display, screen))
1444     default_width = DisplayWidth(x_display, screen);
1445     if (default_height <= 0)
1446     default_height = DisplayHeight(x_display, screen);
1447     else if (default_height > DisplayHeight(x_display, screen))
1448     default_height = DisplayHeight(x_display, screen);
1449     }
1450     }
1451    
1452 cebix 1.1 // Construct video mode table
1453     uint32 window_modes = PrefsFindInt32("windowmodes");
1454     uint32 screen_modes = PrefsFindInt32("screenmodes");
1455     if (!has_dga)
1456     screen_modes = 0;
1457 gbeauche 1.37 if (mode_str)
1458     window_modes = screen_modes = 0;
1459     else if (window_modes == 0 && screen_modes == 0)
1460 cebix 1.1 window_modes |= 3; // Allow at least 640x480 and 800x600 window modes
1461    
1462     VideoInfo *p = VModes;
1463 gbeauche 1.37 if (mode_str) {
1464     if (display_type == DIS_WINDOW) {
1465     for (unsigned int d = APPLE_1_BIT; d <= APPLE_32_BIT; d++) {
1466     if (find_visual_for_depth(d)) {
1467     if (default_width > 640 && default_height > 480)
1468     add_mode(p, 3, 1, d, APPLE_W_640x480, DIS_WINDOW);
1469     if (default_width > 800 && default_height > 600)
1470     add_mode(p, 3, 2, d, APPLE_W_800x600, DIS_WINDOW);
1471     add_custom_mode(p, display_type, default_width, default_height, d, APPLE_CUSTOM);
1472     }
1473     }
1474 gbeauche 1.40 #ifdef ENABLE_VOSF
1475     } else if (display_type == DIS_SCREEN && is_fbdev_dga_mode) {
1476     for (unsigned int d = APPLE_1_BIT; d <= default_mode; d++)
1477     if (find_visual_for_depth(d))
1478     add_custom_mode(p, display_type, default_width, default_height, d, APPLE_CUSTOM);
1479     #endif
1480 gbeauche 1.37 } else
1481     add_custom_mode(p, display_type, default_width, default_height, default_mode, APPLE_CUSTOM);
1482     } else if (window_modes) {
1483     for (unsigned int d = APPLE_1_BIT; d <= APPLE_32_BIT; d++)
1484     if (find_visual_for_depth(d))
1485     add_window_modes(p, window_modes, d);
1486     } else if (has_vidmode) {
1487 cebix 1.1 if (has_mode(640, 480))
1488 gbeauche 1.13 add_mode(p, screen_modes, 1, default_mode, APPLE_640x480, DIS_SCREEN);
1489 cebix 1.1 if (has_mode(800, 600))
1490 gbeauche 1.13 add_mode(p, screen_modes, 2, default_mode, APPLE_800x600, DIS_SCREEN);
1491 cebix 1.1 if (has_mode(1024, 768))
1492 gbeauche 1.13 add_mode(p, screen_modes, 4, default_mode, APPLE_1024x768, DIS_SCREEN);
1493 gbeauche 1.15 if (has_mode(1152, 768))
1494     add_mode(p, screen_modes, 64, default_mode, APPLE_1152x768, DIS_SCREEN);
1495 cebix 1.1 if (has_mode(1152, 900))
1496 gbeauche 1.13 add_mode(p, screen_modes, 8, default_mode, APPLE_1152x900, DIS_SCREEN);
1497 cebix 1.1 if (has_mode(1280, 1024))
1498 gbeauche 1.13 add_mode(p, screen_modes, 16, default_mode, APPLE_1280x1024, DIS_SCREEN);
1499 cebix 1.1 if (has_mode(1600, 1200))
1500 gbeauche 1.13 add_mode(p, screen_modes, 32, default_mode, APPLE_1600x1200, DIS_SCREEN);
1501 cebix 1.1 } else if (screen_modes) {
1502     int xsize = DisplayWidth(x_display, screen);
1503     int ysize = DisplayHeight(x_display, screen);
1504 gbeauche 1.15 int apple_id = find_apple_resolution(xsize, ysize);
1505 cebix 1.1 p->viType = DIS_SCREEN;
1506     p->viRowBytes = 0;
1507     p->viXsize = xsize;
1508     p->viYsize = ysize;
1509 gbeauche 1.13 p->viAppleMode = default_mode;
1510 cebix 1.1 p->viAppleID = apple_id;
1511     p++;
1512     }
1513     p->viType = DIS_INVALID; // End marker
1514     p->viRowBytes = 0;
1515     p->viXsize = p->viYsize = 0;
1516     p->viAppleMode = 0;
1517     p->viAppleID = 0;
1518    
1519 gbeauche 1.13 // Find default mode (window 640x480)
1520     cur_mode = -1;
1521 gbeauche 1.15 if (has_dga && screen_modes) {
1522     int screen_width = DisplayWidth(x_display, screen);
1523     int screen_height = DisplayHeight(x_display, screen);
1524     int apple_id = find_apple_resolution(screen_width, screen_height);
1525     if (apple_id != -1)
1526     cur_mode = find_mode(default_mode, apple_id, DIS_SCREEN);
1527 gbeauche 1.37 } else if (has_dga && mode_str)
1528     cur_mode = find_mode(default_mode, APPLE_CUSTOM, DIS_SCREEN);
1529    
1530 gbeauche 1.25 if (cur_mode == -1) {
1531     // pick up first windowed mode available
1532     for (VideoInfo *p = VModes; p->viType != DIS_INVALID; p++) {
1533     if (p->viType == DIS_WINDOW && p->viAppleMode == default_mode) {
1534     cur_mode = p - VModes;
1535     break;
1536     }
1537     }
1538     }
1539 gbeauche 1.13 assert(cur_mode != -1);
1540    
1541     #if DEBUG
1542     D(bug("Available video modes:\n"));
1543     for (p = VModes; p->viType != DIS_INVALID; p++) {
1544     int bits = depth_of_video_mode(p->viAppleMode);
1545     D(bug(" %dx%d (ID %02x), %d colors\n", p->viXsize, p->viYsize, p->viAppleID, 1 << bits));
1546     }
1547     #endif
1548    
1549 cebix 1.1 // Open window/screen
1550     if (!open_display())
1551     return false;
1552    
1553     #if 0
1554     // Ignore errors from now on
1555     XSetErrorHandler(ignore_errors);
1556     #endif
1557    
1558 gbeauche 1.38 // Lock down frame buffer
1559     XSync(x_display, false);
1560     LOCK_FRAME_BUFFER;
1561    
1562 cebix 1.1 // Start periodic thread
1563     XSync(x_display, false);
1564 gbeauche 1.15 Set_pthread_attr(&redraw_thread_attr, 0);
1565 gbeauche 1.28 redraw_thread_cancel = false;
1566 gbeauche 1.15 redraw_thread_active = (pthread_create(&redraw_thread, &redraw_thread_attr, redraw_func, NULL) == 0);
1567 cebix 1.1 D(bug("Redraw thread installed (%ld)\n", redraw_thread));
1568     return true;
1569     }
1570    
1571    
1572     /*
1573     * Deinitialization
1574     */
1575    
1576     void VideoExit(void)
1577     {
1578     // Stop redraw thread
1579     if (redraw_thread_active) {
1580 gbeauche 1.28 redraw_thread_cancel = true;
1581 cebix 1.1 pthread_cancel(redraw_thread);
1582     pthread_join(redraw_thread, NULL);
1583     redraw_thread_active = false;
1584     }
1585    
1586 gbeauche 1.38 // Unlock frame buffer
1587     UNLOCK_FRAME_BUFFER;
1588     XSync(x_display, false);
1589     D(bug(" frame buffer unlocked\n"));
1590    
1591 gbeauche 1.3 #ifdef ENABLE_VOSF
1592     if (use_vosf) {
1593     // Deinitialize VOSF
1594     video_vosf_exit();
1595     }
1596     #endif
1597    
1598 cebix 1.1 // Close window and server connection
1599     if (x_display != NULL) {
1600     XSync(x_display, false);
1601     close_display();
1602     XFlush(x_display);
1603     XSync(x_display, false);
1604     }
1605 gbeauche 1.38
1606     #ifdef ENABLE_FBDEV_DGA
1607     // Close framebuffer device
1608     if (fb_dev_fd >= 0) {
1609     close(fb_dev_fd);
1610     fb_dev_fd = -1;
1611     }
1612     #endif
1613 cebix 1.1 }
1614    
1615    
1616     /*
1617     * Suspend/resume emulator
1618     */
1619    
1620     static void suspend_emul(void)
1621     {
1622     if (display_type == DIS_SCREEN) {
1623     // Release ctrl key
1624     ADBKeyUp(0x36);
1625     ctrl_down = false;
1626    
1627 gbeauche 1.38 // Lock frame buffer (this will stop the MacOS thread)
1628     LOCK_FRAME_BUFFER;
1629 cebix 1.1
1630     // Save frame buffer
1631     fb_save = malloc(VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1632     if (fb_save)
1633 gbeauche 1.33 Mac2Host_memcpy(fb_save, screen_base, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1634 cebix 1.1
1635     // Close full screen display
1636 gbeauche 1.38 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1637 cebix 1.1 #ifdef ENABLE_XF86_DGA
1638 gbeauche 1.38 if (!is_fbdev_dga_mode)
1639     XF86DGADirectVideo(x_display, screen, 0);
1640     #endif
1641 cebix 1.1 XUngrabPointer(x_display, CurrentTime);
1642     XUngrabKeyboard(x_display, CurrentTime);
1643     #endif
1644 gbeauche 1.38 restore_mouse_accel();
1645     XUnmapWindow(x_display, the_win);
1646     wait_unmapped(the_win);
1647 cebix 1.1 XSync(x_display, false);
1648    
1649     // Open "suspend" window
1650     XSetWindowAttributes wattr;
1651     wattr.event_mask = KeyPressMask;
1652 gbeauche 1.38 wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
1653 cebix 1.1 wattr.backing_store = Always;
1654 gbeauche 1.38 wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
1655    
1656 cebix 1.1 suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1657 gbeauche 1.38 InputOutput, vis, CWEventMask | CWBackPixel | CWBackingStore | CWColormap, &wattr);
1658     set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
1659     set_window_focus(suspend_win);
1660     XMapWindow(x_display, suspend_win);
1661     emul_suspended = true;
1662 cebix 1.1 }
1663     }
1664    
1665     static void resume_emul(void)
1666     {
1667     // Close "suspend" window
1668     XDestroyWindow(x_display, suspend_win);
1669     XSync(x_display, false);
1670    
1671     // Reopen full screen display
1672 gbeauche 1.38 XMapRaised(x_display, the_win);
1673     wait_mapped(the_win);
1674     XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1675     Window w = is_fbdev_dga_mode ? the_win : rootwin;
1676     XGrabKeyboard(x_display, w, True, GrabModeAsync, GrabModeAsync, CurrentTime);
1677     XGrabPointer(x_display, w, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1678     disable_mouse_accel();
1679 gbeauche 1.12 #ifdef ENABLE_XF86_DGA
1680 gbeauche 1.38 if (!is_fbdev_dga_mode) {
1681     XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1682     XF86DGASetViewPort(x_display, screen, 0, 0);
1683     }
1684 gbeauche 1.12 #endif
1685 cebix 1.1 XSync(x_display, false);
1686    
1687 gbeauche 1.3 // the_buffer already contains the data to restore. i.e. since a temporary
1688     // frame buffer is used when VOSF is actually used, fb_save is therefore
1689     // not necessary.
1690     #ifdef ENABLE_VOSF
1691     if (use_vosf) {
1692     LOCK_VOSF;
1693     PFLAG_SET_ALL;
1694     UNLOCK_VOSF;
1695     memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1696     }
1697     #endif
1698    
1699 cebix 1.1 // Restore frame buffer
1700     if (fb_save) {
1701 gbeauche 1.3 #ifdef ENABLE_VOSF
1702     // Don't copy fb_save to the temporary frame buffer in VOSF mode
1703     if (!use_vosf)
1704     #endif
1705 gbeauche 1.33 Host2Mac_memcpy(screen_base, fb_save, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1706 cebix 1.1 free(fb_save);
1707     fb_save = NULL;
1708     }
1709    
1710 gbeauche 1.38 // Unlock frame buffer (and continue MacOS thread)
1711     UNLOCK_FRAME_BUFFER;
1712 cebix 1.1 emul_suspended = false;
1713     }
1714    
1715    
1716     /*
1717     * Close screen in full-screen mode
1718     */
1719    
1720     void VideoQuitFullScreen(void)
1721     {
1722     D(bug("VideoQuitFullScreen()\n"));
1723     if (display_type == DIS_SCREEN) {
1724     quit_full_screen = true;
1725     while (!quit_full_screen_ack) ;
1726     }
1727     }
1728    
1729    
1730     /*
1731     * X11 event handling
1732     */
1733    
1734     // Translate key event to Mac keycode
1735     static int kc_decode(KeySym ks)
1736     {
1737     switch (ks) {
1738     case XK_A: case XK_a: return 0x00;
1739     case XK_B: case XK_b: return 0x0b;
1740     case XK_C: case XK_c: return 0x08;
1741     case XK_D: case XK_d: return 0x02;
1742     case XK_E: case XK_e: return 0x0e;
1743     case XK_F: case XK_f: return 0x03;
1744     case XK_G: case XK_g: return 0x05;
1745     case XK_H: case XK_h: return 0x04;
1746     case XK_I: case XK_i: return 0x22;
1747     case XK_J: case XK_j: return 0x26;
1748     case XK_K: case XK_k: return 0x28;
1749     case XK_L: case XK_l: return 0x25;
1750     case XK_M: case XK_m: return 0x2e;
1751     case XK_N: case XK_n: return 0x2d;
1752     case XK_O: case XK_o: return 0x1f;
1753     case XK_P: case XK_p: return 0x23;
1754     case XK_Q: case XK_q: return 0x0c;
1755     case XK_R: case XK_r: return 0x0f;
1756     case XK_S: case XK_s: return 0x01;
1757     case XK_T: case XK_t: return 0x11;
1758     case XK_U: case XK_u: return 0x20;
1759     case XK_V: case XK_v: return 0x09;
1760     case XK_W: case XK_w: return 0x0d;
1761     case XK_X: case XK_x: return 0x07;
1762     case XK_Y: case XK_y: return 0x10;
1763     case XK_Z: case XK_z: return 0x06;
1764    
1765     case XK_1: case XK_exclam: return 0x12;
1766     case XK_2: case XK_at: return 0x13;
1767     case XK_3: case XK_numbersign: return 0x14;
1768     case XK_4: case XK_dollar: return 0x15;
1769     case XK_5: case XK_percent: return 0x17;
1770     case XK_6: return 0x16;
1771     case XK_7: return 0x1a;
1772     case XK_8: return 0x1c;
1773     case XK_9: return 0x19;
1774     case XK_0: return 0x1d;
1775    
1776     case XK_grave: case XK_asciitilde: return 0x0a;
1777     case XK_minus: case XK_underscore: return 0x1b;
1778     case XK_equal: case XK_plus: return 0x18;
1779     case XK_bracketleft: case XK_braceleft: return 0x21;
1780     case XK_bracketright: case XK_braceright: return 0x1e;
1781     case XK_backslash: case XK_bar: return 0x2a;
1782     case XK_semicolon: case XK_colon: return 0x29;
1783     case XK_apostrophe: case XK_quotedbl: return 0x27;
1784     case XK_comma: case XK_less: return 0x2b;
1785     case XK_period: case XK_greater: return 0x2f;
1786     case XK_slash: case XK_question: return 0x2c;
1787    
1788     case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30;
1789     case XK_Return: return 0x24;
1790     case XK_space: return 0x31;
1791     case XK_BackSpace: return 0x33;
1792    
1793     case XK_Delete: return 0x75;
1794     case XK_Insert: return 0x72;
1795     case XK_Home: case XK_Help: return 0x73;
1796     case XK_End: return 0x77;
1797     #ifdef __hpux
1798     case XK_Prior: return 0x74;
1799     case XK_Next: return 0x79;
1800     #else
1801     case XK_Page_Up: return 0x74;
1802     case XK_Page_Down: return 0x79;
1803     #endif
1804    
1805     case XK_Control_L: return 0x36;
1806     case XK_Control_R: return 0x36;
1807     case XK_Shift_L: return 0x38;
1808     case XK_Shift_R: return 0x38;
1809     case XK_Alt_L: return 0x37;
1810     case XK_Alt_R: return 0x37;
1811     case XK_Meta_L: return 0x3a;
1812     case XK_Meta_R: return 0x3a;
1813     case XK_Menu: return 0x32;
1814     case XK_Caps_Lock: return 0x39;
1815     case XK_Num_Lock: return 0x47;
1816    
1817     case XK_Up: return 0x3e;
1818     case XK_Down: return 0x3d;
1819     case XK_Left: return 0x3b;
1820     case XK_Right: return 0x3c;
1821    
1822     case XK_Escape: if (ctrl_down) {quit_full_screen = true; emerg_quit = true; return -1;} else return 0x35;
1823    
1824     case XK_F1: if (ctrl_down) {SysMountFirstFloppy(); return -1;} else return 0x7a;
1825     case XK_F2: return 0x78;
1826     case XK_F3: return 0x63;
1827     case XK_F4: return 0x76;
1828     case XK_F5: return 0x60;
1829     case XK_F6: return 0x61;
1830     case XK_F7: return 0x62;
1831     case XK_F8: return 0x64;
1832     case XK_F9: return 0x65;
1833     case XK_F10: return 0x6d;
1834     case XK_F11: return 0x67;
1835     case XK_F12: return 0x6f;
1836    
1837     case XK_Print: return 0x69;
1838     case XK_Scroll_Lock: return 0x6b;
1839     case XK_Pause: return 0x71;
1840    
1841     #if defined(XK_KP_Prior) && defined(XK_KP_Left) && defined(XK_KP_Insert) && defined (XK_KP_End)
1842     case XK_KP_0: case XK_KP_Insert: return 0x52;
1843     case XK_KP_1: case XK_KP_End: return 0x53;
1844     case XK_KP_2: case XK_KP_Down: return 0x54;
1845     case XK_KP_3: case XK_KP_Next: return 0x55;
1846     case XK_KP_4: case XK_KP_Left: return 0x56;
1847     case XK_KP_5: case XK_KP_Begin: return 0x57;
1848     case XK_KP_6: case XK_KP_Right: return 0x58;
1849     case XK_KP_7: case XK_KP_Home: return 0x59;
1850     case XK_KP_8: case XK_KP_Up: return 0x5b;
1851     case XK_KP_9: case XK_KP_Prior: return 0x5c;
1852     case XK_KP_Decimal: case XK_KP_Delete: return 0x41;
1853     #else
1854     case XK_KP_0: return 0x52;
1855     case XK_KP_1: return 0x53;
1856     case XK_KP_2: return 0x54;
1857     case XK_KP_3: return 0x55;
1858     case XK_KP_4: return 0x56;
1859     case XK_KP_5: return 0x57;
1860     case XK_KP_6: return 0x58;
1861     case XK_KP_7: return 0x59;
1862     case XK_KP_8: return 0x5b;
1863     case XK_KP_9: return 0x5c;
1864     case XK_KP_Decimal: return 0x41;
1865     #endif
1866     case XK_KP_Add: return 0x45;
1867     case XK_KP_Subtract: return 0x4e;
1868     case XK_KP_Multiply: return 0x43;
1869     case XK_KP_Divide: return 0x4b;
1870     case XK_KP_Enter: return 0x4c;
1871     case XK_KP_Equal: return 0x51;
1872     }
1873     return -1;
1874     }
1875    
1876 gbeauche 1.27 static int event2keycode(XKeyEvent &ev, bool key_down)
1877 cebix 1.1 {
1878     KeySym ks;
1879     int i = 0;
1880    
1881     do {
1882 gbeauche 1.6 ks = XLookupKeysym(&ev, i++);
1883 gbeauche 1.27 int as = kc_decode(ks);
1884     if (as >= 0)
1885     return as;
1886     if (as == -2)
1887 cebix 1.1 return as;
1888     } while (ks != NoSymbol);
1889    
1890     return -1;
1891     }
1892    
1893     static void handle_events(void)
1894     {
1895     // Handle events
1896     for (;;) {
1897     XEvent event;
1898    
1899 gbeauche 1.10 XDisplayLock();
1900 gbeauche 1.9 if (!XCheckMaskEvent(x_display, eventmask, &event)) {
1901     // Handle clipboard events
1902     if (XCheckTypedEvent(x_display, SelectionRequest, &event))
1903     ClipboardSelectionRequest(&event.xselectionrequest);
1904     else if (XCheckTypedEvent(x_display, SelectionClear, &event))
1905     ClipboardSelectionClear(&event.xselectionclear);
1906 gbeauche 1.14
1907     // Window "close" widget clicked
1908     else if (XCheckTypedEvent(x_display, ClientMessage, &event)) {
1909     if (event.xclient.format == 32 && event.xclient.data.l[0] == WM_DELETE_WINDOW) {
1910     ADBKeyDown(0x7f); // Power key
1911     ADBKeyUp(0x7f);
1912     }
1913     }
1914 gbeauche 1.10
1915     XDisplayUnlock();
1916 cebix 1.1 break;
1917 gbeauche 1.9 }
1918 gbeauche 1.10 XDisplayUnlock();
1919 cebix 1.1
1920     switch (event.type) {
1921     // Mouse button
1922     case ButtonPress: {
1923     unsigned int button = ((XButtonEvent *)&event)->button;
1924     if (button < 4)
1925     ADBMouseDown(button - 1);
1926 gbeauche 1.8 else if (button < 6) { // Wheel mouse
1927     if (mouse_wheel_mode == 0) {
1928     int key = (button == 5) ? 0x79 : 0x74; // Page up/down
1929     ADBKeyDown(key);
1930     ADBKeyUp(key);
1931     } else {
1932     int key = (button == 5) ? 0x3d : 0x3e; // Cursor up/down
1933     for(int i=0; i<mouse_wheel_lines; i++) {
1934     ADBKeyDown(key);
1935     ADBKeyUp(key);
1936     }
1937     }
1938     }
1939 cebix 1.1 break;
1940     }
1941     case ButtonRelease: {
1942     unsigned int button = ((XButtonEvent *)&event)->button;
1943     if (button < 4)
1944     ADBMouseUp(button - 1);
1945     break;
1946     }
1947    
1948 gbeauche 1.15 // Mouse entered window
1949 cebix 1.1 case EnterNotify:
1950 gbeauche 1.15 if (event.xcrossing.mode != NotifyGrab && event.xcrossing.mode != NotifyUngrab)
1951     ADBMouseMoved(event.xmotion.x, event.xmotion.y);
1952 cebix 1.1 break;
1953 gbeauche 1.15
1954     // Mouse moved
1955 cebix 1.1 case MotionNotify:
1956 gbeauche 1.15 ADBMouseMoved(event.xmotion.x, event.xmotion.y);
1957 cebix 1.1 break;
1958    
1959     // Keyboard
1960     case KeyPress: {
1961 gbeauche 1.27 int code = -1;
1962     if (use_keycodes) {
1963     if (event2keycode(event.xkey, true) != -2) // This is called to process the hotkeys
1964     code = keycode_table[event.xkey.keycode & 0xff];
1965     } else
1966     code = event2keycode(event.xkey, true);
1967     if (code >= 0) {
1968 cebix 1.1 if (!emul_suspended) {
1969 gbeauche 1.27 if (code == 0x39) { // Caps Lock pressed
1970     if (caps_on) {
1971     ADBKeyUp(code);
1972     caps_on = false;
1973     } else {
1974     ADBKeyDown(code);
1975     caps_on = true;
1976     }
1977     } else
1978     ADBKeyDown(code);
1979 cebix 1.1 if (code == 0x36)
1980     ctrl_down = true;
1981     } else {
1982     if (code == 0x31)
1983     resume_emul(); // Space wakes us up
1984     }
1985     }
1986     break;
1987     }
1988     case KeyRelease: {
1989 gbeauche 1.27 int code = -1;
1990     if (use_keycodes) {
1991     if (event2keycode(event.xkey, false) != -2) // This is called to process the hotkeys
1992     code = keycode_table[event.xkey.keycode & 0xff];
1993     } else
1994     code = event2keycode(event.xkey, false);
1995     if (code >= 0 && code != 0x39) { // Don't propagate Caps Lock releases
1996 cebix 1.1 ADBKeyUp(code);
1997     if (code == 0x36)
1998     ctrl_down = false;
1999     }
2000     break;
2001     }
2002    
2003     // Hidden parts exposed, force complete refresh
2004     case Expose:
2005 gbeauche 1.3 #ifdef ENABLE_VOSF
2006     if (use_vosf) { // VOSF refresh
2007     LOCK_VOSF;
2008     PFLAG_SET_ALL;
2009     UNLOCK_VOSF;
2010     }
2011     #endif
2012 cebix 1.1 memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
2013     break;
2014     }
2015     }
2016     }
2017    
2018    
2019     /*
2020     * Execute video VBL routine
2021     */
2022    
2023     void VideoVBL(void)
2024     {
2025     if (emerg_quit)
2026     QuitEmulator();
2027    
2028 gbeauche 1.38 // Temporarily give up frame buffer lock (this is the point where
2029     // we are suspended when the user presses Ctrl-Tab)
2030     UNLOCK_FRAME_BUFFER;
2031     LOCK_FRAME_BUFFER;
2032    
2033 cebix 1.1 // Execute video VBL
2034     if (private_data != NULL && private_data->interruptsEnabled)
2035     VSLDoInterruptService(private_data->vslServiceID);
2036     }
2037    
2038    
2039     /*
2040     * Change video mode
2041     */
2042    
2043     int16 video_mode_change(VidLocals *csSave, uint32 ParamPtr)
2044     {
2045     /* return if no mode change */
2046     if ((csSave->saveData == ReadMacInt32(ParamPtr + csData)) &&
2047     (csSave->saveMode == ReadMacInt16(ParamPtr + csMode))) return noErr;
2048    
2049     /* first find video mode in table */
2050     for (int i=0; VModes[i].viType != DIS_INVALID; i++) {
2051     if ((ReadMacInt16(ParamPtr + csMode) == VModes[i].viAppleMode) &&
2052     (ReadMacInt32(ParamPtr + csData) == VModes[i].viAppleID)) {
2053     csSave->saveMode = ReadMacInt16(ParamPtr + csMode);
2054     csSave->saveData = ReadMacInt32(ParamPtr + csData);
2055     csSave->savePage = ReadMacInt16(ParamPtr + csPage);
2056    
2057     // Disable interrupts and pause redraw thread
2058     DisableInterrupt();
2059     thread_stop_ack = false;
2060     thread_stop_req = true;
2061     while (!thread_stop_ack) ;
2062    
2063     /* close old display */
2064     close_display();
2065    
2066     /* open new display */
2067     cur_mode = i;
2068     bool ok = open_display();
2069    
2070     /* opening the screen failed? Then bail out */
2071     if (!ok) {
2072     ErrorAlert(GetString(STR_FULL_SCREEN_ERR));
2073     QuitEmulator();
2074     }
2075    
2076     WriteMacInt32(ParamPtr + csBaseAddr, screen_base);
2077     csSave->saveBaseAddr=screen_base;
2078     csSave->saveData=VModes[cur_mode].viAppleID;/* First mode ... */
2079     csSave->saveMode=VModes[cur_mode].viAppleMode;
2080    
2081     // Enable interrupts and resume redraw thread
2082     thread_stop_req = false;
2083     EnableInterrupt();
2084     return noErr;
2085     }
2086     }
2087     return paramErr;
2088     }
2089    
2090    
2091     /*
2092     * Set color palette
2093     */
2094    
2095     void video_set_palette(void)
2096     {
2097 gbeauche 1.13 LOCK_PALETTE;
2098    
2099     // Convert colors to XColor array
2100     int mode = get_current_mode();
2101     int num_in = palette_size(mode);
2102     int num_out = 256;
2103     bool stretch = false;
2104     if (IsDirectMode(mode)) {
2105     // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries
2106     num_out = vis->map_entries;
2107     stretch = true;
2108     }
2109     XColor *p = x_palette;
2110     for (int i=0; i<num_out; i++) {
2111     int c = (stretch ? (i * num_in) / num_out : i);
2112     p->red = mac_pal[c].red * 0x0101;
2113     p->green = mac_pal[c].green * 0x0101;
2114     p->blue = mac_pal[c].blue * 0x0101;
2115     p++;
2116     }
2117    
2118     #ifdef ENABLE_VOSF
2119     // Recalculate pixel color expansion map
2120     if (!IsDirectMode(mode) && xdepth > 8) {
2121     for (int i=0; i<256; i++) {
2122     int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
2123     ExpandMap[i] = map_rgb(mac_pal[c].red, mac_pal[c].green, mac_pal[c].blue);
2124     }
2125    
2126     // We have to redraw everything because the interpretation of pixel values changed
2127     LOCK_VOSF;
2128     PFLAG_SET_ALL;
2129     UNLOCK_VOSF;
2130     memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
2131     }
2132     #endif
2133    
2134     // Tell redraw thread to change palette
2135 cebix 1.1 palette_changed = true;
2136 gbeauche 1.13
2137     UNLOCK_PALETTE;
2138 cebix 1.1 }
2139    
2140    
2141     /*
2142 gbeauche 1.21 * Can we set the MacOS cursor image into the window?
2143     */
2144    
2145     bool video_can_change_cursor(void)
2146     {
2147 gbeauche 1.22 return hw_mac_cursor_accl && (display_type != DIS_SCREEN);
2148 gbeauche 1.21 }
2149    
2150    
2151     /*
2152 cebix 1.1 * Set cursor image for window
2153     */
2154    
2155     void video_set_cursor(void)
2156     {
2157     cursor_changed = true;
2158     }
2159    
2160    
2161     /*
2162     * Thread for window refresh, event handling and other periodic actions
2163     */
2164    
2165     static void update_display(void)
2166     {
2167     // Incremental update code
2168     int wide = 0, high = 0, x1, x2, y1, y2, i, j;
2169     int bytes_per_row = VModes[cur_mode].viRowBytes;
2170     int bytes_per_pixel = VModes[cur_mode].viRowBytes / VModes[cur_mode].viXsize;
2171     uint8 *p, *p2;
2172    
2173     // Check for first line from top and first line from bottom that have changed
2174     y1 = 0;
2175     for (j=0; j<VModes[cur_mode].viYsize; j++) {
2176     if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
2177     y1 = j;
2178     break;
2179     }
2180     }
2181     y2 = y1 - 1;
2182     for (j=VModes[cur_mode].viYsize-1; j>=y1; j--) {
2183     if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
2184     y2 = j;
2185     break;
2186     }
2187     }
2188     high = y2 - y1 + 1;
2189    
2190     // Check for first column from left and first column from right that have changed
2191     if (high) {
2192     if (depth == 1) {
2193     x1 = VModes[cur_mode].viXsize;
2194     for (j=y1; j<=y2; j++) {
2195     p = &the_buffer[j * bytes_per_row];
2196     p2 = &the_buffer_copy[j * bytes_per_row];
2197     for (i=0; i<(x1>>3); i++) {
2198     if (*p != *p2) {
2199     x1 = i << 3;
2200     break;
2201     }
2202     p++;
2203     p2++;
2204     }
2205     }
2206     x2 = x1;
2207     for (j=y1; j<=y2; j++) {
2208     p = &the_buffer[j * bytes_per_row];
2209     p2 = &the_buffer_copy[j * bytes_per_row];
2210     p += bytes_per_row;
2211     p2 += bytes_per_row;
2212     for (i=(VModes[cur_mode].viXsize>>3); i>(x2>>3); i--) {
2213     p--;
2214     p2--;
2215     if (*p != *p2) {
2216     x2 = i << 3;
2217     break;
2218     }
2219     }
2220     }
2221     wide = x2 - x1;
2222    
2223     // Update copy of the_buffer
2224     if (high && wide) {
2225     for (j=y1; j<=y2; j++) {
2226     i = j * bytes_per_row + (x1 >> 3);
2227     memcpy(&the_buffer_copy[i], &the_buffer[i], wide >> 3);
2228     }
2229     }
2230    
2231     } else {
2232     x1 = VModes[cur_mode].viXsize;
2233     for (j=y1; j<=y2; j++) {
2234     p = &the_buffer[j * bytes_per_row];
2235     p2 = &the_buffer_copy[j * bytes_per_row];
2236     for (i=0; i<x1; i++) {
2237     if (memcmp(p, p2, bytes_per_pixel)) {
2238     x1 = i;
2239     break;
2240     }
2241     p += bytes_per_pixel;
2242     p2 += bytes_per_pixel;
2243     }
2244     }
2245     x2 = x1;
2246     for (j=y1; j<=y2; j++) {
2247     p = &the_buffer[j * bytes_per_row];
2248     p2 = &the_buffer_copy[j * bytes_per_row];
2249     p += bytes_per_row;
2250     p2 += bytes_per_row;
2251     for (i=VModes[cur_mode].viXsize; i>x2; i--) {
2252     p -= bytes_per_pixel;
2253     p2 -= bytes_per_pixel;
2254     if (memcmp(p, p2, bytes_per_pixel)) {
2255     x2 = i;
2256     break;
2257     }
2258     }
2259     }
2260     wide = x2 - x1;
2261    
2262     // Update copy of the_buffer
2263     if (high && wide) {
2264     for (j=y1; j<=y2; j++) {
2265     i = j * bytes_per_row + x1 * bytes_per_pixel;
2266     memcpy(&the_buffer_copy[i], &the_buffer[i], bytes_per_pixel * wide);
2267     }
2268     }
2269     }
2270     }
2271    
2272     // Refresh display
2273     if (high && wide) {
2274 gbeauche 1.10 XDisplayLock();
2275 cebix 1.1 if (have_shm)
2276     XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
2277     else
2278     XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
2279 gbeauche 1.10 XDisplayUnlock();
2280 cebix 1.1 }
2281     }
2282    
2283 gbeauche 1.10 const int VIDEO_REFRESH_HZ = 60;
2284     const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
2285    
2286 gbeauche 1.13 static void handle_palette_changes(void)
2287     {
2288     LOCK_PALETTE;
2289    
2290     if (palette_changed && !emul_suspended) {
2291     palette_changed = false;
2292    
2293     int mode = get_current_mode();
2294     if (color_class == PseudoColor || color_class == DirectColor) {
2295     int num = vis->map_entries;
2296     bool set_clut = true;
2297     if (!IsDirectMode(mode) && color_class == DirectColor) {
2298     if (display_type == DIS_WINDOW)
2299     set_clut = false; // Indexed mode on true color screen, don't set CLUT
2300     }
2301    
2302     if (set_clut) {
2303     XDisplayLock();
2304     XStoreColors(x_display, cmap[0], x_palette, num);
2305     XStoreColors(x_display, cmap[1], x_palette, num);
2306     XSync(x_display, false);
2307     XDisplayUnlock();
2308     }
2309     }
2310    
2311     #ifdef ENABLE_XF86_DGA
2312 gbeauche 1.38 if (display_type == DIS_SCREEN && !is_fbdev_dga_mode) {
2313 gbeauche 1.13 current_dga_cmap ^= 1;
2314     if (!IsDirectMode(mode) && cmap[current_dga_cmap])
2315     XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
2316     }
2317     #endif
2318     }
2319    
2320     UNLOCK_PALETTE;
2321     }
2322    
2323 cebix 1.1 static void *redraw_func(void *arg)
2324     {
2325 gbeauche 1.10 int fd = ConnectionNumber(x_display);
2326    
2327     uint64 start = GetTicks_usec();
2328     int64 ticks = 0;
2329     uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2330 cebix 1.1
2331 gbeauche 1.28 while (!redraw_thread_cancel) {
2332 cebix 1.1
2333     // Pause if requested (during video mode switches)
2334     while (thread_stop_req)
2335     thread_stop_ack = true;
2336    
2337 gbeauche 1.10 int64 delay = next - GetTicks_usec();
2338     if (delay < -VIDEO_REFRESH_DELAY) {
2339    
2340     // We are lagging far behind, so we reset the delay mechanism
2341     next = GetTicks_usec();
2342 cebix 1.1
2343 gbeauche 1.10 } else if (delay <= 0) {
2344    
2345     // Delay expired, refresh display
2346     next += VIDEO_REFRESH_DELAY;
2347     ticks++;
2348    
2349     // Handle X11 events
2350     handle_events();
2351    
2352     // Quit DGA mode if requested
2353     if (quit_full_screen) {
2354     quit_full_screen = false;
2355     if (display_type == DIS_SCREEN) {
2356     XDisplayLock();
2357 gbeauche 1.38 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
2358 cebix 1.1 #ifdef ENABLE_XF86_DGA
2359 gbeauche 1.38 if (is_fbdev_dga_mode)
2360     XF86DGADirectVideo(x_display, screen, 0);
2361     #endif
2362 gbeauche 1.10 XUngrabPointer(x_display, CurrentTime);
2363     XUngrabKeyboard(x_display, CurrentTime);
2364 gbeauche 1.15 XUnmapWindow(x_display, the_win);
2365     wait_unmapped(the_win);
2366     XDestroyWindow(x_display, the_win);
2367 gbeauche 1.10 #endif
2368     XSync(x_display, false);
2369     XDisplayUnlock();
2370     quit_full_screen_ack = true;
2371     return NULL;
2372     }
2373 cebix 1.1 }
2374    
2375 gbeauche 1.10 // Refresh display and set cursor image in window mode
2376     static int tick_counter = 0;
2377     if (display_type == DIS_WINDOW) {
2378     tick_counter++;
2379     if (tick_counter >= frame_skip) {
2380     tick_counter = 0;
2381 cebix 1.1
2382 gbeauche 1.10 // Update display
2383 gbeauche 1.3 #ifdef ENABLE_VOSF
2384 gbeauche 1.10 if (use_vosf) {
2385     XDisplayLock();
2386     if (mainBuffer.dirty) {
2387     LOCK_VOSF;
2388     update_display_window_vosf();
2389     UNLOCK_VOSF;
2390     XSync(x_display, false); // Let the server catch up
2391     }
2392     XDisplayUnlock();
2393 gbeauche 1.3 }
2394 gbeauche 1.10 else
2395 gbeauche 1.3 #endif
2396 gbeauche 1.10 update_display();
2397 cebix 1.1
2398 gbeauche 1.10 // Set new cursor image if it was changed
2399 gbeauche 1.22 if (hw_mac_cursor_accl && cursor_changed) {
2400 gbeauche 1.10 cursor_changed = false;
2401 gbeauche 1.31 uint8 *x_data = (uint8 *)cursor_image->data;
2402     uint8 *x_mask = (uint8 *)cursor_mask_image->data;
2403     for (int i = 0; i < 32; i++) {
2404     x_mask[i] = MacCursor[4 + i] | MacCursor[36 + i];
2405     x_data[i] = MacCursor[4 + i];
2406     }
2407 gbeauche 1.10 XDisplayLock();
2408     XFreeCursor(x_display, mac_cursor);
2409     XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
2410     XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
2411     mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, MacCursor[2], MacCursor[3]);
2412     XDefineCursor(x_display, the_win, mac_cursor);
2413     XDisplayUnlock();
2414     }
2415 cebix 1.1 }
2416     }
2417 gbeauche 1.3 #ifdef ENABLE_VOSF
2418 gbeauche 1.10 else if (use_vosf) {
2419     // Update display (VOSF variant)
2420     if (++tick_counter >= frame_skip) {
2421     tick_counter = 0;
2422     if (mainBuffer.dirty) {
2423     LOCK_VOSF;
2424     update_display_dga_vosf();
2425     UNLOCK_VOSF;
2426     }
2427 gbeauche 1.3 }
2428     }
2429     #endif
2430 cebix 1.1
2431 gbeauche 1.10 // Set new palette if it was changed
2432 gbeauche 1.13 handle_palette_changes();
2433 gbeauche 1.10
2434     } else {
2435    
2436     // No display refresh pending, check for X events
2437     fd_set readfds;
2438     FD_ZERO(&readfds);
2439     FD_SET(fd, &readfds);
2440     struct timeval timeout;
2441     timeout.tv_sec = 0;
2442     timeout.tv_usec = delay;
2443     if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0)
2444     handle_events();
2445 cebix 1.1 }
2446     }
2447     return NULL;
2448     }