ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/video_x.cpp
Revision: 1.34
Committed: 2001-01-11T16:38:48Z (23 years, 6 months ago) by gbeauche
Branch: MAIN
Changes since 1.33: +82 -35 lines
Log Message:
- Cleaned up the process for determining the ranges of pages touched
  that have to be blitted onto the screen (find_next_page_set() and
  find_next_page_clear() functions)
- Cleaned up some comments
Changes from Brian J. Johnson
- Fixed mainBuffer.dirtyPages[] array overrun in VOSF code
- Fixed calculation of the frames-per-second value

File Contents

# Content
1 /*
2 * video_x.cpp - Video/graphics emulation, X11 specific stuff
3 *
4 * Basilisk II (C) 1997-2000 Christian Bauer
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
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 /*
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 */
28
29 #include "sysdeps.h"
30
31 #include <X11/Xlib.h>
32 #include <X11/Xutil.h>
33 #include <X11/keysym.h>
34 #include <X11/extensions/XShm.h>
35 #include <sys/ipc.h>
36 #include <sys/shm.h>
37 #include <errno.h>
38
39 #ifdef HAVE_PTHREADS
40 # include <pthread.h>
41 #endif
42
43 #ifdef ENABLE_XF86_DGA
44 # include <X11/extensions/xf86dga.h>
45 #endif
46
47 #ifdef ENABLE_XF86_VIDMODE
48 # include <X11/extensions/xf86vmode.h>
49 #endif
50
51 #ifdef ENABLE_FBDEV_DGA
52 # include <sys/mman.h>
53 #endif
54
55 #ifdef ENABLE_VOSF
56 # include <unistd.h>
57 # include <signal.h>
58 # include <fcntl.h>
59 # include <sys/mman.h>
60 #endif
61
62 #include "cpu_emulation.h"
63 #include "main.h"
64 #include "adb.h"
65 #include "macos_util.h"
66 #include "prefs.h"
67 #include "user_strings.h"
68 #include "video.h"
69
70 #define DEBUG 0
71 #include "debug.h"
72
73
74 // Display types
75 enum {
76 DISPLAY_WINDOW, // X11 window, using MIT SHM extensions if possible
77 DISPLAY_DGA // DGA fullscreen display
78 };
79
80 // Constants
81 const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
82 const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
83
84
85 // Global variables
86 static int32 frame_skip; // Prefs items
87 static int16 mouse_wheel_mode = 1;
88 static int16 mouse_wheel_lines = 3;
89
90 static int display_type = DISPLAY_WINDOW; // See enum above
91 static bool local_X11; // Flag: X server running on local machine?
92 static uint8 *the_buffer; // Mac frame buffer
93
94 #ifdef HAVE_PTHREADS
95 static bool redraw_thread_active = false; // Flag: Redraw thread installed
96 static volatile bool redraw_thread_cancel = false; // Flag: Cancel Redraw thread
97 static pthread_t redraw_thread; // Redraw thread
98 #endif
99
100 static bool has_dga = false; // Flag: Video DGA capable
101 static bool has_vidmode = false; // Flag: VidMode extension available
102
103 static bool ctrl_down = false; // Flag: Ctrl key pressed
104 static bool caps_on = false; // Flag: Caps Lock on
105 static bool quit_full_screen = false; // Flag: DGA close requested from redraw thread
106 static bool emerg_quit = false; // Flag: Ctrl-Esc pressed, emergency quit requested from MacOS thread
107 static bool emul_suspended = false; // Flag: Emulator suspended
108
109 static bool classic_mode = false; // Flag: Classic Mac video mode
110
111 static bool use_keycodes = false; // Flag: Use keycodes rather than keysyms
112 static int keycode_table[256]; // X keycode -> Mac keycode translation table
113
114 // X11 variables
115 static int screen; // Screen number
116 static int xdepth; // Depth of X screen
117 static int depth; // Depth of Mac frame buffer
118 static Window rootwin, the_win; // Root window and our window
119 static XVisualInfo visualInfo;
120 static Visual *vis;
121 static Colormap cmap[2]; // Two colormaps (DGA) for 8-bit mode
122 static XColor black, white;
123 static unsigned long black_pixel, white_pixel;
124 static int eventmask;
125 static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
126 static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
127 static Atom WM_DELETE_WINDOW = (Atom)0;
128
129 static XColor palette[256]; // Color palette for 8-bit mode
130 static bool palette_changed = false; // Flag: Palette changed, redraw thread must set new colors
131 #ifdef HAVE_PTHREADS
132 static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect palette
133 #define LOCK_PALETTE pthread_mutex_lock(&palette_lock)
134 #define UNLOCK_PALETTE pthread_mutex_unlock(&palette_lock)
135 #else
136 #define LOCK_PALETTE
137 #define UNLOCK_PALETTE
138 #endif
139
140 // Variables for window mode
141 static GC the_gc;
142 static XImage *img = NULL;
143 static XShmSegmentInfo shminfo;
144 static Cursor mac_cursor;
145 static uint8 *the_buffer_copy = NULL; // Copy of Mac frame buffer
146 static bool have_shm = false; // Flag: SHM extensions available
147 static bool updt_box[17][17]; // Flag for Update
148 static int nr_boxes;
149 static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
150 static int sm_no_boxes[] = {1,8,32,64,128,300};
151
152 // Variables for XF86 DGA mode
153 static int current_dga_cmap; // Number (0 or 1) of currently installed DGA colormap
154 static Window suspend_win; // "Suspend" window
155 static void *fb_save = NULL; // Saved frame buffer for suspend
156 #ifdef HAVE_PTHREADS
157 static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect frame buffer
158 #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock);
159 #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock);
160 #else
161 #define LOCK_FRAME_BUFFER
162 #define UNLOCK_FRAME_BUFFER
163 #endif
164
165 // Variables for fbdev DGA mode
166 const char FBDEVICE_FILE_NAME[] = "/dev/fb";
167 static int fbdev_fd;
168
169 #ifdef ENABLE_XF86_VIDMODE
170 // Variables for XF86 VidMode support
171 static XF86VidModeModeInfo **x_video_modes; // Array of all available modes
172 static int num_x_video_modes;
173 #endif
174
175 #ifdef ENABLE_VOSF
176 static bool use_vosf = true; // Flag: VOSF enabled
177 #else
178 static const bool use_vosf = false; // Flag: VOSF enabled
179 #endif
180
181 #ifdef ENABLE_VOSF
182 // Variables for Video on SEGV support (taken from the Win32 port)
183 static uint8 *the_host_buffer; // Host frame buffer in VOSF mode
184 static uint32 the_buffer_size; // Size of allocated the_buffer
185
186 struct ScreenPageInfo {
187 int top, bottom; // Mapping between this virtual page and Mac scanlines
188 };
189
190 struct ScreenInfo {
191 uint32 memBase; // Real start address
192 uint32 memStart; // Start address aligned to page boundary
193 uint32 memEnd; // Address of one-past-the-end of the screen
194 uint32 memLength; // Length of the memory addressed by the screen pages
195
196 uint32 pageSize; // Size of a page
197 int pageBits; // Shift count to get the page number
198 uint32 pageCount; // Number of pages allocated to the screen
199
200 char * dirtyPages; // Table of flags set if page was altered
201 ScreenPageInfo * pageInfo; // Table of mappings page -> Mac scanlines
202 };
203
204 static ScreenInfo mainBuffer;
205
206 #define PFLAG_SET_VALUE 0x00
207 #define PFLAG_CLEAR_VALUE 0x01
208 #define PFLAG_SET_VALUE_4 0x00000000
209 #define PFLAG_CLEAR_VALUE_4 0x01010101
210 #define PFLAG_SET(page) mainBuffer.dirtyPages[page] = PFLAG_SET_VALUE
211 #define PFLAG_CLEAR(page) mainBuffer.dirtyPages[page] = PFLAG_CLEAR_VALUE
212 #define PFLAG_ISSET(page) (mainBuffer.dirtyPages[page] == PFLAG_SET_VALUE)
213 #define PFLAG_ISCLEAR(page) (mainBuffer.dirtyPages[page] != PFLAG_SET_VALUE)
214
215 #ifdef UNALIGNED_PROFITABLE
216 # define PFLAG_ISSET_4(page) (*((uint32 *)(mainBuffer.dirtyPages + (page))) == PFLAG_SET_VALUE_4)
217 # define PFLAG_ISCLEAR_4(page) (*((uint32 *)(mainBuffer.dirtyPages + (page))) == PFLAG_CLEAR_VALUE_4)
218 #else
219 # define PFLAG_ISSET_4(page) \
220 PFLAG_ISSET(page ) && PFLAG_ISSET(page+1) \
221 && PFLAG_ISSET(page+2) && PFLAG_ISSET(page+3)
222 # define PFLAG_ISCLEAR_4(page) \
223 PFLAG_ISCLEAR(page ) && PFLAG_ISCLEAR(page+1) \
224 && PFLAG_ISCLEAR(page+2) && PFLAG_ISCLEAR(page+3)
225 #endif
226
227 // Set the selected page range [ first_page, last_page [ into the SET state
228 #define PFLAG_SET_RANGE(first_page, last_page) \
229 memset(mainBuffer.dirtyPages + (first_page), PFLAG_SET_VALUE, \
230 (last_page) - (first_page))
231
232 // Set the selected page range [ first_page, last_page [ into the CLEAR state
233 #define PFLAG_CLEAR_RANGE(first_page, last_page) \
234 memset(mainBuffer.dirtyPages + (first_page), PFLAG_CLEAR_VALUE, \
235 (last_page) - (first_page))
236
237 #define PFLAG_SET_ALL \
238 PFLAG_SET_RANGE(0, mainBuffer.pageCount)
239
240 #define PFLAG_CLEAR_ALL \
241 PFLAG_CLEAR_RANGE(0, mainBuffer.pageCount)
242
243 // Set the following macro definition to 1 if your system
244 // provides a really fast strchr() implementation
245 //#define HAVE_FAST_STRCHR 0
246
247 static inline int find_next_page_set(int page)
248 {
249 #if HAVE_FAST_STRCHR
250 char *match = strchr(mainBuffer.dirtyPages + page, PFLAG_SET_VALUE);
251 return match ? match - mainBuffer.dirtyPages : mainBuffer.pageCount;
252 #else
253 while (PFLAG_ISCLEAR_4(page))
254 page += 4;
255 while (PFLAG_ISCLEAR(page))
256 page++;
257 return page;
258 #endif
259 }
260
261 static inline int find_next_page_clear(int page)
262 {
263 #if HAVE_FAST_STRCHR
264 char *match = strchr(mainBuffer.dirtyPages + page, PFLAG_CLEAR_VALUE);
265 return match ? match - mainBuffer.dirtyPages : mainBuffer.pageCount;
266 #else
267 // NOTE: the loop is bound to terminate because the last
268 // page in mainBuffer.dirtyPages[] shall be set to CLEAR
269 while (PFLAG_ISSET_4(page))
270 page += 4;
271 while (PFLAG_ISSET(page))
272 page++;
273 return page;
274 #endif
275 }
276
277 static int zero_fd = -1;
278 static bool Screen_fault_handler_init();
279 static struct sigaction vosf_sa;
280
281 #ifdef HAVE_PTHREADS
282 static pthread_mutex_t vosf_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect frame buffer (dirtyPages in fact)
283 #define LOCK_VOSF pthread_mutex_lock(&vosf_lock);
284 #define UNLOCK_VOSF pthread_mutex_unlock(&vosf_lock);
285 #else
286 #define LOCK_VOSF
287 #define UNLOCK_VOSF
288 #endif
289
290 static int log_base_2(uint32 x)
291 {
292 uint32 mask = 0x80000000;
293 int l = 31;
294 while (l >= 0 && (x & mask) == 0) {
295 mask >>= 1;
296 l--;
297 }
298 return l;
299 }
300 #endif /* ENABLE_VOSF */
301
302 // VideoRefresh function
303 void VideoRefreshInit(void);
304 static void (*video_refresh)(void);
305
306 // Prototypes
307 static void *redraw_func(void *arg);
308 static int event2keycode(XKeyEvent &ev);
309
310
311 // From main_unix.cpp
312 extern char *x_display_name;
313 extern Display *x_display;
314
315 // From sys_unix.cpp
316 extern void SysMountFirstFloppy(void);
317
318 #ifdef ENABLE_VOSF
319 # include "video_vosf.h"
320 #endif
321
322
323 /*
324 * Initialization
325 */
326
327 // Set VideoMonitor according to video mode
328 void set_video_monitor(int width, int height, int bytes_per_row, bool native_byte_order)
329 {
330 #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
331 int layout = FLAYOUT_DIRECT;
332 switch (depth) {
333 case 1:
334 layout = FLAYOUT_DIRECT;
335 break;
336 case 8:
337 layout = FLAYOUT_DIRECT;
338 break;
339 case 15:
340 layout = FLAYOUT_HOST_555;
341 break;
342 case 16:
343 layout = FLAYOUT_HOST_565;
344 break;
345 case 24:
346 case 32:
347 layout = FLAYOUT_HOST_888;
348 break;
349 }
350 if (native_byte_order)
351 MacFrameLayout = layout;
352 else
353 MacFrameLayout = FLAYOUT_DIRECT;
354 #endif
355 switch (depth) {
356 case 1:
357 VideoMonitor.mode = VMODE_1BIT;
358 break;
359 case 8:
360 VideoMonitor.mode = VMODE_8BIT;
361 break;
362 case 15:
363 VideoMonitor.mode = VMODE_16BIT;
364 break;
365 case 16:
366 VideoMonitor.mode = VMODE_16BIT;
367 break;
368 case 24:
369 case 32:
370 VideoMonitor.mode = VMODE_32BIT;
371 break;
372 }
373 VideoMonitor.x = width;
374 VideoMonitor.y = height;
375 VideoMonitor.bytes_per_row = bytes_per_row;
376 }
377
378 // Set window name and class
379 static void set_window_name(Window w, int name)
380 {
381 const char *str = GetString(name);
382 XStoreName(x_display, w, str);
383 XSetIconName(x_display, w, str);
384
385 XClassHint *hints;
386 hints = XAllocClassHint();
387 if (hints) {
388 hints->res_name = "BasiliskII";
389 hints->res_class = "BasiliskII";
390 XSetClassHint(x_display, w, hints);
391 XFree(hints);
392 }
393 }
394
395 // Set window input focus flag
396 static void set_window_focus(Window w)
397 {
398 XWMHints *hints = XAllocWMHints();
399 if (hints) {
400 hints->input = True;
401 hints->initial_state = NormalState;
402 hints->flags = InputHint | StateHint;
403 XSetWMHints(x_display, w, hints);
404 XFree(hints);
405 }
406 }
407
408 // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
409 static void set_window_delete_protocol(Window w)
410 {
411 WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
412 XSetWMProtocols(x_display, w, &WM_DELETE_WINDOW, 1);
413 }
414
415 // Wait until window is mapped/unmapped
416 void wait_mapped(Window w)
417 {
418 XEvent e;
419 do {
420 XMaskEvent(x_display, StructureNotifyMask, &e);
421 } while ((e.type != MapNotify) || (e.xmap.event != w));
422 }
423
424 void wait_unmapped(Window w)
425 {
426 XEvent e;
427 do {
428 XMaskEvent(x_display, StructureNotifyMask, &e);
429 } while ((e.type != UnmapNotify) || (e.xmap.event != w));
430 }
431
432 // Trap SHM errors
433 static bool shm_error = false;
434 static int (*old_error_handler)(Display *, XErrorEvent *);
435
436 static int error_handler(Display *d, XErrorEvent *e)
437 {
438 if (e->error_code == BadAccess) {
439 shm_error = true;
440 return 0;
441 } else
442 return old_error_handler(d, e);
443 }
444
445 // Init window mode
446 static bool init_window(int width, int height)
447 {
448 int aligned_width = (width + 15) & ~15;
449 int aligned_height = (height + 15) & ~15;
450
451 // Set absolute mouse mode
452 ADBSetRelMouseMode(false);
453
454 // Read frame skip prefs
455 frame_skip = PrefsFindInt32("frameskip");
456
457 // Create window
458 XSetWindowAttributes wattr;
459 wattr.event_mask = eventmask = win_eventmask;
460 wattr.background_pixel = black_pixel;
461 wattr.colormap = cmap[0];
462
463 the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
464 InputOutput, vis, CWEventMask | CWBackPixel | (depth == 8 ? CWColormap : 0), &wattr);
465
466 // Set window name/class
467 set_window_name(the_win, STR_WINDOW_TITLE);
468
469 // Indicate that we want keyboard input
470 set_window_focus(the_win);
471
472 // Set delete protocol property
473 set_window_delete_protocol(the_win);
474
475 // Make window unresizable
476 {
477 XSizeHints *hints = XAllocSizeHints();
478 if (hints) {
479 hints->min_width = width;
480 hints->max_width = width;
481 hints->min_height = height;
482 hints->max_height = height;
483 hints->flags = PMinSize | PMaxSize;
484 XSetWMNormalHints(x_display, the_win, hints);
485 XFree(hints);
486 }
487 }
488
489 // Show window
490 XMapWindow(x_display, the_win);
491 wait_mapped(the_win);
492
493 // Try to create and attach SHM image
494 have_shm = false;
495 if (depth != 1 && local_X11 && XShmQueryExtension(x_display)) {
496
497 // Create SHM image ("height + 2" for safety)
498 img = XShmCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
499 shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
500 the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
501 shminfo.shmaddr = img->data = (char *)the_buffer_copy;
502 shminfo.readOnly = False;
503
504 // Try to attach SHM image, catching errors
505 shm_error = false;
506 old_error_handler = XSetErrorHandler(error_handler);
507 XShmAttach(x_display, &shminfo);
508 XSync(x_display, false);
509 XSetErrorHandler(old_error_handler);
510 if (shm_error) {
511 shmdt(shminfo.shmaddr);
512 XDestroyImage(img);
513 shminfo.shmid = -1;
514 } else {
515 have_shm = true;
516 shmctl(shminfo.shmid, IPC_RMID, 0);
517 }
518 }
519
520 // Create normal X image if SHM doesn't work ("height + 2" for safety)
521 if (!have_shm) {
522 int bytes_per_row = aligned_width;
523 switch (depth) {
524 case 1:
525 bytes_per_row /= 8;
526 break;
527 case 15:
528 case 16:
529 bytes_per_row *= 2;
530 break;
531 case 24:
532 case 32:
533 bytes_per_row *= 4;
534 break;
535 }
536 the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
537 img = XCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
538 }
539
540 // 1-Bit mode is big-endian
541 if (depth == 1) {
542 img->byte_order = MSBFirst;
543 img->bitmap_bit_order = MSBFirst;
544 }
545
546 #ifdef ENABLE_VOSF
547 // Allocate a page-aligned chunk of memory for frame buffer
548 the_buffer_size = align_on_page_boundary((aligned_height + 2) * img->bytes_per_line);
549 the_host_buffer = the_buffer_copy;
550
551 the_buffer_copy = (uint8 *)allocate_framebuffer(the_buffer_size);
552 memset(the_buffer_copy, 0, the_buffer_size);
553
554 the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
555 memset(the_buffer, 0, the_buffer_size);
556 #else
557 // Allocate memory for frame buffer
558 the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
559 #endif
560
561 // Create GC
562 the_gc = XCreateGC(x_display, the_win, 0, 0);
563 XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
564
565 // Create no_cursor
566 mac_cursor = XCreatePixmapCursor(x_display,
567 XCreatePixmap(x_display, the_win, 1, 1, 1),
568 XCreatePixmap(x_display, the_win, 1, 1, 1),
569 &black, &white, 0, 0);
570 XDefineCursor(x_display, the_win, mac_cursor);
571
572 // Set VideoMonitor
573 bool native_byte_order;
574 #ifdef WORDS_BIGENDIAN
575 native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
576 #else
577 native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
578 #endif
579 #ifdef ENABLE_VOSF
580 do_update_framebuffer = GET_FBCOPY_FUNC(depth, native_byte_order, DISPLAY_WINDOW);
581 #endif
582 set_video_monitor(width, height, img->bytes_per_line, native_byte_order);
583
584 #if REAL_ADDRESSING || DIRECT_ADDRESSING
585 VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
586 #else
587 VideoMonitor.mac_frame_base = MacFrameBaseMac;
588 #endif
589 return true;
590 }
591
592 // Init fbdev DGA display
593 static bool init_fbdev_dga(char *in_fb_name)
594 {
595 #ifdef ENABLE_FBDEV_DGA
596 // Find the maximum depth available
597 int ndepths, max_depth(0);
598 int *depths = XListDepths(x_display, screen, &ndepths);
599 if (depths == NULL) {
600 printf("FATAL: Could not determine the maximal depth available\n");
601 return false;
602 } else {
603 while (ndepths-- > 0) {
604 if (depths[ndepths] > max_depth)
605 max_depth = depths[ndepths];
606 }
607 }
608
609 // Get fbdevices file path from preferences
610 const char *fbd_path = PrefsFindString("fbdevicefile");
611
612 // Open fbdevices file
613 FILE *fp = fopen(fbd_path ? fbd_path : FBDEVICES_FILE_NAME, "r");
614 if (fp == NULL) {
615 char str[256];
616 sprintf(str, GetString(STR_NO_FBDEVICE_FILE_ERR), fbd_path ? fbd_path : FBDEVICES_FILE_NAME, strerror(errno));
617 ErrorAlert(str);
618 return false;
619 }
620
621 int fb_depth; // supported depth
622 uint32 fb_offset; // offset used for mmap(2)
623 char fb_name[20];
624 char line[256];
625 bool device_found = false;
626 while (fgets(line, 255, fp)) {
627 // Read line
628 int len = strlen(line);
629 if (len == 0)
630 continue;
631 line[len - 1] = '\0';
632
633 // Comments begin with "#" or ";"
634 if ((line[0] == '#') || (line[0] == ';') || (line[0] == '\0'))
635 continue;
636
637 if ((sscanf(line, "%19s %d %x", &fb_name, &fb_depth, &fb_offset) == 3)
638 && (strcmp(fb_name, in_fb_name) == 0) && (fb_depth == max_depth)) {
639 device_found = true;
640 break;
641 }
642 }
643
644 // fbdevices file completely read
645 fclose(fp);
646
647 // Frame buffer name not found ? Then, display warning
648 if (!device_found) {
649 char str[256];
650 sprintf(str, GetString(STR_FBDEV_NAME_ERR), in_fb_name, max_depth);
651 ErrorAlert(str);
652 return false;
653 }
654
655 int width = DisplayWidth(x_display, screen);
656 int height = DisplayHeight(x_display, screen);
657 depth = fb_depth; // max_depth
658
659 // Set relative mouse mode
660 ADBSetRelMouseMode(false);
661
662 // Create window
663 XSetWindowAttributes wattr;
664 wattr.event_mask = eventmask = dga_eventmask;
665 wattr.background_pixel = white_pixel;
666 wattr.override_redirect = True;
667 wattr.colormap = cmap[0];
668
669 the_win = XCreateWindow(x_display, rootwin,
670 0, 0, width, height,
671 0, xdepth, InputOutput, vis,
672 CWEventMask | CWBackPixel | CWOverrideRedirect | (depth == 8 ? CWColormap : 0),
673 &wattr);
674
675 // Set window name/class
676 set_window_name(the_win, STR_WINDOW_TITLE);
677
678 // Indicate that we want keyboard input
679 set_window_focus(the_win);
680
681 // Show window
682 XMapRaised(x_display, the_win);
683 wait_mapped(the_win);
684
685 // Grab mouse and keyboard
686 XGrabKeyboard(x_display, the_win, True,
687 GrabModeAsync, GrabModeAsync, CurrentTime);
688 XGrabPointer(x_display, the_win, True,
689 PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
690 GrabModeAsync, GrabModeAsync, the_win, None, CurrentTime);
691
692 // Set VideoMonitor
693 int bytes_per_row = width;
694 switch (depth) {
695 case 1:
696 bytes_per_row = ((width | 7) & ~7) >> 3;
697 break;
698 case 15:
699 case 16:
700 bytes_per_row *= 2;
701 break;
702 case 24:
703 case 32:
704 bytes_per_row *= 4;
705 break;
706 }
707
708 if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
709 if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
710 char str[256];
711 sprintf(str, GetString(STR_FBDEV_MMAP_ERR), strerror(errno));
712 ErrorAlert(str);
713 return false;
714 }
715 }
716
717 #if ENABLE_VOSF
718 #if REAL_ADDRESSING || DIRECT_ADDRESSING
719 // If the blit function is null, i.e. just a copy of the buffer,
720 // we first try to avoid the allocation of a temporary frame buffer
721 use_vosf = true;
722 do_update_framebuffer = GET_FBCOPY_FUNC(depth, true, DISPLAY_DGA);
723 if (do_update_framebuffer == FBCOPY_FUNC(fbcopy_raw))
724 use_vosf = false;
725
726 if (use_vosf) {
727 the_host_buffer = the_buffer;
728 the_buffer_size = align_on_page_boundary((height + 2) * bytes_per_row);
729 the_buffer_copy = (uint8 *)malloc(the_buffer_size);
730 memset(the_buffer_copy, 0, the_buffer_size);
731 the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
732 memset(the_buffer, 0, the_buffer_size);
733 }
734 #else
735 use_vosf = false;
736 #endif
737 #endif
738
739 set_video_monitor(width, height, bytes_per_row, true);
740 #if REAL_ADDRESSING || DIRECT_ADDRESSING
741 VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
742 #else
743 VideoMonitor.mac_frame_base = MacFrameBaseMac;
744 #endif
745 return true;
746 #else
747 ErrorAlert("Basilisk II has been compiled with fbdev DGA support disabled.");
748 return false;
749 #endif
750 }
751
752 // Init XF86 DGA display
753 static bool init_xf86_dga(int width, int height)
754 {
755 #ifdef ENABLE_XF86_DGA
756 // Set relative mouse mode
757 ADBSetRelMouseMode(true);
758
759 #ifdef ENABLE_XF86_VIDMODE
760 // Switch to best mode
761 if (has_vidmode) {
762 int best = 0;
763 for (int i=1; i<num_x_video_modes; i++) {
764 if (x_video_modes[i]->hdisplay >= width && x_video_modes[i]->vdisplay >= height &&
765 x_video_modes[i]->hdisplay <= x_video_modes[best]->hdisplay && x_video_modes[i]->vdisplay <= x_video_modes[best]->vdisplay) {
766 best = i;
767 }
768 }
769 XF86VidModeSwitchToMode(x_display, screen, x_video_modes[best]);
770 XF86VidModeSetViewPort(x_display, screen, 0, 0);
771 XSync(x_display, false);
772 }
773 #endif
774
775 // Create window
776 XSetWindowAttributes wattr;
777 wattr.event_mask = eventmask = dga_eventmask;
778 wattr.override_redirect = True;
779
780 the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
781 InputOutput, vis, CWEventMask | CWOverrideRedirect, &wattr);
782
783 // Set window name/class
784 set_window_name(the_win, STR_WINDOW_TITLE);
785
786 // Indicate that we want keyboard input
787 set_window_focus(the_win);
788
789 // Show window
790 XMapRaised(x_display, the_win);
791 wait_mapped(the_win);
792
793 // Establish direct screen connection
794 XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
795 XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
796 XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
797 XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
798
799 int v_width, v_bank, v_size;
800 XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size);
801 XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
802 XF86DGASetViewPort(x_display, screen, 0, 0);
803 XF86DGASetVidPage(x_display, screen, 0);
804
805 // Set colormap
806 if (depth == 8) {
807 XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
808 XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
809 }
810 XSync(x_display, false);
811
812 // Set VideoMonitor
813 int bytes_per_row = (v_width + 7) & ~7;
814 switch (depth) {
815 case 1:
816 bytes_per_row /= 8;
817 break;
818 case 15:
819 case 16:
820 bytes_per_row *= 2;
821 break;
822 case 24:
823 case 32:
824 bytes_per_row *= 4;
825 break;
826 }
827
828 #if REAL_ADDRESSING || DIRECT_ADDRESSING
829 // If the blit function is null, i.e. just a copy of the buffer,
830 // we first try to avoid the allocation of a temporary frame buffer
831 use_vosf = true;
832 do_update_framebuffer = GET_FBCOPY_FUNC(depth, true, DISPLAY_DGA);
833 if (do_update_framebuffer == FBCOPY_FUNC(fbcopy_raw))
834 use_vosf = false;
835
836 if (use_vosf) {
837 the_host_buffer = the_buffer;
838 the_buffer_size = align_on_page_boundary((height + 2) * bytes_per_row);
839 the_buffer_copy = (uint8 *)malloc(the_buffer_size);
840 memset(the_buffer_copy, 0, the_buffer_size);
841 the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
842 memset(the_buffer, 0, the_buffer_size);
843 }
844 #elif defined(ENABLE_VOSF)
845 // The UAE memory handlers will already handle color conversion, if needed.
846 use_vosf = false;
847 #endif
848
849 set_video_monitor(width, height, bytes_per_row, true);
850 #if REAL_ADDRESSING || DIRECT_ADDRESSING
851 VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
852 // MacFrameLayout = FLAYOUT_DIRECT;
853 #else
854 VideoMonitor.mac_frame_base = MacFrameBaseMac;
855 #endif
856 return true;
857 #else
858 ErrorAlert("Basilisk II has been compiled with XF86 DGA support disabled.");
859 return false;
860 #endif
861 }
862
863 // Init keycode translation table
864 static void keycode_init(void)
865 {
866 bool use_kc = PrefsFindBool("keycodes");
867 if (use_kc) {
868
869 // Get keycode file path from preferences
870 const char *kc_path = PrefsFindString("keycodefile");
871
872 // Open keycode table
873 FILE *f = fopen(kc_path ? kc_path : KEYCODE_FILE_NAME, "r");
874 if (f == NULL) {
875 char str[256];
876 sprintf(str, GetString(STR_KEYCODE_FILE_WARN), kc_path ? kc_path : KEYCODE_FILE_NAME, strerror(errno));
877 WarningAlert(str);
878 return;
879 }
880
881 // Default translation table
882 for (int i=0; i<256; i++)
883 keycode_table[i] = -1;
884
885 // Search for server vendor string, then read keycodes
886 const char *vendor = ServerVendor(x_display);
887 bool vendor_found = false;
888 char line[256];
889 while (fgets(line, 255, f)) {
890 // Read line
891 int len = strlen(line);
892 if (len == 0)
893 continue;
894 line[len-1] = 0;
895
896 // Comments begin with "#" or ";"
897 if (line[0] == '#' || line[0] == ';' || line[0] == 0)
898 continue;
899
900 if (vendor_found) {
901 // Read keycode
902 int x_code, mac_code;
903 if (sscanf(line, "%d %d", &x_code, &mac_code) == 2)
904 keycode_table[x_code & 0xff] = mac_code;
905 else
906 break;
907 } else {
908 // Search for vendor string
909 if (strstr(vendor, line) == vendor)
910 vendor_found = true;
911 }
912 }
913
914 // Keycode file completely read
915 fclose(f);
916 use_keycodes = vendor_found;
917
918 // Vendor not found? Then display warning
919 if (!vendor_found) {
920 char str[256];
921 sprintf(str, GetString(STR_KEYCODE_VENDOR_WARN), vendor, kc_path ? kc_path : KEYCODE_FILE_NAME);
922 WarningAlert(str);
923 return;
924 }
925 }
926 }
927
928 bool VideoInitBuffer()
929 {
930 #ifdef ENABLE_VOSF
931 if (use_vosf) {
932 const uint32 page_size = getpagesize();
933 const uint32 page_mask = page_size - 1;
934
935 mainBuffer.memBase = (uint32) the_buffer;
936 // Align the frame buffer on page boundary
937 mainBuffer.memStart = (uint32)((((unsigned long) the_buffer) + page_mask) & ~page_mask);
938 mainBuffer.memLength = the_buffer_size;
939 mainBuffer.memEnd = mainBuffer.memStart + mainBuffer.memLength;
940
941 mainBuffer.pageSize = page_size;
942 mainBuffer.pageCount = (mainBuffer.memLength + page_mask)/mainBuffer.pageSize;
943 mainBuffer.pageBits = log_base_2(mainBuffer.pageSize);
944
945 if (mainBuffer.dirtyPages != 0)
946 free(mainBuffer.dirtyPages);
947
948 mainBuffer.dirtyPages = (char *) malloc(mainBuffer.pageCount + 1);
949
950 if (mainBuffer.pageInfo != 0)
951 free(mainBuffer.pageInfo);
952
953 mainBuffer.pageInfo = (ScreenPageInfo *) malloc(mainBuffer.pageCount * sizeof(ScreenPageInfo));
954
955 if ((mainBuffer.dirtyPages == 0) || (mainBuffer.pageInfo == 0))
956 return false;
957
958 PFLAG_CLEAR_ALL;
959
960 // Make sure there is at least one page marked, so the
961 // loops in the update routine will terminate
962 // gb-- Set the last page as cleared because the update
963 // routine finally searches for a page that was not touched
964 PFLAG_CLEAR(mainBuffer.pageCount);
965
966 uint32 a = 0;
967 for (int i = 0; i < mainBuffer.pageCount; i++) {
968 int y1 = a / VideoMonitor.bytes_per_row;
969 if (y1 >= VideoMonitor.y)
970 y1 = VideoMonitor.y - 1;
971
972 int y2 = (a + mainBuffer.pageSize) / VideoMonitor.bytes_per_row;
973 if (y2 >= VideoMonitor.y)
974 y2 = VideoMonitor.y - 1;
975
976 mainBuffer.pageInfo[i].top = y1;
977 mainBuffer.pageInfo[i].bottom = y2;
978
979 a += mainBuffer.pageSize;
980 if (a > mainBuffer.memLength)
981 a = mainBuffer.memLength;
982 }
983
984 // We can now write-protect the frame buffer
985 if (mprotect((caddr_t)mainBuffer.memStart, mainBuffer.memLength, PROT_READ) != 0)
986 return false;
987 }
988 #endif
989 return true;
990 }
991
992 bool VideoInit(bool classic)
993 {
994 #ifdef ENABLE_VOSF
995 // Open /dev/zero
996 zero_fd = open("/dev/zero", O_RDWR);
997 if (zero_fd < 0) {
998 char str[256];
999 sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
1000 ErrorAlert(str);
1001 return false;
1002 }
1003
1004 // Zero the mainBuffer structure
1005 mainBuffer.dirtyPages = 0;
1006 mainBuffer.pageInfo = 0;
1007 #endif
1008
1009 // Check if X server runs on local machine
1010 local_X11 = (strncmp(XDisplayName(x_display_name), ":", 1) == 0)
1011 || (strncmp(XDisplayName(x_display_name), "unix:", 5) == 0);
1012
1013 // Init keycode translation
1014 keycode_init();
1015
1016 // Read prefs
1017 mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1018 mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1019
1020 // Find screen and root window
1021 screen = XDefaultScreen(x_display);
1022 rootwin = XRootWindow(x_display, screen);
1023
1024 // Get screen depth
1025 xdepth = DefaultDepth(x_display, screen);
1026
1027 #ifdef ENABLE_FBDEV_DGA
1028 // Frame buffer name
1029 char fb_name[20];
1030
1031 // Could do fbdev dga ?
1032 if ((fbdev_fd = open(FBDEVICE_FILE_NAME, O_RDWR)) != -1)
1033 has_dga = true;
1034 else
1035 has_dga = false;
1036 #endif
1037
1038 #ifdef ENABLE_XF86_DGA
1039 // DGA available?
1040 int dga_event_base, dga_error_base;
1041 if (local_X11 && XF86DGAQueryExtension(x_display, &dga_event_base, &dga_error_base)) {
1042 int dga_flags = 0;
1043 XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
1044 has_dga = dga_flags & XF86DGADirectPresent;
1045 } else
1046 has_dga = false;
1047 #endif
1048
1049 #ifdef ENABLE_XF86_VIDMODE
1050 // VidMode available?
1051 int vm_event_base, vm_error_base;
1052 has_vidmode = XF86VidModeQueryExtension(x_display, &vm_event_base, &vm_error_base);
1053 if (has_vidmode)
1054 XF86VidModeGetAllModeLines(x_display, screen, &num_x_video_modes, &x_video_modes);
1055 #endif
1056
1057 // Find black and white colors
1058 XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:00/00/00", &black);
1059 XAllocColor(x_display, DefaultColormap(x_display, screen), &black);
1060 XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:ff/ff/ff", &white);
1061 XAllocColor(x_display, DefaultColormap(x_display, screen), &white);
1062 black_pixel = BlackPixel(x_display, screen);
1063 white_pixel = WhitePixel(x_display, screen);
1064
1065 // Get appropriate visual
1066 int color_class;
1067 switch (xdepth) {
1068 case 1:
1069 color_class = StaticGray;
1070 break;
1071 case 8:
1072 color_class = PseudoColor;
1073 break;
1074 case 15:
1075 case 16:
1076 case 24:
1077 case 32:
1078 color_class = TrueColor;
1079 break;
1080 default:
1081 ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
1082 return false;
1083 }
1084 if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
1085 ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
1086 return false;
1087 }
1088 if (visualInfo.depth != xdepth) {
1089 ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
1090 return false;
1091 }
1092 vis = visualInfo.visual;
1093
1094 // Mac screen depth is always 1 bit in Classic mode, but follows X depth otherwise
1095 classic_mode = classic;
1096 if (classic)
1097 depth = 1;
1098 else
1099 depth = xdepth;
1100
1101 // Create color maps for 8 bit mode
1102 if (depth == 8) {
1103 cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1104 cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1105 XInstallColormap(x_display, cmap[0]);
1106 XInstallColormap(x_display, cmap[1]);
1107 }
1108
1109 // Get screen mode from preferences
1110 const char *mode_str;
1111 if (classic)
1112 mode_str = "win/512/342";
1113 else
1114 mode_str = PrefsFindString("screen");
1115
1116 // Determine type and mode
1117 int width = 512, height = 384;
1118 display_type = DISPLAY_WINDOW;
1119 if (mode_str) {
1120 if (sscanf(mode_str, "win/%d/%d", &width, &height) == 2)
1121 display_type = DISPLAY_WINDOW;
1122 #ifdef ENABLE_FBDEV_DGA
1123 else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) {
1124 #else
1125 else if (has_dga && sscanf(mode_str, "dga/%d/%d", &width, &height) == 2) {
1126 #endif
1127 display_type = DISPLAY_DGA;
1128 if (width > DisplayWidth(x_display, screen))
1129 width = DisplayWidth(x_display, screen);
1130 if (height > DisplayHeight(x_display, screen))
1131 height = DisplayHeight(x_display, screen);
1132 }
1133 if (width <= 0)
1134 width = DisplayWidth(x_display, screen);
1135 if (height <= 0)
1136 height = DisplayHeight(x_display, screen);
1137 }
1138
1139 // Initialize according to display type
1140 switch (display_type) {
1141 case DISPLAY_WINDOW:
1142 if (!init_window(width, height))
1143 return false;
1144 break;
1145 case DISPLAY_DGA:
1146 #ifdef ENABLE_FBDEV_DGA
1147 if (!init_fbdev_dga(fb_name))
1148 #else
1149 if (!init_xf86_dga(width, height))
1150 #endif
1151 return false;
1152 break;
1153 }
1154
1155 // Lock down frame buffer
1156 LOCK_FRAME_BUFFER;
1157
1158 #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
1159 // Set variables for UAE memory mapping
1160 MacFrameBaseHost = the_buffer;
1161 MacFrameSize = VideoMonitor.bytes_per_row * VideoMonitor.y;
1162
1163 // No special frame buffer in Classic mode (frame buffer is in Mac RAM)
1164 if (classic)
1165 MacFrameLayout = FLAYOUT_NONE;
1166 #endif
1167
1168 #ifdef ENABLE_VOSF
1169 if (use_vosf) {
1170 // Initialize the mainBuffer structure
1171 if (!VideoInitBuffer()) {
1172 // TODO: STR_VOSF_INIT_ERR ?
1173 ErrorAlert("Could not initialize Video on SEGV signals");
1174 return false;
1175 }
1176
1177 // Initialize the handler for SIGSEGV
1178 if (!Screen_fault_handler_init()) {
1179 // TODO: STR_VOSF_INIT_ERR ?
1180 ErrorAlert("Could not initialize Video on SEGV signals");
1181 return false;
1182 }
1183 }
1184 #endif
1185
1186 // Initialize VideoRefresh function
1187 VideoRefreshInit();
1188
1189 XSync(x_display, false);
1190
1191 #ifdef HAVE_PTHREADS
1192 // Start redraw/input thread
1193 redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1194 if (!redraw_thread_active) {
1195 printf("FATAL: cannot create redraw thread\n");
1196 return false;
1197 }
1198 #endif
1199 return true;
1200 }
1201
1202
1203 /*
1204 * Deinitialization
1205 */
1206
1207 void VideoExit(void)
1208 {
1209 #ifdef HAVE_PTHREADS
1210 // Stop redraw thread
1211 if (redraw_thread_active) {
1212 redraw_thread_cancel = true;
1213 #ifdef HAVE_PTHREAD_CANCEL
1214 pthread_cancel(redraw_thread);
1215 #endif
1216 pthread_join(redraw_thread, NULL);
1217 redraw_thread_active = false;
1218 }
1219 #endif
1220
1221 // Unlock frame buffer
1222 UNLOCK_FRAME_BUFFER;
1223
1224 // Close window and server connection
1225 if (x_display != NULL) {
1226 XSync(x_display, false);
1227
1228 #ifdef ENABLE_XF86_DGA
1229 if (display_type == DISPLAY_DGA) {
1230 XF86DGADirectVideo(x_display, screen, 0);
1231 XUngrabPointer(x_display, CurrentTime);
1232 XUngrabKeyboard(x_display, CurrentTime);
1233 }
1234 #endif
1235
1236 #ifdef ENABLE_XF86_VIDMODE
1237 if (has_vidmode && display_type == DISPLAY_DGA)
1238 XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1239 #endif
1240
1241 #ifdef ENABLE_FBDEV_DGA
1242 if (display_type == DISPLAY_DGA) {
1243 XUngrabPointer(x_display, CurrentTime);
1244 XUngrabKeyboard(x_display, CurrentTime);
1245 close(fbdev_fd);
1246 }
1247 #endif
1248
1249 XFlush(x_display);
1250 XSync(x_display, false);
1251 if (depth == 8) {
1252 XFreeColormap(x_display, cmap[0]);
1253 XFreeColormap(x_display, cmap[1]);
1254 }
1255
1256 if (!use_vosf) {
1257 if (the_buffer) {
1258 free(the_buffer);
1259 the_buffer = NULL;
1260 }
1261
1262 if (!have_shm && the_buffer_copy) {
1263 free(the_buffer_copy);
1264 the_buffer_copy = NULL;
1265 }
1266 }
1267 #ifdef ENABLE_VOSF
1268 else {
1269 if (the_buffer != (uint8 *)MAP_FAILED) {
1270 munmap((caddr_t)the_buffer, the_buffer_size);
1271 the_buffer = 0;
1272 }
1273
1274 if (the_buffer_copy != (uint8 *)MAP_FAILED) {
1275 munmap((caddr_t)the_buffer_copy, the_buffer_size);
1276 the_buffer_copy = 0;
1277 }
1278 }
1279 #endif
1280 }
1281
1282 #ifdef ENABLE_VOSF
1283 if (use_vosf) {
1284 // Clear mainBuffer data
1285 if (mainBuffer.pageInfo) {
1286 free(mainBuffer.pageInfo);
1287 mainBuffer.pageInfo = 0;
1288 }
1289
1290 if (mainBuffer.dirtyPages) {
1291 free(mainBuffer.dirtyPages);
1292 mainBuffer.dirtyPages = 0;
1293 }
1294 }
1295
1296 // Close /dev/zero
1297 if (zero_fd > 0)
1298 close(zero_fd);
1299 #endif
1300 }
1301
1302
1303 /*
1304 * Close down full-screen mode (if bringing up error alerts is unsafe while in full-screen mode)
1305 */
1306
1307 void VideoQuitFullScreen(void)
1308 {
1309 D(bug("VideoQuitFullScreen()\n"));
1310 if (display_type == DISPLAY_DGA)
1311 quit_full_screen = true;
1312 }
1313
1314
1315 /*
1316 * Mac VBL interrupt
1317 */
1318
1319 void VideoInterrupt(void)
1320 {
1321 // Emergency quit requested? Then quit
1322 if (emerg_quit)
1323 QuitEmulator();
1324
1325 // Temporarily give up frame buffer lock (this is the point where
1326 // we are suspended when the user presses Ctrl-Tab)
1327 UNLOCK_FRAME_BUFFER;
1328 LOCK_FRAME_BUFFER;
1329 }
1330
1331
1332 /*
1333 * Set palette
1334 */
1335
1336 void video_set_palette(uint8 *pal)
1337 {
1338 LOCK_PALETTE;
1339
1340 // Convert colors to XColor array
1341 for (int i=0; i<256; i++) {
1342 palette[i].pixel = i;
1343 palette[i].red = pal[i*3] * 0x0101;
1344 palette[i].green = pal[i*3+1] * 0x0101;
1345 palette[i].blue = pal[i*3+2] * 0x0101;
1346 palette[i].flags = DoRed | DoGreen | DoBlue;
1347 }
1348
1349 // Tell redraw thread to change palette
1350 palette_changed = true;
1351
1352 UNLOCK_PALETTE;
1353 }
1354
1355
1356 /*
1357 * Suspend/resume emulator
1358 */
1359
1360 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1361 static void suspend_emul(void)
1362 {
1363 if (display_type == DISPLAY_DGA) {
1364 // Release ctrl key
1365 ADBKeyUp(0x36);
1366 ctrl_down = false;
1367
1368 // Lock frame buffer (this will stop the MacOS thread)
1369 LOCK_FRAME_BUFFER;
1370
1371 // Save frame buffer
1372 fb_save = malloc(VideoMonitor.y * VideoMonitor.bytes_per_row);
1373 if (fb_save)
1374 memcpy(fb_save, the_buffer, VideoMonitor.y * VideoMonitor.bytes_per_row);
1375
1376 // Close full screen display
1377 #ifdef ENABLE_XF86_DGA
1378 XF86DGADirectVideo(x_display, screen, 0);
1379 #endif
1380 XUngrabPointer(x_display, CurrentTime);
1381 XUngrabKeyboard(x_display, CurrentTime);
1382 XUnmapWindow(x_display, the_win);
1383 wait_unmapped(the_win);
1384
1385 // Open "suspend" window
1386 XSetWindowAttributes wattr;
1387 wattr.event_mask = KeyPressMask;
1388 wattr.background_pixel = black_pixel;
1389
1390 suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1391 InputOutput, vis, CWEventMask | CWBackPixel, &wattr);
1392 set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
1393 set_window_focus(suspend_win);
1394 XMapWindow(x_display, suspend_win);
1395 emul_suspended = true;
1396 }
1397 }
1398
1399 static void resume_emul(void)
1400 {
1401 // Close "suspend" window
1402 XDestroyWindow(x_display, suspend_win);
1403 XSync(x_display, false);
1404
1405 // Reopen full screen display
1406 XMapRaised(x_display, the_win);
1407 wait_mapped(the_win);
1408 XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1409 XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1410 XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1411 #ifdef ENABLE_XF86_DGA
1412 XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1413 XF86DGASetViewPort(x_display, screen, 0, 0);
1414 #endif
1415 XSync(x_display, false);
1416
1417 // the_buffer already contains the data to restore. i.e. since a temporary
1418 // frame buffer is used when VOSF is actually used, fb_save is therefore
1419 // not necessary.
1420 #ifdef ENABLE_VOSF
1421 if (use_vosf) {
1422 LOCK_VOSF;
1423 PFLAG_SET_ALL;
1424 UNLOCK_VOSF;
1425 memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1426 }
1427 #endif
1428
1429 // Restore frame buffer
1430 if (fb_save) {
1431 #ifdef ENABLE_VOSF
1432 // Don't copy fb_save to the temporary frame buffer in VOSF mode
1433 if (!use_vosf)
1434 #endif
1435 memcpy(the_buffer, fb_save, VideoMonitor.y * VideoMonitor.bytes_per_row);
1436 free(fb_save);
1437 fb_save = NULL;
1438 }
1439
1440 #ifdef ENABLE_XF86_DGA
1441 if (depth == 8)
1442 XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1443 #endif
1444
1445 // Unlock frame buffer (and continue MacOS thread)
1446 UNLOCK_FRAME_BUFFER;
1447 emul_suspended = false;
1448 }
1449 #endif
1450
1451
1452 /*
1453 * Translate key event to Mac keycode
1454 */
1455
1456 static int kc_decode(KeySym ks)
1457 {
1458 switch (ks) {
1459 case XK_A: case XK_a: return 0x00;
1460 case XK_B: case XK_b: return 0x0b;
1461 case XK_C: case XK_c: return 0x08;
1462 case XK_D: case XK_d: return 0x02;
1463 case XK_E: case XK_e: return 0x0e;
1464 case XK_F: case XK_f: return 0x03;
1465 case XK_G: case XK_g: return 0x05;
1466 case XK_H: case XK_h: return 0x04;
1467 case XK_I: case XK_i: return 0x22;
1468 case XK_J: case XK_j: return 0x26;
1469 case XK_K: case XK_k: return 0x28;
1470 case XK_L: case XK_l: return 0x25;
1471 case XK_M: case XK_m: return 0x2e;
1472 case XK_N: case XK_n: return 0x2d;
1473 case XK_O: case XK_o: return 0x1f;
1474 case XK_P: case XK_p: return 0x23;
1475 case XK_Q: case XK_q: return 0x0c;
1476 case XK_R: case XK_r: return 0x0f;
1477 case XK_S: case XK_s: return 0x01;
1478 case XK_T: case XK_t: return 0x11;
1479 case XK_U: case XK_u: return 0x20;
1480 case XK_V: case XK_v: return 0x09;
1481 case XK_W: case XK_w: return 0x0d;
1482 case XK_X: case XK_x: return 0x07;
1483 case XK_Y: case XK_y: return 0x10;
1484 case XK_Z: case XK_z: return 0x06;
1485
1486 case XK_1: case XK_exclam: return 0x12;
1487 case XK_2: case XK_at: return 0x13;
1488 case XK_3: case XK_numbersign: return 0x14;
1489 case XK_4: case XK_dollar: return 0x15;
1490 case XK_5: case XK_percent: return 0x17;
1491 case XK_6: return 0x16;
1492 case XK_7: return 0x1a;
1493 case XK_8: return 0x1c;
1494 case XK_9: return 0x19;
1495 case XK_0: return 0x1d;
1496
1497 case XK_grave: case XK_asciitilde: return 0x0a;
1498 case XK_minus: case XK_underscore: return 0x1b;
1499 case XK_equal: case XK_plus: return 0x18;
1500 case XK_bracketleft: case XK_braceleft: return 0x21;
1501 case XK_bracketright: case XK_braceright: return 0x1e;
1502 case XK_backslash: case XK_bar: return 0x2a;
1503 case XK_semicolon: case XK_colon: return 0x29;
1504 case XK_apostrophe: case XK_quotedbl: return 0x27;
1505 case XK_comma: case XK_less: return 0x2b;
1506 case XK_period: case XK_greater: return 0x2f;
1507 case XK_slash: case XK_question: return 0x2c;
1508
1509 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1510 case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30;
1511 #else
1512 case XK_Tab: return 0x30;
1513 #endif
1514 case XK_Return: return 0x24;
1515 case XK_space: return 0x31;
1516 case XK_BackSpace: return 0x33;
1517
1518 case XK_Delete: return 0x75;
1519 case XK_Insert: return 0x72;
1520 case XK_Home: case XK_Help: return 0x73;
1521 case XK_End: return 0x77;
1522 #ifdef __hpux
1523 case XK_Prior: return 0x74;
1524 case XK_Next: return 0x79;
1525 #else
1526 case XK_Page_Up: return 0x74;
1527 case XK_Page_Down: return 0x79;
1528 #endif
1529
1530 case XK_Control_L: return 0x36;
1531 case XK_Control_R: return 0x36;
1532 case XK_Shift_L: return 0x38;
1533 case XK_Shift_R: return 0x38;
1534 case XK_Alt_L: return 0x37;
1535 case XK_Alt_R: return 0x37;
1536 case XK_Meta_L: return 0x3a;
1537 case XK_Meta_R: return 0x3a;
1538 case XK_Menu: return 0x32;
1539 case XK_Caps_Lock: return 0x39;
1540 case XK_Num_Lock: return 0x47;
1541
1542 case XK_Up: return 0x3e;
1543 case XK_Down: return 0x3d;
1544 case XK_Left: return 0x3b;
1545 case XK_Right: return 0x3c;
1546
1547 case XK_Escape: if (ctrl_down) {quit_full_screen = true; emerg_quit = true; return -1;} else return 0x35;
1548
1549 case XK_F1: if (ctrl_down) {SysMountFirstFloppy(); return -1;} else return 0x7a;
1550 case XK_F2: return 0x78;
1551 case XK_F3: return 0x63;
1552 case XK_F4: return 0x76;
1553 case XK_F5: return 0x60;
1554 case XK_F6: return 0x61;
1555 case XK_F7: return 0x62;
1556 case XK_F8: return 0x64;
1557 case XK_F9: return 0x65;
1558 case XK_F10: return 0x6d;
1559 case XK_F11: return 0x67;
1560 case XK_F12: return 0x6f;
1561
1562 case XK_Print: return 0x69;
1563 case XK_Scroll_Lock: return 0x6b;
1564 case XK_Pause: return 0x71;
1565
1566 #if defined(XK_KP_Prior) && defined(XK_KP_Left) && defined(XK_KP_Insert) && defined (XK_KP_End)
1567 case XK_KP_0: case XK_KP_Insert: return 0x52;
1568 case XK_KP_1: case XK_KP_End: return 0x53;
1569 case XK_KP_2: case XK_KP_Down: return 0x54;
1570 case XK_KP_3: case XK_KP_Next: return 0x55;
1571 case XK_KP_4: case XK_KP_Left: return 0x56;
1572 case XK_KP_5: case XK_KP_Begin: return 0x57;
1573 case XK_KP_6: case XK_KP_Right: return 0x58;
1574 case XK_KP_7: case XK_KP_Home: return 0x59;
1575 case XK_KP_8: case XK_KP_Up: return 0x5b;
1576 case XK_KP_9: case XK_KP_Prior: return 0x5c;
1577 case XK_KP_Decimal: case XK_KP_Delete: return 0x41;
1578 #else
1579 case XK_KP_0: return 0x52;
1580 case XK_KP_1: return 0x53;
1581 case XK_KP_2: return 0x54;
1582 case XK_KP_3: return 0x55;
1583 case XK_KP_4: return 0x56;
1584 case XK_KP_5: return 0x57;
1585 case XK_KP_6: return 0x58;
1586 case XK_KP_7: return 0x59;
1587 case XK_KP_8: return 0x5b;
1588 case XK_KP_9: return 0x5c;
1589 case XK_KP_Decimal: return 0x41;
1590 #endif
1591 case XK_KP_Add: return 0x45;
1592 case XK_KP_Subtract: return 0x4e;
1593 case XK_KP_Multiply: return 0x43;
1594 case XK_KP_Divide: return 0x4b;
1595 case XK_KP_Enter: return 0x4c;
1596 case XK_KP_Equal: return 0x51;
1597 }
1598 return -1;
1599 }
1600
1601 static int event2keycode(XKeyEvent &ev)
1602 {
1603 KeySym ks;
1604 int as;
1605 int i = 0;
1606
1607 do {
1608 ks = XLookupKeysym(&ev, i++);
1609 as = kc_decode(ks);
1610 if (as != -1)
1611 return as;
1612 } while (ks != NoSymbol);
1613
1614 return -1;
1615 }
1616
1617
1618 /*
1619 * X event handling
1620 */
1621
1622 static void handle_events(void)
1623 {
1624 while (XPending(x_display)) {
1625 XEvent event;
1626 XNextEvent(x_display, &event);
1627
1628 switch (event.type) {
1629 // Mouse button
1630 case ButtonPress: {
1631 unsigned int button = event.xbutton.button;
1632 if (button < 4)
1633 ADBMouseDown(button - 1);
1634 else if (button < 6) { // Wheel mouse
1635 if (mouse_wheel_mode == 0) {
1636 int key = (button == 5) ? 0x79 : 0x74; // Page up/down
1637 ADBKeyDown(key);
1638 ADBKeyUp(key);
1639 } else {
1640 int key = (button == 5) ? 0x3d : 0x3e; // Cursor up/down
1641 for(int i=0; i<mouse_wheel_lines; i++) {
1642 ADBKeyDown(key);
1643 ADBKeyUp(key);
1644 }
1645 }
1646 }
1647 break;
1648 }
1649 case ButtonRelease: {
1650 unsigned int button = event.xbutton.button;
1651 if (button < 4)
1652 ADBMouseUp(button - 1);
1653 break;
1654 }
1655
1656 // Mouse moved
1657 case EnterNotify:
1658 case MotionNotify:
1659 ADBMouseMoved(event.xmotion.x, event.xmotion.y);
1660 break;
1661
1662 // Keyboard
1663 case KeyPress: {
1664 int code;
1665 if (use_keycodes) {
1666 event2keycode(event.xkey); // This is called to process the hotkeys
1667 code = keycode_table[event.xkey.keycode & 0xff];
1668 } else
1669 code = event2keycode(event.xkey);
1670 if (code != -1) {
1671 if (!emul_suspended) {
1672 if (code == 0x39) { // Caps Lock pressed
1673 if (caps_on) {
1674 ADBKeyUp(code);
1675 caps_on = false;
1676 } else {
1677 ADBKeyDown(code);
1678 caps_on = true;
1679 }
1680 } else
1681 ADBKeyDown(code);
1682 if (code == 0x36)
1683 ctrl_down = true;
1684 } else {
1685 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1686 if (code == 0x31)
1687 resume_emul(); // Space wakes us up
1688 #endif
1689 }
1690 }
1691 break;
1692 }
1693 case KeyRelease: {
1694 int code;
1695 if (use_keycodes) {
1696 event2keycode(event.xkey); // This is called to process the hotkeys
1697 code = keycode_table[event.xkey.keycode & 0xff];
1698 } else
1699 code = event2keycode(event.xkey);
1700 if (code != -1 && code != 0x39) { // Don't propagate Caps Lock releases
1701 ADBKeyUp(code);
1702 if (code == 0x36)
1703 ctrl_down = false;
1704 }
1705 break;
1706 }
1707
1708 // Hidden parts exposed, force complete refresh of window
1709 case Expose:
1710 if (display_type == DISPLAY_WINDOW) {
1711 #ifdef ENABLE_VOSF
1712 if (use_vosf) { // VOSF refresh
1713 LOCK_VOSF;
1714 PFLAG_SET_ALL;
1715 UNLOCK_VOSF;
1716 memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1717 }
1718 else
1719 #endif
1720 if (frame_skip == 0) { // Dynamic refresh
1721 int x1, y1;
1722 for (y1=0; y1<16; y1++)
1723 for (x1=0; x1<16; x1++)
1724 updt_box[x1][y1] = true;
1725 nr_boxes = 16 * 16;
1726 } else // Static refresh
1727 memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1728 }
1729 break;
1730
1731 // Window "close" widget clicked
1732 case ClientMessage:
1733 if (event.xclient.format == 32 && event.xclient.data.l[0] == WM_DELETE_WINDOW) {
1734 ADBKeyDown(0x7f); // Power key
1735 ADBKeyUp(0x7f);
1736 }
1737 break;
1738 }
1739 }
1740 }
1741
1742
1743 /*
1744 * Window display update
1745 */
1746
1747 // Dynamic display update (variable frame rate for each box)
1748 static void update_display_dynamic(int ticker)
1749 {
1750 int y1, y2, y2s, y2a, i, x1, xm, xmo, ymo, yo, yi, yil, xi;
1751 int xil = 0;
1752 int rxm = 0, rxmo = 0;
1753 int bytes_per_row = VideoMonitor.bytes_per_row;
1754 int bytes_per_pixel = VideoMonitor.bytes_per_row / VideoMonitor.x;
1755 int rx = VideoMonitor.bytes_per_row / 16;
1756 int ry = VideoMonitor.y / 16;
1757 int max_box;
1758
1759 y2s = sm_uptd[ticker % 8];
1760 y2a = 8;
1761 for (i = 0; i < 6; i++)
1762 if (ticker % (2 << i))
1763 break;
1764 max_box = sm_no_boxes[i];
1765
1766 if (y2a) {
1767 for (y1=0; y1<16; y1++) {
1768 for (y2=y2s; y2 < ry; y2 += y2a) {
1769 i = ((y1 * ry) + y2) * bytes_per_row;
1770 for (x1=0; x1<16; x1++, i += rx) {
1771 if (updt_box[x1][y1] == false) {
1772 if (memcmp(&the_buffer_copy[i], &the_buffer[i], rx)) {
1773 updt_box[x1][y1] = true;
1774 nr_boxes++;
1775 }
1776 }
1777 }
1778 }
1779 }
1780 }
1781
1782 if ((nr_boxes <= max_box) && (nr_boxes)) {
1783 for (y1=0; y1<16; y1++) {
1784 for (x1=0; x1<16; x1++) {
1785 if (updt_box[x1][y1] == true) {
1786 if (rxm == 0)
1787 xm = x1;
1788 rxm += rx;
1789 updt_box[x1][y1] = false;
1790 }
1791 if (((updt_box[x1+1][y1] == false) || (x1 == 15)) && (rxm)) {
1792 if ((rxmo != rxm) || (xmo != xm) || (yo != y1 - 1)) {
1793 if (rxmo) {
1794 xi = xmo * rx;
1795 yi = ymo * ry;
1796 xil = rxmo;
1797 yil = (yo - ymo +1) * ry;
1798 }
1799 rxmo = rxm;
1800 xmo = xm;
1801 ymo = y1;
1802 }
1803 rxm = 0;
1804 yo = y1;
1805 }
1806 if (xil) {
1807 i = (yi * bytes_per_row) + xi;
1808 for (y2=0; y2 < yil; y2++, i += bytes_per_row)
1809 memcpy(&the_buffer_copy[i], &the_buffer[i], xil);
1810 if (depth == 1) {
1811 if (have_shm)
1812 XShmPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0);
1813 else
1814 XPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil);
1815 } else {
1816 if (have_shm)
1817 XShmPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0);
1818 else
1819 XPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil);
1820 }
1821 xil = 0;
1822 }
1823 if ((x1 == 15) && (y1 == 15) && (rxmo)) {
1824 x1--;
1825 xi = xmo * rx;
1826 yi = ymo * ry;
1827 xil = rxmo;
1828 yil = (yo - ymo +1) * ry;
1829 rxmo = 0;
1830 }
1831 }
1832 }
1833 nr_boxes = 0;
1834 }
1835 }
1836
1837 // Static display update (fixed frame rate, but incremental)
1838 static void update_display_static(void)
1839 {
1840 // Incremental update code
1841 int wide = 0, high = 0, x1, x2, y1, y2, i, j;
1842 int bytes_per_row = VideoMonitor.bytes_per_row;
1843 int bytes_per_pixel = VideoMonitor.bytes_per_row / VideoMonitor.x;
1844 uint8 *p, *p2;
1845
1846 // Check for first line from top and first line from bottom that have changed
1847 y1 = 0;
1848 for (j=0; j<VideoMonitor.y; j++) {
1849 if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1850 y1 = j;
1851 break;
1852 }
1853 }
1854 y2 = y1 - 1;
1855 for (j=VideoMonitor.y-1; j>=y1; j--) {
1856 if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1857 y2 = j;
1858 break;
1859 }
1860 }
1861 high = y2 - y1 + 1;
1862
1863 // Check for first column from left and first column from right that have changed
1864 if (high) {
1865 if (depth == 1) {
1866 x1 = VideoMonitor.x - 1;
1867 for (j=y1; j<=y2; j++) {
1868 p = &the_buffer[j * bytes_per_row];
1869 p2 = &the_buffer_copy[j * bytes_per_row];
1870 for (i=0; i<(x1>>3); i++) {
1871 if (*p != *p2) {
1872 x1 = i << 3;
1873 break;
1874 }
1875 p++; p2++;
1876 }
1877 }
1878 x2 = x1;
1879 for (j=y1; j<=y2; j++) {
1880 p = &the_buffer[j * bytes_per_row];
1881 p2 = &the_buffer_copy[j * bytes_per_row];
1882 p += bytes_per_row;
1883 p2 += bytes_per_row;
1884 for (i=(VideoMonitor.x>>3); i>(x2>>3); i--) {
1885 p--; p2--;
1886 if (*p != *p2) {
1887 x2 = (i << 3) + 7;
1888 break;
1889 }
1890 }
1891 }
1892 wide = x2 - x1 + 1;
1893
1894 // Update copy of the_buffer
1895 if (high && wide) {
1896 for (j=y1; j<=y2; j++) {
1897 i = j * bytes_per_row + (x1 >> 3);
1898 memcpy(the_buffer_copy + i, the_buffer + i, wide >> 3);
1899 }
1900 }
1901
1902 } else {
1903 x1 = VideoMonitor.x;
1904 for (j=y1; j<=y2; j++) {
1905 p = &the_buffer[j * bytes_per_row];
1906 p2 = &the_buffer_copy[j * bytes_per_row];
1907 for (i=0; i<x1*bytes_per_pixel; i++) {
1908 if (*p != *p2) {
1909 x1 = i / bytes_per_pixel;
1910 break;
1911 }
1912 p++; p2++;
1913 }
1914 }
1915 x2 = x1;
1916 for (j=y1; j<=y2; j++) {
1917 p = &the_buffer[j * bytes_per_row];
1918 p2 = &the_buffer_copy[j * bytes_per_row];
1919 p += bytes_per_row;
1920 p2 += bytes_per_row;
1921 for (i=VideoMonitor.x*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
1922 p--;
1923 p2--;
1924 if (*p != *p2) {
1925 x2 = i / bytes_per_pixel;
1926 break;
1927 }
1928 }
1929 }
1930 wide = x2 - x1;
1931
1932 // Update copy of the_buffer
1933 if (high && wide) {
1934 for (j=y1; j<=y2; j++) {
1935 i = j * bytes_per_row + x1 * bytes_per_pixel;
1936 memcpy(the_buffer_copy + i, the_buffer + i, bytes_per_pixel * wide);
1937 }
1938 }
1939 }
1940 }
1941
1942 // Refresh display
1943 if (high && wide) {
1944 if (have_shm)
1945 XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
1946 else
1947 XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
1948 }
1949 }
1950
1951
1952 /*
1953 * Screen refresh functions
1954 */
1955
1956 // We suggest the compiler to inline the next two functions so that it
1957 // may specialise the code according to the current screen depth and
1958 // display type. A clever compiler would that job by itself though...
1959
1960 // NOTE: update_display_vosf is inlined too
1961
1962 static inline void possibly_quit_dga_mode()
1963 {
1964 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1965 // Quit DGA mode if requested
1966 if (quit_full_screen) {
1967 quit_full_screen = false;
1968 #ifdef ENABLE_XF86_DGA
1969 XF86DGADirectVideo(x_display, screen, 0);
1970 #endif
1971 XUngrabPointer(x_display, CurrentTime);
1972 XUngrabKeyboard(x_display, CurrentTime);
1973 XUnmapWindow(x_display, the_win);
1974 XSync(x_display, false);
1975 }
1976 #endif
1977 }
1978
1979 static inline void handle_palette_changes(int depth, int display_type)
1980 {
1981 LOCK_PALETTE;
1982
1983 if (palette_changed) {
1984 palette_changed = false;
1985 if (depth == 8) {
1986 XStoreColors(x_display, cmap[0], palette, 256);
1987 XStoreColors(x_display, cmap[1], palette, 256);
1988 XSync(x_display, false);
1989
1990 #ifdef ENABLE_XF86_DGA
1991 if (display_type == DISPLAY_DGA) {
1992 current_dga_cmap ^= 1;
1993 XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1994 }
1995 #endif
1996 }
1997 }
1998
1999 UNLOCK_PALETTE;
2000 }
2001
2002 static void video_refresh_dga(void)
2003 {
2004 // Quit DGA mode if requested
2005 possibly_quit_dga_mode();
2006
2007 // Handle X events
2008 handle_events();
2009
2010 // Handle palette changes
2011 handle_palette_changes(depth, DISPLAY_DGA);
2012 }
2013
2014 #ifdef ENABLE_VOSF
2015 #if REAL_ADDRESSING || DIRECT_ADDRESSING
2016 static void video_refresh_dga_vosf(void)
2017 {
2018 // Quit DGA mode if requested
2019 possibly_quit_dga_mode();
2020
2021 // Handle X events
2022 handle_events();
2023
2024 // Handle palette changes
2025 handle_palette_changes(depth, DISPLAY_DGA);
2026
2027 // Update display (VOSF variant)
2028 static int tick_counter = 0;
2029 if (++tick_counter >= frame_skip) {
2030 tick_counter = 0;
2031 LOCK_VOSF;
2032 update_display_dga_vosf();
2033 UNLOCK_VOSF;
2034 }
2035 }
2036 #endif
2037
2038 static void video_refresh_window_vosf(void)
2039 {
2040 // Quit DGA mode if requested
2041 possibly_quit_dga_mode();
2042
2043 // Handle X events
2044 handle_events();
2045
2046 // Handle palette changes
2047 handle_palette_changes(depth, DISPLAY_WINDOW);
2048
2049 // Update display (VOSF variant)
2050 static int tick_counter = 0;
2051 if (++tick_counter >= frame_skip) {
2052 tick_counter = 0;
2053 LOCK_VOSF;
2054 update_display_window_vosf();
2055 UNLOCK_VOSF;
2056 }
2057 }
2058 #endif // def ENABLE_VOSF
2059
2060 static void video_refresh_window_static(void)
2061 {
2062 // Handle X events
2063 handle_events();
2064
2065 // Handle_palette changes
2066 handle_palette_changes(depth, DISPLAY_WINDOW);
2067
2068 // Update display (static variant)
2069 static int tick_counter = 0;
2070 if (++tick_counter >= frame_skip) {
2071 tick_counter = 0;
2072 update_display_static();
2073 }
2074 }
2075
2076 static void video_refresh_window_dynamic(void)
2077 {
2078 // Handle X events
2079 handle_events();
2080
2081 // Handle_palette changes
2082 handle_palette_changes(depth, DISPLAY_WINDOW);
2083
2084 // Update display (dynamic variant)
2085 static int tick_counter = 0;
2086 tick_counter++;
2087 update_display_dynamic(tick_counter);
2088 }
2089
2090
2091 /*
2092 * Thread for screen refresh, input handling etc.
2093 */
2094
2095 void VideoRefreshInit(void)
2096 {
2097 // TODO: set up specialised 8bpp VideoRefresh handlers ?
2098 if (display_type == DISPLAY_DGA) {
2099 #if ENABLE_VOSF && (REAL_ADDRESSING || DIRECT_ADDRESSING)
2100 if (use_vosf)
2101 video_refresh = video_refresh_dga_vosf;
2102 else
2103 #endif
2104 video_refresh = video_refresh_dga;
2105 }
2106 else {
2107 #ifdef ENABLE_VOSF
2108 if (use_vosf)
2109 video_refresh = video_refresh_window_vosf;
2110 else
2111 #endif
2112 if (frame_skip == 0)
2113 video_refresh = video_refresh_window_dynamic;
2114 else
2115 video_refresh = video_refresh_window_static;
2116 }
2117 }
2118
2119 void VideoRefresh(void)
2120 {
2121 // TODO: make main_unix/VideoRefresh call directly video_refresh() ?
2122 video_refresh();
2123 }
2124
2125 #ifdef HAVE_PTHREADS
2126 static void *redraw_func(void *arg)
2127 {
2128 uint64 start = GetTicks_usec();
2129 int64 ticks = 0;
2130 uint64 next = GetTicks_usec();
2131 while (!redraw_thread_cancel) {
2132 video_refresh();
2133 next += 16667;
2134 int64 delay = next - GetTicks_usec();
2135 if (delay > 0)
2136 Delay_usec(delay);
2137 else if (delay < -16667)
2138 next = GetTicks_usec();
2139 ticks++;
2140 }
2141 uint64 end = GetTicks_usec();
2142 printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, ticks * 1000000 / (end - start));
2143 return NULL;
2144 }
2145 #endif