Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
customMenuItem.py
# from https://gist.github.com/jsbain/9edea18951d296ca46aca8868791e04e
# small modifications of @jonB script to:
# - pass to MenuNotificationObserver class, new menu items as
# either one item, as originally
# either as a tuple with 2nd element as title of an existing option
# where to insert before
# - no insert if existing option does not exist to avoid unuseless option
from objc_util import *
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
#. there is probably a better way to do this
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(UIApplication.om_firstResponder())
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'''
def update_menu():
items = list(menucontroller.menuItems())
change = False
for item in self.menuitems:
if isinstance(item, tuple):
uimenu = item[0]
if uimenu.__title__ in [str(i.title()) for i in items]:
continue # aleady in menu options
before_title = item[1]
for idx in range(len(items)):
if before_title in str(items[idx].title()):
change = True
items.insert(idx,uimenu.__menuitem__)
break
# before_title not found, do not append new menu
else:
uimenu = item
if uimenu.__title__ in [str(i.title()) for i in items]:
continue # aleady in menu options
change = True
items.append(uimenu.__menuitem__)
if change:
# at least one new menu option was not already there
menucontroller.setMenuVisible_animated_(False,False)
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
#OMTextContentView for console..
editorView=editor._get_editor_tab().editorView()
OMTextEditorView=ObjCInstance(c.object_getClass(editorView.ptr))
for item in self.menuitems:
uimenu = item[0] if isinstance(item, tuple) else item
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(),'Help')])
g.register()
g.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment