ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/video_x.cpp
Revision: 1.14
Committed: 2004-04-11T10:46:32Z (20 years, 6 months ago) by gbeauche
Branch: MAIN
Changes since 1.13: +19 -0 lines
Log Message:
Map window close widget to the Mac "power" key.

File Contents

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