Title: macOS backend rework, initial PR by iccir · Pull Request #32161 · matplotlib/matplotlib · GitHub
Open Graph Title: macOS backend rework, initial PR by iccir · Pull Request #32161 · matplotlib/matplotlib
X Title: macOS backend rework, initial PR by iccir · Pull Request #32161 · matplotlib/matplotlib
Description: PR summary As discussed in Thursday's meeting, this pull request starts the process of merging the reworked macOS backend into main. The macosx backend is still the default for now, the reworked backend can be tested with: export MPLBACKEND=macos Closes #31770 Closes #31813 Closes #31875 Closes #31933 File Structure Previously, the Objective-C layer used a single "_macosx.m" file with several @interface and @implementation blocks. This file also contained all the Python/Obj-C glue code as well as the PyTypeObject declarations. This PR splits that file into several files with distinct responsibilities: File Contains _macos.m • Module initialization• Python/Obj-C glue code • PyTypeObject declarations• Backing PyTypeObject C structs MPLAppDelegate.[hm] Optional NSApplication delegate MPLClassName.[hm] Obj-C classes "paired" with Python classes(most non-glue code should live here) MPLUtils.[hm] Utility functions. Why? Objective-C is typically organized in .h/.m file pairs with one public class per file. This is how Objective-C enforces encapsulation. There are no private or protected keywords like in other languages (there was a @private keyword for instance variables, but this fell out of usage when ivars were moved to the .m file circa-2007). A private method is never declared in the header file, it only shows up in the .m file. A protected method typically appears in the header file as a category called "SubclassesToOverride" / "ProtectedMethods" / etc. Some projects will use a "MyClass_Internal.h" or "MyClass_Private.h" file with a category for the concept of package methods. Additionally, compiler flags operate at a per-compile-unit basis. Had the file already been split, the migration to ARC could have taken place in segments rather than all at once. Typically, an Objective-C project will compile most sources with -Os and have one or two "Fast" files with -O3, -ffast-math, etc. Paired Classes As discussed in my ARC PR, I believe that an ideal architecture involves pairing each Python backend class with a corresponding Objective-C class. Each Python class in "backend_macos.py" inherits from parent class defined in "_macos.m". That parent class creates and then maintains a strong ownership of its Objective-C pair via a struct member called _object. The Objective-C class has a weakly-held reference back to the Python instance via the pyObject property. This pull request has the following paired classes: Python Class(backend_macos.py) Inherits from:(_macos.m) Obj-C Pair(various .h/.m files) FigureCanvasMac _macos.FigureCanvas MPLFigureCanvas FigureManagerMac _macos.FigureManager MPLFigureManager NavigationToolbar2Mac _macos.NavigationToolbar2 MPLNavigationToolbar2 Future pull requests will introduce MPLTimer and MPLSubplotTool. Calling Objective-C from Python A Python class (in "backend_macos.py") calls a method on its PyTypeObject parent class (in "_macos.m"). The corresponding C function is invoked via the Python C API. Any arguments are extracted via PyArg_ParseTuple() or a utility method such as MPLGetStringWithPyString(). The C function calls a corresponding method on the Objective-C pair. Calling Python from Objective-C The Objective-C uses MPLCallMethod() on its _pyObject ivar. A corresponding method is called on the Python pair. By design, this is it! Unlike the previous backend, there is no concept of "reaching in" to the Python layer to instantiate events or acquire the GIL (MPLCallMethod() handles this for you). Anything that needs more advanced logic than a simple void call takes place in Python-land. Notes on Naming As much as possible, I have tried to keep similar names between each Python-exposed method and the destination Objective-C method. However, there are a few exceptions: Objective-C includes parameters in the method name. addItem() with title and description parameters would be addItemWithTitle:description: in Objective-C. setFoo:, foo, and getFoo: have a different meaning in Objective-C compared to Python. setFoo: and foo are accessor methods for a property named foo. The get prefix is reserved for methods that fetch multiple values, such as getDeviceX:deviceY:. I use updateFoo: in situations where there is no foo getter. Per-class Overview MPLAppDelegate This is an "optional" class that implements niceties like the main menu and app icon. It should only be instantiated by the macOS backend when there is no existing NSApplication delegate. Else, we can prevent already-running apps from embedding Python and using us. In a future PR, this class will generate a macOS-styled app icon from image resources. I'm also investigating adding more main menu items for accessibility reasons. MPLFigureManager Previously, some of this logic lived in an NSWindow subclass named Window (which is a dangerous name). Some logic lived in View as it was the window's delegate (this was incorrect as it inverts the traditional object-ownership graph). I made the following notable changes: MPLFigureManager is now an NSWindowController. It owns an NSWindow and is the delegate of said window. The window in question is a special private subclass called MPLUnconstrainedWindow. It overrides a single method to disable macOS's window constraining logic. The window is specifically configured to use the sRGB color space. This prevents a color space conversion inside our process and (hopefully) allows the sRGB-based Agg buffer to be converted on the GPU. MPLFigureCanvas Previously, this was View. A lot of changes here: We now use layer-hosting. See the "Drawing Changes" section below. I reworked and cleaned up keyboard events. I checked examples from #21512 and #20486 to verify no changed behavior. Event instantiation, mouse button mapping, and keyboard modifier mappings all happen in Python now. This mimics other backends. MPLNavigationToolbar2 Previously, this was NavigationToolbar2Handler. Notable changes: I now send all toolitems data to the Objective-C layer, via add_item() and add_separator(). I added set_history_buttons(), similar to other backends. I changed the way pan/zoom selection works and added _update_buttons_checked(), similar to other backends. A future PR will update the appearance of the buttons and address issues with macOS Tahoe's (rather-ridiculously-sized) window corners overlapping the home button. Drawing Changes macOS's AppKit framework has various ways of compositing views to the screen. Previously, we were using -setNeedsDisplay: and -drawRect:. -drawRect: would call into Python, grab the Agg-rendered buffer, wrap it in a CGImage, and then draw it via CGContextDrawImage. The actual call to -setNeedsDisplay: occurred in response to a single-shot timer firing. Ultimately, this approach resulted in double drawing and flicker. We now use layer-hosting. This is a lower-level API designed to give app developers direct control over Core Animation. We don't need to animate, but we do need to get our buffer to the lower levels of macOS without AppKit trying to redraw it. All of the single-shot timer logic goes away. Instead: draw_idle() and other methods route to _request_display_layer. This calls -[MPLFigureCanvas requestDisplayLayerWithNeedsDraw:]. If called on a worker thread, we dispatch_async the call to the main thread. The _needsDrawOnNextDisplayLayer flag is set and -[CALayer setNeedsDisplay] is called on the backing CALayer. If called on the main thread (which is usually the case), this guarantees that a layer update will occur on the current iteration of the event loop. Any use of a timer would instead defer to the next iteration. Later in the event loop, we enter the drawing phase: The CALayer invokes -displayLayer: on its delegate (our MPLFigureCanvas). We call _handle_display_layer on our paired Python object. This re-renders if necessary, and sends the Agg buffer back to Objective-C-land. The Agg buffer is set as the CALayer.contents property. It's now up to macOS to render/composite the layer. Since the NSView is layer-hosted, the CALayer has sRGB contents, and the NSWindow is also in sRGB, there shouldn't be any CPU-based compositing in our process. This is a macOS implementation detail, however, and may vary between macOS versions. In the worst case, macOS decides to re-composite the layer on the CPU in WindowServer. In the best case, macOS lets the GPU handle it. It's beyond our control. That said, with this PR, no compositing occurs in our own process on my test devices. LegacyMac / Backwards Compatibility While we are in the process of migrating to the new macos backend, I didn't want to have files named "macosx" and "macos" that also have similar content. Ideally, I'd prefer to not have "backend_macosx.py" at all as I keep opening it by accident. I chose "legacymac" for now since it starts with an "L" and doesn't pop up when I type "backend_m". I had AI make suggestions and create the "backend_macosx.py" compatibility shim. I could use some guidance on this approach as I don't want to break projects using backend_macosx directly. Is there a better way? AI Disclosure AI was used to help me check various implementations in MPLUtils. I asked AI for advice with the "backend_macosx.py" compatibility shim. I had AI proofread this PR. PR quality check Use an expressive title, e.g. "Fix title font property precedence" New and changed code is tested [N/A] Plotting related features are demonstrated in an example [N/A] New features and API changes have release notes (Marking as N/A as we probably want to wait till a later PR) Documentation complies with general and docstring guidelines Remaining Work Once this is in, I'll be able to create the following independent PRs which can be reviewed and merged independently of each other: Moving to MPLEventLoop (#30419) Native subplot tool (#27592) Moving to MPLTimer from NSTimer (#29062) App Icon (#31895) Various cosmetic changes Additionally: I need to research IPython and the mapping between "macosx"/"macos"/"osx" in _fix_ipython_backend2gui. "test_backend_macosx.py" should probably become "test_backend_macos.py", and a new "test_backend_macosx.py" goes in to test deprecation notices and/or the compatibility shim. Documentation changes / API Notes
Open Graph Description: PR summary As discussed in Thursday's meeting, this pull request starts the process of merging the reworked macOS backend into main. The macosx backend is still the default for now, the reworke...
X Description: PR summary As discussed in Thursday's meeting, this pull request starts the process of merging the reworked macOS backend into main. The macosx backend is still the default for now, the rew...
Opengraph URL: https://github.com/matplotlib/matplotlib/pull/32161
X: @github
Domain: github.com
IPv4 address: 140.82.112.3
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:39606d42-dafc-4395-f126-5d5594f44d4e |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | 8980:F286:1C3F00D:2542AF4:6B0686DC |
| html-safe-nonce | 208b8b1b68fb4d6a5710470ab8a74075537ad3aeba336ab19be2fcaf5af71c59 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4OTgwOkYyODY6MUMzRjAwRDoyNTQyQUY0OjZCMDY4NkRDIiwidmlzaXRvcl9pZCI6Ijk0Nzg2NjYwNzkxMTYwMTg4NCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | a4ce3332ceb09b4ddc29017e0c493f91489764fcf4f3ee6902cf58a7ad7dc7bf |
| hovercard-subject-tag | pull_request:4184734895 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/matplotlib/matplotlib/pull/32161/files |
| twitter:image | https://avatars.githubusercontent.com/u/1097294?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/1097294?s=400&v=4 |
| og:image:alt | PR summary As discussed in Thursday's meeting, this pull request starts the process of merging the reworked macOS backend into main. The macosx backend is still the default for now, the reworke... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | 4462ff7ebfd3d551f202659f2423dae617b6849d23b1df6465dc504ef497d14a |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/matplotlib/matplotlib git https://github.com/matplotlib/matplotlib.git |
| octolytics-dimension-user_id | 215947 |
| octolytics-dimension-user_login | matplotlib |
| octolytics-dimension-repository_id | 1385122 |
| octolytics-dimension-repository_nwo | matplotlib/matplotlib |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 1385122 |
| octolytics-dimension-repository_network_root_nwo | matplotlib/matplotlib |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 6d3909414814ff86ce7da4c51a0f4918a13fb41b |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | no-cache |
Viewport: width=device-width