Skip to content

Instantly share code, notes, and snippets.

@jsbain
Created April 3, 2020 17:05
Show Gist options
  • Save jsbain/b008a7556a0fdd93481ef62688d81462 to your computer and use it in GitHub Desktop.
Save jsbain/b008a7556a0fdd93481ef62688d81462 to your computer and use it in GitHub Desktop.
customMenuItem.py
from objc_util import *
from objc_hacks import swizzle # github.com/jsbain/objc_hacks.git
NSNotificationCenter=ObjCClass('NSNotificationCenter')
class PYUIMenuItem(object):
'''Base class representing a uimenuitem, which can be added to the manager.
Each item must have a title string, a selector name, and an action callback.
Must define subclasses with __selector__ field, __title__ string
Action callback must be of form
def action(self, selected_text (str), selection (list), editorview):
'''
def __new__(cls):
if not hasattr(cls,'__selector__'):
raise Exception('Subclass must define __selector__')
if not hasattr(cls,'__title__'):
raise Exception('Subclass must define __title__')
if not hasattr(cls,'action'):
raise Exception('Subclass must define action method')
menuitem=ObjCClass('UIMenuItem').alloc().initWithTitle_action_(cls.__title__,sel(cls.__selector__))
cls.__menuitem__=menuitem
return cls
def __callback__(self, _editorview, _cmd, menucontroller):
# this is the actual callback that objc sees.
# dont override this
editorView=ObjCInstance(_editorview)
txt=str(editorView.textView().text())
start=editorView.textView().selectedTextRange().start().index()
end=editorView.textView().selectedTextRange().end().index()
selected_text=txt[start:end]
self.action(self,selected_text, [start, end], editorView)
class MenuNotificationObserver(object):
def __init__(self,menuitems) :
self.menuitems=menuitems
self._observer=None
self.center=NSNotificationCenter.defaultCenter()
#clean up old observers, so we dont have old copies responding to notifications
import objc_util
for obj in objc_util._retained_globals:
if isinstance(obj,ObjCInstance):
if 'NSObserver' in str(ObjCInstance(c.object_getClass(obj.ptr))):
if 'ShowMenuNotification' in str(obj.name()):
self.center.removeObserver_(obj)
release_global(obj)
def _block(self,_cmd,notification):
try:
#print('observer')
menucontroller=ObjCInstance(notification).object()
#print(menucontroller)
''' if we hook WillShow instead of DidShow, we can stop the menu from showing, then update it, and show it to avoid blinking effect. but, willshow gets fired twice, so need to only run if our custom menu is not there'''
items=list(menucontroller.menuItems())
itemTitles=[item.__title__ for item in self.menuitems]
if not itemTitles[-1] in [str(i.title()) for i in items]:
def update_menu():
menucontroller.setMenuVisible_animated_(False,False)
for item in self.menuitems:
items.append(item.__menuitem__)
menucontroller.setMenuItems_(ns(items))
menucontroller.update()
menucontroller.setMenuVisible_animated_(True,False)
update_menu()
except Exception as e:
print(e)
def start(self):
if self._observer:
raise Exception('observer already started')
self._blk=ObjCBlock(self._block,
restype=None,
argtypes=[c_void_p,c_void_p])
self._observer = self.center.addObserverForName_object_queue_usingBlock_(
'UIMenuControllerWillShowMenuNotification',None,None,self._blk)
observer=self._observer
center=self.center
retain_global(observer)
#attempt at safety.. this doesnt work at all..
'''
import weakref
def on_die(killed_ref):
print('reference released!')
import objc_util
center.removeObserver_(observer)
objc_util.release_global(observer)
self._del_ref = weakref.ref(self, on_die)
'''
def stop(self):
import objc_util
if self._observer:
self.center.removeObserver_(self._observer)
objc_util.release_global(self._observer)
self._observer=None
self._del_ref=None
def register(self):
#we must swizzle our own selector into the responder chain
import editor
editorView=editor._get_editor_tab().editorView()
OMTextEditorView=ObjCInstance(c.object_getClass(editorView.ptr))
for uimenu in self.menuitems:
try:
import functools
cb=functools.partial(uimenu.__callback__,uimenu)
swizzle.swizzle(OMTextEditorView,uimenu.__selector__,cb,type_encoding='v@:@')
except:
print('could not swizzle', uimenu.__title__)
if __name__=='__main__':
#create two example menu items
class AppleLookupMenu(PYUIMenuItem):
__selector__ = 'appleDocLookup:'
__title__ = 'Apple'
def action(self, selected_text, selection, editorview):
import ui
w=ui.WebView()
import urllib.parse
w.load_url('http://www.google.com#q={}'.format(urllib.parse.quote(selected_text+' host:developer.apple.com')))
w.present('panel')
class TestMenu(PYUIMenuItem):
__selector__ = 'handleTestMenu:'
__title__ = 'Test'
def action(self, selected_text, selection, editorview):
import ui
print(selected_text)
print(selection)
print(editorview)
g=MenuNotificationObserver([AppleLookupMenu(), TestMenu()])
g.register()
g.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment