Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
#. 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'''
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
#OMTextContentView for console..
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()
@cvpe

This comment has been minimized.

Copy link

@cvpe cvpe commented Apr 12, 2020

Found a bug/problem/issue.
If the edited file contains some Unicode characters longer than one, like '🕐',
selected_text (and also editor.get_selection) is incorrect. It does not take in account real length of such strings.

@cvpe

This comment has been minimized.

Copy link

@cvpe cvpe commented Apr 12, 2020

@jsbain

This comment has been minimized.

Copy link
Owner Author

@jsbain jsbain commented Apr 14, 2020

yeah, i noticed that too (my original example used an emoji for the Apple search menu item, and i got an off by one error).

I think this is also a problem with editor.get_selection? I remember some discussion in the forums a while back -- there may be a workaround using some nsstring or uitextview methods.

@cvpe

This comment has been minimized.

Copy link

@cvpe cvpe commented Apr 14, 2020

I remember I met the same problem when I wrote a script for Japanese emoji in a TextField. Perhaps we could enter an issue for Pythonista editor module.

@jsbain

This comment has been minimized.

Copy link
Owner Author

@jsbain jsbain commented Apr 15, 2020

str(tv.text().substringWithRange_(tv.selectedRange())) seems like it migt work

@jsbain

This comment has been minimized.

Copy link
Owner Author

@jsbain jsbain commented Apr 15, 2020

str(tv.text().substringWithRange_(tv.selectedRange())) seems like it migt work

@cvpe

This comment has been minimized.

Copy link

@cvpe cvpe commented Apr 15, 2020

Seems ok, I'll change my code
Thanks

@cvpe

This comment has been minimized.

Copy link

@cvpe cvpe commented Apr 15, 2020

Perhaps you should also change your code, and I'm sorry but I don't know (or I forgot) how to send you a request to modify
# if selected text contains long unicode characters, erroneous range
# thus we use other way

	#txt=str(editorView.textView().text())
	#start=editorView.textView().selectedTextRange().start().index()
	#end=editorView.textView().selectedTextRange().end().index()
	#selected_text=txt[start:end]
	
	tv = editorView.textView()
	rge = tv.selectedRange()
	start = rge.location
	end   = start + rge.length
	selected_text = str(tv.text().substringWithRange_(rge))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment