Statistics
| Branch: | Revision:

root / cocoa.m @ 44e4c0ba

History | View | Annotate | Download (36.6 kB)

1
/*
2
 * QEMU Cocoa CG display driver
3
 *
4
 * Copyright (c) 2008 Mike Kronenberg
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24

    
25
#import <Cocoa/Cocoa.h>
26

    
27
#include "qemu-common.h"
28
#include "console.h"
29
#include "sysemu.h"
30

    
31
#ifndef MAC_OS_X_VERSION_10_5
32
#define MAC_OS_X_VERSION_10_5 1050
33
#endif
34

    
35

    
36
//#define DEBUG
37

    
38
#ifdef DEBUG
39
#define COCOA_DEBUG(...)  { (void) fprintf (stdout, __VA_ARGS__); }
40
#else
41
#define COCOA_DEBUG(...)  ((void) 0)
42
#endif
43

    
44
#define cgrect(nsrect) (*(CGRect *)&(nsrect))
45
#define COCOA_MOUSE_EVENT \
46
        if (isTabletEnabled) { \
47
            kbd_mouse_event((int)(p.x * 0x7FFF / (screen.width - 1)), (int)((screen.height - p.y) * 0x7FFF / (screen.height - 1)), 0, buttons); \
48
        } else if (isMouseGrabed) { \
49
            kbd_mouse_event((int)[event deltaX], (int)[event deltaY], 0, buttons); \
50
        } else { \
51
            [NSApp sendEvent:event]; \
52
        }
53

    
54
typedef struct {
55
    int width;
56
    int height;
57
    int bitsPerComponent;
58
    int bitsPerPixel;
59
} QEMUScreen;
60

    
61
int qemu_main(int argc, char **argv); // main defined in qemu/vl.c
62
NSWindow *normalWindow;
63
id cocoaView;
64
static DisplayChangeListener *dcl;
65

    
66
int gArgc;
67
char **gArgv;
68

    
69
// keymap conversion
70
int keymap[] =
71
{
72
//  SdlI    macI    macH    SdlH    104xtH  104xtC  sdl
73
    30, //  0       0x00    0x1e            A       QZ_a
74
    31, //  1       0x01    0x1f            S       QZ_s
75
    32, //  2       0x02    0x20            D       QZ_d
76
    33, //  3       0x03    0x21            F       QZ_f
77
    35, //  4       0x04    0x23            H       QZ_h
78
    34, //  5       0x05    0x22            G       QZ_g
79
    44, //  6       0x06    0x2c            Z       QZ_z
80
    45, //  7       0x07    0x2d            X       QZ_x
81
    46, //  8       0x08    0x2e            C       QZ_c
82
    47, //  9       0x09    0x2f            V       QZ_v
83
    0,  //  10      0x0A    Undefined
84
    48, //  11      0x0B    0x30            B       QZ_b
85
    16, //  12      0x0C    0x10            Q       QZ_q
86
    17, //  13      0x0D    0x11            W       QZ_w
87
    18, //  14      0x0E    0x12            E       QZ_e
88
    19, //  15      0x0F    0x13            R       QZ_r
89
    21, //  16      0x10    0x15            Y       QZ_y
90
    20, //  17      0x11    0x14            T       QZ_t
91
    2,  //  18      0x12    0x02            1       QZ_1
92
    3,  //  19      0x13    0x03            2       QZ_2
93
    4,  //  20      0x14    0x04            3       QZ_3
94
    5,  //  21      0x15    0x05            4       QZ_4
95
    7,  //  22      0x16    0x07            6       QZ_6
96
    6,  //  23      0x17    0x06            5       QZ_5
97
    13, //  24      0x18    0x0d            =       QZ_EQUALS
98
    10, //  25      0x19    0x0a            9       QZ_9
99
    8,  //  26      0x1A    0x08            7       QZ_7
100
    12, //  27      0x1B    0x0c            -       QZ_MINUS
101
    9,  //  28      0x1C    0x09            8       QZ_8
102
    11, //  29      0x1D    0x0b            0       QZ_0
103
    27, //  30      0x1E    0x1b            ]       QZ_RIGHTBRACKET
104
    24, //  31      0x1F    0x18            O       QZ_o
105
    22, //  32      0x20    0x16            U       QZ_u
106
    26, //  33      0x21    0x1a            [       QZ_LEFTBRACKET
107
    23, //  34      0x22    0x17            I       QZ_i
108
    25, //  35      0x23    0x19            P       QZ_p
109
    28, //  36      0x24    0x1c            ENTER   QZ_RETURN
110
    38, //  37      0x25    0x26            L       QZ_l
111
    36, //  38      0x26    0x24            J       QZ_j
112
    40, //  39      0x27    0x28            '       QZ_QUOTE
113
    37, //  40      0x28    0x25            K       QZ_k
114
    39, //  41      0x29    0x27            ;       QZ_SEMICOLON
115
    43, //  42      0x2A    0x2b            \       QZ_BACKSLASH
116
    51, //  43      0x2B    0x33            ,       QZ_COMMA
117
    53, //  44      0x2C    0x35            /       QZ_SLASH
118
    49, //  45      0x2D    0x31            N       QZ_n
119
    50, //  46      0x2E    0x32            M       QZ_m
120
    52, //  47      0x2F    0x34            .       QZ_PERIOD
121
    15, //  48      0x30    0x0f            TAB     QZ_TAB
122
    57, //  49      0x31    0x39            SPACE   QZ_SPACE
123
    41, //  50      0x32    0x29            `       QZ_BACKQUOTE
124
    14, //  51      0x33    0x0e            BKSP    QZ_BACKSPACE
125
    0,  //  52      0x34    Undefined
126
    1,  //  53      0x35    0x01            ESC     QZ_ESCAPE
127
    0,  //  54      0x36                            QZ_RMETA
128
    0,  //  55      0x37                            QZ_LMETA
129
    42, //  56      0x38    0x2a            L SHFT  QZ_LSHIFT
130
    58, //  57      0x39    0x3a            CAPS    QZ_CAPSLOCK
131
    56, //  58      0x3A    0x38            L ALT   QZ_LALT
132
    29, //  59      0x3B    0x1d            L CTRL  QZ_LCTRL
133
    54, //  60      0x3C    0x36            R SHFT  QZ_RSHIFT
134
    184,//  61      0x3D    0xb8    E0,38   R ALT   QZ_RALT
135
    157,//  62      0x3E    0x9d    E0,1D   R CTRL  QZ_RCTRL
136
    0,  //  63      0x3F    Undefined
137
    0,  //  64      0x40    Undefined
138
    0,  //  65      0x41    Undefined
139
    0,  //  66      0x42    Undefined
140
    55, //  67      0x43    0x37            KP *    QZ_KP_MULTIPLY
141
    0,  //  68      0x44    Undefined
142
    78, //  69      0x45    0x4e            KP +    QZ_KP_PLUS
143
    0,  //  70      0x46    Undefined
144
    69, //  71      0x47    0x45            NUM     QZ_NUMLOCK
145
    0,  //  72      0x48    Undefined
146
    0,  //  73      0x49    Undefined
147
    0,  //  74      0x4A    Undefined
148
    181,//  75      0x4B    0xb5    E0,35   KP /    QZ_KP_DIVIDE
149
    152,//  76      0x4C    0x9c    E0,1C   KP EN   QZ_KP_ENTER
150
    0,  //  77      0x4D    undefined
151
    74, //  78      0x4E    0x4a            KP -    QZ_KP_MINUS
152
    0,  //  79      0x4F    Undefined
153
    0,  //  80      0x50    Undefined
154
    0,  //  81      0x51                            QZ_KP_EQUALS
155
    82, //  82      0x52    0x52            KP 0    QZ_KP0
156
    79, //  83      0x53    0x4f            KP 1    QZ_KP1
157
    80, //  84      0x54    0x50            KP 2    QZ_KP2
158
    81, //  85      0x55    0x51            KP 3    QZ_KP3
159
    75, //  86      0x56    0x4b            KP 4    QZ_KP4
160
    76, //  87      0x57    0x4c            KP 5    QZ_KP5
161
    77, //  88      0x58    0x4d            KP 6    QZ_KP6
162
    71, //  89      0x59    0x47            KP 7    QZ_KP7
163
    0,  //  90      0x5A    Undefined
164
    72, //  91      0x5B    0x48            KP 8    QZ_KP8
165
    73, //  92      0x5C    0x49            KP 9    QZ_KP9
166
    0,  //  93      0x5D    Undefined
167
    0,  //  94      0x5E    Undefined
168
    0,  //  95      0x5F    Undefined
169
    63, //  96      0x60    0x3f            F5      QZ_F5
170
    64, //  97      0x61    0x40            F6      QZ_F6
171
    65, //  98      0x62    0x41            F7      QZ_F7
172
    61, //  99      0x63    0x3d            F3      QZ_F3
173
    66, //  100     0x64    0x42            F8      QZ_F8
174
    67, //  101     0x65    0x43            F9      QZ_F9
175
    0,  //  102     0x66    Undefined
176
    87, //  103     0x67    0x57            F11     QZ_F11
177
    0,  //  104     0x68    Undefined
178
    183,//  105     0x69    0xb7                    QZ_PRINT
179
    0,  //  106     0x6A    Undefined
180
    70, //  107     0x6B    0x46            SCROLL  QZ_SCROLLOCK
181
    0,  //  108     0x6C    Undefined
182
    68, //  109     0x6D    0x44            F10     QZ_F10
183
    0,  //  110     0x6E    Undefined
184
    88, //  111     0x6F    0x58            F12     QZ_F12
185
    0,  //  112     0x70    Undefined
186
    110,//  113     0x71    0x0                     QZ_PAUSE
187
    210,//  114     0x72    0xd2    E0,52   INSERT  QZ_INSERT
188
    199,//  115     0x73    0xc7    E0,47   HOME    QZ_HOME
189
    201,//  116     0x74    0xc9    E0,49   PG UP   QZ_PAGEUP
190
    211,//  117     0x75    0xd3    E0,53   DELETE  QZ_DELETE
191
    62, //  118     0x76    0x3e            F4      QZ_F4
192
    207,//  119     0x77    0xcf    E0,4f   END     QZ_END
193
    60, //  120     0x78    0x3c            F2      QZ_F2
194
    209,//  121     0x79    0xd1    E0,51   PG DN   QZ_PAGEDOWN
195
    59, //  122     0x7A    0x3b            F1      QZ_F1
196
    203,//  123     0x7B    0xcb    e0,4B   L ARROW QZ_LEFT
197
    205,//  124     0x7C    0xcd    e0,4D   R ARROW QZ_RIGHT
198
    208,//  125     0x7D    0xd0    E0,50   D ARROW QZ_DOWN
199
    200,//  126     0x7E    0xc8    E0,48   U ARROW QZ_UP
200
/* completed according to http://www.libsdl.org/cgi/cvsweb.cgi/SDL12/src/video/quartz/SDL_QuartzKeys.h?rev=1.6&content-type=text/x-cvsweb-markup */
201

    
202
/* Aditional 104 Key XP-Keyboard Scancodes from http://www.computer-engineering.org/ps2keyboard/scancodes1.html */
203
/*
204
    219 //          0xdb            e0,5b   L GUI
205
    220 //          0xdc            e0,5c   R GUI
206
    221 //          0xdd            e0,5d   APPS
207
        //              E0,2A,E0,37         PRNT SCRN
208
        //              E1,1D,45,E1,9D,C5   PAUSE
209
    83  //          0x53    0x53            KP .
210
// ACPI Scan Codes
211
    222 //          0xde            E0, 5E  Power
212
    223 //          0xdf            E0, 5F  Sleep
213
    227 //          0xe3            E0, 63  Wake
214
// Windows Multimedia Scan Codes
215
    153 //          0x99            E0, 19  Next Track
216
    144 //          0x90            E0, 10  Previous Track
217
    164 //          0xa4            E0, 24  Stop
218
    162 //          0xa2            E0, 22  Play/Pause
219
    160 //          0xa0            E0, 20  Mute
220
    176 //          0xb0            E0, 30  Volume Up
221
    174 //          0xae            E0, 2E  Volume Down
222
    237 //          0xed            E0, 6D  Media Select
223
    236 //          0xec            E0, 6C  E-Mail
224
    161 //          0xa1            E0, 21  Calculator
225
    235 //          0xeb            E0, 6B  My Computer
226
    229 //          0xe5            E0, 65  WWW Search
227
    178 //          0xb2            E0, 32  WWW Home
228
    234 //          0xea            E0, 6A  WWW Back
229
    233 //          0xe9            E0, 69  WWW Forward
230
    232 //          0xe8            E0, 68  WWW Stop
231
    231 //          0xe7            E0, 67  WWW Refresh
232
    230 //          0xe6            E0, 66  WWW Favorites
233
*/
234
};
235

    
236
int cocoa_keycode_to_qemu(int keycode)
237
{
238
    if((sizeof(keymap)/sizeof(int)) <= keycode)
239
    {
240
        printf("(cocoa) warning unknow keycode 0x%x\n", keycode);
241
        return 0;
242
    }
243
    return keymap[keycode];
244
}
245

    
246

    
247

    
248
/*
249
 ------------------------------------------------------
250
    QemuCocoaView
251
 ------------------------------------------------------
252
*/
253
@interface QemuCocoaView : NSView
254
{
255
    QEMUScreen screen;
256
    NSWindow *fullScreenWindow;
257
    float cx,cy,cw,ch,cdx,cdy;
258
    CGDataProviderRef dataProviderRef;
259
    int modifiers_state[256];
260
    BOOL isMouseGrabed;
261
    BOOL isFullscreen;
262
    BOOL isAbsoluteEnabled;
263
    BOOL isTabletEnabled;
264
}
265
- (void) resizeContentToWidth:(int)w height:(int)h displayState:(DisplayState *)ds;
266
- (void) grabMouse;
267
- (void) ungrabMouse;
268
- (void) toggleFullScreen:(id)sender;
269
- (void) handleEvent:(NSEvent *)event;
270
- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
271
- (BOOL) isMouseGrabed;
272
- (BOOL) isAbsoluteEnabled;
273
- (float) cdx;
274
- (float) cdy;
275
- (QEMUScreen) gscreen;
276
@end
277

    
278
@implementation QemuCocoaView
279
- (id)initWithFrame:(NSRect)frameRect
280
{
281
    COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
282

    
283
    self = [super initWithFrame:frameRect];
284
    if (self) {
285

    
286
        screen.bitsPerComponent = 8;
287
        screen.bitsPerPixel = 32;
288
        screen.width = frameRect.size.width;
289
        screen.height = frameRect.size.height;
290

    
291
    }
292
    return self;
293
}
294

    
295
- (void) dealloc
296
{
297
    COCOA_DEBUG("QemuCocoaView: dealloc\n");
298

    
299
    if (dataProviderRef)
300
        CGDataProviderRelease(dataProviderRef);
301

    
302
    [super dealloc];
303
}
304

    
305
- (void) drawRect:(NSRect) rect
306
{
307
    COCOA_DEBUG("QemuCocoaView: drawRect\n");
308

    
309
    // get CoreGraphic context
310
    CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
311
    CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
312
    CGContextSetShouldAntialias (viewContextRef, NO);
313

    
314
    // draw screen bitmap directly to Core Graphics context
315
    if (dataProviderRef) {
316
        CGImageRef imageRef = CGImageCreate(
317
            screen.width, //width
318
            screen.height, //height
319
            screen.bitsPerComponent, //bitsPerComponent
320
            screen.bitsPerPixel, //bitsPerPixel
321
            (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
322
#if __LITTLE_ENDIAN__
323
            CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
324
            kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
325
#else
326
            CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
327
            kCGImageAlphaNoneSkipFirst, //bitmapInfo
328
#endif
329
            dataProviderRef, //provider
330
            NULL, //decode
331
            0, //interpolate
332
            kCGRenderingIntentDefault //intent
333
        );
334
// test if host support "CGImageCreateWithImageInRect" at compiletime
335
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
336
        if (CGImageCreateWithImageInRect == NULL) { // test if "CGImageCreateWithImageInRect" is supported on host at runtime
337
#endif
338
            // compatibility drawing code (draws everything) (OS X < 10.4)
339
            CGContextDrawImage (viewContextRef, CGRectMake(0, 0, [self bounds].size.width, [self bounds].size.height), imageRef);
340
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
341
        } else {
342
            // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
343
            const NSRect *rectList;
344
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
345
            NSInteger rectCount;
346
#else
347
            int rectCount;
348
#endif
349
            int i;
350
            CGImageRef clipImageRef;
351
            CGRect clipRect;
352

    
353
            [self getRectsBeingDrawn:&rectList count:&rectCount];
354
            for (i = 0; i < rectCount; i++) {
355
                clipRect.origin.x = rectList[i].origin.x / cdx;
356
                clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
357
                clipRect.size.width = rectList[i].size.width / cdx;
358
                clipRect.size.height = rectList[i].size.height / cdy;
359
                clipImageRef = CGImageCreateWithImageInRect(
360
                    imageRef,
361
                    clipRect
362
                );
363
                CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
364
                CGImageRelease (clipImageRef);
365
            }
366
        }
367
#endif
368
        CGImageRelease (imageRef);
369
    }
370
}
371

    
372
- (void) setContentDimensions
373
{
374
    COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
375

    
376
    if (isFullscreen) {
377
        cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
378
        cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
379
        cw = screen.width * cdx;
380
        ch = screen.height * cdy;
381
        cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
382
        cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
383
    } else {
384
        cx = 0;
385
        cy = 0;
386
        cw = screen.width;
387
        ch = screen.height;
388
        cdx = 1.0;
389
        cdy = 1.0;
390
    }
391
}
392

    
393
- (void) resizeContentToWidth:(int)w height:(int)h displayState:(DisplayState *)ds
394
{
395
    COCOA_DEBUG("QemuCocoaView: resizeContent\n");
396

    
397
    // update screenBuffer
398
    if (dataProviderRef)
399
        CGDataProviderRelease(dataProviderRef);
400

    
401
    //sync host window color space with guests
402
	screen.bitsPerPixel = ds_get_bits_per_pixel(ds);
403
	screen.bitsPerComponent = ds_get_bytes_per_pixel(ds) * 2;
404

    
405
    dataProviderRef = CGDataProviderCreateWithData(NULL, ds_get_data(ds), w * 4 * h, NULL);
406

    
407
    // update windows
408
    if (isFullscreen) {
409
        [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
410
        [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + screen.height, w, h + [normalWindow frame].size.height - screen.height) display:NO animate:NO];
411
    } else {
412
        if (qemu_name)
413
            [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
414
        [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + screen.height, w, h + [normalWindow frame].size.height - screen.height) display:YES animate:YES];
415
    }
416
    screen.width = w;
417
    screen.height = h;
418
	[normalWindow center];
419
    [self setContentDimensions];
420
    [self setFrame:NSMakeRect(cx, cy, cw, ch)];
421
}
422

    
423
- (void) toggleFullScreen:(id)sender
424
{
425
    COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
426

    
427
    if (isFullscreen) { // switch from fullscreen to desktop
428
        isFullscreen = FALSE;
429
        [self ungrabMouse];
430
        [self setContentDimensions];
431
// test if host support "enterFullScreenMode:withOptions" at compiletime
432
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
433
        if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
434
            [self exitFullScreenModeWithOptions:nil];
435
        } else {
436
#endif
437
            [fullScreenWindow close];
438
            [normalWindow setContentView: self];
439
            [normalWindow makeKeyAndOrderFront: self];
440
            [NSMenu setMenuBarVisible:YES];
441
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
442
        }
443
#endif
444
    } else { // switch from desktop to fullscreen
445
        isFullscreen = TRUE;
446
        [self grabMouse];
447
        [self setContentDimensions];
448
// test if host support "enterFullScreenMode:withOptions" at compiletime
449
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
450
        if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
451
            [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
452
                [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
453
                [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
454
                 nil]];
455
        } else {
456
#endif
457
            [NSMenu setMenuBarVisible:NO];
458
            fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
459
                styleMask:NSBorderlessWindowMask
460
                backing:NSBackingStoreBuffered
461
                defer:NO];
462
            [fullScreenWindow setHasShadow:NO];
463
            [fullScreenWindow setContentView:self];
464
            [fullScreenWindow makeKeyAndOrderFront:self];
465
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
466
        }
467
#endif
468
    }
