ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/video_x.cpp
Revision: 1.35
Committed: 2001-01-11T18:00:40Z (23 years, 10 months ago) by gbeauche
Branch: MAIN
Changes since 1.34: +5 -9 lines
Log Message:
- Cleaned up some comments again
- The dirtyPages[] array overrun conditions should be really safe now

File Contents

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