ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/MacOSX/video_macosx.mm
Revision: 1.1
Committed: 2002-03-16T04:00:35Z (22 years, 2 months ago) by nigel
Branch: MAIN
CVS Tags: nigel-build-10
Log Message:
Initial revision of Mac OS X port code. Uses Objective-C++. Needs Mac OS 10.1

File Contents

# User Rev Content
1 nigel 1.1 /*
2     * $Id$
3     *
4     * video_macosx.mm - Interface between Basilisk II and Cocoa windowing.
5     * Based on video_amiga.cpp and video_x.cpp
6     *
7     * Basilisk II (C) 1997-2002 Christian Bauer
8     *
9     * This program is free software; you can redistribute it and/or modify
10     * it under the terms of the GNU General Public License as published by
11     * the Free Software Foundation; either version 2 of the License, or
12     * (at your option) any later version.
13     *
14     * This program is distributed in the hope that it will be useful,
15     * but WITHOUT ANY WARRANTY; without even the implied warranty of
16     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17     * GNU General Public License for more details.
18     *
19     * You should have received a copy of the GNU General Public License
20     * along with this program; if not, write to the Free Software
21     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22     */
23    
24    
25     #include "sysdeps.h"
26    
27     #ifdef HAVE_PTHREADS
28     # include <pthread.h>
29     #endif
30    
31     #include <adb.h>
32     #include <cpu_emulation.h>
33     #include <main.h>
34     #include "macos_util_macosx.h"
35     #include <prefs.h>
36     #include <user_strings.h>
37     #include "video_macosx.h"
38    
39     #define DEBUG 0
40     #include "debug.h"
41    
42    
43    
44     // Global variables
45     uint8 display_type = DISPLAY_WINDOW, // These are used by PrefsEditor
46     frame_skip;
47     uint16 init_width = MIN_WIDTH, // as well as this code
48     init_height = MIN_HEIGHT,
49     init_depth = 32,
50     screen_height = MIN_HEIGHT; // Used by processMouseMove
51    
52     EmulatorView *output = nil; // Set by [EmulatorView init]
53     NSWindow *the_win = nil; // Set by [Emulator awakeFromNib]
54     static void *the_buffer = NULL;
55    
56    
57     #import <Foundation/NSString.h> // Needed for NSLog(@"")
58    
59     #ifdef CGIMAGEREF
60     static CGImageRef imageRef = nil;
61     #endif
62    
63     #ifdef NSBITMAP
64     #import <AppKit/NSBitmapImageRep.h>
65    
66     static NSBitmapImageRep *bitmap = nil;
67     #endif
68    
69     // These record changes we made in setting full screen mode
70     CGDirectDisplayID theDisplay = NULL;
71     CFDictionaryRef originalMode = NULL,
72     newMode = NULL;
73    
74    
75    
76     // Prototypes
77    
78     static void add_mode (const uint16 width, const uint16 height,
79     const uint32 resolution_id,
80     const uint32 bytes_per_row,
81     const video_depth depth);
82     static void add_standard_modes (const video_depth depth);
83    
84     static bool video_open (const video_mode &mode);
85     static void video_close (void);
86    
87    
88    
89     /*
90     * Utility functions
91     */
92    
93     uint8 bits_from_depth(const video_depth depth)
94     {
95     int bits = 1 << depth;
96     // if (bits == 16)
97     // bits = 15;
98     // else if (bits == 32)
99     // bits = 24;
100     return bits;
101     }
102    
103     char *
104     colours_from_depth(const video_depth depth)
105     {
106     switch ( depth )
107     {
108     case VDEPTH_1BIT : return "Monochrome";
109     case VDEPTH_2BIT : return "4 colours";
110     case VDEPTH_4BIT : return "16 colours";
111     case VDEPTH_8BIT : return "256 colours";
112     case VDEPTH_16BIT: return "Thousands of colours";
113     case VDEPTH_32BIT: return "Millions of colours";
114     }
115    
116     return "illegal colour depth";
117     }
118    
119     char *
120     colours_from_depth(const uint16 depth)
121     {
122     return colours_from_depth(DepthModeForPixelDepth(depth) );
123     }
124    
125     bool
126     parse_screen_prefs(const char *mode_str)
127     {
128     if (sscanf(mode_str, "win/%hd/%hd/%hd",
129     &init_width, &init_height, &init_depth) == 3)
130     display_type = DISPLAY_WINDOW;
131     else if (sscanf(mode_str, "win/%hd/%hd", &init_width, &init_height) == 2)
132     display_type = DISPLAY_WINDOW;
133     else if (strcmp(mode_str, "full") == 0)
134     display_type = DISPLAY_SCREEN;
135     else if (sscanf(mode_str, "full/%hd/%hd/%hd",
136     &init_width, &init_height, &init_depth) == 3)
137     display_type = DISPLAY_SCREEN;
138     else if (sscanf(mode_str, "full/%hd/%hd", &init_width, &init_height) == 2)
139     display_type = DISPLAY_SCREEN;
140     else if (sscanf(mode_str, "opengl/%hd/%hd/%hd",
141     &init_width, &init_height, &init_depth) == 3)
142     display_type = DISPLAY_OPENGL;
143     else if (sscanf(mode_str, "opengl/%hd/%hd", &init_width, &init_height) == 2)
144     display_type = DISPLAY_OPENGL;
145     else return false;
146    
147     return true;
148     }
149    
150    
151     // Add mode to list of supported modes
152     static void
153     add_mode(const uint16 width, const uint16 height,
154     const uint32 resolution_id, const uint32 bytes_per_row,
155     const video_depth depth)
156     {
157     video_mode mode;
158     mode.x = width;
159     mode.y = height;
160     mode.resolution_id = resolution_id;
161     mode.bytes_per_row = bytes_per_row;
162     mode.depth = depth;
163    
164     D(bug("Added video mode: w=%ld h=%ld d=%ld(%d bits)\n",
165     width, height, depth, bits_from_depth(depth) ));
166    
167     VideoModes.push_back(mode);
168     }
169    
170     // Add standard list of windowed modes for given color depth
171     static void add_standard_modes(const video_depth depth)
172     {
173     D(bug("add_standard_modes: depth=%ld(%d bits)\n",
174     depth, bits_from_depth(depth) ));
175    
176     add_mode(512, 384, 0x80, TrivialBytesPerRow(512, depth), depth);
177     add_mode(640, 480, 0x81, TrivialBytesPerRow(640, depth), depth);
178     add_mode(800, 600, 0x82, TrivialBytesPerRow(800, depth), depth);
179     add_mode(832, 624, 0x83, TrivialBytesPerRow(832, depth), depth);
180     add_mode(1024, 768, 0x84, TrivialBytesPerRow(1024, depth), depth);
181     add_mode(1152, 768, 0x85, TrivialBytesPerRow(1152, depth), depth);
182     add_mode(1152, 870, 0x86, TrivialBytesPerRow(1152, depth), depth);
183     add_mode(1280, 1024, 0x87, TrivialBytesPerRow(1280, depth), depth);
184     add_mode(1600, 1200, 0x88, TrivialBytesPerRow(1600, depth), depth);
185     }
186    
187     // Helper function to get a 32bit int from a dictionary
188     static int32 getCFint32 (CFDictionaryRef dict, CFStringRef key)
189     {
190     int32 val = 0;
191     CFNumberRef ref = CFDictionaryGetValue(dict, key);
192    
193     if ( ref && CFNumberGetValue(ref, kCFNumberSInt32Type, &val) )
194     if ( ! val )
195     NSLog(@"getCFint32() - Logic error - Got a value of 0");
196    
197     return val;
198     }
199    
200     static bool add_CGDirectDisplay_modes()
201     {
202     #define kMaxDisplays 8
203     CGDirectDisplayID displays[kMaxDisplays];
204     CGDisplayErr err;
205     CGDisplayCount n;
206     int32 oldRes = 0,
207     res_id = 0x80;
208    
209    
210     err = CGGetActiveDisplayList(kMaxDisplays, displays, &n);
211     if ( err != CGDisplayNoErr )
212     return false;
213    
214     for ( CGDisplayCount dc = 0; dc < n; ++dc )
215     {
216     CGDirectDisplayID d = displays[dc];
217     CFArrayRef m = CGDisplayAvailableModes(d);
218    
219     if ( m == NULL ) // Store the current display mode
220     add_mode(CGDisplayPixelsWide(d),
221     CGDisplayPixelsHigh(d),
222     res_id++, CGDisplayBytesPerRow(d),
223     DepthModeForPixelDepth(CGDisplayBitsPerPixel(d)));
224     else
225     {
226     CFIndex nModes = CFArrayGetCount(m);
227    
228     for ( CFIndex mc = 0; mc < nModes; ++mc )
229     {
230     CFDictionaryRef modeSpec = CFArrayGetValueAtIndex(m, mc);
231    
232     int32 bpp = getCFint32(modeSpec, kCGDisplayBitsPerPixel);
233     int32 height = getCFint32(modeSpec, kCGDisplayHeight);
234     int32 mode = getCFint32(modeSpec, kCGDisplayMode);
235     int32 width = getCFint32(modeSpec, kCGDisplayWidth);
236     video_depth depth = DepthModeForPixelDepth(bpp);
237    
238     if ( ! bpp || ! height || ! width )
239     {
240     NSLog(@"Could not get details of mode %d, display %d",
241     mc, dc);
242     return false;
243     }
244     #if DEBUG
245     else
246     NSLog(@"Display %ld, spec = %@", d, modeSpec);
247     #endif
248    
249     add_mode(width, height, res_id,
250     TrivialBytesPerRow(width, depth), depth);
251    
252     if ( ! oldRes )
253     oldRes = width * height;
254     else
255     if ( oldRes != width * height )
256     {
257     oldRes = width * height;
258     ++res_id;
259     }
260     }
261     }
262     }
263    
264     return true;
265     }
266    
267     // Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac)
268     static void set_mac_frame_buffer(video_depth depth)
269     {
270     #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
271     switch ( depth )
272     {
273     // case VDEPTH_15BIT:
274     case VDEPTH_16BIT: MacFrameLayout = FLAYOUT_HOST_555; break;
275     // case VDEPTH_24BIT:
276     case VDEPTH_32BIT: MacFrameLayout = FLAYOUT_HOST_888; break;
277     default : MacFrameLayout = FLAYOUT_DIRECT;
278     }
279     VideoMonitor.mac_frame_base = MacFrameBaseMac;
280    
281     // Set variables used by UAE memory banking
282     MacFrameBaseHost = the_buffer;
283     MacFrameSize = VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y;
284     InitFrameBufferMapping();
285     #else
286     VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
287     #endif
288     D(bug("VideoMonitor.mac_frame_base = %08x\n", VideoMonitor.mac_frame_base));
289     }
290    
291     void resizeWinBy(const short deltaX, const short deltaY)
292     {
293     NSRect rect = [the_win frame];
294    
295     D(bug("resizeWinBy(%d,%d) - ", deltaX, deltaY));
296     D(bug("old x=%g, y=%g", rect.size.width, rect.size.height));
297    
298     rect.size.width += deltaX;
299     rect.size.height += deltaY;
300    
301     D(bug(", new x=%g, y=%g\n", rect.size.width, rect.size.height));
302    
303     [the_win setFrame: rect display: YES];
304     rect = [the_win frame];
305     }
306    
307     void resizeWinTo(const uint16 newWidth, const uint16 newHeight)
308     {
309     int deltaX = newWidth - [output width],
310     deltaY = newHeight - [output height];
311    
312     D(bug("resizeWinTo(%d,%d)\n", newWidth, newHeight));
313    
314     if ( deltaX || deltaY )
315     resizeWinBy(deltaX, deltaY);
316     }
317    
318     // Open window
319     static bool init_window(const video_mode &mode)
320     {
321     #ifdef CGIMAGEREF
322     CGColorSpaceRef colourSpace;
323     CGDataProviderRef provider;
324     #endif
325     short bitsPer, samplesPer; // How big is each Pixel?
326     int the_buffer_size;
327    
328     D(bug("init_window: depth=%ld(%d bits)\n",
329     mode.depth, bits_from_depth(mode.depth) ));
330    
331    
332     // Set absolute mouse mode
333     ADBSetRelMouseMode(false);
334    
335    
336     // Open window
337     if (the_win == NULL)
338     {
339     ErrorAlert(STR_OPEN_WINDOW_ERR);
340     return false;
341     }
342     resizeWinTo(mode.x, mode.y);
343    
344    
345     // Create frame buffer ("height + 2" for safety)
346     the_buffer_size = mode.bytes_per_row * (mode.y + 2);
347     the_buffer = calloc(the_buffer_size, 1);
348     if (the_buffer == NULL)
349     {
350     NSLog(@"calloc(%d) failed", the_buffer_size);
351     ErrorAlert(STR_NO_MEM_ERR);
352     return false;
353     }
354     D(bug("the_buffer = %p\n", the_buffer));
355    
356    
357     if ( mode.depth == VDEPTH_1BIT )
358     bitsPer = 1;
359     else
360     bitsPer = 8;
361    
362     if ( mode.depth == VDEPTH_32BIT )
363     samplesPer = 3;
364     else
365     samplesPer = 1;
366    
367     #ifdef CGIMAGEREF
368     switch ( mode.depth )
369     {
370     //case VDEPTH_1BIT: colourSpace = CGColorSpaceCreateDeviceMono(); break
371     case VDEPTH_8BIT: colourSpace = CGColorSpaceCreateDeviceGray(); break;
372     case VDEPTH_32BIT: colourSpace = CGColorSpaceCreateDeviceRGB(); break;
373     default: colourSpace = NULL;
374     }
375    
376     if ( ! colourSpace )
377     {
378     ErrorAlert("No valid colour space");
379     return false;
380     }
381    
382     provider = CGDataProviderCreateWithData(NULL, the_buffer,
383     the_buffer_size, NULL);
384     if ( ! provider )
385     {
386     ErrorAlert("Could not create CGDataProvider from buffer data");
387     return false;
388     }
389     imageRef = CGImageCreate(mode.x,
390     mode.y,
391     bitsPer,
392     bits_from_depth(mode.depth),
393     mode.bytes_per_row,
394     colourSpace,
395     kCGImageAlphaNoneSkipFirst,
396     provider,
397     NULL, // colourMap
398     NO, // shouldInterpolate
399     kCGRenderingIntentDefault);
400     if ( ! imageRef )
401     {
402     ErrorAlert("Could not create CGImage from CGDataProvider");
403     return false;
404     }
405     CGDataProviderRelease(provider);
406     CGColorSpaceRelease(colourSpace);
407    
408     [output readyToDraw: imageRef
409     imageWidth: mode.x
410     imageHeight: mode.y];
411     #else
412     unsigned char *offsetBuffer = the_buffer;
413     offsetBuffer += 1; // OS X NSBitmaps are RGBA, but Basilisk generates ARGB
414     #endif
415    
416     #ifdef NSBITMAP
417     bitmap = [NSBitmapImageRep alloc];
418     bitmap = [bitmap initWithBitmapDataPlanes: (unsigned char **) &offsetBuffer
419     pixelsWide: mode.x
420     pixelsHigh: mode.y
421     bitsPerSample: bitsPer
422     samplesPerPixel: samplesPer
423     hasAlpha: NO
424     isPlanar: NO
425     colorSpaceName: NSCalibratedRGBColorSpace
426     bytesPerRow: mode.bytes_per_row
427     bitsPerPixel: bits_from_depth(mode.depth)];
428    
429     if ( bitmap == nil )
430     {
431     ErrorAlert("Could not allocate an NSBitmapImageRep");
432     return false;
433     }
434    
435     [output readyToDraw: bitmap
436     imageWidth: mode.x
437     imageHeight: mode.y];
438     #endif
439    
440     #ifdef CGDRAWBITMAP
441     [output readyToDraw: offsetBuffer
442     width: mode.x
443     height: mode.y
444     bps: bitsPer
445     spp: samplesPer
446     bpp: bits_from_depth(mode.depth)
447     bpr: mode.bytes_per_row
448     isPlanar: NO
449     hasAlpha: NO];
450     #endif
451    
452     // Set VideoMonitor
453     VideoMonitor.mode = mode;
454     set_mac_frame_buffer(mode.depth);
455    
456     return true;
457     }
458    
459     #import <AppKit/NSEvent.h>
460    
461     // How do I include this file?
462     // #import <Carbon/HIToolbox/Menus.h>
463     extern "C" void HideMenuBar(),
464     ShowMenuBar();
465    
466     static bool init_screen(const video_mode &mode)
467     {
468     // Set absolute mouse mode
469     ADBSetRelMouseMode(false);
470    
471    
472     theDisplay = kCGDirectMainDisplay; // For now
473     originalMode = CGDisplayCurrentMode(theDisplay);
474    
475     newMode = CGDisplayBestModeForParameters(theDisplay,
476     bits_from_depth(mode.depth),
477     mode.x, mode.y, NULL);
478     if ( NULL == newMode )
479     {
480     ErrorAlert("Could not find a matching screen mode");
481     return false;
482     }
483    
484     [the_win miniaturize: nil];
485     // [the_win setLevel: CGShieldingWindowLevel()];
486     the_win = nil;
487    
488     HideMenuBar();
489    
490     CGDisplayCapture(theDisplay);
491    
492     if ( CGDisplaySwitchToMode(theDisplay, newMode) != CGDisplayNoErr )
493     {
494     ErrorAlert("Could not switch to matching screen mode");
495     return false;
496     }
497    
498     CGDisplayHideCursor(theDisplay);
499    
500     the_buffer = CGDisplayBaseAddress(theDisplay);
501     if ( the_buffer == NULL )
502     {
503     ErrorAlert("Could not get base address of screen");
504     return false;
505     }
506    
507     screen_height = mode.y; // For mouse co-ordinate flipping
508    
509     // Send emulated mouse to current location
510    
511     NSPoint mouse = [NSEvent mouseLocation];
512     ADBMouseMoved((int)mouse.x, screen_height - (int)mouse.y);
513    
514     // Set VideoMonitor
515     VideoMonitor.mode = mode;
516     set_mac_frame_buffer(mode.depth);
517    
518     return true;
519     }
520    
521    
522     static bool init_opengl(const video_mode &mode)
523     {
524     ErrorAlert("Sorry. OpenGL mode is not implemented yet");
525     return false;
526     }
527    
528     /*
529     * Initialization
530     */
531    
532     bool VideoInit(bool classic)
533     {
534     // Read frame skip prefs
535     frame_skip = PrefsFindInt32("frameskip");
536     if (frame_skip == 0)
537     frame_skip = 1;
538    
539     // Get screen mode from preferences
540     const char *mode_str;
541     if (classic)
542     mode_str = "win/512/342";
543     else
544     mode_str = PrefsFindString("screen");
545    
546     // Determine display_type and init_width, height & depth
547     parse_screen_prefs(mode_str);
548    
549     // Construct list of supported modes
550     if (classic)
551     add_mode(512, 342, 0x80, 64, VDEPTH_1BIT);
552     else
553     switch ( display_type )
554     {
555     case DISPLAY_SCREEN:
556     if ( ! add_CGDirectDisplay_modes() )
557     {
558     ErrorAlert("Unable to get list of displays for full screen mode");
559     return false;
560     }
561     break;
562     case DISPLAY_OPENGL:
563     // Same as window depths and sizes?
564     case DISPLAY_WINDOW:
565     //add_standard_modes(VDEPTH_1BIT);
566     //add_standard_modes(VDEPTH_8BIT);
567     //add_standard_modes(VDEPTH_16BIT);
568     add_standard_modes(VDEPTH_32BIT);
569     break;
570     }
571    
572     video_init_depth_list();
573    
574     #if DEBUG
575     bug("Available video modes:\n");
576     vector<video_mode>::const_iterator i, end = VideoModes.end();
577     for (i = VideoModes.begin(); i != end; ++i)
578     bug(" %dx%d (ID %02x), %s\n", i->x, i->y, i->resolution_id,
579     colours_from_depth(i->depth));
580     #endif
581    
582     D(bug("VideoInit: width=%hd height=%hd depth=%ld\n",
583     init_width, init_height, init_depth));
584    
585     // Find requested default mode and open display
586     if (VideoModes.size() > 0)
587     {
588     // Find mode with specified dimensions
589     std::vector<video_mode>::const_iterator i, end = VideoModes.end();
590     for (i = VideoModes.begin(); i != end; ++i)
591     {
592     D(bug("VideoInit: w=%ld h=%ld d=%ld\n",
593     i->x, i->y, bits_from_depth(i->depth)));
594     if (i->x == init_width && i->y == init_height
595     && bits_from_depth(i->depth) == init_depth)
596     return video_open(*i);
597     }
598     }
599    
600     char str[150];
601     sprintf(str, "Cannot open selected video mode\r(%hd x %hd, %s).\r%s",
602     init_width, init_height,
603     colours_from_depth(init_depth), "Using lowest resolution");
604     WarningAlert(str);
605    
606     return video_open(VideoModes[0]);
607     }
608    
609    
610     // Open display for specified mode
611     static bool video_open(const video_mode &mode)
612     {
613     D(bug("video_open: width=%ld height=%ld depth=%ld bytes_per_row=%ld\n",
614     mode.x, mode.y, bits_from_depth(mode.depth), mode.bytes_per_row));
615    
616     // Open display
617     switch ( display_type ) {
618     case DISPLAY_WINDOW:
619     if ( ! init_window(mode) )
620     return false;
621     break;
622    
623     case DISPLAY_SCREEN:
624     if ( ! init_screen(mode) )
625     return false;
626     break;
627    
628     case DISPLAY_OPENGL:
629     if ( ! init_opengl(mode) )
630     return false;
631     break;
632     }
633    
634     return true;
635     }
636    
637    
638     static void video_close()
639     {
640     D(bug("video_close()\n"));
641    
642     switch ( display_type ) {
643     case DISPLAY_WINDOW:
644     // Stop redraw thread
645     [output disableDrawing];
646    
647     // Free frame buffer stuff
648     #ifdef CGIMAGEREF
649     CGImageRelease(imageRef);
650     #endif
651     #ifdef NSBITMAP
652     [bitmap release];
653     #endif
654     free(the_buffer);
655    
656     break;
657    
658     case DISPLAY_SCREEN:
659     if ( theDisplay && originalMode )
660     {
661     //CGDisplayShowCursor(theDisplay);
662     CGDisplaySwitchToMode(theDisplay, originalMode);
663     CGDisplayRelease(theDisplay);
664     ShowMenuBar();
665     }
666     break;
667    
668     case DISPLAY_OPENGL:
669     break;
670     }
671     }
672    
673    
674     /*
675     * Deinitialization
676     */
677    
678     void VideoExit(void)
679     {
680     video_close();
681     }
682    
683    
684     /*
685     * Set palette
686     */
687    
688     void video_set_palette(uint8 *pal, int num)
689     {
690     if ( FULLSCREEN && CGDisplayCanSetPalette(theDisplay)
691     && ! IsDirectMode(VideoMonitor.mode) )
692     {
693     CGDirectPaletteRef CGpal;
694     CGDisplayErr err;
695    
696    
697     CGpal = CGPaletteCreateWithByteSamples((CGDeviceByteColor *)pal, num);
698     err = CGDisplaySetPalette(theDisplay, CGpal);
699     if ( err != noErr )
700     NSLog(@"Failed to set palette, error = %d", err);
701     CGPaletteRelease(CGpal);
702     }
703     }
704    
705    
706     /*
707     * Switch video mode
708     */
709    
710     void video_switch_to_mode(const video_mode &mode)
711     {
712     // Close and reopen display
713     video_close();
714     if (!video_open(mode))
715     {
716     if ( display_type == DISPLAY_SCREEN )
717     ErrorAlert("Cannot switch screen to selected video mode");
718     else
719     ErrorAlert(STR_OPEN_WINDOW_ERR);
720     QuitEmulator();
721     }
722     }
723    
724     /*
725     * Close down full-screen mode
726     * (if bringing up error alerts is unsafe while in full-screen mode)
727     */
728    
729     void VideoQuitFullScreen(void)
730     {
731     }
732    
733    
734     /*
735     * Mac VBL interrupt
736     */
737    
738     void VideoInterrupt(void)
739     {
740     }
741    
742    
743     // This function is called on non-threaded platforms from a timer interrupt
744     void VideoRefresh(void)
745     {
746     }