469
}
470

    
471
- (void) handleEvent:(NSEvent *)event
472
{
473
    COCOA_DEBUG("QemuCocoaView: handleEvent\n");
474

    
475
    int buttons = 0;
476
    int keycode;
477
    NSPoint p = [event locationInWindow];
478

    
479
    switch ([event type]) {
480
        case NSFlagsChanged:
481
            keycode = cocoa_keycode_to_qemu([event keyCode]);
482
            if (keycode) {
483
                if (keycode == 58 || keycode == 69) { // emulate caps lock and num lock keydown and keyup
484
                    kbd_put_keycode(keycode);
485
                    kbd_put_keycode(keycode | 0x80);
486
                } else if (is_graphic_console()) {
487
                    if (keycode & 0x80)
488
                        kbd_put_keycode(0xe0);
489
                    if (modifiers_state[keycode] == 0) { // keydown
490
                        kbd_put_keycode(keycode & 0x7f);
491
                        modifiers_state[keycode] = 1;
492
                    } else { // keyup
493
                        kbd_put_keycode(keycode | 0x80);
494
                        modifiers_state[keycode] = 0;
495
                    }
496
                }
497
            }
498

    
499
            // release Mouse grab when pressing ctrl+alt
500
            if (!isFullscreen && ([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
501
                [self ungrabMouse];
502
            }
503
            break;
504
        case NSKeyDown:
505

    
506
            // forward command Key Combos
507
            if ([event modifierFlags] & NSCommandKeyMask) {
508
                [NSApp sendEvent:event];
509
                return;
510
            }
511

    
512
            // default
513
            keycode = cocoa_keycode_to_qemu([event keyCode]);
514

    
515
            // handle control + alt Key Combos (ctrl+alt is reserved for QEMU)
516
            if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
517
                switch (keycode) {
518

    
519
                    // enable graphic console
520
                    case 0x02 ... 0x0a: // '1' to '9' keys
521
                        console_select(keycode - 0x02);
522
                        break;
523
                }
524

    
525
            // handle keys for graphic console
526
            } else if (is_graphic_console()) {
527
                if (keycode & 0x80) //check bit for e0 in front
528
                    kbd_put_keycode(0xe0);
529
                kbd_put_keycode(keycode & 0x7f); //remove e0 bit in front
530

    
531
            // handlekeys for Monitor
532
            } else {
533
                int keysym = 0;
534
                switch([event keyCode]) {
535
                case 115:
536
                    keysym = QEMU_KEY_HOME;
537
                    break;
538
                case 117:
539
                    keysym = QEMU_KEY_DELETE;
540
                    break;
541
                case 119:
542
                    keysym = QEMU_KEY_END;
543
                    break;
544
                case 123:
545
                    keysym = QEMU_KEY_LEFT;
546
                    break;
547
                case 124:
548
                    keysym = QEMU_KEY_RIGHT;
549
                    break;
550
                case 125:
551
                    keysym = QEMU_KEY_DOWN;
552
                    break;
553
                case 126:
554
                    keysym = QEMU_KEY_UP;
555
                    break;
556
                default:
557
                    {
558
                        NSString *ks = [event characters];
559
                        if ([ks length] > 0)
560
                            keysym = [ks characterAtIndex:0];
561
                    }
562
                }
563
                if (keysym)
564
                    kbd_put_keysym(keysym);
565
            }
566
            break;
567
        case NSKeyUp:
568
            keycode = cocoa_keycode_to_qemu([event keyCode]);
569
            if (is_graphic_console()) {
570
                if (keycode & 0x80)
571
                    kbd_put_keycode(0xe0);
572
                kbd_put_keycode(keycode | 0x80); //add 128 to signal release of key
573
            }
574
            break;
575
        case NSMouseMoved:
576
            if (isAbsoluteEnabled) {
577
                if (p.x < 0 || p.x > screen.width || p.y < 0 || p.y > screen.height || ![[self window] isKeyWindow]) {
578
                    if (isTabletEnabled) { // if we leave the window, deactivate the tablet
579
                        [NSCursor unhide];
580
                        isTabletEnabled = FALSE;
581
                    }
582
                } else {
583
                    if (!isTabletEnabled) { // if we enter the window, activate the tablet
584
                        [NSCursor hide];
585
                        isTabletEnabled = TRUE;
586
                    }
587
                }
588
            }
589
            COCOA_MOUSE_EVENT
590
            break;
591
        case NSLeftMouseDown:
592
            if ([event modifierFlags] & NSCommandKeyMask) {
593
                buttons |= MOUSE_EVENT_RBUTTON;
594
            } else {
595
                buttons |= MOUSE_EVENT_LBUTTON;
596
            }
597
            COCOA_MOUSE_EVENT
598
            break;
599
        case NSRightMouseDown:
600
            buttons |= MOUSE_EVENT_RBUTTON;
601
            COCOA_MOUSE_EVENT
602
            break;
603
        case NSOtherMouseDown:
604
            buttons |= MOUSE_EVENT_MBUTTON;
605
            COCOA_MOUSE_EVENT
606
            break;
607
        case NSLeftMouseDragged:
608
            if ([event modifierFlags] & NSCommandKeyMask) {
609
                buttons |= MOUSE_EVENT_RBUTTON;
610
            } else {
611
                buttons |= MOUSE_EVENT_LBUTTON;
612
            }
613
            COCOA_MOUSE_EVENT
614
            break;
615
        case NSRightMouseDragged:
616
            buttons |= MOUSE_EVENT_RBUTTON;
617
            COCOA_MOUSE_EVENT
618
            break;
619
        case NSOtherMouseDragged:
620
            buttons |= MOUSE_EVENT_MBUTTON;
621
            COCOA_MOUSE_EVENT
622
            break;
623
        case NSLeftMouseUp:
624
            if (isTabletEnabled) {
625
                    COCOA_MOUSE_EVENT
626
            } else if (!isMouseGrabed) {
627
                if (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height) {
628
                    [self grabMouse];
629
                } else {
630
                    [NSApp sendEvent:event];
631
                }
632
            } else {
633
                COCOA_MOUSE_EVENT
634
            }
635
            break;
636
        case NSRightMouseUp:
637
            COCOA_MOUSE_EVENT
638
            break;
639
        case NSOtherMouseUp:
640
            COCOA_MOUSE_EVENT
641
            break;
642
        case NSScrollWheel:
643
            if (isTabletEnabled || isMouseGrabed) {
644
                kbd_mouse_event(0, 0, -[event deltaY], 0);
645
            } else {
646
                [NSApp sendEvent:event];
647
            }
648
            break;
649
        default:
650
            [NSApp sendEvent:event];
651
    }
652
}
653

    
654
- (void) grabMouse
655
{
656
    COCOA_DEBUG("QemuCocoaView: grabMouse\n");
657

    
658
    if (!isFullscreen) {
659
        if (qemu_name)
660
            [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt to release Mouse)", qemu_name]];
661
        else
662
            [normalWindow setTitle:@"QEMU - (Press ctrl + alt to release Mouse)"];
663
    }
664
    [NSCursor hide];
665
    CGAssociateMouseAndMouseCursorPosition(FALSE);
666
    isMouseGrabed = TRUE; // while isMouseGrabed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
667
}
668

    
669
- (void) ungrabMouse
670
{
671
    COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
672

    
673
    if (!isFullscreen) {
674
        if (qemu_name)
675
            [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
676
        else
677
            [normalWindow setTitle:@"QEMU"];
678
    }
679
    [NSCursor unhide];
680
    CGAssociateMouseAndMouseCursorPosition(TRUE);
681
    isMouseGrabed = FALSE;
682
}
683

    
684
- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
685
- (BOOL) isMouseGrabed {return isMouseGrabed;}
686
- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
687
- (float) cdx {return cdx;}
688
- (float) cdy {return cdy;}
689
- (QEMUScreen) gscreen {return screen;}
690
@end
691

    
692

    
693

    
694
/*
695
 ------------------------------------------------------
696
    QemuCocoaAppController
697
 ------------------------------------------------------
698
*/
699
@interface QemuCocoaAppController : NSObject
700
{
701
}
702
- (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
703
- (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
704
- (void)toggleFullScreen:(id)sender;
705
- (void)showQEMUDoc:(id)sender;
706
- (void)showQEMUTec:(id)sender;
707
@end
708

    
709
@implementation QemuCocoaAppController
710
- (id) init
711
{
712
    COCOA_DEBUG("QemuCocoaAppController: init\n");
713

    
714
    self = [super init];
715
    if (self) {
716

    
717
        // create a view and add it to the window
718
        cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
719
        if(!cocoaView) {
720
            fprintf(stderr, "(cocoa) can't create a view\n");
721
            exit(1);
722
        }
723

    
724
        // create a window
725
        normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
726
            styleMask:NSTitledWindowMask|NSMiniaturizableWindowMask|NSClosableWindowMask
727
            backing:NSBackingStoreBuffered defer:NO];
728
        if(!normalWindow) {
729
            fprintf(stderr, "(cocoa) can't create window\n");
730
            exit(1);
731
        }
732
        [normalWindow setAcceptsMouseMovedEvents:YES];
733
        [normalWindow setTitle:[NSString stringWithFormat:@"QEMU"]];
734
        [normalWindow setContentView:cocoaView];
735
        [normalWindow makeKeyAndOrderFront:self];
736
		[normalWindow center];
737

    
738
    }
739
    return self;
740
}
741

    
742
- (void) dealloc
743
{
744
    COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
745

    
746
    if (cocoaView)
747
        [cocoaView release];
748
    [super dealloc];
749
}
750

    
751
- (void)applicationDidFinishLaunching: (NSNotification *) note
752
{
753
    COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
754

    
755
    // Display an open dialog box if no argument were passed or
756
    // if qemu was launched from the finder ( the Finder passes "-psn" )
757
    if( gArgc <= 1 || strncmp ((char *)gArgv[1], "-psn", 4) == 0) {
758
        NSOpenPanel *op = [[NSOpenPanel alloc] init];
759
        [op setPrompt:@"Boot image"];
760
        [op setMessage:@"Select the disk image you want to boot.\n\nHit the \"Cancel\" button to quit"];
761
        [op beginSheetForDirectory:nil file:nil types:[NSArray arrayWithObjects:@"img",@"iso",@"dmg",@"qcow",@"cow",@"cloop",@"vmdk",nil]
762
              modalForWindow:normalWindow modalDelegate:self
763
              didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
764
    } else {
765
        // or Launch Qemu, with the global args
766
        [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
767
    }
768
}
769

    
770
- (void)applicationWillTerminate:(NSNotification *)aNotification
771
{
772
    COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
773

    
774
    qemu_system_shutdown_request();
775
    exit(0);
776
}
777

    
778
- (void)startEmulationWithArgc:(int)argc argv:(char**)argv
779
{
780
    COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
781

    
782
    int status;
783
    status = qemu_main(argc, argv);
784
    exit(status);
785
}
786

    
787
- (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
788
{
789
    COCOA_DEBUG("QemuCocoaAppController: openPanelDidEnd\n");
790

    
791
    if(returnCode == NSCancelButton) {
792
        exit(0);
793
    } else if(returnCode == NSOKButton) {
794
        char *bin = "qemu";
795
        char *img = (char*)[ [ sheet filename ] cStringUsingEncoding:NSASCIIStringEncoding];
796

    
797
        char **argv = (char**)malloc( sizeof(char*)*3 );
798

    
799
        asprintf(&argv[0], "%s", bin);
800
        asprintf(&argv[1], "-hda");
801
        asprintf(&argv[2], "%s", img);
802

    
803
        printf("Using argc %d argv %s -hda %s\n", 3, bin, img);
804

    
805
        [self startEmulationWithArgc:3 argv:(char**)argv];
806
    }
807
}
808
- (void)toggleFullScreen:(id)sender
809
{
810
    COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
811

    
812
    [cocoaView toggleFullScreen:sender];
813
}
814

    
815
- (void)showQEMUDoc:(id)sender
816
{
817
    COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
818

    
819
    [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-doc.html",
820
        [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
821
}
822

    
823
- (void)showQEMUTec:(id)sender
824
{
825
    COCOA_DEBUG("QemuCocoaAppController: showQEMUTec\n");
826

    
827
    [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-tech.html",
828
        [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
829
}
830
@end
831

    
832

    
833

    
834
// Dock Connection
835
typedef struct CPSProcessSerNum
836
{
837
        UInt32                lo;
838
        UInt32                hi;
839
} CPSProcessSerNum;
840

    
841
extern OSErr    CPSGetCurrentProcess( CPSProcessSerNum *psn);
842
extern OSErr    CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
843
extern OSErr    CPSSetFrontProcess( CPSProcessSerNum *psn);
844

    
845
int main (int argc, const char * argv[]) {
846

    
847
    gArgc = argc;
848
    gArgv = (char **)argv;
849
    CPSProcessSerNum PSN;
850

    
851
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
852
    [NSApplication sharedApplication];
853

    
854
    if (!CPSGetCurrentProcess(&PSN))
855
        if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
856
            if (!CPSSetFrontProcess(&PSN))
857
                [NSApplication sharedApplication];
858

    
859
    // Add menus
860
    NSMenu      *menu;
861
    NSMenuItem  *menuItem;
862

    
863
    [NSApp setMainMenu:[[NSMenu alloc] init]];
864

    
865
    // Application menu
866
    menu = [[NSMenu alloc] initWithTitle:@""];
867
    [menu addItemWithTitle:@"About QEMU" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; // About QEMU
868
    [menu addItem:[NSMenuItem separatorItem]]; //Separator
869
    [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
870
    menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
871
    [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
872
    [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
873
    [menu addItem:[NSMenuItem separatorItem]]; //Separator
874
    [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
875
    menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
876
    [menuItem setSubmenu:menu];
877
    [[NSApp mainMenu] addItem:menuItem];
878
    [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
879

    
880
    // View menu
881
    menu = [[NSMenu alloc] initWithTitle:@"View"];
882
    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
883
    menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
884
    [menuItem setSubmenu:menu];
885
    [[NSApp mainMenu] addItem:menuItem];
886

    
887
    // Window menu
888
    menu = [[NSMenu alloc] initWithTitle:@"Window"];
889
    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
890
    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
891
    [menuItem setSubmenu:menu];
892
    [[NSApp mainMenu] addItem:menuItem];
893
    [NSApp setWindowsMenu:menu];
894

    
895
    // Help menu
896
    menu = [[NSMenu alloc] initWithTitle:@"Help"];
897
    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
898
    [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Technology" action:@selector(showQEMUTec:) keyEquivalent:@""] autorelease]]; // QEMU Help
899
    menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
900
    [menuItem setSubmenu:menu];
901
    [[NSApp mainMenu] addItem:menuItem];
902

    
903
    // Create an Application controller
904
    QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
905
    [NSApp setDelegate:appController];
906

    
907
    // Start the main event loop
908
    [NSApp run];
909

    
910
    [appController release];
911
    [pool release];
912

    
913
    return 0;
914
}
915

    
916

    
917

    
918
#pragma mark qemu
919
static void cocoa_update(DisplayState *ds, int x, int y, int w, int h)
920
{
921
    COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
922

    
923
    NSRect rect;
924
    if ([cocoaView cdx] == 1.0) {
925
        rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
926
    } else {
927
        rect = NSMakeRect(
928
            x * [cocoaView cdx],
929
            ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
930
            w * [cocoaView cdx],
931
            h * [cocoaView cdy]);
932
    }
933
    [cocoaView displayRect:rect];
934
}
935

    
936
static void cocoa_resize(DisplayState *ds)
937
{
938
    COCOA_DEBUG("qemu_cocoa: cocoa_resize\n");
939

    
940
    [cocoaView resizeContentToWidth:(int)(ds_get_width(ds)) height:(int)(ds_get_height(ds)) displayState:ds];
941
}
942

    
943
static void cocoa_refresh(DisplayState *ds)
944
{
945
    COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
946

    
947
    if (kbd_mouse_is_absolute()) {
948
        if (![cocoaView isAbsoluteEnabled]) {
949
            if ([cocoaView isMouseGrabed]) {
950
                [cocoaView ungrabMouse];
951
            }
952
        }
953
        [cocoaView setAbsoluteEnabled:YES];
954
    }
955

    
956
    NSDate *distantPast;
957
    NSEvent *event;
958
    distantPast = [NSDate distantPast];
959
    do {
960
        event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:distantPast
961
                        inMode: NSDefaultRunLoopMode dequeue:YES];
962
        if (event != nil) {
963
            [cocoaView handleEvent:event];
964
        }
965
    } while(event != nil);
966
    vga_hw_update();
967
}
968

    
969
static void cocoa_cleanup(void)
970
{
971
    COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
972
	qemu_free(dcl);
973
}
974

    
975
void cocoa_display_init(DisplayState *ds, int full_screen)
976
{
977
    COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
978

    
979
	dcl = qemu_mallocz(sizeof(DisplayChangeListener));
980
	
981
    // register vga output callbacks
982
    dcl->dpy_update = cocoa_update;
983
    dcl->dpy_resize = cocoa_resize;
984
    dcl->dpy_refresh = cocoa_refresh;
985

    
986
	register_displaychangelistener(ds, dcl);
987

    
988
    // register cleanup function
989
    atexit(cocoa_cleanup);
990
}