cocoa.m 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  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. #include "qemu/osdep.h"
  25. #import <Cocoa/Cocoa.h>
  26. #include <crt_externs.h>
  27. #include "qemu-common.h"
  28. #include "ui/console.h"
  29. #include "ui/input.h"
  30. #include "sysemu/sysemu.h"
  31. #include "sysemu/runstate.h"
  32. #include "qapi/error.h"
  33. #include "qapi/qapi-commands-block.h"
  34. #include "qapi/qapi-commands-misc.h"
  35. #include "sysemu/blockdev.h"
  36. #include "qemu-version.h"
  37. #include "qemu/main-loop.h"
  38. #include "qemu/module.h"
  39. #include <Carbon/Carbon.h>
  40. #include "hw/core/cpu.h"
  41. #ifndef MAC_OS_X_VERSION_10_5
  42. #define MAC_OS_X_VERSION_10_5 1050
  43. #endif
  44. #ifndef MAC_OS_X_VERSION_10_6
  45. #define MAC_OS_X_VERSION_10_6 1060
  46. #endif
  47. #ifndef MAC_OS_X_VERSION_10_9
  48. #define MAC_OS_X_VERSION_10_9 1090
  49. #endif
  50. #ifndef MAC_OS_X_VERSION_10_10
  51. #define MAC_OS_X_VERSION_10_10 101000
  52. #endif
  53. #ifndef MAC_OS_X_VERSION_10_12
  54. #define MAC_OS_X_VERSION_10_12 101200
  55. #endif
  56. #ifndef MAC_OS_X_VERSION_10_13
  57. #define MAC_OS_X_VERSION_10_13 101300
  58. #endif
  59. /* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
  60. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
  61. #define NSEventMaskAny NSAnyEventMask
  62. #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
  63. #define NSEventModifierFlagShift NSShiftKeyMask
  64. #define NSEventModifierFlagCommand NSCommandKeyMask
  65. #define NSEventModifierFlagControl NSControlKeyMask
  66. #define NSEventModifierFlagOption NSAlternateKeyMask
  67. #define NSEventTypeFlagsChanged NSFlagsChanged
  68. #define NSEventTypeKeyUp NSKeyUp
  69. #define NSEventTypeKeyDown NSKeyDown
  70. #define NSEventTypeMouseMoved NSMouseMoved
  71. #define NSEventTypeLeftMouseDown NSLeftMouseDown
  72. #define NSEventTypeRightMouseDown NSRightMouseDown
  73. #define NSEventTypeOtherMouseDown NSOtherMouseDown
  74. #define NSEventTypeLeftMouseDragged NSLeftMouseDragged
  75. #define NSEventTypeRightMouseDragged NSRightMouseDragged
  76. #define NSEventTypeOtherMouseDragged NSOtherMouseDragged
  77. #define NSEventTypeLeftMouseUp NSLeftMouseUp
  78. #define NSEventTypeRightMouseUp NSRightMouseUp
  79. #define NSEventTypeOtherMouseUp NSOtherMouseUp
  80. #define NSEventTypeScrollWheel NSScrollWheel
  81. #define NSTextAlignmentCenter NSCenterTextAlignment
  82. #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
  83. #define NSWindowStyleMaskClosable NSClosableWindowMask
  84. #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
  85. #define NSWindowStyleMaskTitled NSTitledWindowMask
  86. #endif
  87. /* 10.13 deprecates NSFileHandlingPanelOKButton in favour of
  88. * NSModalResponseOK, which was introduced in 10.9. Define
  89. * it for older versions.
  90. */
  91. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
  92. #define NSModalResponseOK NSFileHandlingPanelOKButton
  93. #endif
  94. /* 10.14 deprecates NSOnState and NSOffState in favor of
  95. * NSControlStateValueOn/Off, which were introduced in 10.13.
  96. * Define for older versions
  97. */
  98. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
  99. #define NSControlStateValueOn NSOnState
  100. #define NSControlStateValueOff NSOffState
  101. #endif
  102. //#define DEBUG
  103. #ifdef DEBUG
  104. #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
  105. #else
  106. #define COCOA_DEBUG(...) ((void) 0)
  107. #endif
  108. #define cgrect(nsrect) (*(CGRect *)&(nsrect))
  109. typedef struct {
  110. int width;
  111. int height;
  112. int bitsPerComponent;
  113. int bitsPerPixel;
  114. } QEMUScreen;
  115. NSWindow *normalWindow, *about_window;
  116. static DisplayChangeListener *dcl;
  117. static int last_buttons;
  118. int gArgc;
  119. char **gArgv;
  120. bool stretch_video;
  121. NSTextField *pauseLabel;
  122. NSArray * supportedImageFileTypes;
  123. static QemuSemaphore display_init_sem;
  124. static QemuSemaphore app_started_sem;
  125. static bool allow_events;
  126. // Utility functions to run specified code block with iothread lock held
  127. typedef void (^CodeBlock)(void);
  128. typedef bool (^BoolCodeBlock)(void);
  129. static void with_iothread_lock(CodeBlock block)
  130. {
  131. bool locked = qemu_mutex_iothread_locked();
  132. if (!locked) {
  133. qemu_mutex_lock_iothread();
  134. }
  135. block();
  136. if (!locked) {
  137. qemu_mutex_unlock_iothread();
  138. }
  139. }
  140. static bool bool_with_iothread_lock(BoolCodeBlock block)
  141. {
  142. bool locked = qemu_mutex_iothread_locked();
  143. bool val;
  144. if (!locked) {
  145. qemu_mutex_lock_iothread();
  146. }
  147. val = block();
  148. if (!locked) {
  149. qemu_mutex_unlock_iothread();
  150. }
  151. return val;
  152. }
  153. // Mac to QKeyCode conversion
  154. const int mac_to_qkeycode_map[] = {
  155. [kVK_ANSI_A] = Q_KEY_CODE_A,
  156. [kVK_ANSI_B] = Q_KEY_CODE_B,
  157. [kVK_ANSI_C] = Q_KEY_CODE_C,
  158. [kVK_ANSI_D] = Q_KEY_CODE_D,
  159. [kVK_ANSI_E] = Q_KEY_CODE_E,
  160. [kVK_ANSI_F] = Q_KEY_CODE_F,
  161. [kVK_ANSI_G] = Q_KEY_CODE_G,
  162. [kVK_ANSI_H] = Q_KEY_CODE_H,
  163. [kVK_ANSI_I] = Q_KEY_CODE_I,
  164. [kVK_ANSI_J] = Q_KEY_CODE_J,
  165. [kVK_ANSI_K] = Q_KEY_CODE_K,
  166. [kVK_ANSI_L] = Q_KEY_CODE_L,
  167. [kVK_ANSI_M] = Q_KEY_CODE_M,
  168. [kVK_ANSI_N] = Q_KEY_CODE_N,
  169. [kVK_ANSI_O] = Q_KEY_CODE_O,
  170. [kVK_ANSI_P] = Q_KEY_CODE_P,
  171. [kVK_ANSI_Q] = Q_KEY_CODE_Q,
  172. [kVK_ANSI_R] = Q_KEY_CODE_R,
  173. [kVK_ANSI_S] = Q_KEY_CODE_S,
  174. [kVK_ANSI_T] = Q_KEY_CODE_T,
  175. [kVK_ANSI_U] = Q_KEY_CODE_U,
  176. [kVK_ANSI_V] = Q_KEY_CODE_V,
  177. [kVK_ANSI_W] = Q_KEY_CODE_W,
  178. [kVK_ANSI_X] = Q_KEY_CODE_X,
  179. [kVK_ANSI_Y] = Q_KEY_CODE_Y,
  180. [kVK_ANSI_Z] = Q_KEY_CODE_Z,
  181. [kVK_ANSI_0] = Q_KEY_CODE_0,
  182. [kVK_ANSI_1] = Q_KEY_CODE_1,
  183. [kVK_ANSI_2] = Q_KEY_CODE_2,
  184. [kVK_ANSI_3] = Q_KEY_CODE_3,
  185. [kVK_ANSI_4] = Q_KEY_CODE_4,
  186. [kVK_ANSI_5] = Q_KEY_CODE_5,
  187. [kVK_ANSI_6] = Q_KEY_CODE_6,
  188. [kVK_ANSI_7] = Q_KEY_CODE_7,
  189. [kVK_ANSI_8] = Q_KEY_CODE_8,
  190. [kVK_ANSI_9] = Q_KEY_CODE_9,
  191. [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
  192. [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
  193. [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
  194. [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
  195. [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
  196. [kVK_Tab] = Q_KEY_CODE_TAB,
  197. [kVK_Return] = Q_KEY_CODE_RET,
  198. [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
  199. [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
  200. [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
  201. [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
  202. [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
  203. [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
  204. [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
  205. [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
  206. [kVK_Shift] = Q_KEY_CODE_SHIFT,
  207. [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
  208. [kVK_Control] = Q_KEY_CODE_CTRL,
  209. [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
  210. [kVK_Option] = Q_KEY_CODE_ALT,
  211. [kVK_RightOption] = Q_KEY_CODE_ALT_R,
  212. [kVK_Command] = Q_KEY_CODE_META_L,
  213. [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
  214. [kVK_Space] = Q_KEY_CODE_SPC,
  215. [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
  216. [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
  217. [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
  218. [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
  219. [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
  220. [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
  221. [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
  222. [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
  223. [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
  224. [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
  225. [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
  226. [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
  227. [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
  228. [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
  229. [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
  230. [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
  231. [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
  232. [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
  233. [kVK_UpArrow] = Q_KEY_CODE_UP,
  234. [kVK_DownArrow] = Q_KEY_CODE_DOWN,
  235. [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
  236. [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
  237. [kVK_Help] = Q_KEY_CODE_INSERT,
  238. [kVK_Home] = Q_KEY_CODE_HOME,
  239. [kVK_PageUp] = Q_KEY_CODE_PGUP,
  240. [kVK_PageDown] = Q_KEY_CODE_PGDN,
  241. [kVK_End] = Q_KEY_CODE_END,
  242. [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
  243. [kVK_Escape] = Q_KEY_CODE_ESC,
  244. /* The Power key can't be used directly because the operating system uses
  245. * it. This key can be emulated by using it in place of another key such as
  246. * F1. Don't forget to disable the real key binding.
  247. */
  248. /* [kVK_F1] = Q_KEY_CODE_POWER, */
  249. [kVK_F1] = Q_KEY_CODE_F1,
  250. [kVK_F2] = Q_KEY_CODE_F2,
  251. [kVK_F3] = Q_KEY_CODE_F3,
  252. [kVK_F4] = Q_KEY_CODE_F4,
  253. [kVK_F5] = Q_KEY_CODE_F5,
  254. [kVK_F6] = Q_KEY_CODE_F6,
  255. [kVK_F7] = Q_KEY_CODE_F7,
  256. [kVK_F8] = Q_KEY_CODE_F8,
  257. [kVK_F9] = Q_KEY_CODE_F9,
  258. [kVK_F10] = Q_KEY_CODE_F10,
  259. [kVK_F11] = Q_KEY_CODE_F11,
  260. [kVK_F12] = Q_KEY_CODE_F12,
  261. [kVK_F13] = Q_KEY_CODE_PRINT,
  262. [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
  263. [kVK_F15] = Q_KEY_CODE_PAUSE,
  264. /*
  265. * The eject and volume keys can't be used here because they are handled at
  266. * a lower level than what an Application can see.
  267. */
  268. };
  269. static int cocoa_keycode_to_qemu(int keycode)
  270. {
  271. if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
  272. fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
  273. return 0;
  274. }
  275. return mac_to_qkeycode_map[keycode];
  276. }
  277. /* Displays an alert dialog box with the specified message */
  278. static void QEMU_Alert(NSString *message)
  279. {
  280. NSAlert *alert;
  281. alert = [NSAlert new];
  282. [alert setMessageText: message];
  283. [alert runModal];
  284. }
  285. /* Handles any errors that happen with a device transaction */
  286. static void handleAnyDeviceErrors(Error * err)
  287. {
  288. if (err) {
  289. QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
  290. encoding: NSASCIIStringEncoding]);
  291. error_free(err);
  292. }
  293. }
  294. /*
  295. ------------------------------------------------------
  296. QemuCocoaView
  297. ------------------------------------------------------
  298. */
  299. @interface QemuCocoaView : NSView
  300. {
  301. QEMUScreen screen;
  302. NSWindow *fullScreenWindow;
  303. float cx,cy,cw,ch,cdx,cdy;
  304. CGDataProviderRef dataProviderRef;
  305. pixman_image_t *pixman_image;
  306. BOOL modifiers_state[256];
  307. BOOL isMouseGrabbed;
  308. BOOL isFullscreen;
  309. BOOL isAbsoluteEnabled;
  310. BOOL isMouseDeassociated;
  311. }
  312. - (void) switchSurface:(pixman_image_t *)image;
  313. - (void) grabMouse;
  314. - (void) ungrabMouse;
  315. - (void) toggleFullScreen:(id)sender;
  316. - (void) handleMonitorInput:(NSEvent *)event;
  317. - (bool) handleEvent:(NSEvent *)event;
  318. - (bool) handleEventLocked:(NSEvent *)event;
  319. - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
  320. /* The state surrounding mouse grabbing is potentially confusing.
  321. * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
  322. * pointing device an absolute-position one?"], but is only updated on
  323. * next refresh.
  324. * isMouseGrabbed tracks whether GUI events are directed to the guest;
  325. * it controls whether special keys like Cmd get sent to the guest,
  326. * and whether we capture the mouse when in non-absolute mode.
  327. * isMouseDeassociated tracks whether we've told MacOSX to disassociate
  328. * the mouse and mouse cursor position by calling
  329. * CGAssociateMouseAndMouseCursorPosition(FALSE)
  330. * (which basically happens if we grab in non-absolute mode).
  331. */
  332. - (BOOL) isMouseGrabbed;
  333. - (BOOL) isAbsoluteEnabled;
  334. - (BOOL) isMouseDeassociated;
  335. - (float) cdx;
  336. - (float) cdy;
  337. - (QEMUScreen) gscreen;
  338. - (void) raiseAllKeys;
  339. @end
  340. QemuCocoaView *cocoaView;
  341. @implementation QemuCocoaView
  342. - (id)initWithFrame:(NSRect)frameRect
  343. {
  344. COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
  345. self = [super initWithFrame:frameRect];
  346. if (self) {
  347. screen.bitsPerComponent = 8;
  348. screen.bitsPerPixel = 32;
  349. screen.width = frameRect.size.width;
  350. screen.height = frameRect.size.height;
  351. }
  352. return self;
  353. }
  354. - (void) dealloc
  355. {
  356. COCOA_DEBUG("QemuCocoaView: dealloc\n");
  357. if (dataProviderRef) {
  358. CGDataProviderRelease(dataProviderRef);
  359. pixman_image_unref(pixman_image);
  360. }
  361. [super dealloc];
  362. }
  363. - (BOOL) isOpaque
  364. {
  365. return YES;
  366. }
  367. - (BOOL) screenContainsPoint:(NSPoint) p
  368. {
  369. return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
  370. }
  371. /* Get location of event and convert to virtual screen coordinate */
  372. - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
  373. {
  374. NSWindow *eventWindow = [ev window];
  375. // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
  376. CGRect r = CGRectZero;
  377. r.origin = [ev locationInWindow];
  378. if (!eventWindow) {
  379. if (!isFullscreen) {
  380. return [[self window] convertRectFromScreen:r].origin;
  381. } else {
  382. CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
  383. CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
  384. if (stretch_video) {
  385. loc.x /= cdx;
  386. loc.y /= cdy;
  387. }
  388. return loc;
  389. }
  390. } else if ([[self window] isEqual:eventWindow]) {
  391. if (!isFullscreen) {
  392. return r.origin;
  393. } else {
  394. CGPoint loc = [self convertPoint:r.origin fromView:nil];
  395. if (stretch_video) {
  396. loc.x /= cdx;
  397. loc.y /= cdy;
  398. }
  399. return loc;
  400. }
  401. } else {
  402. return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
  403. }
  404. }
  405. - (void) hideCursor
  406. {
  407. if (!cursor_hide) {
  408. return;
  409. }
  410. [NSCursor hide];
  411. }
  412. - (void) unhideCursor
  413. {
  414. if (!cursor_hide) {
  415. return;
  416. }
  417. [NSCursor unhide];
  418. }
  419. - (void) drawRect:(NSRect) rect
  420. {
  421. COCOA_DEBUG("QemuCocoaView: drawRect\n");
  422. // get CoreGraphic context
  423. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
  424. CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
  425. #else
  426. CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
  427. #endif
  428. CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
  429. CGContextSetShouldAntialias (viewContextRef, NO);
  430. // draw screen bitmap directly to Core Graphics context
  431. if (!dataProviderRef) {
  432. // Draw request before any guest device has set up a framebuffer:
  433. // just draw an opaque black rectangle
  434. CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
  435. CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
  436. } else {
  437. CGImageRef imageRef = CGImageCreate(
  438. screen.width, //width
  439. screen.height, //height
  440. screen.bitsPerComponent, //bitsPerComponent
  441. screen.bitsPerPixel, //bitsPerPixel
  442. (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
  443. #ifdef __LITTLE_ENDIAN__
  444. CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
  445. kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
  446. #else
  447. CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
  448. kCGImageAlphaNoneSkipFirst, //bitmapInfo
  449. #endif
  450. dataProviderRef, //provider
  451. NULL, //decode
  452. 0, //interpolate
  453. kCGRenderingIntentDefault //intent
  454. );
  455. // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
  456. const NSRect *rectList;
  457. NSInteger rectCount;
  458. int i;
  459. CGImageRef clipImageRef;
  460. CGRect clipRect;
  461. [self getRectsBeingDrawn:&rectList count:&rectCount];
  462. for (i = 0; i < rectCount; i++) {
  463. clipRect.origin.x = rectList[i].origin.x / cdx;
  464. clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
  465. clipRect.size.width = rectList[i].size.width / cdx;
  466. clipRect.size.height = rectList[i].size.height / cdy;
  467. clipImageRef = CGImageCreateWithImageInRect(
  468. imageRef,
  469. clipRect
  470. );
  471. CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
  472. CGImageRelease (clipImageRef);
  473. }
  474. CGImageRelease (imageRef);
  475. }
  476. }
  477. - (void) setContentDimensions
  478. {
  479. COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
  480. if (isFullscreen) {
  481. cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
  482. cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
  483. /* stretches video, but keeps same aspect ratio */
  484. if (stretch_video == true) {
  485. /* use smallest stretch value - prevents clipping on sides */
  486. if (MIN(cdx, cdy) == cdx) {
  487. cdy = cdx;
  488. } else {
  489. cdx = cdy;
  490. }
  491. } else { /* No stretching */
  492. cdx = cdy = 1;
  493. }
  494. cw = screen.width * cdx;
  495. ch = screen.height * cdy;
  496. cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
  497. cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
  498. } else {
  499. cx = 0;
  500. cy = 0;
  501. cw = screen.width;
  502. ch = screen.height;
  503. cdx = 1.0;
  504. cdy = 1.0;
  505. }
  506. }
  507. - (void) switchSurface:(pixman_image_t *)image
  508. {
  509. COCOA_DEBUG("QemuCocoaView: switchSurface\n");
  510. int w = pixman_image_get_width(image);
  511. int h = pixman_image_get_height(image);
  512. pixman_format_code_t image_format = pixman_image_get_format(image);
  513. /* cdx == 0 means this is our very first surface, in which case we need
  514. * to recalculate the content dimensions even if it happens to be the size
  515. * of the initial empty window.
  516. */
  517. bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
  518. int oldh = screen.height;
  519. if (isResize) {
  520. // Resize before we trigger the redraw, or we'll redraw at the wrong size
  521. COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
  522. screen.width = w;
  523. screen.height = h;
  524. [self setContentDimensions];
  525. [self setFrame:NSMakeRect(cx, cy, cw, ch)];
  526. }
  527. // update screenBuffer
  528. if (dataProviderRef) {
  529. CGDataProviderRelease(dataProviderRef);
  530. pixman_image_unref(pixman_image);
  531. }
  532. //sync host window color space with guests
  533. screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
  534. screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
  535. pixman_image = image;
  536. dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
  537. // update windows
  538. if (isFullscreen) {
  539. [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
  540. [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
  541. } else {
  542. if (qemu_name)
  543. [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
  544. [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
  545. }
  546. if (isResize) {
  547. [normalWindow center];
  548. }
  549. }
  550. - (void) toggleFullScreen:(id)sender
  551. {
  552. COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
  553. if (isFullscreen) { // switch from fullscreen to desktop
  554. isFullscreen = FALSE;
  555. [self ungrabMouse];
  556. [self setContentDimensions];
  557. if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
  558. [self exitFullScreenModeWithOptions:nil];
  559. } else {
  560. [fullScreenWindow close];
  561. [normalWindow setContentView: self];
  562. [normalWindow makeKeyAndOrderFront: self];
  563. [NSMenu setMenuBarVisible:YES];
  564. }
  565. } else { // switch from desktop to fullscreen
  566. isFullscreen = TRUE;
  567. [normalWindow orderOut: nil]; /* Hide the window */
  568. [self grabMouse];
  569. [self setContentDimensions];
  570. if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
  571. [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
  572. [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
  573. [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
  574. nil]];
  575. } else {
  576. [NSMenu setMenuBarVisible:NO];
  577. fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
  578. styleMask:NSWindowStyleMaskBorderless
  579. backing:NSBackingStoreBuffered
  580. defer:NO];
  581. [fullScreenWindow setAcceptsMouseMovedEvents: YES];
  582. [fullScreenWindow setHasShadow:NO];
  583. [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
  584. [self setFrame:NSMakeRect(cx, cy, cw, ch)];
  585. [[fullScreenWindow contentView] addSubview: self];
  586. [fullScreenWindow makeKeyAndOrderFront:self];
  587. }
  588. }
  589. }
  590. - (void) toggleModifier: (int)keycode {
  591. // Toggle the stored state.
  592. modifiers_state[keycode] = !modifiers_state[keycode];
  593. // Send a keyup or keydown depending on the state.
  594. qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
  595. }
  596. - (void) toggleStatefulModifier: (int)keycode {
  597. // Toggle the stored state.
  598. modifiers_state[keycode] = !modifiers_state[keycode];
  599. // Generate keydown and keyup.
  600. qemu_input_event_send_key_qcode(dcl->con, keycode, true);
  601. qemu_input_event_send_key_qcode(dcl->con, keycode, false);
  602. }
  603. // Does the work of sending input to the monitor
  604. - (void) handleMonitorInput:(NSEvent *)event
  605. {
  606. int keysym = 0;
  607. int control_key = 0;
  608. // if the control key is down
  609. if ([event modifierFlags] & NSEventModifierFlagControl) {
  610. control_key = 1;
  611. }
  612. /* translates Macintosh keycodes to QEMU's keysym */
  613. int without_control_translation[] = {
  614. [0 ... 0xff] = 0, // invalid key
  615. [kVK_UpArrow] = QEMU_KEY_UP,
  616. [kVK_DownArrow] = QEMU_KEY_DOWN,
  617. [kVK_RightArrow] = QEMU_KEY_RIGHT,
  618. [kVK_LeftArrow] = QEMU_KEY_LEFT,
  619. [kVK_Home] = QEMU_KEY_HOME,
  620. [kVK_End] = QEMU_KEY_END,
  621. [kVK_PageUp] = QEMU_KEY_PAGEUP,
  622. [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
  623. [kVK_ForwardDelete] = QEMU_KEY_DELETE,
  624. [kVK_Delete] = QEMU_KEY_BACKSPACE,
  625. };
  626. int with_control_translation[] = {
  627. [0 ... 0xff] = 0, // invalid key
  628. [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
  629. [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
  630. [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
  631. [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
  632. [kVK_Home] = QEMU_KEY_CTRL_HOME,
  633. [kVK_End] = QEMU_KEY_CTRL_END,
  634. [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
  635. [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
  636. };
  637. if (control_key != 0) { /* If the control key is being used */
  638. if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
  639. keysym = with_control_translation[[event keyCode]];
  640. }
  641. } else {
  642. if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
  643. keysym = without_control_translation[[event keyCode]];
  644. }
  645. }
  646. // if not a key that needs translating
  647. if (keysym == 0) {
  648. NSString *ks = [event characters];
  649. if ([ks length] > 0) {
  650. keysym = [ks characterAtIndex:0];
  651. }
  652. }
  653. if (keysym) {
  654. kbd_put_keysym(keysym);
  655. }
  656. }
  657. - (bool) handleEvent:(NSEvent *)event
  658. {
  659. if(!allow_events) {
  660. /*
  661. * Just let OSX have all events that arrive before
  662. * applicationDidFinishLaunching.
  663. * This avoids a deadlock on the iothread lock, which cocoa_display_init()
  664. * will not drop until after the app_started_sem is posted. (In theory
  665. * there should not be any such events, but OSX Catalina now emits some.)
  666. */
  667. return false;
  668. }
  669. return bool_with_iothread_lock(^{
  670. return [self handleEventLocked:event];
  671. });
  672. }
  673. - (bool) handleEventLocked:(NSEvent *)event
  674. {
  675. /* Return true if we handled the event, false if it should be given to OSX */
  676. COCOA_DEBUG("QemuCocoaView: handleEvent\n");
  677. int buttons = 0;
  678. int keycode = 0;
  679. bool mouse_event = false;
  680. static bool switched_to_fullscreen = false;
  681. // Location of event in virtual screen coordinates
  682. NSPoint p = [self screenLocationOfEvent:event];
  683. switch ([event type]) {
  684. case NSEventTypeFlagsChanged:
  685. if ([event keyCode] == 0) {
  686. // When the Cocoa keyCode is zero that means keys should be
  687. // synthesized based on the values in in the eventModifiers
  688. // bitmask.
  689. if (qemu_console_is_graphic(NULL)) {
  690. NSUInteger modifiers = [event modifierFlags];
  691. if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
  692. [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
  693. }
  694. if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
  695. [self toggleModifier:Q_KEY_CODE_SHIFT];
  696. }
  697. if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
  698. [self toggleModifier:Q_KEY_CODE_CTRL];
  699. }
  700. if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
  701. [self toggleModifier:Q_KEY_CODE_ALT];
  702. }
  703. if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
  704. [self toggleModifier:Q_KEY_CODE_META_L];
  705. }
  706. }
  707. } else {
  708. keycode = cocoa_keycode_to_qemu([event keyCode]);
  709. }
  710. if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
  711. && !isMouseGrabbed) {
  712. /* Don't pass command key changes to guest unless mouse is grabbed */
  713. keycode = 0;
  714. }
  715. if (keycode) {
  716. // emulate caps lock and num lock keydown and keyup
  717. if (keycode == Q_KEY_CODE_CAPS_LOCK ||
  718. keycode == Q_KEY_CODE_NUM_LOCK) {
  719. [self toggleStatefulModifier:keycode];
  720. } else if (qemu_console_is_graphic(NULL)) {
  721. if (switched_to_fullscreen) {
  722. switched_to_fullscreen = false;
  723. } else {
  724. [self toggleModifier:keycode];
  725. }
  726. }
  727. }
  728. break;
  729. case NSEventTypeKeyDown:
  730. keycode = cocoa_keycode_to_qemu([event keyCode]);
  731. // forward command key combos to the host UI unless the mouse is grabbed
  732. if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
  733. /*
  734. * Prevent the command key from being stuck down in the guest
  735. * when using Command-F to switch to full screen mode.
  736. */
  737. if (keycode == Q_KEY_CODE_F) {
  738. switched_to_fullscreen = true;
  739. }
  740. return false;
  741. }
  742. // default
  743. // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
  744. if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
  745. NSString *keychar = [event charactersIgnoringModifiers];
  746. if ([keychar length] == 1) {
  747. char key = [keychar characterAtIndex:0];
  748. switch (key) {
  749. // enable graphic console
  750. case '1' ... '9':
  751. console_select(key - '0' - 1); /* ascii math */
  752. return true;
  753. // release the mouse grab
  754. case 'g':
  755. [self ungrabMouse];
  756. return true;
  757. }
  758. }
  759. }
  760. if (qemu_console_is_graphic(NULL)) {
  761. qemu_input_event_send_key_qcode(dcl->con, keycode, true);
  762. } else {
  763. [self handleMonitorInput: event];
  764. }
  765. break;
  766. case NSEventTypeKeyUp:
  767. keycode = cocoa_keycode_to_qemu([event keyCode]);
  768. // don't pass the guest a spurious key-up if we treated this
  769. // command-key combo as a host UI action
  770. if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
  771. return true;
  772. }
  773. if (qemu_console_is_graphic(NULL)) {
  774. qemu_input_event_send_key_qcode(dcl->con, keycode, false);
  775. }
  776. break;
  777. case NSEventTypeMouseMoved:
  778. if (isAbsoluteEnabled) {
  779. // Cursor re-entered into a window might generate events bound to screen coordinates
  780. // and `nil` window property, and in full screen mode, current window might not be
  781. // key window, where event location alone should suffice.
  782. if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
  783. if (isMouseGrabbed) {
  784. [self ungrabMouse];
  785. }
  786. } else {
  787. if (!isMouseGrabbed) {
  788. [self grabMouse];
  789. }
  790. }
  791. }
  792. mouse_event = true;
  793. break;
  794. case NSEventTypeLeftMouseDown:
  795. if ([event modifierFlags] & NSEventModifierFlagCommand) {
  796. buttons |= MOUSE_EVENT_RBUTTON;
  797. } else {
  798. buttons |= MOUSE_EVENT_LBUTTON;
  799. }
  800. mouse_event = true;
  801. break;
  802. case NSEventTypeRightMouseDown:
  803. buttons |= MOUSE_EVENT_RBUTTON;
  804. mouse_event = true;
  805. break;
  806. case NSEventTypeOtherMouseDown:
  807. buttons |= MOUSE_EVENT_MBUTTON;
  808. mouse_event = true;
  809. break;
  810. case NSEventTypeLeftMouseDragged:
  811. if ([event modifierFlags] & NSEventModifierFlagCommand) {
  812. buttons |= MOUSE_EVENT_RBUTTON;
  813. } else {
  814. buttons |= MOUSE_EVENT_LBUTTON;
  815. }
  816. mouse_event = true;
  817. break;
  818. case NSEventTypeRightMouseDragged:
  819. buttons |= MOUSE_EVENT_RBUTTON;
  820. mouse_event = true;
  821. break;
  822. case NSEventTypeOtherMouseDragged:
  823. buttons |= MOUSE_EVENT_MBUTTON;
  824. mouse_event = true;
  825. break;
  826. case NSEventTypeLeftMouseUp:
  827. mouse_event = true;
  828. if (!isMouseGrabbed && [self screenContainsPoint:p]) {
  829. /*
  830. * In fullscreen mode, the window of cocoaView may not be the
  831. * key window, therefore the position relative to the virtual
  832. * screen alone will be sufficient.
  833. */
  834. if(isFullscreen || [[self window] isKeyWindow]) {
  835. [self grabMouse];
  836. }
  837. }
  838. break;
  839. case NSEventTypeRightMouseUp:
  840. mouse_event = true;
  841. break;
  842. case NSEventTypeOtherMouseUp:
  843. mouse_event = true;
  844. break;
  845. case NSEventTypeScrollWheel:
  846. /*
  847. * Send wheel events to the guest regardless of window focus.
  848. * This is in-line with standard Mac OS X UI behaviour.
  849. */
  850. /*
  851. * When deltaY is zero, it means that this scrolling event was
  852. * either horizontal, or so fine that it only appears in
  853. * scrollingDeltaY. So we drop the event.
  854. */
  855. if ([event deltaY] != 0) {
  856. /* Determine if this is a scroll up or scroll down event */
  857. buttons = ([event deltaY] > 0) ?
  858. INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
  859. qemu_input_queue_btn(dcl->con, buttons, true);
  860. qemu_input_event_sync();
  861. qemu_input_queue_btn(dcl->con, buttons, false);
  862. qemu_input_event_sync();
  863. }
  864. /*
  865. * Since deltaY also reports scroll wheel events we prevent mouse
  866. * movement code from executing.
  867. */
  868. mouse_event = false;
  869. break;
  870. default:
  871. return false;
  872. }
  873. if (mouse_event) {
  874. /* Don't send button events to the guest unless we've got a
  875. * mouse grab or window focus. If we have neither then this event
  876. * is the user clicking on the background window to activate and
  877. * bring us to the front, which will be done by the sendEvent
  878. * call below. We definitely don't want to pass that click through
  879. * to the guest.
  880. */
  881. if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
  882. (last_buttons != buttons)) {
  883. static uint32_t bmap[INPUT_BUTTON__MAX] = {
  884. [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
  885. [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
  886. [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
  887. };
  888. qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
  889. last_buttons = buttons;
  890. }
  891. if (isMouseGrabbed) {
  892. if (isAbsoluteEnabled) {
  893. /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
  894. * The check on screenContainsPoint is to avoid sending out of range values for
  895. * clicks in the titlebar.
  896. */
  897. if ([self screenContainsPoint:p]) {
  898. qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
  899. qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
  900. }
  901. } else {
  902. qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
  903. qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
  904. }
  905. } else {
  906. return false;
  907. }
  908. qemu_input_event_sync();
  909. }
  910. return true;
  911. }
  912. - (void) grabMouse
  913. {
  914. COCOA_DEBUG("QemuCocoaView: grabMouse\n");
  915. if (!isFullscreen) {
  916. if (qemu_name)
  917. [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
  918. else
  919. [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
  920. }
  921. [self hideCursor];
  922. if (!isAbsoluteEnabled) {
  923. isMouseDeassociated = TRUE;
  924. CGAssociateMouseAndMouseCursorPosition(FALSE);
  925. }
  926. isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
  927. }
  928. - (void) ungrabMouse
  929. {
  930. COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
  931. if (!isFullscreen) {
  932. if (qemu_name)
  933. [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
  934. else
  935. [normalWindow setTitle:@"QEMU"];
  936. }
  937. [self unhideCursor];
  938. if (isMouseDeassociated) {
  939. CGAssociateMouseAndMouseCursorPosition(TRUE);
  940. isMouseDeassociated = FALSE;
  941. }
  942. isMouseGrabbed = FALSE;
  943. }
  944. - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
  945. - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
  946. - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
  947. - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
  948. - (float) cdx {return cdx;}
  949. - (float) cdy {return cdy;}
  950. - (QEMUScreen) gscreen {return screen;}
  951. /*
  952. * Makes the target think all down keys are being released.
  953. * This prevents a stuck key problem, since we will not see
  954. * key up events for those keys after we have lost focus.
  955. */
  956. - (void) raiseAllKeys
  957. {
  958. const int max_index = ARRAY_SIZE(modifiers_state);
  959. with_iothread_lock(^{
  960. int index;
  961. for (index = 0; index < max_index; index++) {
  962. if (modifiers_state[index]) {
  963. modifiers_state[index] = 0;
  964. qemu_input_event_send_key_qcode(dcl->con, index, false);
  965. }
  966. }
  967. });
  968. }
  969. @end
  970. /*
  971. ------------------------------------------------------
  972. QemuCocoaAppController
  973. ------------------------------------------------------
  974. */
  975. @interface QemuCocoaAppController : NSObject
  976. #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
  977. <NSWindowDelegate, NSApplicationDelegate>
  978. #endif
  979. {
  980. }
  981. - (void)doToggleFullScreen:(id)sender;
  982. - (void)toggleFullScreen:(id)sender;
  983. - (void)showQEMUDoc:(id)sender;
  984. - (void)zoomToFit:(id) sender;
  985. - (void)displayConsole:(id)sender;
  986. - (void)pauseQEMU:(id)sender;
  987. - (void)resumeQEMU:(id)sender;
  988. - (void)displayPause;
  989. - (void)removePause;
  990. - (void)restartQEMU:(id)sender;
  991. - (void)powerDownQEMU:(id)sender;
  992. - (void)ejectDeviceMedia:(id)sender;
  993. - (void)changeDeviceMedia:(id)sender;
  994. - (BOOL)verifyQuit;
  995. - (void)openDocumentation:(NSString *)filename;
  996. - (IBAction) do_about_menu_item: (id) sender;
  997. - (void)make_about_window;
  998. - (void)adjustSpeed:(id)sender;
  999. @end
  1000. @implementation QemuCocoaAppController
  1001. - (id) init
  1002. {
  1003. COCOA_DEBUG("QemuCocoaAppController: init\n");
  1004. self = [super init];
  1005. if (self) {
  1006. // create a view and add it to the window
  1007. cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
  1008. if(!cocoaView) {
  1009. fprintf(stderr, "(cocoa) can't create a view\n");
  1010. exit(1);
  1011. }
  1012. // create a window
  1013. normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
  1014. styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
  1015. backing:NSBackingStoreBuffered defer:NO];
  1016. if(!normalWindow) {
  1017. fprintf(stderr, "(cocoa) can't create window\n");
  1018. exit(1);
  1019. }
  1020. [normalWindow setAcceptsMouseMovedEvents:YES];
  1021. [normalWindow setTitle:@"QEMU"];
  1022. [normalWindow setContentView:cocoaView];
  1023. #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
  1024. [normalWindow useOptimizedDrawing:YES];
  1025. #endif
  1026. [normalWindow makeKeyAndOrderFront:self];
  1027. [normalWindow center];
  1028. [normalWindow setDelegate: self];
  1029. stretch_video = false;
  1030. /* Used for displaying pause on the screen */
  1031. pauseLabel = [NSTextField new];
  1032. [pauseLabel setBezeled:YES];
  1033. [pauseLabel setDrawsBackground:YES];
  1034. [pauseLabel setBackgroundColor: [NSColor whiteColor]];
  1035. [pauseLabel setEditable:NO];
  1036. [pauseLabel setSelectable:NO];
  1037. [pauseLabel setStringValue: @"Paused"];
  1038. [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
  1039. [pauseLabel setTextColor: [NSColor blackColor]];
  1040. [pauseLabel sizeToFit];
  1041. // set the supported image file types that can be opened
  1042. supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
  1043. @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
  1044. @"toast", nil];
  1045. [self make_about_window];
  1046. }
  1047. return self;
  1048. }
  1049. - (void) dealloc
  1050. {
  1051. COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
  1052. if (cocoaView)
  1053. [cocoaView release];
  1054. [super dealloc];
  1055. }
  1056. - (void)applicationDidFinishLaunching: (NSNotification *) note
  1057. {
  1058. COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
  1059. allow_events = true;
  1060. /* Tell cocoa_display_init to proceed */
  1061. qemu_sem_post(&app_started_sem);
  1062. }
  1063. - (void)applicationWillTerminate:(NSNotification *)aNotification
  1064. {
  1065. COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
  1066. qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
  1067. exit(0);
  1068. }
  1069. - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
  1070. {
  1071. return YES;
  1072. }
  1073. - (NSApplicationTerminateReply)applicationShouldTerminate:
  1074. (NSApplication *)sender
  1075. {
  1076. COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
  1077. return [self verifyQuit];
  1078. }
  1079. /* Called when the user clicks on a window's close button */
  1080. - (BOOL)windowShouldClose:(id)sender
  1081. {
  1082. COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
  1083. [NSApp terminate: sender];
  1084. /* If the user allows the application to quit then the call to
  1085. * NSApp terminate will never return. If we get here then the user
  1086. * cancelled the quit, so we should return NO to not permit the
  1087. * closing of this window.
  1088. */
  1089. return NO;
  1090. }
  1091. /* Called when QEMU goes into the background */
  1092. - (void) applicationWillResignActive: (NSNotification *)aNotification
  1093. {
  1094. COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
  1095. [cocoaView raiseAllKeys];
  1096. }
  1097. /* We abstract the method called by the Enter Fullscreen menu item
  1098. * because Mac OS 10.7 and higher disables it. This is because of the
  1099. * menu item's old selector's name toggleFullScreen:
  1100. */
  1101. - (void) doToggleFullScreen:(id)sender
  1102. {
  1103. [self toggleFullScreen:(id)sender];
  1104. }
  1105. - (void)toggleFullScreen:(id)sender
  1106. {
  1107. COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
  1108. [cocoaView toggleFullScreen:sender];
  1109. }
  1110. /* Tries to find then open the specified filename */
  1111. - (void) openDocumentation: (NSString *) filename
  1112. {
  1113. /* Where to look for local files */
  1114. NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
  1115. NSString *full_file_path;
  1116. /* iterate thru the possible paths until the file is found */
  1117. int index;
  1118. for (index = 0; index < ARRAY_SIZE(path_array); index++) {
  1119. full_file_path = [[NSBundle mainBundle] executablePath];
  1120. full_file_path = [full_file_path stringByDeletingLastPathComponent];
  1121. full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
  1122. path_array[index], filename];
  1123. if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
  1124. return;
  1125. }
  1126. }
  1127. /* If none of the paths opened a file */
  1128. NSBeep();
  1129. QEMU_Alert(@"Failed to open file");
  1130. }
  1131. - (void)showQEMUDoc:(id)sender
  1132. {
  1133. COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
  1134. [self openDocumentation: @"qemu-doc.html"];
  1135. }
  1136. /* Stretches video to fit host monitor size */
  1137. - (void)zoomToFit:(id) sender
  1138. {
  1139. stretch_video = !stretch_video;
  1140. if (stretch_video == true) {
  1141. [sender setState: NSControlStateValueOn];
  1142. } else {
  1143. [sender setState: NSControlStateValueOff];
  1144. }
  1145. }
  1146. /* Displays the console on the screen */
  1147. - (void)displayConsole:(id)sender
  1148. {
  1149. console_select([sender tag]);
  1150. }
  1151. /* Pause the guest */
  1152. - (void)pauseQEMU:(id)sender
  1153. {
  1154. with_iothread_lock(^{
  1155. qmp_stop(NULL);
  1156. });
  1157. [sender setEnabled: NO];
  1158. [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
  1159. [self displayPause];
  1160. }
  1161. /* Resume running the guest operating system */
  1162. - (void)resumeQEMU:(id) sender
  1163. {
  1164. with_iothread_lock(^{
  1165. qmp_cont(NULL);
  1166. });
  1167. [sender setEnabled: NO];
  1168. [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
  1169. [self removePause];
  1170. }
  1171. /* Displays the word pause on the screen */
  1172. - (void)displayPause
  1173. {
  1174. /* Coordinates have to be calculated each time because the window can change its size */
  1175. int xCoord, yCoord, width, height;
  1176. xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
  1177. yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
  1178. width = [pauseLabel frame].size.width;
  1179. height = [pauseLabel frame].size.height;
  1180. [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
  1181. [cocoaView addSubview: pauseLabel];
  1182. }
  1183. /* Removes the word pause from the screen */
  1184. - (void)removePause
  1185. {
  1186. [pauseLabel removeFromSuperview];
  1187. }
  1188. /* Restarts QEMU */
  1189. - (void)restartQEMU:(id)sender
  1190. {
  1191. with_iothread_lock(^{
  1192. qmp_system_reset(NULL);
  1193. });
  1194. }
  1195. /* Powers down QEMU */
  1196. - (void)powerDownQEMU:(id)sender
  1197. {
  1198. with_iothread_lock(^{
  1199. qmp_system_powerdown(NULL);
  1200. });
  1201. }
  1202. /* Ejects the media.
  1203. * Uses sender's tag to figure out the device to eject.
  1204. */
  1205. - (void)ejectDeviceMedia:(id)sender
  1206. {
  1207. NSString * drive;
  1208. drive = [sender representedObject];
  1209. if(drive == nil) {
  1210. NSBeep();
  1211. QEMU_Alert(@"Failed to find drive to eject!");
  1212. return;
  1213. }
  1214. __block Error *err = NULL;
  1215. with_iothread_lock(^{
  1216. qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
  1217. false, NULL, false, false, &err);
  1218. });
  1219. handleAnyDeviceErrors(err);
  1220. }
  1221. /* Displays a dialog box asking the user to select an image file to load.
  1222. * Uses sender's represented object value to figure out which drive to use.
  1223. */
  1224. - (void)changeDeviceMedia:(id)sender
  1225. {
  1226. /* Find the drive name */
  1227. NSString * drive;
  1228. drive = [sender representedObject];
  1229. if(drive == nil) {
  1230. NSBeep();
  1231. QEMU_Alert(@"Could not find drive!");
  1232. return;
  1233. }
  1234. /* Display the file open dialog */
  1235. NSOpenPanel * openPanel;
  1236. openPanel = [NSOpenPanel openPanel];
  1237. [openPanel setCanChooseFiles: YES];
  1238. [openPanel setAllowsMultipleSelection: NO];
  1239. [openPanel setAllowedFileTypes: supportedImageFileTypes];
  1240. if([openPanel runModal] == NSModalResponseOK) {
  1241. NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
  1242. if(file == nil) {
  1243. NSBeep();
  1244. QEMU_Alert(@"Failed to convert URL to file path!");
  1245. return;
  1246. }
  1247. __block Error *err = NULL;
  1248. with_iothread_lock(^{
  1249. qmp_blockdev_change_medium(true,
  1250. [drive cStringUsingEncoding:
  1251. NSASCIIStringEncoding],
  1252. false, NULL,
  1253. [file cStringUsingEncoding:
  1254. NSASCIIStringEncoding],
  1255. true, "raw",
  1256. false, 0,
  1257. &err);
  1258. });
  1259. handleAnyDeviceErrors(err);
  1260. }
  1261. }
  1262. /* Verifies if the user really wants to quit */
  1263. - (BOOL)verifyQuit
  1264. {
  1265. NSAlert *alert = [NSAlert new];
  1266. [alert autorelease];
  1267. [alert setMessageText: @"Are you sure you want to quit QEMU?"];
  1268. [alert addButtonWithTitle: @"Cancel"];
  1269. [alert addButtonWithTitle: @"Quit"];
  1270. if([alert runModal] == NSAlertSecondButtonReturn) {
  1271. return YES;
  1272. } else {
  1273. return NO;
  1274. }
  1275. }
  1276. /* The action method for the About menu item */
  1277. - (IBAction) do_about_menu_item: (id) sender
  1278. {
  1279. [about_window makeKeyAndOrderFront: nil];
  1280. }
  1281. /* Create and display the about dialog */
  1282. - (void)make_about_window
  1283. {
  1284. /* Make the window */
  1285. int x = 0, y = 0, about_width = 400, about_height = 200;
  1286. NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
  1287. about_window = [[NSWindow alloc] initWithContentRect:window_rect
  1288. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
  1289. NSWindowStyleMaskMiniaturizable
  1290. backing:NSBackingStoreBuffered
  1291. defer:NO];
  1292. [about_window setTitle: @"About"];
  1293. [about_window setReleasedWhenClosed: NO];
  1294. [about_window center];
  1295. NSView *superView = [about_window contentView];
  1296. /* Create the dimensions of the picture */
  1297. int picture_width = 80, picture_height = 80;
  1298. x = (about_width - picture_width)/2;
  1299. y = about_height - picture_height - 10;
  1300. NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
  1301. /* Get the path to the QEMU binary */
  1302. NSString *binary_name = [NSString stringWithCString: gArgv[0]
  1303. encoding: NSASCIIStringEncoding];
  1304. binary_name = [binary_name lastPathComponent];
  1305. NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
  1306. [[NSBundle mainBundle] bundlePath], binary_name];
  1307. /* Make the picture of QEMU */
  1308. NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
  1309. picture_rect];
  1310. NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
  1311. program_path];
  1312. [picture_view setImage: qemu_image];
  1313. [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
  1314. [superView addSubview: picture_view];
  1315. /* Make the name label */
  1316. x = 0;
  1317. y = y - 25;
  1318. int name_width = about_width, name_height = 20;
  1319. NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
  1320. NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
  1321. [name_label setEditable: NO];
  1322. [name_label setBezeled: NO];
  1323. [name_label setDrawsBackground: NO];
  1324. [name_label setAlignment: NSTextAlignmentCenter];
  1325. NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
  1326. encoding: NSASCIIStringEncoding];
  1327. qemu_name = [qemu_name lastPathComponent];
  1328. [name_label setStringValue: qemu_name];
  1329. [superView addSubview: name_label];
  1330. /* Set the version label's attributes */
  1331. x = 0;
  1332. y = 50;
  1333. int version_width = about_width, version_height = 20;
  1334. NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
  1335. NSTextField *version_label = [[NSTextField alloc] initWithFrame:
  1336. version_rect];
  1337. [version_label setEditable: NO];
  1338. [version_label setBezeled: NO];
  1339. [version_label setAlignment: NSTextAlignmentCenter];
  1340. [version_label setDrawsBackground: NO];
  1341. /* Create the version string*/
  1342. NSString *version_string;
  1343. version_string = [[NSString alloc] initWithFormat:
  1344. @"QEMU emulator version %s", QEMU_FULL_VERSION];
  1345. [version_label setStringValue: version_string];
  1346. [superView addSubview: version_label];
  1347. /* Make copyright label */
  1348. x = 0;
  1349. y = 35;
  1350. int copyright_width = about_width, copyright_height = 20;
  1351. NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
  1352. NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
  1353. copyright_rect];
  1354. [copyright_label setEditable: NO];
  1355. [copyright_label setBezeled: NO];
  1356. [copyright_label setDrawsBackground: NO];
  1357. [copyright_label setAlignment: NSTextAlignmentCenter];
  1358. [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
  1359. QEMU_COPYRIGHT]];
  1360. [superView addSubview: copyright_label];
  1361. }
  1362. /* Used by the Speed menu items */
  1363. - (void)adjustSpeed:(id)sender
  1364. {
  1365. int throttle_pct; /* throttle percentage */
  1366. NSMenu *menu;
  1367. menu = [sender menu];
  1368. if (menu != nil)
  1369. {
  1370. /* Unselect the currently selected item */
  1371. for (NSMenuItem *item in [menu itemArray]) {
  1372. if (item.state == NSControlStateValueOn) {
  1373. [item setState: NSControlStateValueOff];
  1374. break;
  1375. }
  1376. }
  1377. }
  1378. // check the menu item
  1379. [sender setState: NSControlStateValueOn];
  1380. // get the throttle percentage
  1381. throttle_pct = [sender tag];
  1382. with_iothread_lock(^{
  1383. cpu_throttle_set(throttle_pct);
  1384. });
  1385. COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
  1386. }
  1387. @end
  1388. @interface QemuApplication : NSApplication
  1389. @end
  1390. @implementation QemuApplication
  1391. - (void)sendEvent:(NSEvent *)event
  1392. {
  1393. COCOA_DEBUG("QemuApplication: sendEvent\n");
  1394. if (![cocoaView handleEvent:event]) {
  1395. [super sendEvent: event];
  1396. }
  1397. }
  1398. @end
  1399. static void create_initial_menus(void)
  1400. {
  1401. // Add menus
  1402. NSMenu *menu;
  1403. NSMenuItem *menuItem;
  1404. [NSApp setMainMenu:[[NSMenu alloc] init]];
  1405. // Application menu
  1406. menu = [[NSMenu alloc] initWithTitle:@""];
  1407. [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
  1408. [menu addItem:[NSMenuItem separatorItem]]; //Separator
  1409. [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
  1410. menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
  1411. [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
  1412. [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
  1413. [menu addItem:[NSMenuItem separatorItem]]; //Separator
  1414. [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
  1415. menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
  1416. [menuItem setSubmenu:menu];
  1417. [[NSApp mainMenu] addItem:menuItem];
  1418. [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
  1419. // Machine menu
  1420. menu = [[NSMenu alloc] initWithTitle: @"Machine"];
  1421. [menu setAutoenablesItems: NO];
  1422. [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
  1423. menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
  1424. [menu addItem: menuItem];
  1425. [menuItem setEnabled: NO];
  1426. [menu addItem: [NSMenuItem separatorItem]];
  1427. [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
  1428. [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
  1429. menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
  1430. [menuItem setSubmenu:menu];
  1431. [[NSApp mainMenu] addItem:menuItem];
  1432. // View menu
  1433. menu = [[NSMenu alloc] initWithTitle:@"View"];
  1434. [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
  1435. [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
  1436. menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
  1437. [menuItem setSubmenu:menu];
  1438. [[NSApp mainMenu] addItem:menuItem];
  1439. // Speed menu
  1440. menu = [[NSMenu alloc] initWithTitle:@"Speed"];
  1441. // Add the rest of the Speed menu items
  1442. int p, percentage, throttle_pct;
  1443. for (p = 10; p >= 0; p--)
  1444. {
  1445. percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
  1446. menuItem = [[[NSMenuItem alloc]
  1447. initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
  1448. if (percentage == 100) {
  1449. [menuItem setState: NSControlStateValueOn];
  1450. }
  1451. /* Calculate the throttle percentage */
  1452. throttle_pct = -1 * percentage + 100;
  1453. [menuItem setTag: throttle_pct];
  1454. [menu addItem: menuItem];
  1455. }
  1456. menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
  1457. [menuItem setSubmenu:menu];
  1458. [[NSApp mainMenu] addItem:menuItem];
  1459. // Window menu
  1460. menu = [[NSMenu alloc] initWithTitle:@"Window"];
  1461. [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
  1462. menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
  1463. [menuItem setSubmenu:menu];
  1464. [[NSApp mainMenu] addItem:menuItem];
  1465. [NSApp setWindowsMenu:menu];
  1466. // Help menu
  1467. menu = [[NSMenu alloc] initWithTitle:@"Help"];
  1468. [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
  1469. menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
  1470. [menuItem setSubmenu:menu];
  1471. [[NSApp mainMenu] addItem:menuItem];
  1472. }
  1473. /* Returns a name for a given console */
  1474. static NSString * getConsoleName(QemuConsole * console)
  1475. {
  1476. return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
  1477. }
  1478. /* Add an entry to the View menu for each console */
  1479. static void add_console_menu_entries(void)
  1480. {
  1481. NSMenu *menu;
  1482. NSMenuItem *menuItem;
  1483. int index = 0;
  1484. menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
  1485. [menu addItem:[NSMenuItem separatorItem]];
  1486. while (qemu_console_lookup_by_index(index) != NULL) {
  1487. menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
  1488. action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
  1489. [menuItem setTag: index];
  1490. [menu addItem: menuItem];
  1491. index++;
  1492. }
  1493. }
  1494. /* Make menu items for all removable devices.
  1495. * Each device is given an 'Eject' and 'Change' menu item.
  1496. */
  1497. static void addRemovableDevicesMenuItems(void)
  1498. {
  1499. NSMenu *menu;
  1500. NSMenuItem *menuItem;
  1501. BlockInfoList *currentDevice, *pointerToFree;
  1502. NSString *deviceName;
  1503. currentDevice = qmp_query_block(NULL);
  1504. pointerToFree = currentDevice;
  1505. if(currentDevice == NULL) {
  1506. NSBeep();
  1507. QEMU_Alert(@"Failed to query for block devices!");
  1508. return;
  1509. }
  1510. menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
  1511. // Add a separator between related groups of menu items
  1512. [menu addItem:[NSMenuItem separatorItem]];
  1513. // Set the attributes to the "Removable Media" menu item
  1514. NSString *titleString = @"Removable Media";
  1515. NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
  1516. NSColor *newColor = [NSColor blackColor];
  1517. NSFontManager *fontManager = [NSFontManager sharedFontManager];
  1518. NSFont *font = [fontManager fontWithFamily:@"Helvetica"
  1519. traits:NSBoldFontMask|NSItalicFontMask
  1520. weight:0
  1521. size:14];
  1522. [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
  1523. [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
  1524. [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
  1525. // Add the "Removable Media" menu item
  1526. menuItem = [NSMenuItem new];
  1527. [menuItem setAttributedTitle: attString];
  1528. [menuItem setEnabled: NO];
  1529. [menu addItem: menuItem];
  1530. /* Loop through all the block devices in the emulator */
  1531. while (currentDevice) {
  1532. deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
  1533. if(currentDevice->value->removable) {
  1534. menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
  1535. action: @selector(changeDeviceMedia:)
  1536. keyEquivalent: @""];
  1537. [menu addItem: menuItem];
  1538. [menuItem setRepresentedObject: deviceName];
  1539. [menuItem autorelease];
  1540. menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
  1541. action: @selector(ejectDeviceMedia:)
  1542. keyEquivalent: @""];
  1543. [menu addItem: menuItem];
  1544. [menuItem setRepresentedObject: deviceName];
  1545. [menuItem autorelease];
  1546. }
  1547. currentDevice = currentDevice->next;
  1548. }
  1549. qapi_free_BlockInfoList(pointerToFree);
  1550. }
  1551. /*
  1552. * The startup process for the OSX/Cocoa UI is complicated, because
  1553. * OSX insists that the UI runs on the initial main thread, and so we
  1554. * need to start a second thread which runs the vl.c qemu_main():
  1555. *
  1556. * Initial thread: 2nd thread:
  1557. * in main():
  1558. * create qemu-main thread
  1559. * wait on display_init semaphore
  1560. * call qemu_main()
  1561. * ...
  1562. * in cocoa_display_init():
  1563. * post the display_init semaphore
  1564. * wait on app_started semaphore
  1565. * create application, menus, etc
  1566. * enter OSX run loop
  1567. * in applicationDidFinishLaunching:
  1568. * post app_started semaphore
  1569. * tell main thread to fullscreen if needed
  1570. * [...]
  1571. * run qemu main-loop
  1572. *
  1573. * We do this in two stages so that we don't do the creation of the
  1574. * GUI application menus and so on for command line options like --help
  1575. * where we want to just print text to stdout and exit immediately.
  1576. */
  1577. static void *call_qemu_main(void *opaque)
  1578. {
  1579. int status;
  1580. COCOA_DEBUG("Second thread: calling qemu_main()\n");
  1581. status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
  1582. COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
  1583. exit(status);
  1584. }
  1585. int main (int argc, const char * argv[]) {
  1586. QemuThread thread;
  1587. COCOA_DEBUG("Entered main()\n");
  1588. gArgc = argc;
  1589. gArgv = (char **)argv;
  1590. qemu_sem_init(&display_init_sem, 0);
  1591. qemu_sem_init(&app_started_sem, 0);
  1592. qemu_thread_create(&thread, "qemu_main", call_qemu_main,
  1593. NULL, QEMU_THREAD_DETACHED);
  1594. COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
  1595. qemu_sem_wait(&display_init_sem);
  1596. COCOA_DEBUG("Main thread: initializing app\n");
  1597. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  1598. // Pull this console process up to being a fully-fledged graphical
  1599. // app with a menubar and Dock icon
  1600. ProcessSerialNumber psn = { 0, kCurrentProcess };
  1601. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  1602. [QemuApplication sharedApplication];
  1603. create_initial_menus();
  1604. /*
  1605. * Create the menu entries which depend on QEMU state (for consoles
  1606. * and removeable devices). These make calls back into QEMU functions,
  1607. * which is OK because at this point we know that the second thread
  1608. * holds the iothread lock and is synchronously waiting for us to
  1609. * finish.
  1610. */
  1611. add_console_menu_entries();
  1612. addRemovableDevicesMenuItems();
  1613. // Create an Application controller
  1614. QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
  1615. [NSApp setDelegate:appController];
  1616. // Start the main event loop
  1617. COCOA_DEBUG("Main thread: entering OSX run loop\n");
  1618. [NSApp run];
  1619. COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
  1620. [appController release];
  1621. [pool release];
  1622. return 0;
  1623. }
  1624. #pragma mark qemu
  1625. static void cocoa_update(DisplayChangeListener *dcl,
  1626. int x, int y, int w, int h)
  1627. {
  1628. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  1629. COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
  1630. dispatch_async(dispatch_get_main_queue(), ^{
  1631. NSRect rect;
  1632. if ([cocoaView cdx] == 1.0) {
  1633. rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
  1634. } else {
  1635. rect = NSMakeRect(
  1636. x * [cocoaView cdx],
  1637. ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
  1638. w * [cocoaView cdx],
  1639. h * [cocoaView cdy]);
  1640. }
  1641. [cocoaView setNeedsDisplayInRect:rect];
  1642. });
  1643. [pool release];
  1644. }
  1645. static void cocoa_switch(DisplayChangeListener *dcl,
  1646. DisplaySurface *surface)
  1647. {
  1648. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  1649. pixman_image_t *image = surface->image;
  1650. COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
  1651. // The DisplaySurface will be freed as soon as this callback returns.
  1652. // We take a reference to the underlying pixman image here so it does
  1653. // not disappear from under our feet; the switchSurface method will
  1654. // deref the old image when it is done with it.
  1655. pixman_image_ref(image);
  1656. dispatch_async(dispatch_get_main_queue(), ^{
  1657. [cocoaView switchSurface:image];
  1658. });
  1659. [pool release];
  1660. }
  1661. static void cocoa_refresh(DisplayChangeListener *dcl)
  1662. {
  1663. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  1664. COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
  1665. graphic_hw_update(NULL);
  1666. if (qemu_input_is_absolute()) {
  1667. dispatch_async(dispatch_get_main_queue(), ^{
  1668. if (![cocoaView isAbsoluteEnabled]) {
  1669. if ([cocoaView isMouseGrabbed]) {
  1670. [cocoaView ungrabMouse];
  1671. }
  1672. }
  1673. [cocoaView setAbsoluteEnabled:YES];
  1674. });
  1675. }
  1676. [pool release];
  1677. }
  1678. static void cocoa_cleanup(void)
  1679. {
  1680. COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
  1681. g_free(dcl);
  1682. }
  1683. static const DisplayChangeListenerOps dcl_ops = {
  1684. .dpy_name = "cocoa",
  1685. .dpy_gfx_update = cocoa_update,
  1686. .dpy_gfx_switch = cocoa_switch,
  1687. .dpy_refresh = cocoa_refresh,
  1688. };
  1689. static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
  1690. {
  1691. COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
  1692. /* Tell main thread to go ahead and create the app and enter the run loop */
  1693. qemu_sem_post(&display_init_sem);
  1694. qemu_sem_wait(&app_started_sem);
  1695. COCOA_DEBUG("cocoa_display_init: app start completed\n");
  1696. /* if fullscreen mode is to be used */
  1697. if (opts->has_full_screen && opts->full_screen) {
  1698. dispatch_async(dispatch_get_main_queue(), ^{
  1699. [NSApp activateIgnoringOtherApps: YES];
  1700. [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
  1701. });
  1702. }
  1703. dcl = g_malloc0(sizeof(DisplayChangeListener));
  1704. // register vga output callbacks
  1705. dcl->ops = &dcl_ops;
  1706. register_displaychangelistener(dcl);
  1707. // register cleanup function
  1708. atexit(cocoa_cleanup);
  1709. }
  1710. static QemuDisplay qemu_display_cocoa = {
  1711. .type = DISPLAY_TYPE_COCOA,
  1712. .init = cocoa_display_init,
  1713. };
  1714. static void register_cocoa(void)
  1715. {
  1716. qemu_display_register(&qemu_display_cocoa);
  1717. }
  1718. type_init(register_cocoa);