godot_application_delegate.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**************************************************************************/
  2. /* godot_application_delegate.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "godot_application_delegate.h"
  31. #include "display_server_macos.h"
  32. #include "native_menu_macos.h"
  33. #include "os_macos.h"
  34. @implementation GodotApplicationDelegate
  35. - (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app {
  36. return YES;
  37. }
  38. - (NSArray<NSString *> *)localizedTitlesForItem:(id)item {
  39. NSArray *item_name = @[ item[1] ];
  40. return item_name;
  41. }
  42. - (void)searchForItemsWithSearchString:(NSString *)searchString resultLimit:(NSInteger)resultLimit matchedItemHandler:(void (^)(NSArray *items))handleMatchedItems {
  43. NSMutableArray *found_items = [[NSMutableArray alloc] init];
  44. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  45. if (ds && ds->_help_get_search_callback().is_valid()) {
  46. Callable cb = ds->_help_get_search_callback();
  47. Variant ret;
  48. Variant search_string = String::utf8([searchString UTF8String]);
  49. Variant result_limit = (uint64_t)resultLimit;
  50. Callable::CallError ce;
  51. const Variant *args[2] = { &search_string, &result_limit };
  52. cb.callp(args, 2, ret, ce);
  53. if (ce.error != Callable::CallError::CALL_OK) {
  54. ERR_PRINT(vformat(RTR("Failed to execute help search callback: %s."), Variant::get_callable_error_text(cb, args, 2, ce)));
  55. }
  56. Dictionary results = ret;
  57. for (const Variant *E = results.next(); E; E = results.next(E)) {
  58. const String &key = *E;
  59. const String &value = results[*E];
  60. if (key.length() > 0 && value.length() > 0) {
  61. NSArray *item = @[ [NSString stringWithUTF8String:key.utf8().get_data()], [NSString stringWithUTF8String:value.utf8().get_data()] ];
  62. [found_items addObject:item];
  63. }
  64. }
  65. }
  66. handleMatchedItems(found_items);
  67. }
  68. - (void)performActionForItem:(id)item {
  69. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  70. if (ds && ds->_help_get_action_callback().is_valid()) {
  71. Callable cb = ds->_help_get_action_callback();
  72. Variant ret;
  73. Variant item_string = String::utf8([item[0] UTF8String]);
  74. Callable::CallError ce;
  75. const Variant *args[1] = { &item_string };
  76. cb.callp(args, 1, ret, ce);
  77. if (ce.error != Callable::CallError::CALL_OK) {
  78. ERR_PRINT(vformat(RTR("Failed to execute help action callback: %s."), Variant::get_callable_error_text(cb, args, 1, ce)));
  79. }
  80. }
  81. }
  82. - (void)forceUnbundledWindowActivationHackStep1 {
  83. // Step 1: Switch focus to macOS SystemUIServer process.
  84. // Required to perform step 2, TransformProcessType will fail if app is already the in focus.
  85. for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.systemuiserver"]) {
  86. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  87. break;
  88. }
  89. [self performSelector:@selector(forceUnbundledWindowActivationHackStep2)
  90. withObject:nil
  91. afterDelay:0.02];
  92. }
  93. - (void)forceUnbundledWindowActivationHackStep2 {
  94. // Step 2: Register app as foreground process.
  95. ProcessSerialNumber psn = { 0, kCurrentProcess };
  96. (void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  97. [self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
  98. }
  99. - (void)forceUnbundledWindowActivationHackStep3 {
  100. // Step 3: Switch focus back to app window.
  101. [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  102. }
  103. - (void)system_theme_changed:(NSNotification *)notification {
  104. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  105. if (ds) {
  106. ds->emit_system_theme_changed();
  107. }
  108. }
  109. - (void)applicationDidFinishLaunching:(NSNotification *)notice {
  110. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  111. const char *bundled_id = getenv("__CFBundleIdentifier");
  112. NSString *nsbundleid_env = [NSString stringWithUTF8String:(bundled_id != nullptr) ? bundled_id : ""];
  113. NSString *nsbundleid = [[NSBundle mainBundle] bundleIdentifier];
  114. if (nsappname == nil || isatty(STDOUT_FILENO) || isatty(STDIN_FILENO) || isatty(STDERR_FILENO) || ![nsbundleid isEqualToString:nsbundleid_env]) {
  115. // If the executable is started from terminal or is not bundled, macOS WindowServer won't register and activate app window correctly (menu and title bar are grayed out and input ignored).
  116. [self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
  117. }
  118. [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(system_theme_changed:) name:@"AppleInterfaceThemeChangedNotification" object:nil];
  119. [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(system_theme_changed:) name:@"AppleColorPreferencesChangedNotification" object:nil];
  120. }
  121. - (id)init {
  122. self = [super init];
  123. NSAppleEventManager *aem = [NSAppleEventManager sharedAppleEventManager];
  124. [aem setEventHandler:self andSelector:@selector(handleAppleEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
  125. [aem setEventHandler:self andSelector:@selector(handleAppleEvent:withReplyEvent:) forEventClass:kCoreEventClass andEventID:kAEOpenDocuments];
  126. return self;
  127. }
  128. - (void)dealloc {
  129. [[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:@"AppleInterfaceThemeChangedNotification" object:nil];
  130. [[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:@"AppleColorPreferencesChangedNotification" object:nil];
  131. }
  132. - (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
  133. OS_MacOS *os = (OS_MacOS *)OS::get_singleton();
  134. if (!event || !os) {
  135. return;
  136. }
  137. List<String> args;
  138. if (([event eventClass] == kInternetEventClass) && ([event eventID] == kAEGetURL)) {
  139. // Opening URL scheme.
  140. NSString *url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
  141. args.push_back(vformat("--uri=\"%s\"", String::utf8([url UTF8String])));
  142. }
  143. if (([event eventClass] == kCoreEventClass) && ([event eventID] == kAEOpenDocuments)) {
  144. // Opening file association.
  145. NSAppleEventDescriptor *files = [event paramDescriptorForKeyword:keyDirectObject];
  146. if (files) {
  147. NSInteger count = [files numberOfItems];
  148. for (NSInteger i = 1; i <= count; i++) {
  149. NSURL *url = [NSURL URLWithString:[[files descriptorAtIndex:i] stringValue]];
  150. args.push_back(String::utf8([url.path UTF8String]));
  151. }
  152. }
  153. }
  154. if (!args.is_empty()) {
  155. if (os->get_main_loop()) {
  156. // Application is already running, open a new instance with the URL/files as command line arguments.
  157. os->create_instance(args);
  158. } else {
  159. // Application is just started, add to the list of command line arguments and continue.
  160. os->set_cmdline_platform_args(args);
  161. }
  162. }
  163. }
  164. - (void)applicationDidResignActive:(NSNotification *)notification {
  165. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  166. if (ds) {
  167. ds->mouse_process_popups(true);
  168. }
  169. if (OS::get_singleton()->get_main_loop()) {
  170. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  171. }
  172. }
  173. - (void)applicationDidBecomeActive:(NSNotification *)notification {
  174. if (OS::get_singleton()->get_main_loop()) {
  175. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
  176. }
  177. }
  178. - (void)globalMenuCallback:(id)sender {
  179. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  180. if (ds) {
  181. return ds->menu_callback(sender);
  182. }
  183. }
  184. - (NSMenu *)applicationDockMenu:(NSApplication *)sender {
  185. if (NativeMenu::get_singleton()) {
  186. NativeMenuMacOS *nmenu = (NativeMenuMacOS *)NativeMenu::get_singleton();
  187. return nmenu->_get_dock_menu();
  188. } else {
  189. return nullptr;
  190. }
  191. }
  192. - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
  193. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  194. if (ds) {
  195. ds->send_window_event(ds->get_window(DisplayServerMacOS::MAIN_WINDOW_ID), DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  196. }
  197. return NSTerminateCancel;
  198. }
  199. - (void)showAbout:(id)sender {
  200. OS_MacOS *os = (OS_MacOS *)OS::get_singleton();
  201. if (os && os->get_main_loop()) {
  202. os->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_ABOUT);
  203. }
  204. }
  205. @end