--- BasiliskII/src/Unix/video_x.cpp 2001/06/27 19:03:37 1.40 +++ BasiliskII/src/Unix/video_x.cpp 2001/07/11 17:04:41 1.59 @@ -24,6 +24,7 @@ * Ctrl-Tab = suspend DGA mode * Ctrl-Esc = emergency quit * Ctrl-F1 = mount floppy + * Ctrl-F5 = grab mouse (in windowed mode) */ #include "sysdeps.h" @@ -36,6 +37,12 @@ #include #include +#include + +#ifndef NO_STD_NAMESPACE +using std::sort; +#endif + #ifdef HAVE_PTHREADS # include #endif @@ -52,13 +59,6 @@ # include #endif -#ifdef ENABLE_VOSF -# include -# include -# include "sigsegv.h" -# include "vm_alloc.h" -#endif - #include "cpu_emulation.h" #include "main.h" #include "adb.h" @@ -79,27 +79,37 @@ enum { // Constants const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes"; -const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices"; + +static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask; +static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; // Global variables static int32 frame_skip; // Prefs items -static int16 mouse_wheel_mode = 1; -static int16 mouse_wheel_lines = 3; +static int16 mouse_wheel_mode; +static int16 mouse_wheel_lines; static int display_type = DISPLAY_WINDOW; // See enum above static bool local_X11; // Flag: X server running on local machine? -static uint8 *the_buffer; // Mac frame buffer +static uint8 *the_buffer = NULL; // Mac frame buffer (where MacOS draws into) +static uint8 *the_buffer_copy = NULL; // Copy of Mac frame buffer (for refreshed modes) +static uint32 the_buffer_size; // Size of allocated the_buffer -#ifdef HAVE_PTHREADS static bool redraw_thread_active = false; // Flag: Redraw thread installed -static volatile bool redraw_thread_cancel = false; // Flag: Cancel Redraw thread +#ifdef HAVE_PTHREADS +static volatile bool redraw_thread_cancel; // Flag: Cancel Redraw thread static pthread_t redraw_thread; // Redraw thread #endif static bool has_dga = false; // Flag: Video DGA capable static bool has_vidmode = false; // Flag: VidMode extension available +#ifdef ENABLE_VOSF +static bool use_vosf = true; // Flag: VOSF enabled +#else +static const bool use_vosf = false; // VOSF not possible +#endif + static bool ctrl_down = false; // Flag: Ctrl key pressed static bool caps_on = false; // Flag: Caps Lock on static bool quit_full_screen = false; // Flag: DGA close requested from redraw thread @@ -113,23 +123,37 @@ static int keycode_table[256]; // X // X11 variables static int screen; // Screen number -static int xdepth; // Depth of X screen -static int depth; // Depth of Mac frame buffer -static Window rootwin, the_win; // Root window and our window -static XVisualInfo visualInfo; -static Visual *vis; -static Colormap cmap[2]; // Two colormaps (DGA) for 8-bit mode +static Window rootwin; // Root window and our window +static int num_depths = 0; // Number of available X depths +static int *avail_depths = NULL; // List of available X depths static XColor black, white; static unsigned long black_pixel, white_pixel; static int eventmask; -static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask; -static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask; -static Atom WM_DELETE_WINDOW = (Atom)0; -static XColor palette[256]; // Color palette for 8-bit mode +static int xdepth; // Depth of X screen +static XVisualInfo visualInfo; +static Visual *vis; +static int color_class; + +static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes + +static Colormap cmap[2] = {0, 0}; // Colormaps for indexed modes (DGA needs two of them) + +static XColor palette[256]; // Color palette to be used as CLUT and gamma table static bool palette_changed = false; // Flag: Palette changed, redraw thread must set new colors + +#ifdef ENABLE_FBDEV_DGA +static int fbdev_fd = -1; +#endif + +#ifdef ENABLE_XF86_VIDMODE +static XF86VidModeModeInfo **x_video_modes = NULL; // Array of all available modes +static int num_x_video_modes; +#endif + +// Mutex to protect palette #ifdef HAVE_PTHREADS -static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect palette +static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER; #define LOCK_PALETTE pthread_mutex_lock(&palette_lock) #define UNLOCK_PALETTE pthread_mutex_unlock(&palette_lock) #else @@ -137,24 +161,9 @@ static pthread_mutex_t palette_lock = PT #define UNLOCK_PALETTE #endif -// Variables for window mode -static GC the_gc; -static XImage *img = NULL; -static XShmSegmentInfo shminfo; -static Cursor mac_cursor; -static uint8 *the_buffer_copy = NULL; // Copy of Mac frame buffer -static bool have_shm = false; // Flag: SHM extensions available -static bool updt_box[17][17]; // Flag for Update -static int nr_boxes; -static const int sm_uptd[] = {4,1,6,3,0,5,2,7}; -static int sm_no_boxes[] = {1,8,32,64,128,300}; - -// Variables for XF86 DGA mode -static int current_dga_cmap; // Number (0 or 1) of currently installed DGA colormap -static Window suspend_win; // "Suspend" window -static void *fb_save = NULL; // Saved frame buffer for suspend +// Mutex to protect frame buffer #ifdef HAVE_PTHREADS -static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect frame buffer +static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER; #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock); #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock); #else @@ -162,153 +171,21 @@ static pthread_mutex_t frame_buffer_lock #define UNLOCK_FRAME_BUFFER #endif -// Variables for fbdev DGA mode -const char FBDEVICE_FILE_NAME[] = "/dev/fb"; -static int fbdev_fd; - -#ifdef ENABLE_XF86_VIDMODE -// Variables for XF86 VidMode support -static XF86VidModeModeInfo **x_video_modes; // Array of all available modes -static int num_x_video_modes; -#endif - -#ifdef ENABLE_VOSF -static bool use_vosf = true; // Flag: VOSF enabled -#else -static const bool use_vosf = false; // Flag: VOSF enabled -#endif - -#ifdef ENABLE_VOSF -// Variables for Video on SEGV support (taken from the Win32 port) -static uint8 *the_host_buffer; // Host frame buffer in VOSF mode -static uint32 the_buffer_size; // Size of allocated the_buffer - -struct ScreenPageInfo { - int top, bottom; // Mapping between this virtual page and Mac scanlines -}; - -struct ScreenInfo { - uintptr memBase; // Real start address - uintptr memStart; // Start address aligned to page boundary - uintptr memEnd; // Address of one-past-the-end of the screen - uint32 memLength; // Length of the memory addressed by the screen pages - - uint32 pageSize; // Size of a page - int pageBits; // Shift count to get the page number - uint32 pageCount; // Number of pages allocated to the screen - - bool dirty; // Flag: set if the frame buffer was touched - char * dirtyPages; // Table of flags set if page was altered - ScreenPageInfo * pageInfo; // Table of mappings page -> Mac scanlines -}; - -static ScreenInfo mainBuffer; - -#define PFLAG_SET_VALUE 0x00 -#define PFLAG_CLEAR_VALUE 0x01 -#define PFLAG_SET_VALUE_4 0x00000000 -#define PFLAG_CLEAR_VALUE_4 0x01010101 -#define PFLAG_SET(page) mainBuffer.dirtyPages[page] = PFLAG_SET_VALUE -#define PFLAG_CLEAR(page) mainBuffer.dirtyPages[page] = PFLAG_CLEAR_VALUE -#define PFLAG_ISSET(page) (mainBuffer.dirtyPages[page] == PFLAG_SET_VALUE) -#define PFLAG_ISCLEAR(page) (mainBuffer.dirtyPages[page] != PFLAG_SET_VALUE) - -#ifdef UNALIGNED_PROFITABLE -# define PFLAG_ISSET_4(page) (*((uint32 *)(mainBuffer.dirtyPages + (page))) == PFLAG_SET_VALUE_4) -# define PFLAG_ISCLEAR_4(page) (*((uint32 *)(mainBuffer.dirtyPages + (page))) == PFLAG_CLEAR_VALUE_4) -#else -# define PFLAG_ISSET_4(page) \ - PFLAG_ISSET(page ) && PFLAG_ISSET(page+1) \ - && PFLAG_ISSET(page+2) && PFLAG_ISSET(page+3) -# define PFLAG_ISCLEAR_4(page) \ - PFLAG_ISCLEAR(page ) && PFLAG_ISCLEAR(page+1) \ - && PFLAG_ISCLEAR(page+2) && PFLAG_ISCLEAR(page+3) -#endif - -// Set the selected page range [ first_page, last_page [ into the SET state -#define PFLAG_SET_RANGE(first_page, last_page) \ - memset(mainBuffer.dirtyPages + (first_page), PFLAG_SET_VALUE, \ - (last_page) - (first_page)) - -// Set the selected page range [ first_page, last_page [ into the CLEAR state -#define PFLAG_CLEAR_RANGE(first_page, last_page) \ - memset(mainBuffer.dirtyPages + (first_page), PFLAG_CLEAR_VALUE, \ - (last_page) - (first_page)) - -#define PFLAG_SET_ALL do { \ - PFLAG_SET_RANGE(0, mainBuffer.pageCount); \ - mainBuffer.dirty = true; \ -} while (0) - -#define PFLAG_CLEAR_ALL do { \ - PFLAG_CLEAR_RANGE(0, mainBuffer.pageCount); \ - mainBuffer.dirty = false; \ -} while (0) - -// Set the following macro definition to 1 if your system -// provides a really fast strchr() implementation -//#define HAVE_FAST_STRCHR 0 - -static inline int find_next_page_set(int page) -{ -#if HAVE_FAST_STRCHR - char *match = strchr(mainBuffer.dirtyPages + page, PFLAG_SET_VALUE); - return match ? match - mainBuffer.dirtyPages : mainBuffer.pageCount; -#else - while (PFLAG_ISCLEAR_4(page)) - page += 4; - while (PFLAG_ISCLEAR(page)) - page++; - return page; -#endif -} - -static inline int find_next_page_clear(int page) -{ -#if HAVE_FAST_STRCHR - char *match = strchr(mainBuffer.dirtyPages + page, PFLAG_CLEAR_VALUE); - return match ? match - mainBuffer.dirtyPages : mainBuffer.pageCount; -#else - while (PFLAG_ISSET_4(page)) - page += 4; - while (PFLAG_ISSET(page)) - page++; - return page; -#endif -} - -static int zero_fd = -1; - -#ifdef HAVE_PTHREADS -static pthread_mutex_t vosf_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect frame buffer (dirtyPages in fact) -#define LOCK_VOSF pthread_mutex_lock(&vosf_lock); -#define UNLOCK_VOSF pthread_mutex_unlock(&vosf_lock); -#else -#define LOCK_VOSF -#define UNLOCK_VOSF -#endif - -static int log_base_2(uint32 x) -{ - uint32 mask = 0x80000000; - int l = 31; - while (l >= 0 && (x & mask) == 0) { - mask >>= 1; - l--; - } - return l; -} -#endif /* ENABLE_VOSF */ +// Variables for non-VOSF incremental refresh +static const int sm_uptd[] = {4,1,6,3,0,5,2,7}; +static int sm_no_boxes[] = {1,8,32,64,128,300}; +static bool updt_box[17][17]; +static int nr_boxes; -// VideoRefresh function -void VideoRefreshInit(void); +// Video refresh function +static void VideoRefreshInit(void); static void (*video_refresh)(void); + // Prototypes static void *redraw_func(void *arg); static int event2keycode(XKeyEvent &ev); - // From main_unix.cpp extern char *x_display_name; extern Display *x_display; @@ -316,77 +193,156 @@ extern Display *x_display; // From sys_unix.cpp extern void SysMountFirstFloppy(void); -#ifdef ENABLE_VOSF -# include "video_vosf.h" -#endif - /* - * Initialization + * Utility functions */ -// Add resolution to list of supported modes and set VideoMonitor -static void set_video_monitor(uint32 width, uint32 height, uint32 bytes_per_row, bool native_byte_order) +// Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals) +static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue) { - video_mode mode; -#if !REAL_ADDRESSING && !DIRECT_ADDRESSING - int layout = FLAYOUT_DIRECT; + return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift); +} + +// Do we have a visual for handling the specified Mac depth? If so, set the +// global variables "xdepth", "visualInfo", "vis" and "color_class". +static bool find_visual_for_depth(video_depth depth) +{ + D(bug("have_visual_for_depth(%d)\n", 1 << depth)); + + // Calculate minimum and maximum supported X depth + int min_depth = 1, max_depth = 32; switch (depth) { - case 1: - layout = FLAYOUT_DIRECT; + case VDEPTH_1BIT: // 1-bit works always and uses default visual + min_depth = max_depth = DefaultDepth(x_display, screen); break; - case 8: - layout = FLAYOUT_DIRECT; +#ifdef ENABLE_VOSF + case VDEPTH_2BIT: + case VDEPTH_4BIT: // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit + case VDEPTH_8BIT: + min_depth = 8; + max_depth = 32; break; - case 15: - layout = FLAYOUT_HOST_555; +#else + case VDEPTH_2BIT: + case VDEPTH_4BIT: // 2/4-bit requires VOSF blitters + return false; + case VDEPTH_8BIT: // 8-bit without VOSF requires an 8-bit visual + min_depth = 8; + max_depth = 8; break; - case 16: - layout = FLAYOUT_HOST_565; +#endif + case VDEPTH_16BIT: // 16-bit requires a 15/16-bit visual + min_depth = 15; + max_depth = 16; break; - case 24: - case 32: - layout = FLAYOUT_HOST_888; + case VDEPTH_32BIT: // 32-bit requires a 24/32-bit visual + min_depth = 24; + max_depth = 32; break; } - if (native_byte_order) - MacFrameLayout = layout; - else - MacFrameLayout = FLAYOUT_DIRECT; + D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth)); + + // Try to find a visual for one of the color depths + bool visual_found = false; + for (int i=0; i max_depth) + continue; + + // Determine best color class for this depth + switch (xdepth) { + case 1: // Try StaticGray or StaticColor + if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo) + || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo)) + visual_found = true; + break; + case 8: // Need PseudoColor + if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo)) + visual_found = true; + break; + case 15: + case 16: + case 24: + case 32: // Try DirectColor first, as this will allow gamma correction + if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo) + || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo)) + visual_found = true; + break; + default: + D(bug(" not a supported depth\n")); + break; + } + } + if (!visual_found) + return false; + + // Visual was found + vis = visualInfo.visual; + color_class = visualInfo.c_class; + D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth)); +#if DEBUG + switch (color_class) { + case StaticGray: D(bug("StaticGray\n")); break; + case GrayScale: D(bug("GrayScale\n")); break; + case StaticColor: D(bug("StaticColor\n")); break; + case PseudoColor: D(bug("PseudoColor\n")); break; + case TrueColor: D(bug("TrueColor\n")); break; + case DirectColor: D(bug("DirectColor\n")); break; + } #endif + return true; +} +// Add mode to list of supported modes +static void add_mode(uint32 width, uint32 height, uint32 resolution_id, uint32 bytes_per_row, video_depth depth) +{ + video_mode mode; mode.x = width; mode.y = height; - mode.resolution_id = 0x80; + mode.resolution_id = resolution_id; mode.bytes_per_row = bytes_per_row; + mode.depth = depth; + VideoModes.push_back(mode); +} - switch (depth) { - case 1: - mode.depth = VDEPTH_1BIT; - break; - case 2: - mode.depth = VDEPTH_2BIT; - break; - case 4: - mode.depth = VDEPTH_4BIT; - break; - case 8: - mode.depth = VDEPTH_8BIT; - break; - case 15: - mode.depth = VDEPTH_16BIT; - break; - case 16: - mode.depth = VDEPTH_16BIT; - break; - case 24: - case 32: - mode.depth = VDEPTH_32BIT; - break; - } +// Add standard list of windowed modes for given color depth +static void add_window_modes(video_depth depth) +{ + add_mode(512, 384, 0x80, TrivialBytesPerRow(512, depth), depth); + add_mode(640, 480, 0x81, TrivialBytesPerRow(640, depth), depth); + add_mode(800, 600, 0x82, TrivialBytesPerRow(800, depth), depth); + add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, depth), depth); + add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, depth), depth); + add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, depth), depth); + add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, depth), depth); +} - VideoModes.push_back(mode); - VideoMonitor.mode = mode; +// Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac) +static void set_mac_frame_buffer(video_depth depth, bool native_byte_order) +{ +#if !REAL_ADDRESSING && !DIRECT_ADDRESSING + int layout = FLAYOUT_DIRECT; + if (depth == VDEPTH_16BIT) + layout = (xdepth == 15) ? FLAYOUT_HOST_555 : FLAYOUT_HOST_565; + else if (depth == VDEPTH_32BIT) + layout = (xdepth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT; + if (native_byte_order) + MacFrameLayout = layout; + else + MacFrameLayout = FLAYOUT_DIRECT; + VideoMonitor.mac_frame_base = MacFrameBaseMac; + + // Set variables used by UAE memory banking + MacFrameBaseHost = the_buffer; + MacFrameSize = VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y; + InitFrameBufferMapping(); +#else + VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer); +#endif + D(bug("VideoMonitor.mac_frame_base = %08x\n", VideoMonitor.mac_frame_base)); } // Set window name and class @@ -420,6 +376,7 @@ static void set_window_focus(Window w) } // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget) +static Atom WM_DELETE_WINDOW = (Atom)0; static void set_window_delete_protocol(Window w) { WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false); @@ -456,35 +413,182 @@ static int error_handler(Display *d, XEr return old_error_handler(d, e); } -// Init window mode -static bool init_window(int width, int height) + +/* + * Display "driver" classes + */ + +class driver_base { +public: + driver_base(); + virtual ~driver_base(); + + virtual void update_palette(void); + virtual void suspend(void) {} + virtual void resume(void) {} + virtual void toggle_mouse_grab(void) {} + virtual void mouse_moved(int x, int y) { ADBMouseMoved(x, y); } + + void disable_mouse_accel(void); + void restore_mouse_accel(void); + + virtual void grab_mouse(void) {} + virtual void ungrab_mouse(void) {} + +public: + bool init_ok; // Initialization succeeded (we can't use exceptions because of -fomit-frame-pointer) + Window w; // The window we draw into + + int orig_accel_numer, orig_accel_denom, orig_threshold; // Original mouse acceleration +}; + +class driver_window; +static void update_display_window_vosf(driver_window *drv); +static void update_display_dynamic(int ticker, driver_window *drv); +static void update_display_static(driver_window *drv); + +class driver_window : public driver_base { + friend void update_display_window_vosf(driver_window *drv); + friend void update_display_dynamic(int ticker, driver_window *drv); + friend void update_display_static(driver_window *drv); + +public: + driver_window(const video_mode &mode); + ~driver_window(); + + void toggle_mouse_grab(void); + void mouse_moved(int x, int y); + + void grab_mouse(void); + void ungrab_mouse(void); + +private: + GC gc; + XImage *img; + bool have_shm; // Flag: SHM extensions available + XShmSegmentInfo shminfo; + Cursor mac_cursor; + bool mouse_grabbed; // Flag: mouse pointer grabbed, using relative mouse mode + int mouse_last_x, mouse_last_y; // Last mouse position (for relative mode) +}; + +static driver_base *drv = NULL; // Pointer to currently used driver object + +#ifdef ENABLE_VOSF +# include "video_vosf.h" +#endif + +driver_base::driver_base() + : init_ok(false), w(0) +{ + the_buffer = NULL; + the_buffer_copy = NULL; + XGetPointerControl(x_display, &orig_accel_numer, &orig_accel_denom, &orig_threshold); +} + +driver_base::~driver_base() { + ungrab_mouse(); + restore_mouse_accel(); + + if (w) { + XUnmapWindow(x_display, w); + wait_unmapped(w); + XDestroyWindow(x_display, w); + } + + XFlush(x_display); + XSync(x_display, false); + + // Free frame buffer(s) + if (!use_vosf) { + if (the_buffer) { + free(the_buffer); + the_buffer = NULL; + } + if (the_buffer_copy) { + free(the_buffer_copy); + the_buffer_copy = NULL; + } + } +#ifdef ENABLE_VOSF + else { + if (the_host_buffer) { + free(the_host_buffer); + the_host_buffer = NULL; + } + if (the_buffer) { + free(the_buffer); + the_buffer = NULL; + } + if (the_buffer_copy) { + free(the_buffer_copy); + the_buffer_copy = NULL; + } + } +#endif +} + +// Palette has changed +void driver_base::update_palette(void) +{ + if (color_class == PseudoColor || color_class == DirectColor) { + int num = vis->map_entries; + if (!IsDirectMode(VideoMonitor.mode) && color_class == DirectColor) + return; // Indexed mode on true color screen, don't set CLUT + XStoreColors(x_display, cmap[0], palette, num); + XStoreColors(x_display, cmap[1], palette, num); + } + XSync(x_display, false); +} + +// Disable mouse acceleration +void driver_base::disable_mouse_accel(void) +{ + XChangePointerControl(x_display, True, False, 1, 1, 0); +} + +// Restore mouse acceleration to original value +void driver_base::restore_mouse_accel(void) +{ + XChangePointerControl(x_display, True, True, orig_accel_numer, orig_accel_denom, orig_threshold); +} + + +/* + * Windowed display driver + */ + +// Open display +driver_window::driver_window(const video_mode &mode) + : gc(0), img(NULL), have_shm(false), mouse_grabbed(false), mac_cursor(0) +{ + int width = mode.x, height = mode.y; int aligned_width = (width + 15) & ~15; int aligned_height = (height + 15) & ~15; // Set absolute mouse mode - ADBSetRelMouseMode(false); + ADBSetRelMouseMode(mouse_grabbed); - // Read frame skip prefs - frame_skip = PrefsFindInt32("frameskip"); - - // Create window + // Create window (setting backround_pixel, border_pixel and colormap is + // mandatory when using a non-default visual; in 1-bit mode we use the + // default visual, so we can also use the default colormap) XSetWindowAttributes wattr; wattr.event_mask = eventmask = win_eventmask; - wattr.background_pixel = black_pixel; - wattr.colormap = cmap[0]; - - the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth, - InputOutput, vis, CWEventMask | CWBackPixel | (depth == 8 ? CWColormap : 0), &wattr); + wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0); + wattr.border_pixel = 0; + wattr.colormap = (mode.depth == VDEPTH_1BIT ? DefaultColormap(x_display, screen) : cmap[0]); + w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth, + InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWColormap, &wattr); // Set window name/class - set_window_name(the_win, STR_WINDOW_TITLE); + set_window_name(w, STR_WINDOW_TITLE); // Indicate that we want keyboard input - set_window_focus(the_win); + set_window_focus(w); // Set delete protocol property - set_window_delete_protocol(the_win); + set_window_delete_protocol(w); // Make window unresizable { @@ -495,21 +599,24 @@ static bool init_window(int width, int h hints->min_height = height; hints->max_height = height; hints->flags = PMinSize | PMaxSize; - XSetWMNormalHints(x_display, the_win, hints); + XSetWMNormalHints(x_display, w, hints); XFree(hints); } } // Show window - XMapWindow(x_display, the_win); - wait_mapped(the_win); + XMapWindow(x_display, w); + wait_mapped(w); + + // 1-bit mode is big-endian; if the X server is little-endian, we can't + // use SHM because that doesn't allow changing the image byte order + bool need_msb_image = (mode.depth == VDEPTH_1BIT && XImageByteOrder(x_display) == LSBFirst); // Try to create and attach SHM image - have_shm = false; - if (depth != 1 && local_X11 && XShmQueryExtension(x_display)) { + if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) { // Create SHM image ("height + 2" for safety) - img = XShmCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height); + img = XShmCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, &shminfo, width, height); shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777); the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0); shminfo.shmaddr = img->data = (char *)the_buffer_copy; @@ -524,6 +631,7 @@ static bool init_window(int width, int h if (shm_error) { shmdt(shminfo.shmaddr); XDestroyImage(img); + img = NULL; shminfo.shmid = -1; } else { have_shm = true; @@ -533,53 +641,42 @@ static bool init_window(int width, int h // Create normal X image if SHM doesn't work ("height + 2" for safety) if (!have_shm) { - int bytes_per_row = aligned_width; - switch (depth) { - case 1: - bytes_per_row /= 8; - break; - case 15: - case 16: - bytes_per_row *= 2; - break; - case 24: - case 32: - bytes_per_row *= 4; - break; - } + int bytes_per_row = (mode.depth == VDEPTH_1BIT ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth))); the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row); - img = XCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row); + img = XCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row); } - // 1-Bit mode is big-endian - if (depth == 1) { + if (need_msb_image) { img->byte_order = MSBFirst; img->bitmap_bit_order = MSBFirst; } #ifdef ENABLE_VOSF + use_vosf = true; // Allocate memory for frame buffer (SIZE is extended to page-boundary) the_host_buffer = the_buffer_copy; the_buffer_size = page_extend((aligned_height + 2) * img->bytes_per_line); the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size); the_buffer = (uint8 *)vm_acquire(the_buffer_size); + D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer)); #else // Allocate memory for frame buffer the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line); + D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy)); #endif // Create GC - the_gc = XCreateGC(x_display, the_win, 0, 0); - XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes); + gc = XCreateGC(x_display, w, 0, 0); + XSetState(x_display, gc, black_pixel, white_pixel, GXcopy, AllPlanes); // Create no_cursor mac_cursor = XCreatePixmapCursor(x_display, - XCreatePixmap(x_display, the_win, 1, 1, 1), - XCreatePixmap(x_display, the_win, 1, 1, 1), + XCreatePixmap(x_display, w, 1, 1, 1), + XCreatePixmap(x_display, w, 1, 1, 1), &black, &white, 0, 0); - XDefineCursor(x_display, the_win, mac_cursor); + XDefineCursor(x_display, w, mac_cursor); - // Add resolution and set VideoMonitor + // Init blitting routines bool native_byte_order; #ifdef WORDS_BIGENDIAN native_byte_order = (XImageByteOrder(x_display) == MSBFirst); @@ -587,28 +684,276 @@ static bool init_window(int width, int h native_byte_order = (XImageByteOrder(x_display) == LSBFirst); #endif #ifdef ENABLE_VOSF - Screen_blitter_init(&visualInfo, native_byte_order); + Screen_blitter_init(&visualInfo, native_byte_order, mode.depth); #endif - set_video_monitor(width, height, img->bytes_per_line, native_byte_order); - -#if REAL_ADDRESSING || DIRECT_ADDRESSING - VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer); + + // Set VideoMonitor + VideoMonitor.mode = mode; + set_mac_frame_buffer(mode.depth, native_byte_order); + + // Everything went well + init_ok = true; +} + +// Close display +driver_window::~driver_window() +{ + if (have_shm) { + XShmDetach(x_display, &shminfo); +#ifdef ENABLE_VOSF + the_host_buffer = NULL; // don't free() in driver_base dtor #else - VideoMonitor.mac_frame_base = MacFrameBaseMac; + the_buffer_copy = NULL; // don't free() in driver_base dtor #endif - return true; + } +#ifdef ENABLE_VOSF + if (use_vosf) { + // don't free() memory mapped buffers in driver_base dtor + if (the_buffer != VM_MAP_FAILED) { + vm_release(the_buffer, the_buffer_size); + the_buffer = NULL; + } + if (the_buffer_copy != VM_MAP_FAILED) { + vm_release(the_buffer_copy, the_buffer_size); + the_buffer_copy = NULL; + } + } +#endif + if (img) + XDestroyImage(img); + if (have_shm) { + shmdt(shminfo.shmaddr); + shmctl(shminfo.shmid, IPC_RMID, 0); + } + if (gc) + XFreeGC(x_display, gc); +} + +// Toggle mouse grab +void driver_window::toggle_mouse_grab(void) +{ + if (mouse_grabbed) + ungrab_mouse(); + else + grab_mouse(); +} + +// Grab mouse, switch to relative mouse mode +void driver_window::grab_mouse(void) +{ + int result; + for (int i=0; i<10; i++) { + result = XGrabPointer(x_display, w, True, 0, + GrabModeAsync, GrabModeAsync, w, None, CurrentTime); + if (result != AlreadyGrabbed) + break; + Delay_usec(100000); + } + if (result == GrabSuccess) { + XStoreName(x_display, w, GetString(STR_WINDOW_TITLE_GRABBED)); + ADBSetRelMouseMode(mouse_grabbed = true); + disable_mouse_accel(); + } +} + +// Ungrab mouse, switch to absolute mouse mode +void driver_window::ungrab_mouse(void) +{ + if (mouse_grabbed) { + XUngrabPointer(x_display, CurrentTime); + XStoreName(x_display, w, GetString(STR_WINDOW_TITLE)); + ADBSetRelMouseMode(mouse_grabbed = false); + restore_mouse_accel(); + } +} + +// Mouse moved +void driver_window::mouse_moved(int x, int y) +{ + if (!mouse_grabbed) { + mouse_last_x = x; mouse_last_y = y; + ADBMouseMoved(x, y); + return; + } + + // Warped mouse motion (this code is taken from SDL) + + // Post first mouse event + int width = VideoMonitor.mode.x, height = VideoMonitor.mode.y; + int delta_x = x - mouse_last_x, delta_y = y - mouse_last_y; + mouse_last_x = x; mouse_last_y = y; + ADBMouseMoved(delta_x, delta_y); + + // Only warp the pointer when it has reached the edge + const int MOUSE_FUDGE_FACTOR = 8; + if (x < MOUSE_FUDGE_FACTOR || x > (width - MOUSE_FUDGE_FACTOR) + || y < MOUSE_FUDGE_FACTOR || y > (height - MOUSE_FUDGE_FACTOR)) { + XEvent event; + while (XCheckTypedEvent(x_display, MotionNotify, &event)) { + delta_x = x - mouse_last_x; delta_y = y - mouse_last_y; + mouse_last_x = x; mouse_last_y = y; + ADBMouseMoved(delta_x, delta_y); + } + mouse_last_x = width/2; + mouse_last_y = height/2; + XWarpPointer(x_display, None, w, 0, 0, 0, 0, mouse_last_x, mouse_last_y); + for (int i=0; i<10; i++) { + XMaskEvent(x_display, PointerMotionMask, &event); + if (event.xmotion.x > (mouse_last_x - MOUSE_FUDGE_FACTOR) + && event.xmotion.x < (mouse_last_x + MOUSE_FUDGE_FACTOR) + && event.xmotion.y > (mouse_last_y - MOUSE_FUDGE_FACTOR) + && event.xmotion.y < (mouse_last_y + MOUSE_FUDGE_FACTOR)) + break; + } + } +} + + +#if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA) +/* + * DGA display driver base class + */ + +class driver_dga : public driver_base { +public: + driver_dga(); + ~driver_dga(); + + void suspend(void); + void resume(void); + +private: + Window suspend_win; // "Suspend" information window + void *fb_save; // Saved frame buffer for suspend/resume +}; + +driver_dga::driver_dga() + : suspend_win(0), fb_save(NULL) +{ +} + +driver_dga::~driver_dga() +{ + XUngrabPointer(x_display, CurrentTime); + XUngrabKeyboard(x_display, CurrentTime); +} + +// Suspend emulation +void driver_dga::suspend(void) +{ + // Release ctrl key + ADBKeyUp(0x36); + ctrl_down = false; + + // Lock frame buffer (this will stop the MacOS thread) + LOCK_FRAME_BUFFER; + + // Save frame buffer + fb_save = malloc(VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row); + if (fb_save) + memcpy(fb_save, the_buffer, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row); + + // Close full screen display +#ifdef ENABLE_XF86_DGA + XF86DGADirectVideo(x_display, screen, 0); +#endif + XUngrabPointer(x_display, CurrentTime); + XUngrabKeyboard(x_display, CurrentTime); + restore_mouse_accel(); + XUnmapWindow(x_display, w); + wait_unmapped(w); + + // Open "suspend" window + XSetWindowAttributes wattr; + wattr.event_mask = KeyPressMask; + wattr.background_pixel = black_pixel; + + suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth, + InputOutput, vis, CWEventMask | CWBackPixel, &wattr); + set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE); + set_window_focus(suspend_win); + XMapWindow(x_display, suspend_win); + emul_suspended = true; } -// Init fbdev DGA display -static bool init_fbdev_dga(char *in_fb_name) +// Resume emulation +void driver_dga::resume(void) { + // Close "suspend" window + XDestroyWindow(x_display, suspend_win); + XSync(x_display, false); + + // Reopen full screen display + XMapRaised(x_display, w); + wait_mapped(w); + XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0); + XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime); + XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); + disable_mouse_accel(); +#ifdef ENABLE_XF86_DGA + XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse); + XF86DGASetViewPort(x_display, screen, 0, 0); +#endif + XSync(x_display, false); + + // the_buffer already contains the data to restore. i.e. since a temporary + // frame buffer is used when VOSF is actually used, fb_save is therefore + // not necessary. +#ifdef ENABLE_VOSF + if (use_vosf) { + LOCK_VOSF; + PFLAG_SET_ALL; + UNLOCK_VOSF; + memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y); + } +#endif + + // Restore frame buffer + if (fb_save) { +#ifdef ENABLE_VOSF + // Don't copy fb_save to the temporary frame buffer in VOSF mode + if (!use_vosf) +#endif + memcpy(the_buffer, fb_save, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row); + free(fb_save); + fb_save = NULL; + } + + // Unlock frame buffer (and continue MacOS thread) + UNLOCK_FRAME_BUFFER; + emul_suspended = false; +} +#endif + + #ifdef ENABLE_FBDEV_DGA +/* + * fbdev DGA display driver + */ + +const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices"; +const char FBDEVICE_FILE_NAME[] = "/dev/fb"; + +class driver_fbdev : public driver_dga { +public: + driver_fbdev(const video_mode &mode); + ~driver_fbdev(); +}; + +// Open display +driver_fbdev::driver_fbdev(const video_mode &mode) +{ + int width = mode.x, height = mode.y; + + // Set absolute mouse mode + ADBSetRelMouseMode(false); + // Find the maximum depth available int ndepths, max_depth(0); int *depths = XListDepths(x_display, screen, &ndepths); if (depths == NULL) { printf("FATAL: Could not determine the maximal depth available\n"); - return false; + return; } else { while (ndepths-- > 0) { if (depths[ndepths] > max_depth) @@ -625,7 +970,7 @@ static bool init_fbdev_dga(char *in_fb_n char str[256]; sprintf(str, GetString(STR_NO_FBDEVICE_FILE_ERR), fbd_path ? fbd_path : FBDEVICES_FILE_NAME, strerror(errno)); ErrorAlert(str); - return false; + return; } int fb_depth; // supported depth @@ -645,7 +990,7 @@ static bool init_fbdev_dga(char *in_fb_n continue; if ((sscanf(line, "%19s %d %x", &fb_name, &fb_depth, &fb_offset) == 3) - && (strcmp(fb_name, in_fb_name) == 0) && (fb_depth == max_depth)) { + && (strcmp(fb_name, fb_name) == 0) && (fb_depth == max_depth)) { device_found = true; break; } @@ -657,18 +1002,11 @@ static bool init_fbdev_dga(char *in_fb_n // Frame buffer name not found ? Then, display warning if (!device_found) { char str[256]; - sprintf(str, GetString(STR_FBDEV_NAME_ERR), in_fb_name, max_depth); + sprintf(str, GetString(STR_FBDEV_NAME_ERR), fb_name, max_depth); ErrorAlert(str); - return false; + return; } - int width = DisplayWidth(x_display, screen); - int height = DisplayHeight(x_display, screen); - depth = fb_depth; // max_depth - - // Set relative mouse mode - ADBSetRelMouseMode(false); - // Create window XSetWindowAttributes wattr; wattr.event_mask = eventmask = dga_eventmask; @@ -676,51 +1014,41 @@ static bool init_fbdev_dga(char *in_fb_n wattr.override_redirect = True; wattr.colormap = cmap[0]; - the_win = XCreateWindow(x_display, rootwin, + w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth, InputOutput, vis, - CWEventMask | CWBackPixel | CWOverrideRedirect | (depth == 8 ? CWColormap : 0), + CWEventMask | CWBackPixel | CWOverrideRedirect | (fb_depth <= 8 ? CWColormap : 0), &wattr); // Set window name/class - set_window_name(the_win, STR_WINDOW_TITLE); + set_window_name(w, STR_WINDOW_TITLE); // Indicate that we want keyboard input - set_window_focus(the_win); + set_window_focus(w); // Show window - XMapRaised(x_display, the_win); - wait_mapped(the_win); + XMapRaised(x_display, w); + wait_mapped(w); // Grab mouse and keyboard - XGrabKeyboard(x_display, the_win, True, + XGrabKeyboard(x_display, w, True, GrabModeAsync, GrabModeAsync, CurrentTime); - XGrabPointer(x_display, the_win, True, + XGrabPointer(x_display, w, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, - GrabModeAsync, GrabModeAsync, the_win, None, CurrentTime); + GrabModeAsync, GrabModeAsync, w, None, CurrentTime); + disable_mouse_accel(); - // Set VideoMonitor - int bytes_per_row = width; - switch (depth) { - case 1: - bytes_per_row = ((width | 7) & ~7) >> 3; - break; - case 15: - case 16: - bytes_per_row *= 2; - break; - case 24: - case 32: - bytes_per_row *= 4; - break; - } + // Calculate bytes per row + int bytes_per_row = TrivialBytesPerRow(mode.x, mode.depth); - if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) { - if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) { + // Map frame buffer + the_buffer_size = height * bytes_per_row; + if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) { + if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) { char str[256]; sprintf(str, GetString(STR_FBDEV_MMAP_ERR), strerror(errno)); ErrorAlert(str); - return false; + return; } } @@ -728,7 +1056,7 @@ static bool init_fbdev_dga(char *in_fb_n #if REAL_ADDRESSING || DIRECT_ADDRESSING // Screen_blitter_init() returns TRUE if VOSF is mandatory // i.e. the framebuffer update function is not Blit_Copy_Raw - use_vosf = Screen_blitter_init(&visualInfo, true); + use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth); if (use_vosf) { // Allocate memory for frame buffer (SIZE is extended to page-boundary) @@ -742,23 +1070,70 @@ static bool init_fbdev_dga(char *in_fb_n #endif #endif - set_video_monitor(width, height, bytes_per_row, true); -#if REAL_ADDRESSING || DIRECT_ADDRESSING - VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer); -#else - VideoMonitor.mac_frame_base = MacFrameBaseMac; -#endif - return true; -#else - ErrorAlert("Basilisk II has been compiled with fbdev DGA support disabled."); - return false; -#endif + // Set VideoMonitor + VideoModes[0].bytes_per_row = bytes_per_row; + VideoModes[0].depth = DepthModeForPixelDepth(fb_depth); + VideoMonitor.mode = mode; + set_mac_frame_buffer(mode.depth, true); + + // Everything went well + init_ok = true; } -// Init XF86 DGA display -static bool init_xf86_dga(int width, int height) +// Close display +driver_fbdev::~driver_fbdev() { + if (!use_vosf) { + if (the_buffer != MAP_FAILED) { + // don't free() the screen buffer in driver_base dtor + munmap(the_buffer, the_buffer_size); + the_buffer = NULL; + } + } +#ifdef ENABLE_VOSF + else { + if (the_host_buffer != MAP_FAILED) { + // don't free() the screen buffer in driver_base dtor + munmap(the_host_buffer, the_buffer_size); + the_host_buffer = NULL; + } + if (the_buffer_copy != VM_MAP_FAILED) { + vm_release(the_buffer_copy, the_buffer_size); + the_buffer_copy = NULL; + } + if (the_buffer != VM_MAP_FAILED) { + vm_release(the_buffer, the_buffer_size); + the_buffer = NULL; + } + } +#endif +} +#endif + + #ifdef ENABLE_XF86_DGA +/* + * XFree86 DGA display driver + */ + +class driver_xf86dga : public driver_dga { +public: + driver_xf86dga(const video_mode &mode); + ~driver_xf86dga(); + + void update_palette(void); + void resume(void); + +private: + int current_dga_cmap; // Number (0 or 1) of currently installed DGA colormap +}; + +// Open display +driver_xf86dga::driver_xf86dga(const video_mode &mode) + : current_dga_cmap(0) +{ + int width = mode.x, height = mode.y; + // Set relative mouse mode ADBSetRelMouseMode(true); @@ -783,24 +1158,25 @@ static bool init_xf86_dga(int width, int wattr.event_mask = eventmask = dga_eventmask; wattr.override_redirect = True; - the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth, + w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth, InputOutput, vis, CWEventMask | CWOverrideRedirect, &wattr); // Set window name/class - set_window_name(the_win, STR_WINDOW_TITLE); + set_window_name(w, STR_WINDOW_TITLE); // Indicate that we want keyboard input - set_window_focus(the_win); + set_window_focus(w); // Show window - XMapRaised(x_display, the_win); - wait_mapped(the_win); + XMapRaised(x_display, w); + wait_mapped(w); // Establish direct screen connection - XMoveResizeWindow(x_display, the_win, 0, 0, width, height); + XMoveResizeWindow(x_display, w, 0, 0, width, height); XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0); XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); + disable_mouse_accel(); int v_width, v_bank, v_size; XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size); @@ -809,33 +1185,19 @@ static bool init_xf86_dga(int width, int XF86DGASetVidPage(x_display, screen, 0); // Set colormap - if (depth == 8) { - XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]); + if (!IsDirectMode(mode)) { + XSetWindowColormap(x_display, w, cmap[current_dga_cmap = 0]); XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]); } XSync(x_display, false); - // Set VideoMonitor - int bytes_per_row = (v_width + 7) & ~7; - switch (depth) { - case 1: - bytes_per_row /= 8; - break; - case 15: - case 16: - bytes_per_row *= 2; - break; - case 24: - case 32: - bytes_per_row *= 4; - break; - } - -#ifdef VIDEO_VOSF + // Init blitting routines + int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, mode.depth); +#if VIDEO_VOSF #if REAL_ADDRESSING || DIRECT_ADDRESSING // Screen_blitter_init() returns TRUE if VOSF is mandatory // i.e. the framebuffer update function is not Blit_Copy_Raw - use_vosf = Screen_blitter_init(&visualInfo, true); + use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth); if (use_vosf) { // Allocate memory for frame buffer (SIZE is extended to page-boundary) @@ -849,20 +1211,67 @@ static bool init_xf86_dga(int width, int #endif #endif - set_video_monitor(width, height, bytes_per_row, true); -#if REAL_ADDRESSING || DIRECT_ADDRESSING - VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer); -// MacFrameLayout = FLAYOUT_DIRECT; -#else - VideoMonitor.mac_frame_base = MacFrameBaseMac; + // Set VideoMonitor + const_cast(&mode)->bytes_per_row = bytes_per_row; + VideoMonitor.mode = mode; + set_mac_frame_buffer(mode.depth, true); + + // Everything went well + init_ok = true; +} + +// Close display +driver_xf86dga::~driver_xf86dga() +{ + XF86DGADirectVideo(x_display, screen, 0); + if (!use_vosf) { + // don't free() the screen buffer in driver_base dtor + the_buffer = NULL; + } +#ifdef ENABLE_VOSF + else { + // don't free() the screen buffer in driver_base dtor + the_host_buffer = NULL; + + if (the_buffer_copy != VM_MAP_FAILED) { + vm_release(the_buffer_copy, the_buffer_size); + the_buffer_copy = NULL; + } + if (the_buffer != VM_MAP_FAILED) { + vm_release(the_buffer, the_buffer_size); + the_buffer = NULL; + } + } #endif - return true; -#else - ErrorAlert("Basilisk II has been compiled with XF86 DGA support disabled."); - return false; +#ifdef ENABLE_XF86_VIDMODE + if (has_vidmode) + XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]); #endif } +// Palette has changed +void driver_xf86dga::update_palette(void) +{ + driver_dga::update_palette(); + current_dga_cmap ^= 1; + if (!IsDirectMode(VideoMonitor.mode) && cmap[current_dga_cmap]) + XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]); +} + +// Resume emulation +void driver_xf86dga::resume(void) +{ + driver_dga::resume(); + if (!IsDirectMode(VideoMonitor.mode)) + XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]); +} +#endif + + +/* + * Initialization + */ + // Init keycode translation table static void keycode_init(void) { @@ -928,85 +1337,142 @@ static void keycode_init(void) } } -bool VideoInitBuffer() +// Open display for specified mode +static bool video_open(const video_mode &mode) { -#ifdef ENABLE_VOSF - if (use_vosf) { - const uint32 page_size = getpagesize(); - const uint32 page_mask = page_size - 1; - - mainBuffer.memBase = (uintptr) the_buffer; - // Align the frame buffer on page boundary - mainBuffer.memStart = (uintptr)((((unsigned long) the_buffer) + page_mask) & ~page_mask); - mainBuffer.memLength = the_buffer_size; - mainBuffer.memEnd = mainBuffer.memStart + mainBuffer.memLength; - - mainBuffer.pageSize = page_size; - mainBuffer.pageCount = (mainBuffer.memLength + page_mask)/mainBuffer.pageSize; - mainBuffer.pageBits = log_base_2(mainBuffer.pageSize); + // Find best available X visual + if (!find_visual_for_depth(mode.depth)) { + ErrorAlert(STR_NO_XVISUAL_ERR); + return false; + } - if (mainBuffer.dirtyPages != 0) - free(mainBuffer.dirtyPages); + // Create color maps + if (color_class == PseudoColor || color_class == DirectColor) { + cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll); + cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll); + } else { + cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone); + cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone); + } - mainBuffer.dirtyPages = (char *) malloc(mainBuffer.pageCount + 2); + // Find pixel format of direct modes + if (color_class == DirectColor || color_class == TrueColor) { + rshift = gshift = bshift = 0; + rloss = gloss = bloss = 8; + uint32 mask; + for (mask=vis->red_mask; !(mask&1); mask>>=1) + ++rshift; + for (; mask&1; mask>>=1) + --rloss; + for (mask=vis->green_mask; !(mask&1); mask>>=1) + ++gshift; + for (; mask&1; mask>>=1) + --gloss; + for (mask=vis->blue_mask; !(mask&1); mask>>=1) + ++bshift; + for (; mask&1; mask>>=1) + --bloss; + } + + // Preset palette pixel values for CLUT or gamma table + if (color_class == DirectColor) { + int num = vis->map_entries; + for (int i=0; imap_entries : 256); + for (int i=0; i16/32 expand map + if (!IsDirectMode(mode) && xdepth > 8) + for (int i=0; i<256; i++) + ExpandMap[i] = map_rgb(i, i, i); +#endif - if ((mainBuffer.dirtyPages == 0) || (mainBuffer.pageInfo == 0)) - return false; - - mainBuffer.dirty = false; + // Create display driver object of requested type + switch (display_type) { + case DISPLAY_WINDOW: + drv = new driver_window(mode); + break; +#ifdef ENABLE_FBDEV_DGA + case DISPLAY_DGA: + drv = new driver_fbdev(mode); + break; +#endif +#ifdef ENABLE_XF86_DGA + case DISPLAY_DGA: + drv = new driver_xf86dga(mode); + break; +#endif + } + if (drv == NULL) + return false; + if (!drv->init_ok) { + delete drv; + drv = NULL; + return false; + } - PFLAG_CLEAR_ALL; - // Safety net to insure the loops in the update routines will terminate - // See a discussion in for further details - PFLAG_CLEAR(mainBuffer.pageCount); - PFLAG_SET(mainBuffer.pageCount+1); - - uint32 a = 0; - for (int i = 0; i < mainBuffer.pageCount; i++) { - int y1 = a / VideoMonitor.mode.bytes_per_row; - if (y1 >= VideoMonitor.mode.y) - y1 = VideoMonitor.mode.y - 1; - - int y2 = (a + mainBuffer.pageSize) / VideoMonitor.mode.bytes_per_row; - if (y2 >= VideoMonitor.mode.y) - y2 = VideoMonitor.mode.y - 1; - - mainBuffer.pageInfo[i].top = y1; - mainBuffer.pageInfo[i].bottom = y2; - - a += mainBuffer.pageSize; - if (a > mainBuffer.memLength) - a = mainBuffer.memLength; +#ifdef ENABLE_VOSF + if (use_vosf) { + // Initialize the VOSF system + if (!video_vosf_init()) { + ErrorAlert(STR_VOSF_INIT_ERR); + return false; } - - // We can now write-protect the frame buffer - if (vm_protect((char *)mainBuffer.memStart, mainBuffer.memLength, VM_PAGE_READ) != 0) - return false; } #endif + + // Initialize VideoRefresh function + VideoRefreshInit(); + + // Lock down frame buffer + XSync(x_display, false); + LOCK_FRAME_BUFFER; + + // Start redraw/input thread +#ifdef HAVE_PTHREADS + redraw_thread_cancel = false; + redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0); + if (!redraw_thread_active) { + printf("FATAL: cannot create redraw thread\n"); + return false; + } +#else + redraw_thread_active = true; +#endif + return true; } bool VideoInit(bool classic) { + classic_mode = classic; + #ifdef ENABLE_VOSF - // Open /dev/zero - zero_fd = open("/dev/zero", O_RDWR); - if (zero_fd < 0) { - char str[256]; - sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno)); - ErrorAlert(str); - return false; - } - // Zero the mainBuffer structure - mainBuffer.dirtyPages = 0; - mainBuffer.pageInfo = 0; + mainBuffer.dirtyPages = NULL; + mainBuffer.pageInfo = NULL; #endif // Check if X server runs on local machine @@ -1017,21 +1483,27 @@ bool VideoInit(bool classic) keycode_init(); // Read prefs + frame_skip = PrefsFindInt32("frameskip"); mouse_wheel_mode = PrefsFindInt32("mousewheelmode"); mouse_wheel_lines = PrefsFindInt32("mousewheellines"); // Find screen and root window screen = XDefaultScreen(x_display); rootwin = XRootWindow(x_display, screen); - - // Get screen depth - xdepth = DefaultDepth(x_display, screen); + + // Get sorted list of available depths + avail_depths = XListDepths(x_display, screen, &num_depths); + if (avail_depths == NULL) { + ErrorAlert(STR_UNSUPP_DEPTH_ERR); + return false; + } + sort(avail_depths, avail_depths + num_depths); #ifdef ENABLE_FBDEV_DGA // Frame buffer name char fb_name[20]; - // Could do fbdev dga ? + // Could do fbdev DGA? if ((fbdev_fd = open(FBDEVICE_FILE_NAME, O_RDWR)) != -1) has_dga = true; else @@ -1065,141 +1537,97 @@ bool VideoInit(bool classic) black_pixel = BlackPixel(x_display, screen); white_pixel = WhitePixel(x_display, screen); - // Get appropriate visual - int color_class; - switch (xdepth) { - case 1: - color_class = StaticGray; - break; - case 8: - color_class = PseudoColor; - break; - case 15: - case 16: - case 24: - case 32: - color_class = TrueColor; - break; - default: - ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR)); - return false; - } - if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) { - ErrorAlert(GetString(STR_NO_XVISUAL_ERR)); - return false; - } - if (visualInfo.depth != xdepth) { - ErrorAlert(GetString(STR_NO_XVISUAL_ERR)); - return false; - } - vis = visualInfo.visual; - - // Mac screen depth is always 1 bit in Classic mode, but follows X depth otherwise - classic_mode = classic; - if (classic) - depth = 1; - else - depth = xdepth; - - // Create color maps for 8 bit mode - if (depth == 8) { - cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll); - cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll); - XInstallColormap(x_display, cmap[0]); - XInstallColormap(x_display, cmap[1]); - } - // Get screen mode from preferences const char *mode_str; - if (classic) + if (classic_mode) mode_str = "win/512/342"; else mode_str = PrefsFindString("screen"); - // Determine type and mode - int width = 512, height = 384; + // Determine display type and default dimensions + int default_width = 512, default_height = 384; display_type = DISPLAY_WINDOW; if (mode_str) { - if (sscanf(mode_str, "win/%d/%d", &width, &height) == 2) + if (sscanf(mode_str, "win/%d/%d", &default_width, &default_height) == 2) { display_type = DISPLAY_WINDOW; #ifdef ENABLE_FBDEV_DGA - else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) { -#else - else if (has_dga && sscanf(mode_str, "dga/%d/%d", &width, &height) == 2) { + } else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) { + display_type = DISPLAY_DGA; + default_width = -1; default_height = -1; // use entire screen #endif +#ifdef ENABLE_XF86_DGA + } else if (has_dga && sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2) { display_type = DISPLAY_DGA; - if (width > DisplayWidth(x_display, screen)) - width = DisplayWidth(x_display, screen); - if (height > DisplayHeight(x_display, screen)) - height = DisplayHeight(x_display, screen); - } - if (width <= 0) - width = DisplayWidth(x_display, screen); - if (height <= 0) - height = DisplayHeight(x_display, screen); +#endif + } } - - // Initialize according to display type - switch (display_type) { - case DISPLAY_WINDOW: - if (!init_window(width, height)) - return false; + if (default_width <= 0) + default_width = DisplayWidth(x_display, screen); + else if (default_width > DisplayWidth(x_display, screen)) + default_width = DisplayWidth(x_display, screen); + if (default_height <= 0) + default_height = DisplayHeight(x_display, screen); + else if (default_height > DisplayHeight(x_display, screen)) + default_height = DisplayHeight(x_display, screen); + + // Mac screen depth follows X depth + video_depth default_depth = VDEPTH_1BIT; + switch (DefaultDepth(x_display, screen)) { + case 8: + default_depth = VDEPTH_8BIT; break; - case DISPLAY_DGA: -#ifdef ENABLE_FBDEV_DGA - if (!init_fbdev_dga(fb_name)) -#else - if (!init_xf86_dga(width, height)) -#endif - return false; + case 15: case 16: + default_depth = VDEPTH_16BIT; + break; + case 24: case 32: + default_depth = VDEPTH_32BIT; break; } - // Lock down frame buffer - LOCK_FRAME_BUFFER; - -#if !REAL_ADDRESSING && !DIRECT_ADDRESSING - // Set variables for UAE memory mapping - MacFrameBaseHost = the_buffer; - MacFrameSize = VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y; - - // No special frame buffer in Classic mode (frame buffer is in Mac RAM) - if (classic) - MacFrameLayout = FLAYOUT_NONE; -#endif - -#ifdef ENABLE_VOSF - if (use_vosf) { - // Initialize the mainBuffer structure - if (!VideoInitBuffer()) { - // TODO: STR_VOSF_INIT_ERR ? - ErrorAlert("Could not initialize Video on SEGV signals"); - return false; + // Construct list of supported modes + if (display_type == DISPLAY_WINDOW) { + if (classic) + add_mode(512, 342, 0x80, 64, VDEPTH_1BIT); + else { + for (unsigned d=VDEPTH_1BIT; d<=VDEPTH_32BIT; d++) { + if (find_visual_for_depth(video_depth(d))) + add_window_modes(video_depth(d)); + } } + } else + add_mode(default_width, default_height, 0x80, TrivialBytesPerRow(default_width, default_depth), default_depth); + if (VideoModes.empty()) { + ErrorAlert(STR_NO_XVISUAL_ERR); + return false; + } + video_init_depth_list(); - // Initialize the handler for SIGSEGV - if (!sigsegv_install_handler(screen_fault_handler)) { - // TODO: STR_VOSF_INIT_ERR ? - ErrorAlert("Could not initialize Video on SEGV signals"); - return false; - } +#if DEBUG + D(bug("Available video modes:\n")); + vector::const_iterator i = VideoModes.begin(), end = VideoModes.end(); + while (i != end) { + int bits = 1 << i->depth; + if (bits == 16) + bits = 15; + else if (bits == 32) + bits = 24; + D(bug(" %dx%d (ID %02x), %d colors\n", i->x, i->y, i->resolution_id, 1 << bits)); + ++i; } #endif - - // Initialize VideoRefresh function - VideoRefreshInit(); - - XSync(x_display, false); -#ifdef HAVE_PTHREADS - // Start redraw/input thread - redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0); - if (!redraw_thread_active) { - printf("FATAL: cannot create redraw thread\n"); - return false; + // Find requested default mode and open display + if (VideoModes.size() == 1) + return video_open(VideoModes[0]); + else { + // Find mode with specified dimensions + std::vector::const_iterator i, end = VideoModes.end(); + for (i = VideoModes.begin(); i != end; ++i) { + if (i->x == default_width && i->y == default_height && i->depth == default_depth) + return video_open(*i); + } + return video_open(VideoModes[0]); } -#endif - return true; } @@ -1207,99 +1635,73 @@ bool VideoInit(bool classic) * Deinitialization */ -void VideoExit(void) +// Close display +static void video_close(void) { -#ifdef HAVE_PTHREADS // Stop redraw thread +#ifdef HAVE_PTHREADS if (redraw_thread_active) { redraw_thread_cancel = true; #ifdef HAVE_PTHREAD_CANCEL pthread_cancel(redraw_thread); #endif pthread_join(redraw_thread, NULL); - redraw_thread_active = false; } #endif + redraw_thread_active = false; // Unlock frame buffer UNLOCK_FRAME_BUFFER; + XSync(x_display, false); - // Close window and server connection - if (x_display != NULL) { - XSync(x_display, false); - -#ifdef ENABLE_XF86_DGA - if (display_type == DISPLAY_DGA) { - XF86DGADirectVideo(x_display, screen, 0); - XUngrabPointer(x_display, CurrentTime); - XUngrabKeyboard(x_display, CurrentTime); - } +#ifdef ENABLE_VOSF + if (use_vosf) { + // Deinitialize VOSF + video_vosf_exit(); + } #endif -#ifdef ENABLE_XF86_VIDMODE - if (has_vidmode && display_type == DISPLAY_DGA) - XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]); -#endif + // Close display + delete drv; + drv = NULL; -#ifdef ENABLE_FBDEV_DGA - if (display_type == DISPLAY_DGA) { - XUngrabPointer(x_display, CurrentTime); - XUngrabKeyboard(x_display, CurrentTime); - close(fbdev_fd); - } -#endif + // Free colormaps + if (cmap[0]) { + XFreeColormap(x_display, cmap[0]); + cmap[0] = 0; + } + if (cmap[1]) { + XFreeColormap(x_display, cmap[1]); + cmap[1] = 0; + } +} - XFlush(x_display); - XSync(x_display, false); - if (depth == 8) { - XFreeColormap(x_display, cmap[0]); - XFreeColormap(x_display, cmap[1]); - } - - if (!use_vosf) { - if (the_buffer) { - free(the_buffer); - the_buffer = NULL; - } +void VideoExit(void) +{ + // Close display + video_close(); - if (!have_shm && the_buffer_copy) { - free(the_buffer_copy); - the_buffer_copy = NULL; - } - } -#ifdef ENABLE_VOSF - else { - if (the_buffer != (uint8 *)VM_MAP_FAILED) { - vm_release(the_buffer, the_buffer_size); - the_buffer = 0; - } - - if (the_buffer_copy != (uint8 *)VM_MAP_FAILED) { - vm_release(the_buffer_copy, the_buffer_size); - the_buffer_copy = 0; - } - } -#endif +#ifdef ENABLE_XF86_VIDMODE + // Free video mode list + if (x_video_modes) { + XFree(x_video_modes); + x_video_modes = NULL; } - -#ifdef ENABLE_VOSF - if (use_vosf) { - // Clear mainBuffer data - if (mainBuffer.pageInfo) { - free(mainBuffer.pageInfo); - mainBuffer.pageInfo = 0; - } +#endif - if (mainBuffer.dirtyPages) { - free(mainBuffer.dirtyPages); - mainBuffer.dirtyPages = 0; - } +#ifdef ENABLE_FBDEV_DGA + // Close framebuffer device + if (fbdev_fd >= 0) { + close(fbdev_fd); + fbdev_fd = -1; } - - // Close /dev/zero - if (zero_fd > 0) - close(zero_fd); #endif + + // Free depth list + if (avail_depths) { + XFree(avail_depths); + avail_depths = NULL; + } } @@ -1310,8 +1712,7 @@ void VideoExit(void) void VideoQuitFullScreen(void) { D(bug("VideoQuitFullScreen()\n")); - if (display_type == DISPLAY_DGA) - quit_full_screen = true; + quit_full_screen = true; } @@ -1336,18 +1737,42 @@ void VideoInterrupt(void) * Set palette */ -void video_set_palette(uint8 *pal) +void video_set_palette(uint8 *pal, int num_in) { LOCK_PALETTE; // Convert colors to XColor array - for (int i=0; i<256; i++) { - palette[i].pixel = i; - palette[i].red = pal[i*3] * 0x0101; - palette[i].green = pal[i*3+1] * 0x0101; - palette[i].blue = pal[i*3+2] * 0x0101; - palette[i].flags = DoRed | DoGreen | DoBlue; + int num_out = 256; + bool stretch = false; + if (IsDirectMode(VideoMonitor.mode)) { + // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries + num_out = vis->map_entries; + stretch = true; + } + XColor *p = palette; + for (int i=0; ired = pal[c*3 + 0] * 0x0101; + p->green = pal[c*3 + 1] * 0x0101; + p->blue = pal[c*3 + 2] * 0x0101; + p++; + } + +#ifdef ENABLE_VOSF + // Recalculate pixel color expansion map + if (!IsDirectMode(VideoMonitor.mode) && xdepth > 8) { + for (int i=0; i<256; i++) { + int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier) + ExpandMap[i] = map_rgb(pal[c*3+0], pal[c*3+1], pal[c*3+2]); + } + + // We have to redraw everything because the interpretation of pixel values changed + LOCK_VOSF; + PFLAG_SET_ALL; + UNLOCK_VOSF; + memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y); } +#endif // Tell redraw thread to change palette palette_changed = true; @@ -1357,106 +1782,28 @@ void video_set_palette(uint8 *pal) /* - * Suspend/resume emulator + * Switch video mode */ -#if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA) -static void suspend_emul(void) +void video_switch_to_mode(const video_mode &mode) { - if (display_type == DISPLAY_DGA) { - // Release ctrl key - ADBKeyUp(0x36); - ctrl_down = false; - - // Lock frame buffer (this will stop the MacOS thread) - LOCK_FRAME_BUFFER; - - // Save frame buffer - fb_save = malloc(VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row); - if (fb_save) - memcpy(fb_save, the_buffer, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row); - - // Close full screen display -#ifdef ENABLE_XF86_DGA - XF86DGADirectVideo(x_display, screen, 0); -#endif - XUngrabPointer(x_display, CurrentTime); - XUngrabKeyboard(x_display, CurrentTime); - XUnmapWindow(x_display, the_win); - wait_unmapped(the_win); - - // Open "suspend" window - XSetWindowAttributes wattr; - wattr.event_mask = KeyPressMask; - wattr.background_pixel = black_pixel; - - suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth, - InputOutput, vis, CWEventMask | CWBackPixel, &wattr); - set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE); - set_window_focus(suspend_win); - XMapWindow(x_display, suspend_win); - emul_suspended = true; - } -} + // Close and reopen display + video_close(); + video_open(mode); -static void resume_emul(void) -{ - // Close "suspend" window - XDestroyWindow(x_display, suspend_win); - XSync(x_display, false); - - // Reopen full screen display - XMapRaised(x_display, the_win); - wait_mapped(the_win); - XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0); - XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime); - XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime); -#ifdef ENABLE_XF86_DGA - XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse); - XF86DGASetViewPort(x_display, screen, 0, 0); -#endif - XSync(x_display, false); - - // the_buffer already contains the data to restore. i.e. since a temporary - // frame buffer is used when VOSF is actually used, fb_save is therefore - // not necessary. -#ifdef ENABLE_VOSF - if (use_vosf) { - LOCK_VOSF; - PFLAG_SET_ALL; - UNLOCK_VOSF; - memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y); - } -#endif - - // Restore frame buffer - if (fb_save) { -#ifdef ENABLE_VOSF - // Don't copy fb_save to the temporary frame buffer in VOSF mode - if (!use_vosf) -#endif - memcpy(the_buffer, fb_save, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row); - free(fb_save); - fb_save = NULL; + if (drv == NULL) { + ErrorAlert(STR_OPEN_WINDOW_ERR); + QuitEmulator(); } - -#ifdef ENABLE_XF86_DGA - if (depth == 8) - XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]); -#endif - - // Unlock frame buffer (and continue MacOS thread) - UNLOCK_FRAME_BUFFER; - emul_suspended = false; } -#endif /* - * Translate key event to Mac keycode + * Translate key event to Mac keycode, returns -1 if no keycode was found + * and -2 if the key was recognized as a hotkey */ -static int kc_decode(KeySym ks) +static int kc_decode(KeySym ks, bool key_down) { switch (ks) { case XK_A: case XK_a: return 0x00; @@ -1509,11 +1856,7 @@ static int kc_decode(KeySym ks) case XK_period: case XK_greater: return 0x2f; case XK_slash: case XK_question: return 0x2c; -#if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA) - case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30; -#else - case XK_Tab: return 0x30; -#endif + case XK_Tab: if (ctrl_down) {if (key_down) drv->suspend(); return -2;} else return 0x30; case XK_Return: return 0x24; case XK_space: return 0x31; case XK_BackSpace: return 0x33; @@ -1547,13 +1890,13 @@ static int kc_decode(KeySym ks) case XK_Left: return 0x3b; case XK_Right: return 0x3c; - case XK_Escape: if (ctrl_down) {quit_full_screen = true; emerg_quit = true; return -1;} else return 0x35; + case XK_Escape: if (ctrl_down) {if (key_down) { quit_full_screen = true; emerg_quit = true; } return -2;} else return 0x35; - case XK_F1: if (ctrl_down) {SysMountFirstFloppy(); return -1;} else return 0x7a; + case XK_F1: if (ctrl_down) {if (key_down) SysMountFirstFloppy(); return -2;} else return 0x7a; case XK_F2: return 0x78; case XK_F3: return 0x63; case XK_F4: return 0x76; - case XK_F5: return 0x60; + case XK_F5: if (ctrl_down) {if (key_down) drv->toggle_mouse_grab(); return -2;} else return 0x60; case XK_F6: return 0x61; case XK_F7: return 0x62; case XK_F8: return 0x64; @@ -1601,16 +1944,17 @@ static int kc_decode(KeySym ks) return -1; } -static int event2keycode(XKeyEvent &ev) +static int event2keycode(XKeyEvent &ev, bool key_down) { KeySym ks; - int as; int i = 0; do { ks = XLookupKeysym(&ev, i++); - as = kc_decode(ks); - if (as != -1) + int as = kc_decode(ks, key_down); + if (as >= 0) + return as; + if (as == -2) return as; } while (ks != NoSymbol); @@ -1629,6 +1973,7 @@ static void handle_events(void) XNextEvent(x_display, &event); switch (event.type) { + // Mouse button case ButtonPress: { unsigned int button = event.xbutton.button; @@ -1657,20 +2002,25 @@ static void handle_events(void) } // Mouse moved - case EnterNotify: case MotionNotify: - ADBMouseMoved(event.xmotion.x, event.xmotion.y); + drv->mouse_moved(event.xmotion.x, event.xmotion.y); + break; + + // Mouse entered window + case EnterNotify: + if (event.xcrossing.mode != NotifyGrab && event.xcrossing.mode != NotifyUngrab) + drv->mouse_moved(event.xmotion.x, event.xmotion.y); break; // Keyboard case KeyPress: { - int code; + int code = -1; if (use_keycodes) { - event2keycode(event.xkey); // This is called to process the hotkeys - code = keycode_table[event.xkey.keycode & 0xff]; + if (event2keycode(event.xkey, true) != -2) // This is called to process the hotkeys + code = keycode_table[event.xkey.keycode & 0xff]; } else - code = event2keycode(event.xkey); - if (code != -1) { + code = event2keycode(event.xkey, true); + if (code >= 0) { if (!emul_suspended) { if (code == 0x39) { // Caps Lock pressed if (caps_on) { @@ -1685,22 +2035,20 @@ static void handle_events(void) if (code == 0x36) ctrl_down = true; } else { -#if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA) if (code == 0x31) - resume_emul(); // Space wakes us up -#endif + drv->resume(); // Space wakes us up } } break; } case KeyRelease: { - int code; + int code = -1; if (use_keycodes) { - event2keycode(event.xkey); // This is called to process the hotkeys - code = keycode_table[event.xkey.keycode & 0xff]; + if (event2keycode(event.xkey, false) != -2) // This is called to process the hotkeys + code = keycode_table[event.xkey.keycode & 0xff]; } else - code = event2keycode(event.xkey); - if (code != -1 && code != 0x39) { // Don't propagate Caps Lock releases + code = event2keycode(event.xkey, false); + if (code >= 0 && code != 0x39) { // Don't propagate Caps Lock releases ADBKeyUp(code); if (code == 0x36) ctrl_down = false; @@ -1748,7 +2096,7 @@ static void handle_events(void) */ // Dynamic display update (variable frame rate for each box) -static void update_display_dynamic(int ticker) +static void update_display_dynamic(int ticker, driver_window *drv) { int y1, y2, y2s, y2a, i, x1, xm, xmo, ymo, yo, yi, yil, xi; int xil = 0; @@ -1810,16 +2158,16 @@ static void update_display_dynamic(int t i = (yi * bytes_per_row) + xi; for (y2=0; y2 < yil; y2++, i += bytes_per_row) memcpy(&the_buffer_copy[i], &the_buffer[i], xil); - if (depth == 1) { - if (have_shm) - XShmPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0); + if (VideoMonitor.mode.depth == VDEPTH_1BIT) { + if (drv->have_shm) + XShmPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0); else - XPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil); + XPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil); } else { - if (have_shm) - XShmPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0); + if (drv->have_shm) + XShmPutImage(x_display, drv->w, drv->gc, drv->img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0); else - XPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil); + XPutImage(x_display, drv->w, drv->gc, drv->img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil); } xil = 0; } @@ -1838,7 +2186,7 @@ static void update_display_dynamic(int t } // Static display update (fixed frame rate, but incremental) -static void update_display_static(void) +static void update_display_static(driver_window *drv) { // Incremental update code int wide = 0, high = 0, x1, x2, y1, y2, i, j; @@ -1865,7 +2213,7 @@ static void update_display_static(void) // Check for first column from left and first column from right that have changed if (high) { - if (depth == 1) { + if (VideoMonitor.mode.depth == VDEPTH_1BIT) { x1 = VideoMonitor.mode.x - 1; for (j=y1; j<=y2; j++) { p = &the_buffer[j * bytes_per_row]; @@ -1944,10 +2292,10 @@ static void update_display_static(void) // Refresh display if (high && wide) { - if (have_shm) - XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0); + if (drv->have_shm) + XShmPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high, 0); else - XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high); + XPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high); } } @@ -1964,39 +2312,33 @@ static void update_display_static(void) static inline void possibly_quit_dga_mode() { -#if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA) - // Quit DGA mode if requested + // Quit DGA mode if requested (something terrible has happened and we + // want to give control back to the user) if (quit_full_screen) { quit_full_screen = false; -#ifdef ENABLE_XF86_DGA - XF86DGADirectVideo(x_display, screen, 0); -#endif - XUngrabPointer(x_display, CurrentTime); - XUngrabKeyboard(x_display, CurrentTime); - XUnmapWindow(x_display, the_win); - XSync(x_display, false); + delete drv; + drv = NULL; } -#endif } -static inline void handle_palette_changes(int depth, int display_type) +static inline void possibly_ungrab_mouse() +{ + // Ungrab mouse if requested (something terrible has happened and we + // want to give control back to the user) + if (quit_full_screen) { + quit_full_screen = false; + if (drv) + drv->ungrab_mouse(); + } +} + +static inline void handle_palette_changes(void) { LOCK_PALETTE; if (palette_changed) { palette_changed = false; - if (depth == 8) { - XStoreColors(x_display, cmap[0], palette, 256); - XStoreColors(x_display, cmap[1], palette, 256); - XSync(x_display, false); - -#ifdef ENABLE_XF86_DGA - if (display_type == DISPLAY_DGA) { - current_dga_cmap ^= 1; - XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]); - } -#endif - } + drv->update_palette(); } UNLOCK_PALETTE; @@ -2006,12 +2348,6 @@ static void video_refresh_dga(void) { // Quit DGA mode if requested possibly_quit_dga_mode(); - - // Handle X events - handle_events(); - - // Handle palette changes - handle_palette_changes(depth, DISPLAY_DGA); } #ifdef ENABLE_VOSF @@ -2021,12 +2357,6 @@ static void video_refresh_dga_vosf(void) // Quit DGA mode if requested possibly_quit_dga_mode(); - // Handle X events - handle_events(); - - // Handle palette changes - handle_palette_changes(depth, DISPLAY_DGA); - // Update display (VOSF variant) static int tick_counter = 0; if (++tick_counter >= frame_skip) { @@ -2042,14 +2372,8 @@ static void video_refresh_dga_vosf(void) static void video_refresh_window_vosf(void) { - // Quit DGA mode if requested - possibly_quit_dga_mode(); - - // Handle X events - handle_events(); - - // Handle palette changes - handle_palette_changes(depth, DISPLAY_WINDOW); + // Ungrab mouse if requested + possibly_ungrab_mouse(); // Update display (VOSF variant) static int tick_counter = 0; @@ -2057,7 +2381,7 @@ static void video_refresh_window_vosf(vo tick_counter = 0; if (mainBuffer.dirty) { LOCK_VOSF; - update_display_window_vosf(); + update_display_window_vosf(static_cast(drv)); UNLOCK_VOSF; XSync(x_display, false); // Let the server catch up } @@ -2067,32 +2391,26 @@ static void video_refresh_window_vosf(vo static void video_refresh_window_static(void) { - // Handle X events - handle_events(); - - // Handle_palette changes - handle_palette_changes(depth, DISPLAY_WINDOW); - + // Ungrab mouse if requested + possibly_ungrab_mouse(); + // Update display (static variant) static int tick_counter = 0; if (++tick_counter >= frame_skip) { tick_counter = 0; - update_display_static(); + update_display_static(static_cast(drv)); } } static void video_refresh_window_dynamic(void) { - // Handle X events - handle_events(); - - // Handle_palette changes - handle_palette_changes(depth, DISPLAY_WINDOW); - + // Ungrab mouse if requested + possibly_ungrab_mouse(); + // Update display (dynamic variant) static int tick_counter = 0; tick_counter++; - update_display_dynamic(tick_counter); + update_display_dynamic(tick_counter, static_cast(drv)); } @@ -2100,7 +2418,7 @@ static void video_refresh_window_dynamic * Thread for screen refresh, input handling etc. */ -void VideoRefreshInit(void) +static void VideoRefreshInit(void) { // TODO: set up specialised 8bpp VideoRefresh handlers ? if (display_type == DISPLAY_DGA) { @@ -2124,30 +2442,69 @@ void VideoRefreshInit(void) } } +// This function is called on non-threaded platforms from a timer interrupt void VideoRefresh(void) { - // TODO: make main_unix/VideoRefresh call directly video_refresh() ? + // We need to check redraw_thread_active to inhibit refreshed during + // mode changes on non-threaded platforms + if (!redraw_thread_active) + return; + + // Handle X events + handle_events(); + + // Handle palette changes + handle_palette_changes(); + + // Update display video_refresh(); } +const int VIDEO_REFRESH_HZ = 60; +const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ; + #ifdef HAVE_PTHREADS static void *redraw_func(void *arg) { + int fd = ConnectionNumber(x_display); + uint64 start = GetTicks_usec(); int64 ticks = 0; - uint64 next = GetTicks_usec(); + uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY; + while (!redraw_thread_cancel) { - video_refresh(); - next += 16667; + int64 delay = next - GetTicks_usec(); - if (delay > 0) - Delay_usec(delay); - else if (delay < -16667) + if (delay < -VIDEO_REFRESH_DELAY) { + + // We are lagging far behind, so we reset the delay mechanism next = GetTicks_usec(); - ticks++; + + } else if (delay <= 0) { + + // Delay expired, refresh display + handle_events(); + handle_palette_changes(); + video_refresh(); + next += VIDEO_REFRESH_DELAY; + ticks++; + + } else { + + // No display refresh pending, check for X events + fd_set readfds; + FD_ZERO(&readfds); + FD_SET(fd, &readfds); + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = delay; + if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0) + handle_events(); + } } + uint64 end = GetTicks_usec(); - // printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, ticks * 1000000 / (end - start)); + D(bug("%Ld refreshes in %Ld usec = %f refreshes/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start))); return NULL; } #endif