Skip to content

Instantly share code, notes, and snippets.

@dsandler
Last active September 19, 2019 07:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dsandler/9d9150834d0652d358e9d4847fe75db9 to your computer and use it in GitHub Desktop.
Save dsandler/9d9150834d0652d358e9d4847fe75db9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# touchbar_demo.py
# dsandler@dsandler.org
# PyObjC proof of concept NSTouchBar implementation.
# Note that exceptions in the delegates will crash with "Illegal instruction: 4"
# rather than printing helpful stack traces; look in CrashReporter for the
# exception string.
import objc
from AppKit import \
NSObject, NSTouchBar, NSButton, NSCustomTouchBarItem, \
NSColor, NSApplication, NSApp
from PyObjCTools import AppHelper
NSApplicationDelegate = objc.protocolNamed('NSApplicationDelegate')
NSTouchBarProvider = objc.protocolNamed('NSTouchBarProvider')
class AppDelegate (NSObject, NSTouchBarProvider, NSApplicationDelegate):
FOO_BUTTON = "fooButton"
def applicationDidFinishLaunching_(self, aNotification):
print("Hello, World!")
def buttonClicked_(self, view):
print("Clicked: " + repr(view))
def touchBar_makeItemForIdentifier_(self, bar, ident):
print("makeItemForIdentifier: " + ident)
if ident == AppDelegate.FOO_BUTTON:
item = NSCustomTouchBarItem.alloc().initWithIdentifier_(ident)
print("made item: " + repr(item))
button = NSButton.buttonWithTitle_target_action_(
"foo", self, "buttonClicked:")
button.setBezelColor_(
NSColor.colorWithRed_green_blue_alpha_(
1.0, 0.0, 0.0, 1.0))
print("made button: " + repr(button))
item.setCustomizationLabel_(ident)
item.setView_(button)
return item
# NSTouchBarProvider protocol
def touchBar(self):
print('touchBar start')
tb = NSTouchBar.alloc().init()
print('alloc')
tb.setDelegate_(self)
print('setDelegate_')
#tb.setCustomizationIdentifier_('fooBar')
tb.setDefaultItemIdentifiers_([AppDelegate.FOO_BUTTON])
#tb.setCustomizationAllowedItemIdentifiers_(['fooButton'])
print('touchBar: ' + repr(tb))
return tb
def main():
app = NSApplication.sharedApplication()
app.setAutomaticCustomizeTouchBarMenuItemEnabled_(True)
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
@ipfans
Copy link

ipfans commented Sep 19, 2019

Traceback (most recent call last):
  File "demo.py", line 18, in <module>
    class AppDelegate (NSObject, NSTouchBarProvider, NSApplicationDelegate):
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

It seems that demo code outdated?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment