We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Make app respond to Cmd-H, Cmd-Opt-H on macOS; add menu bar items
Toga apps do not respond to Cmd-H and Cmd-Opt-H on macOS and there are no options to hide the app or hide other apps on the application menu.  These could be added to the `APP` command group in `toga-cocoa` so that they are always present for macOS apps, under a separate section.  I could look into what this might require although I've no experience with ObjC and friends.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/cocoa/toga_cocoa/app.py`
Content:
```
1 import asyncio
2 import inspect
3 import os
4 import sys
5 from urllib.parse import unquote, urlparse
6 
7 from rubicon.objc.eventloop import CocoaLifecycle, EventLoopPolicy
8 
9 import toga
10 from toga.handlers import wrapped_handler
11 
12 from .keys import cocoa_key
13 from .libs import (
14     SEL,
15     NSMenu,
16     NSMenuItem,
17     NSURL,
18     NSAboutPanelOptionApplicationIcon,
19     NSAboutPanelOptionApplicationName,
20     NSAboutPanelOptionApplicationVersion,
21     NSApplication,
22     NSApplicationActivationPolicyRegular,
23     NSBundle,
24     NSCursor,
25     NSDocumentController,
26     NSMutableArray,
27     NSMutableDictionary,
28     NSNumber,
29     NSObject,
30     NSOpenPanel,
31     NSScreen,
32     NSString,
33     objc_method
34 )
35 from .window import Window
36 
37 
38 class MainWindow(Window):
39     def on_close(self):
40         self.interface.app.exit()
41 
42 
43 class AppDelegate(NSObject):
44     @objc_method
45     def applicationWillTerminate_(self, sender):
46         if self.interface.app.on_exit:
47             self.interface.app.on_exit(self.interface.app)
48 
49     @objc_method
50     def applicationDidFinishLaunching_(self, notification):
51         self.native.activateIgnoringOtherApps(True)
52 
53     @objc_method
54     def applicationOpenUntitledFile_(self, sender) -> bool:
55         self.impl.select_file()
56         return True
57 
58     @objc_method
59     def addDocument_(self, document) -> None:
60         # print("Add Document", document)
61         super().addDocument_(document)
62 
63     @objc_method
64     def applicationShouldOpenUntitledFile_(self, sender) -> bool:
65         return True
66 
67     @objc_method
68     def application_openFiles_(self, app, filenames) -> None:
69         for i in range(0, len(filenames)):
70             filename = filenames[i]
71             # If you start your Toga application as `python myapp.py` or
72             # `myapp.py`, the name of the Python script is included as a
73             # filename to be processed. Inspect the stack, and ignore any
74             # "document" that matches the file doing the executing
75             if filename == inspect.stack(-1)[-1].filename:
76                 continue
77 
78             if isinstance(filename, NSString):
79                 fileURL = NSURL.fileURLWithPath(filename)
80 
81             elif isinstance(filename, NSURL):
82                 # This case only exists because we aren't using the
83                 # DocumentController to display the file open dialog.
84                 # If we were, *all* filenames passed in would be
85                 # string paths.
86                 fileURL = filename
87             else:
88                 return
89 
90             self.impl.open_document(str(fileURL.absoluteString))
91 
92     @objc_method
93     def selectMenuItem_(self, sender) -> None:
94         cmd = self.interface._impl._menu_items[sender]
95         if cmd.action:
96             cmd.action(None)
97 
98 
99 class App:
100     _MAIN_WINDOW_CLASS = MainWindow
101 
102     def __init__(self, interface):
103         self.interface = interface
104         self.interface._impl = self
105 
106         self._cursor_visible = True
107 
108         asyncio.set_event_loop_policy(EventLoopPolicy())
109         self.loop = asyncio.get_event_loop()
110 
111     def create(self):
112         self.native = NSApplication.sharedApplication
113         self.native.setActivationPolicy(NSApplicationActivationPolicyRegular)
114 
115         icon = self.interface.icon.bind(self.interface.factory)
116         self.native.setApplicationIconImage_(icon.native)
117 
118         self.resource_path = os.path.dirname(os.path.dirname(NSBundle.mainBundle.bundlePath))
119 
120         self.appDelegate = AppDelegate.alloc().init()
121         self.appDelegate.impl = self
122         self.appDelegate.interface = self.interface
123         self.appDelegate.native = self.native
124         self.native.setDelegate_(self.appDelegate)
125 
126         formal_name = self.interface.formal_name
127 
128         self.interface.commands.add(
129             toga.Command(
130                 lambda _: self.interface.about(),
131                 'About ' + formal_name,
132                 group=toga.Group.APP
133             ),
134             toga.Command(None, 'Preferences', group=toga.Group.APP),
135             # Quit should always be the last item, in a section on it's own
136             toga.Command(
137                 lambda _: self.interface.exit(),
138                 'Quit ' + formal_name,
139                 shortcut=toga.Key.MOD_1 + 'q',
140                 group=toga.Group.APP,
141                 section=sys.maxsize
142             ),
143 
144             toga.Command(
145                 lambda _: self.interface.visit_homepage(),
146                 'Visit homepage',
147                 enabled=self.interface.home_page is not None,
148                 group=toga.Group.HELP
149             )
150         )
151         self._create_app_commands()
152 
153         # Call user code to populate the main window
154         self.interface.startup()
155 
156         # Create the lookup table of menu items,
157         # then force the creation of the menus.
158         self.create_menus()
159 
160     def _create_app_commands(self):
161         # No extra commands
162         pass
163 
164     def create_menus(self):
165         # Recreate the menu
166         self._menu_items = {}
167         self._menu_groups = {}
168         menubar = NSMenu.alloc().initWithTitle('MainMenu')
169         submenu = None
170         for cmd in self.interface.commands:
171             if cmd == toga.GROUP_BREAK:
172                 submenu = None
173             elif cmd == toga.SECTION_BREAK:
174                 submenu.addItem_(NSMenuItem.separatorItem())
175             else:
176                 submenu = self._submenu(cmd.group, menubar)
177 
178                 if cmd.shortcut:
179                     key, modifier = cocoa_key(cmd.shortcut)
180                 else:
181                     key = ''
182                     modifier = None
183 
184                 item = NSMenuItem.alloc().initWithTitle(
185                     cmd.label,
186                     action=SEL('selectMenuItem:'),
187                     keyEquivalent=key,
188                 )
189                 if modifier is not None:
190                     item.keyEquivalentModifierMask = modifier
191 
192                 cmd._impl.native.append(item)
193                 self._menu_items[item] = cmd
194 
195                 # This line may appear redundant, but it triggers the logic
196                 # to force the enabled status on the underlying widgets.
197                 cmd.enabled = cmd.enabled
198                 submenu.addItem(item)
199 
200         # Set the menu for the app.
201         self.native.mainMenu = menubar
202 
203     def _submenu(self, group, menubar):
204         """
205         Obtain the submenu representing the command group.
206 
207         This will create the submenu if it doesn't exist. It will call itself
208         recursively to build the full path to menus inside submenus, returning
209         the "leaf" node in the submenu path. Once created, it caches the menu
210         that has been created for future lookup.
211         """
212         try:
213             return self._menu_groups[group]
214         except KeyError:
215             if group is None:
216                 submenu = menubar
217             else:
218                 parent_menu = self._submenu(group.parent, menubar)
219 
220                 menu_item = parent_menu.addItemWithTitle(
221                     group.label, action=None, keyEquivalent=''
222                 )
223                 submenu = NSMenu.alloc().initWithTitle(group.label)
224                 submenu.setAutoenablesItems(False)
225 
226                 parent_menu.setSubmenu(submenu, forItem=menu_item)
227 
228             # Install the item in the group cache.
229             self._menu_groups[group] = submenu
230             return submenu
231 
232     def main_loop(self):
233         # Stimulate the build of the app
234         self.create()
235 
236         self.loop.run_forever(lifecycle=CocoaLifecycle(self.native))
237 
238     def set_main_window(self, window):
239         pass
240 
241     def show_about_dialog(self):
242         options = NSMutableDictionary.alloc().init()
243 
244         options[NSAboutPanelOptionApplicationIcon] = self.interface.icon.bind(self.interface.factory).native
245 
246         if self.interface.name is not None:
247             options[NSAboutPanelOptionApplicationName] = self.interface.name
248 
249         if self.interface.version is not None:
250             options[NSAboutPanelOptionApplicationVersion] = self.interface.version
251 
252         # The build number
253         # if self.interface.version is not None:
254         #     options[NSAboutPanelOptionVersion] = "the build"
255 
256         if self.interface.author is not None:
257             options["Copyright"] = "Copyright © {author}".format(
258                 author=self.interface.author
259             )
260 
261         self.native.orderFrontStandardAboutPanelWithOptions(options)
262 
263     def exit(self):
264         self.native.terminate(None)
265 
266     def set_on_exit(self, value):
267         pass
268 
269     def current_window(self):
270         return self.native.keyWindow
271 
272     def enter_full_screen(self, windows):
273         # If we're already in full screen mode, exit so that
274         # we can re-assign windows to screens.
275         if self.interface.is_full_screen:
276             self.interface.exit_full_screen()
277 
278         opts = NSMutableDictionary.alloc().init()
279         opts.setObject(NSNumber.numberWithBool(True), forKey="NSFullScreenModeAllScreens")
280 
281         for window, screen in zip(windows, NSScreen.screens):
282             window.content._impl.native.enterFullScreenMode(screen, withOptions=opts)
283             # Going full screen causes the window content to be re-homed
284             # in a NSFullScreenWindow; teach the new parent window
285             # about it's Toga representations.
286             window.content._impl.native.window._impl = window._impl
287             window.content._impl.native.window.interface = window
288 
289     def exit_full_screen(self, windows):
290         opts = NSMutableDictionary.alloc().init()
291         opts.setObject(NSNumber.numberWithBool(True), forKey="NSFullScreenModeAllScreens")
292 
293         for window in windows:
294             window.content._impl.native.exitFullScreenModeWithOptions(opts)
295 
296     def show_cursor(self):
297         if not self._cursor_visible:
298             NSCursor.unhide()
299 
300         self._cursor_visible = True
301 
302     def hide_cursor(self):
303         if self._cursor_visible:
304             NSCursor.hide()
305 
306         self._cursor_visible = False
307 
308     def add_background_task(self, handler):
309         self.loop.call_soon(wrapped_handler(self, handler), self)
310 
311 
312 class DocumentApp(App):
313     def _create_app_commands(self):
314         self.interface.commands.add(
315             toga.Command(
316                 lambda _: self.select_file(),
317                 label='Open...',
318                 shortcut=toga.Key.MOD_1 + 'o',
319                 group=toga.Group.FILE,
320                 section=0
321             ),
322         )
323 
324     def select_file(self, **kwargs):
325         # FIXME This should be all we need; but for some reason, application types
326         # aren't being registered correctly..
327         # NSDocumentController.sharedDocumentController().openDocument_(None)
328 
329         # ...so we do this instead.
330         panel = NSOpenPanel.openPanel()
331         # print("Open documents of type", NSDocumentController.sharedDocumentController().defaultType)
332 
333         fileTypes = NSMutableArray.alloc().init()
334         for filetype in self.interface.document_types:
335             fileTypes.addObject(filetype)
336 
337         NSDocumentController.sharedDocumentController.runModalOpenPanel(panel, forTypes=fileTypes)
338 
339         # print("Untitled File opened?", panel.URLs)
340         self.appDelegate.application_openFiles_(None, panel.URLs)
341 
342     def open_document(self, fileURL):
343         """Open a new document in this app.
344 
345         Args:
346             fileURL (str): The URL/path to the file to add as a document.
347         """
348         # Convert a cocoa fileURL to a file path.
349         fileURL = fileURL.rstrip('/')
350         path = unquote(urlparse(fileURL).path)
351         extension = os.path.splitext(path)[1][1:]
352 
353         # Create the document instance
354         DocType = self.interface.document_types[extension]
355         document = DocType(path, app=self.interface)
356         self.interface._documents.append(document)
357 
358         # Show the document.
359         document.show()
360
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/cocoa/toga_cocoa/app.py b/src/cocoa/toga_cocoa/app.py
--- a/src/cocoa/toga_cocoa/app.py
+++ b/src/cocoa/toga_cocoa/app.py
@@ -131,8 +131,37 @@
                 'About ' + formal_name,
                 group=toga.Group.APP
             ),
-            toga.Command(None, 'Preferences', group=toga.Group.APP),
-            # Quit should always be the last item, in a section on it's own
+            toga.Command(
+                None,
+                'Preferences',
+                shortcut=toga.Key.MOD_1 + ',',
+                group=toga.Group.APP,
+                section=20,
+            ),
+            toga.Command(
+                lambda _: self.native.hide(self.native),
+                'Hide ' + formal_name,
+                shortcut=toga.Key.MOD_1 + 'h',
+                group=toga.Group.APP,
+                order=0,
+                section=sys.maxsize - 1,
+            ),
+            toga.Command(
+                lambda _: self.native.hideOtherApplications(self.native),
+                'Hide Others',
+                shortcut=toga.Key.MOD_1 + toga.Key.MOD_2 + 'h',
+                group=toga.Group.APP,
+                order=1,
+                section=sys.maxsize - 1,
+            ),
+            toga.Command(
+                lambda _: self.native.unhideAllApplications(self.native),
+                'Show All',
+                group=toga.Group.APP,
+                order=2,
+                section=sys.maxsize - 1,
+            ),
+            # Quit should always be the last item, in a section on its own
             toga.Command(
                 lambda _: self.interface.exit(),
                 'Quit ' + formal_name,

{"golden_diff": "diff --git a/src/cocoa/toga_cocoa/app.py b/src/cocoa/toga_cocoa/app.py\n--- a/src/cocoa/toga_cocoa/app.py\n+++ b/src/cocoa/toga_cocoa/app.py\n@@ -131,8 +131,37 @@\n                 'About ' + formal_name,\n                 group=toga.Group.APP\n             ),\n-            toga.Command(None, 'Preferences', group=toga.Group.APP),\n-            # Quit should always be the last item, in a section on it's own\n+            toga.Command(\n+                None,\n+                'Preferences',\n+                shortcut=toga.Key.MOD_1 + ',',\n+                group=toga.Group.APP,\n+                section=20,\n+            ),\n+            toga.Command(\n+                lambda _: self.native.hide(self.native),\n+                'Hide ' + formal_name,\n+                shortcut=toga.Key.MOD_1 + 'h',\n+                group=toga.Group.APP,\n+                order=0,\n+                section=sys.maxsize - 1,\n+            ),\n+            toga.Command(\n+                lambda _: self.native.hideOtherApplications(self.native),\n+                'Hide Others',\n+                shortcut=toga.Key.MOD_1 + toga.Key.MOD_2 + 'h',\n+                group=toga.Group.APP,\n+                order=1,\n+                section=sys.maxsize - 1,\n+            ),\n+            toga.Command(\n+                lambda _: self.native.unhideAllApplications(self.native),\n+                'Show All',\n+                group=toga.Group.APP,\n+                order=2,\n+                section=sys.maxsize - 1,\n+            ),\n+            # Quit should always be the last item, in a section on its own\n             toga.Command(\n                 lambda _: self.interface.exit(),\n                 'Quit ' + formal_name,\n", "issue": "Make app respond to Cmd-H, Cmd-Opt-H on macOS; add menu bar items\nToga apps do not respond to Cmd-H and Cmd-Opt-H on macOS and there are no options to hide the app or hide other apps on the application menu.  These could be added to the `APP` command group in `toga-cocoa` so that they are always present for macOS apps, under a separate section.  I could look into what this might require although I've no experience with ObjC and friends.\n", "before_files": [{"content": "import asyncio\nimport inspect\nimport os\nimport sys\nfrom urllib.parse import unquote, urlparse\n\nfrom rubicon.objc.eventloop import CocoaLifecycle, EventLoopPolicy\n\nimport toga\nfrom toga.handlers import wrapped_handler\n\nfrom .keys import cocoa_key\nfrom .libs import (\n    SEL,\n    NSMenu,\n    NSMenuItem,\n    NSURL,\n    NSAboutPanelOptionApplicationIcon,\n    NSAboutPanelOptionApplicationName,\n    NSAboutPanelOptionApplicationVersion,\n    NSApplication,\n    NSApplicationActivationPolicyRegular,\n    NSBundle,\n    NSCursor,\n    NSDocumentController,\n    NSMutableArray,\n    NSMutableDictionary,\n    NSNumber,\n    NSObject,\n    NSOpenPanel,\n    NSScreen,\n    NSString,\n    objc_method\n)\nfrom .window import Window\n\n\nclass MainWindow(Window):\n    def on_close(self):\n        self.interface.app.exit()\n\n\nclass AppDelegate(NSObject):\n    @objc_method\n    def applicationWillTerminate_(self, sender):\n        if self.interface.app.on_exit:\n            self.interface.app.on_exit(self.interface.app)\n\n    @objc_method\n    def applicationDidFinishLaunching_(self, notification):\n        self.native.activateIgnoringOtherApps(True)\n\n    @objc_method\n    def applicationOpenUntitledFile_(self, sender) -> bool:\n        self.impl.select_file()\n        return True\n\n    @objc_method\n    def addDocument_(self, document) -> None:\n        # print(\"Add Document\", document)\n        super().addDocument_(document)\n\n    @objc_method\n    def applicationShouldOpenUntitledFile_(self, sender) -> bool:\n        return True\n\n    @objc_method\n    def application_openFiles_(self, app, filenames) -> None:\n        for i in range(0, len(filenames)):\n            filename = filenames[i]\n            # If you start your Toga application as `python myapp.py` or\n            # `myapp.py`, the name of the Python script is included as a\n            # filename to be processed. Inspect the stack, and ignore any\n            # \"document\" that matches the file doing the executing\n            if filename == inspect.stack(-1)[-1].filename:\n                continue\n\n            if isinstance(filename, NSString):\n                fileURL = NSURL.fileURLWithPath(filename)\n\n            elif isinstance(filename, NSURL):\n                # This case only exists because we aren't using the\n                # DocumentController to display the file open dialog.\n                # If we were, *all* filenames passed in would be\n                # string paths.\n                fileURL = filename\n            else:\n                return\n\n            self.impl.open_document(str(fileURL.absoluteString))\n\n    @objc_method\n    def selectMenuItem_(self, sender) -> None:\n        cmd = self.interface._impl._menu_items[sender]\n        if cmd.action:\n            cmd.action(None)\n\n\nclass App:\n    _MAIN_WINDOW_CLASS = MainWindow\n\n    def __init__(self, interface):\n        self.interface = interface\n        self.interface._impl = self\n\n        self._cursor_visible = True\n\n        asyncio.set_event_loop_policy(EventLoopPolicy())\n        self.loop = asyncio.get_event_loop()\n\n    def create(self):\n        self.native = NSApplication.sharedApplication\n        self.native.setActivationPolicy(NSApplicationActivationPolicyRegular)\n\n        icon = self.interface.icon.bind(self.interface.factory)\n        self.native.setApplicationIconImage_(icon.native)\n\n        self.resource_path = os.path.dirname(os.path.dirname(NSBundle.mainBundle.bundlePath))\n\n        self.appDelegate = AppDelegate.alloc().init()\n        self.appDelegate.impl = self\n        self.appDelegate.interface = self.interface\n        self.appDelegate.native = self.native\n        self.native.setDelegate_(self.appDelegate)\n\n        formal_name = self.interface.formal_name\n\n        self.interface.commands.add(\n            toga.Command(\n                lambda _: self.interface.about(),\n                'About ' + formal_name,\n                group=toga.Group.APP\n            ),\n            toga.Command(None, 'Preferences', group=toga.Group.APP),\n            # Quit should always be the last item, in a section on it's own\n            toga.Command(\n                lambda _: self.interface.exit(),\n                'Quit ' + formal_name,\n                shortcut=toga.Key.MOD_1 + 'q',\n                group=toga.Group.APP,\n                section=sys.maxsize\n            ),\n\n            toga.Command(\n                lambda _: self.interface.visit_homepage(),\n                'Visit homepage',\n                enabled=self.interface.home_page is not None,\n                group=toga.Group.HELP\n            )\n        )\n        self._create_app_commands()\n\n        # Call user code to populate the main window\n        self.interface.startup()\n\n        # Create the lookup table of menu items,\n        # then force the creation of the menus.\n        self.create_menus()\n\n    def _create_app_commands(self):\n        # No extra commands\n        pass\n\n    def create_menus(self):\n        # Recreate the menu\n        self._menu_items = {}\n        self._menu_groups = {}\n        menubar = NSMenu.alloc().initWithTitle('MainMenu')\n        submenu = None\n        for cmd in self.interface.commands:\n            if cmd == toga.GROUP_BREAK:\n                submenu = None\n            elif cmd == toga.SECTION_BREAK:\n                submenu.addItem_(NSMenuItem.separatorItem())\n            else:\n                submenu = self._submenu(cmd.group, menubar)\n\n                if cmd.shortcut:\n                    key, modifier = cocoa_key(cmd.shortcut)\n                else:\n                    key = ''\n                    modifier = None\n\n                item = NSMenuItem.alloc().initWithTitle(\n                    cmd.label,\n                    action=SEL('selectMenuItem:'),\n                    keyEquivalent=key,\n                )\n                if modifier is not None:\n                    item.keyEquivalentModifierMask = modifier\n\n                cmd._impl.native.append(item)\n                self._menu_items[item] = cmd\n\n                # This line may appear redundant, but it triggers the logic\n                # to force the enabled status on the underlying widgets.\n                cmd.enabled = cmd.enabled\n                submenu.addItem(item)\n\n        # Set the menu for the app.\n        self.native.mainMenu = menubar\n\n    def _submenu(self, group, menubar):\n        \"\"\"\n        Obtain the submenu representing the command group.\n\n        This will create the submenu if it doesn't exist. It will call itself\n        recursively to build the full path to menus inside submenus, returning\n        the \"leaf\" node in the submenu path. Once created, it caches the menu\n        that has been created for future lookup.\n        \"\"\"\n        try:\n            return self._menu_groups[group]\n        except KeyError:\n            if group is None:\n                submenu = menubar\n            else:\n                parent_menu = self._submenu(group.parent, menubar)\n\n                menu_item = parent_menu.addItemWithTitle(\n                    group.label, action=None, keyEquivalent=''\n                )\n                submenu = NSMenu.alloc().initWithTitle(group.label)\n                submenu.setAutoenablesItems(False)\n\n                parent_menu.setSubmenu(submenu, forItem=menu_item)\n\n            # Install the item in the group cache.\n            self._menu_groups[group] = submenu\n            return submenu\n\n    def main_loop(self):\n        # Stimulate the build of the app\n        self.create()\n\n        self.loop.run_forever(lifecycle=CocoaLifecycle(self.native))\n\n    def set_main_window(self, window):\n        pass\n\n    def show_about_dialog(self):\n        options = NSMutableDictionary.alloc().init()\n\n        options[NSAboutPanelOptionApplicationIcon] = self.interface.icon.bind(self.interface.factory).native\n\n        if self.interface.name is not None:\n            options[NSAboutPanelOptionApplicationName] = self.interface.name\n\n        if self.interface.version is not None:\n            options[NSAboutPanelOptionApplicationVersion] = self.interface.version\n\n        # The build number\n        # if self.interface.version is not None:\n        #     options[NSAboutPanelOptionVersion] = \"the build\"\n\n        if self.interface.author is not None:\n            options[\"Copyright\"] = \"Copyright \u00a9 {author}\".format(\n                author=self.interface.author\n            )\n\n        self.native.orderFrontStandardAboutPanelWithOptions(options)\n\n    def exit(self):\n        self.native.terminate(None)\n\n    def set_on_exit(self, value):\n        pass\n\n    def current_window(self):\n        return self.native.keyWindow\n\n    def enter_full_screen(self, windows):\n        # If we're already in full screen mode, exit so that\n        # we can re-assign windows to screens.\n        if self.interface.is_full_screen:\n            self.interface.exit_full_screen()\n\n        opts = NSMutableDictionary.alloc().init()\n        opts.setObject(NSNumber.numberWithBool(True), forKey=\"NSFullScreenModeAllScreens\")\n\n        for window, screen in zip(windows, NSScreen.screens):\n            window.content._impl.native.enterFullScreenMode(screen, withOptions=opts)\n            # Going full screen causes the window content to be re-homed\n            # in a NSFullScreenWindow; teach the new parent window\n            # about it's Toga representations.\n            window.content._impl.native.window._impl = window._impl\n            window.content._impl.native.window.interface = window\n\n    def exit_full_screen(self, windows):\n        opts = NSMutableDictionary.alloc().init()\n        opts.setObject(NSNumber.numberWithBool(True), forKey=\"NSFullScreenModeAllScreens\")\n\n        for window in windows:\n            window.content._impl.native.exitFullScreenModeWithOptions(opts)\n\n    def show_cursor(self):\n        if not self._cursor_visible:\n            NSCursor.unhide()\n\n        self._cursor_visible = True\n\n    def hide_cursor(self):\n        if self._cursor_visible:\n            NSCursor.hide()\n\n        self._cursor_visible = False\n\n    def add_background_task(self, handler):\n        self.loop.call_soon(wrapped_handler(self, handler), self)\n\n\nclass DocumentApp(App):\n    def _create_app_commands(self):\n        self.interface.commands.add(\n            toga.Command(\n                lambda _: self.select_file(),\n                label='Open...',\n                shortcut=toga.Key.MOD_1 + 'o',\n                group=toga.Group.FILE,\n                section=0\n            ),\n        )\n\n    def select_file(self, **kwargs):\n        # FIXME This should be all we need; but for some reason, application types\n        # aren't being registered correctly..\n        # NSDocumentController.sharedDocumentController().openDocument_(None)\n\n        # ...so we do this instead.\n        panel = NSOpenPanel.openPanel()\n        # print(\"Open documents of type\", NSDocumentController.sharedDocumentController().defaultType)\n\n        fileTypes = NSMutableArray.alloc().init()\n        for filetype in self.interface.document_types:\n            fileTypes.addObject(filetype)\n\n        NSDocumentController.sharedDocumentController.runModalOpenPanel(panel, forTypes=fileTypes)\n\n        # print(\"Untitled File opened?\", panel.URLs)\n        self.appDelegate.application_openFiles_(None, panel.URLs)\n\n    def open_document(self, fileURL):\n        \"\"\"Open a new document in this app.\n\n        Args:\n            fileURL (str): The URL/path to the file to add as a document.\n        \"\"\"\n        # Convert a cocoa fileURL to a file path.\n        fileURL = fileURL.rstrip('/')\n        path = unquote(urlparse(fileURL).path)\n        extension = os.path.splitext(path)[1][1:]\n\n        # Create the document instance\n        DocType = self.interface.document_types[extension]\n        document = DocType(path, app=self.interface)\n        self.interface._documents.append(document)\n\n        # Show the document.\n        document.show()\n", "path": "src/cocoa/toga_cocoa/app.py"}], "after_files": [{"content": "import asyncio\nimport inspect\nimport os\nimport sys\nfrom urllib.parse import unquote, urlparse\n\nfrom rubicon.objc.eventloop import CocoaLifecycle, EventLoopPolicy\n\nimport toga\nfrom toga.handlers import wrapped_handler\n\nfrom .keys import cocoa_key\nfrom .libs import (\n    SEL,\n    NSMenu,\n    NSMenuItem,\n    NSURL,\n    NSAboutPanelOptionApplicationIcon,\n    NSAboutPanelOptionApplicationName,\n    NSAboutPanelOptionApplicationVersion,\n    NSApplication,\n    NSApplicationActivationPolicyRegular,\n    NSBundle,\n    NSCursor,\n    NSDocumentController,\n    NSMutableArray,\n    NSMutableDictionary,\n    NSNumber,\n    NSObject,\n    NSOpenPanel,\n    NSScreen,\n    NSString,\n    objc_method\n)\nfrom .window import Window\n\n\nclass MainWindow(Window):\n    def on_close(self):\n        self.interface.app.exit()\n\n\nclass AppDelegate(NSObject):\n    @objc_method\n    def applicationWillTerminate_(self, sender):\n        if self.interface.app.on_exit:\n            self.interface.app.on_exit(self.interface.app)\n\n    @objc_method\n    def applicationDidFinishLaunching_(self, notification):\n        self.native.activateIgnoringOtherApps(True)\n\n    @objc_method\n    def applicationOpenUntitledFile_(self, sender) -> bool:\n        self.impl.select_file()\n        return True\n\n    @objc_method\n    def addDocument_(self, document) -> None:\n        # print(\"Add Document\", document)\n        super().addDocument_(document)\n\n    @objc_method\n    def applicationShouldOpenUntitledFile_(self, sender) -> bool:\n        return True\n\n    @objc_method\n    def application_openFiles_(self, app, filenames) -> None:\n        for i in range(0, len(filenames)):\n            filename = filenames[i]\n            # If you start your Toga application as `python myapp.py` or\n            # `myapp.py`, the name of the Python script is included as a\n            # filename to be processed. Inspect the stack, and ignore any\n            # \"document\" that matches the file doing the executing\n            if filename == inspect.stack(-1)[-1].filename:\n                continue\n\n            if isinstance(filename, NSString):\n                fileURL = NSURL.fileURLWithPath(filename)\n\n            elif isinstance(filename, NSURL):\n                # This case only exists because we aren't using the\n                # DocumentController to display the file open dialog.\n                # If we were, *all* filenames passed in would be\n                # string paths.\n                fileURL = filename\n            else:\n                return\n\n            self.impl.open_document(str(fileURL.absoluteString))\n\n    @objc_method\n    def selectMenuItem_(self, sender) -> None:\n        cmd = self.interface._impl._menu_items[sender]\n        if cmd.action:\n            cmd.action(None)\n\n\nclass App:\n    _MAIN_WINDOW_CLASS = MainWindow\n\n    def __init__(self, interface):\n        self.interface = interface\n        self.interface._impl = self\n\n        self._cursor_visible = True\n\n        asyncio.set_event_loop_policy(EventLoopPolicy())\n        self.loop = asyncio.get_event_loop()\n\n    def create(self):\n        self.native = NSApplication.sharedApplication\n        self.native.setActivationPolicy(NSApplicationActivationPolicyRegular)\n\n        icon = self.interface.icon.bind(self.interface.factory)\n        self.native.setApplicationIconImage_(icon.native)\n\n        self.resource_path = os.path.dirname(os.path.dirname(NSBundle.mainBundle.bundlePath))\n\n        self.appDelegate = AppDelegate.alloc().init()\n        self.appDelegate.impl = self\n        self.appDelegate.interface = self.interface\n        self.appDelegate.native = self.native\n        self.native.setDelegate_(self.appDelegate)\n\n        formal_name = self.interface.formal_name\n\n        self.interface.commands.add(\n            toga.Command(\n                lambda _: self.interface.about(),\n                'About ' + formal_name,\n                group=toga.Group.APP\n            ),\n            toga.Command(\n                None,\n                'Preferences',\n                shortcut=toga.Key.MOD_1 + ',',\n                group=toga.Group.APP,\n                section=20,\n            ),\n            toga.Command(\n                lambda _: self.native.hide(self.native),\n                'Hide ' + formal_name,\n                shortcut=toga.Key.MOD_1 + 'h',\n                group=toga.Group.APP,\n                order=0,\n                section=sys.maxsize - 1,\n            ),\n            toga.Command(\n                lambda _: self.native.hideOtherApplications(self.native),\n                'Hide Others',\n                shortcut=toga.Key.MOD_1 + toga.Key.MOD_2 + 'h',\n                group=toga.Group.APP,\n                order=1,\n                section=sys.maxsize - 1,\n            ),\n            toga.Command(\n                lambda _: self.native.unhideAllApplications(self.native),\n                'Show All',\n                group=toga.Group.APP,\n                order=2,\n                section=sys.maxsize - 1,\n            ),\n            # Quit should always be the last item, in a section on its own\n            toga.Command(\n                lambda _: self.interface.exit(),\n                'Quit ' + formal_name,\n                shortcut=toga.Key.MOD_1 + 'q',\n                group=toga.Group.APP,\n                section=sys.maxsize\n            ),\n\n            toga.Command(\n                lambda _: self.interface.visit_homepage(),\n                'Visit homepage',\n                enabled=self.interface.home_page is not None,\n                group=toga.Group.HELP\n            )\n        )\n        self._create_app_commands()\n\n        # Call user code to populate the main window\n        self.interface.startup()\n\n        # Create the lookup table of menu items,\n        # then force the creation of the menus.\n        self.create_menus()\n\n    def _create_app_commands(self):\n        # No extra commands\n        pass\n\n    def create_menus(self):\n        # Recreate the menu\n        self._menu_items = {}\n        self._menu_groups = {}\n        menubar = NSMenu.alloc().initWithTitle('MainMenu')\n        submenu = None\n        for cmd in self.interface.commands:\n            if cmd == toga.GROUP_BREAK:\n                submenu = None\n            elif cmd == toga.SECTION_BREAK:\n                submenu.addItem_(NSMenuItem.separatorItem())\n            else:\n                submenu = self._submenu(cmd.group, menubar)\n\n                if cmd.shortcut:\n                    key, modifier = cocoa_key(cmd.shortcut)\n                else:\n                    key = ''\n                    modifier = None\n\n                item = NSMenuItem.alloc().initWithTitle(\n                    cmd.label,\n                    action=SEL('selectMenuItem:'),\n                    keyEquivalent=key,\n                )\n                if modifier is not None:\n                    item.keyEquivalentModifierMask = modifier\n\n                cmd._impl.native.append(item)\n                self._menu_items[item] = cmd\n\n                # This line may appear redundant, but it triggers the logic\n                # to force the enabled status on the underlying widgets.\n                cmd.enabled = cmd.enabled\n                submenu.addItem(item)\n\n        # Set the menu for the app.\n        self.native.mainMenu = menubar\n\n    def _submenu(self, group, menubar):\n        \"\"\"\n        Obtain the submenu representing the command group.\n\n        This will create the submenu if it doesn't exist. It will call itself\n        recursively to build the full path to menus inside submenus, returning\n        the \"leaf\" node in the submenu path. Once created, it caches the menu\n        that has been created for future lookup.\n        \"\"\"\n        try:\n            return self._menu_groups[group]\n        except KeyError:\n            if group is None:\n                submenu = menubar\n            else:\n                parent_menu = self._submenu(group.parent, menubar)\n\n                menu_item = parent_menu.addItemWithTitle(\n                    group.label, action=None, keyEquivalent=''\n                )\n                submenu = NSMenu.alloc().initWithTitle(group.label)\n                submenu.setAutoenablesItems(False)\n\n                parent_menu.setSubmenu(submenu, forItem=menu_item)\n\n            # Install the item in the group cache.\n            self._menu_groups[group] = submenu\n            return submenu\n\n    def main_loop(self):\n        # Stimulate the build of the app\n        self.create()\n\n        self.loop.run_forever(lifecycle=CocoaLifecycle(self.native))\n\n    def set_main_window(self, window):\n        pass\n\n    def show_about_dialog(self):\n        options = NSMutableDictionary.alloc().init()\n\n        options[NSAboutPanelOptionApplicationIcon] = self.interface.icon.bind(self.interface.factory).native\n\n        if self.interface.name is not None:\n            options[NSAboutPanelOptionApplicationName] = self.interface.name\n\n        if self.interface.version is not None:\n            options[NSAboutPanelOptionApplicationVersion] = self.interface.version\n\n        # The build number\n        # if self.interface.version is not None:\n        #     options[NSAboutPanelOptionVersion] = \"the build\"\n\n        if self.interface.author is not None:\n            options[\"Copyright\"] = \"Copyright \u00a9 {author}\".format(\n                author=self.interface.author\n            )\n\n        self.native.orderFrontStandardAboutPanelWithOptions(options)\n\n    def exit(self):\n        self.native.terminate(None)\n\n    def set_on_exit(self, value):\n        pass\n\n    def current_window(self):\n        return self.native.keyWindow\n\n    def enter_full_screen(self, windows):\n        # If we're already in full screen mode, exit so that\n        # we can re-assign windows to screens.\n        if self.interface.is_full_screen:\n            self.interface.exit_full_screen()\n\n        opts = NSMutableDictionary.alloc().init()\n        opts.setObject(NSNumber.numberWithBool(True), forKey=\"NSFullScreenModeAllScreens\")\n\n        for window, screen in zip(windows, NSScreen.screens):\n            window.content._impl.native.enterFullScreenMode(screen, withOptions=opts)\n            # Going full screen causes the window content to be re-homed\n            # in a NSFullScreenWindow; teach the new parent window\n            # about it's Toga representations.\n            window.content._impl.native.window._impl = window._impl\n            window.content._impl.native.window.interface = window\n\n    def exit_full_screen(self, windows):\n        opts = NSMutableDictionary.alloc().init()\n        opts.setObject(NSNumber.numberWithBool(True), forKey=\"NSFullScreenModeAllScreens\")\n\n        for window in windows:\n            window.content._impl.native.exitFullScreenModeWithOptions(opts)\n\n    def show_cursor(self):\n        if not self._cursor_visible:\n            NSCursor.unhide()\n\n        self._cursor_visible = True\n\n    def hide_cursor(self):\n        if self._cursor_visible:\n            NSCursor.hide()\n\n        self._cursor_visible = False\n\n    def add_background_task(self, handler):\n        self.loop.call_soon(wrapped_handler(self, handler), self)\n\n\nclass DocumentApp(App):\n    def _create_app_commands(self):\n        self.interface.commands.add(\n            toga.Command(\n                lambda _: self.select_file(),\n                label='Open...',\n                shortcut=toga.Key.MOD_1 + 'o',\n                group=toga.Group.FILE,\n                section=0\n            ),\n        )\n\n    def select_file(self, **kwargs):\n        # FIXME This should be all we need; but for some reason, application types\n        # aren't being registered correctly..\n        # NSDocumentController.sharedDocumentController().openDocument_(None)\n\n        # ...so we do this instead.\n        panel = NSOpenPanel.openPanel()\n        # print(\"Open documents of type\", NSDocumentController.sharedDocumentController().defaultType)\n\n        fileTypes = NSMutableArray.alloc().init()\n        for filetype in self.interface.document_types:\n            fileTypes.addObject(filetype)\n\n        NSDocumentController.sharedDocumentController.runModalOpenPanel(panel, forTypes=fileTypes)\n\n        # print(\"Untitled File opened?\", panel.URLs)\n        self.appDelegate.application_openFiles_(None, panel.URLs)\n\n    def open_document(self, fileURL):\n        \"\"\"Open a new document in this app.\n\n        Args:\n            fileURL (str): The URL/path to the file to add as a document.\n        \"\"\"\n        # Convert a cocoa fileURL to a file path.\n        fileURL = fileURL.rstrip('/')\n        path = unquote(urlparse(fileURL).path)\n        extension = os.path.splitext(path)[1][1:]\n\n        # Create the document instance\n        DocType = self.interface.document_types[extension]\n        document = DocType(path, app=self.interface)\n        self.interface._documents.append(document)\n\n        # Show the document.\n        document.show()\n", "path": "src/cocoa/toga_cocoa/app.py"}]}