Skip to content

Commit 29c372f

Browse files
author
jon b
committed
various fixes
1 parent ed6bfdf commit 29c372f

9 files changed

+139
-50
lines changed

apphack.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def get_toolbar(view):
1515
sv=view.subviews()
1616

1717
for v in sv:
18-
if v._get_objc_classname()=='OMTabViewToolbar':
18+
if v._get_objc_classname().startswith(b'OMTabViewToolbar'):
1919
return v
2020
tb= get_toolbar(v)
2121
if tb:
@@ -59,7 +59,6 @@ def remove_toolbar_button(index):
5959
def run_script(sender):
6060
'''run a script without clearing glbals'''
6161
import editor
62-
editor.reload_files()
63-
execfile(editor.get_path(),globals())
62+
exec(editor.get_text(),globals())
6463

65-
create_toolbar_button(run_script,'iow:play_32',0,'execfile')
64+
create_toolbar_button(run_script,'iow:play_32',0,'execfile')

attribtext2.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# set attributed text dor existing textview
33
# same works for Label, except dont need to set allowsAttributedTextEditing, or call on main thread
44
from objc_util import *
5+
import re
56

67
mystr='''here are some colors:
78
red, yellow, blue, magenta, black, cyan
@@ -26,8 +27,9 @@
2627
for m in sre:
2728
st,end=m.span()
2829
l=end-st
29-
mystro.addAttribute_value_range_('NSColor',color,NSRange(st,l))
30-
30+
mystro.addAttribute_value_range_('NSBackgroundColor',color,NSRange(st,l))
31+
f=ObjCClass('UIFont').fontWithName_size_('Courier',15)
32+
mystro.addAttribute_value_range_(ObjCInstance(c_void_p.in_dll(c,'NSFontAttributeName')),f,NSRange(st,l))
3133
# setup views
3234
import ui
3335

attribtxt.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# coding: utf-8
22
# experiments with attributed strings
33

4-
from objc import *
4+
from objc_util import *
55
import ctypes
66

77
NSMutableAttributedString=ObjCClass('NSMutableAttributedString')
@@ -14,13 +14,13 @@
1414

1515
sz=6.0
1616
traits=0
17-
for i in xrange(len(strtext)/2):
17+
for i in range(len(strtext)//2):
1818
f=UIFont.systemFontOfSize_traits_(sz,traits)
1919
nsr=NSRange(i,1)
2020
attrtext.addAttribute_value_range_(NSFontAttributeName,f,nsr)
2121
sz+=2.5
2222
traits+=1
23-
for i in xrange(len(strtext)/2,len(strtext)-1):
23+
for i in range(len(strtext)//2,len(strtext)-1):
2424
f=UIFont.systemFontOfSize_traits_(sz,traits)
2525
nsr=NSRange(i,1)
2626
attrtext.addAttribute_value_range_(NSFontAttributeName,f,nsr)
@@ -34,4 +34,4 @@
3434
lblobj=ObjCInstance(lbl._objc_ptr)
3535
lblobj.setAttributedText_(attrtext)
3636
lbl.size_to_fit()
37-
s=v.draw_snapshot()
37+
s=v.draw_snapshot()

completer.py

+30-3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ class completion_block_literal(Structure):
3434
c._Block_signature.restype=c_char_p
3535
c._Block_signature.argtypes=[c_void_p]
3636

37+
c._Block_copy.argtypes=[c_void_p]
38+
c._Block_copy.restype=c_void_p
39+
3740
class Suggestion(dict):
3841
def __init__(self,casematches=True,fuzzy=False,isFuzzy=False,isKeyword=False,matchedRanges=0,name='apparent_endoding',rank=0,typ='function',underscores=False):
3942

@@ -48,6 +51,26 @@ def __init__(self,casematches=True,fuzzy=False,isFuzzy=False,isKeyword=False,mat
4851
'type': typ,
4952
'underscores': underscores})
5053
import rlcompleterjb
54+
import ui,time
55+
def complete_later(blk,_requestid):
56+
ui.cancel_delays()
57+
blkcopy=c._Block_copy(c_void_p(blk))
58+
logger.debug(blk,blkcopy)
59+
b=cast(blkcopy,POINTER(completion_block_literal)).contents
60+
61+
s=Suggestion(matchedRanges=0,
62+
name='poop')
63+
s2=Suggestion(matchedRanges=0,
64+
name='pooperiffic')
65+
@ui.in_background
66+
def invoke():
67+
time.sleep(2)
68+
completiondictlist=ns([s,s2])
69+
on_main_thread(
70+
b.invoke)(c_void_p(blkcopy),c_short(_requestid),completiondictlist)
71+
#ui.delay(invoke,0.05)
72+
invoke()
73+
5174

5275
comp=rlcompleterjb.Completer()
5376
def complete(txt,_self):
@@ -87,9 +110,13 @@ def completion_block(_cmd,_requestid,completiondict):
87110
#logger.debug(' calling orig({},{},{},{})'.format(position, cast(tv,c_void_p), requestid,cast(completion,c_void_p)))
88111
#originalmethod(position, cast(tv,c_void_p), requestid,blk)
89112
#sugg=ns([Suggestion(),])
90-
sugg=ns(complete(str(ObjCInstance(tv).text())[0:position], c_void_p(_self)))
91-
if sugg:
92-
completion_block(completion,requestid, sugg.ptr)
113+
114+
if 0:
115+
sugg=ns(complete(str(ObjCInstance(tv).text())[0:position], c_void_p(_self)))
116+
if sugg:
117+
completion_block(completion,requestid, sugg.ptr)
118+
else:
119+
complete_later(completion,requestid)
93120
logger.debug(' done orig')
94121
swizzle.swizzle(ObjCClass('PA2ConsoleCompletionProvider'),'suggestCompletionsForPosition:inTextView:requestID:completion:'
95122
,suggestCompletionsForPosition_inTextView_requestID_completion_,type_encoding=None,debug=True)

keycommands.py

+10-7
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,16 @@ def handleCommandH(_cmd,_sel):
3939
# note __keycommands_obj must hang around in globals, there is probably a more robust way to do this.
4040
def replacement_keyCommands(_self,_cmd):
4141
return __keycommands_obj.ptr
42-
replacement=create_objc_class('replacement',
43-
ObjCClass('UIResponder'),
44-
[replacement_keyCommands])
45-
replacement_obj=replacement.new()
46-
newimp=c.method_getImplementation(replacement_obj.keyCommands.method)
47-
oldimp=c.method_setImplementation(app.keyCommands.method,newimp)
48-
42+
43+
44+
if 0:
45+
replacement=create_objc_class('replacement',
46+
ObjCClass('UIResponder'),
47+
[replacement_keyCommands])
48+
replacement_obj=replacement.new()
49+
newimp=c.method_getImplementation(replacement_obj.keyCommands.method)
50+
oldimp=c.method_setImplementation(app.keyCommands.method,newimp)
51+
swizzle(UIApplication,'keyCommands',replacement_keyCommands)
4952
print 'testing if keycommand was added'
5053
assert(sel_getName(app.keyCommands()[-1].action())=='handleCommandH') #was key added?
5154
print 'testing that action was added'

notification_capture.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
class GlobalNotificationObserver(object):
1212
def __init__(self, excludes=('UI','NS','_UI')) :
13+
#self.captured=[]
1314
self.captured={}
1415
self.center=NSNotificationCenter.defaultCenter()
1516
self.excludes=excludes
@@ -25,7 +26,8 @@ def _block(self,_cmd,notification):
2526
obj=str(ObjCInstance(notification).object())
2627
userInfo=str(ObjCInstance(notification).userInfo())
2728

28-
self.captured[name]=str(obj)+str(userInfo)
29+
#self.captured.append(ObjCInstance(notification),)
30+
self.captured[name]=ObjCInstance(notification)
2931
#console.hud_alert(name)
3032
except:
3133
pass
@@ -54,9 +56,11 @@ def reset(self):
5456
self.stop()
5557
self.captured={}
5658
if __name__=='__main__':
57-
g=GlobalNotificationObserver()
59+
g=GlobalNotificationObserver(excludes='zzz')
5860
g.start()
59-
60-
61-
62-
61+
import ui,time
62+
v=ui.View()
63+
v.present('sheet')
64+
time.sleep(5)
65+
g.stop()
66+
print(list(g.captured.keys()))

reprint_line.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ def reprint_line(text):
1111
p= ts.paragraphs()[r.location-1]
1212
ts.replaceCharactersInRange_withString_(p.range(),ns(text+'\n'))
1313
tv.setNeedsLayout()
14+
return p
1415
if __name__=='__main__':
1516
import time,console
1617
console.clear()
18+
console.set_color(1,0,0)
1719
print('Starting download')
1820
print('downloading')
1921
for i in range(0,100,10):
2022
time.sleep(0.5)
2123
p=reprint_line('downloading {}%'.format(i))
22-
reprint_line('Complete!')
24+
p=reprint_line('Complete!')
2325

swizzlelog.py

+73-22
Original file line numberDiff line numberDiff line change
@@ -5,49 +5,100 @@
55
except:
66
import swizzle
77
from objc_util import *
8+
import ctypes
9+
from ctypes import cast, POINTER, c_int, CFUNCTYPE
10+
import logging
11+
from objc_util import _block_descriptor
12+
13+
logger = logging.getLogger('swizzle')
14+
if not logger.handlers:
15+
hdlr = logging.FileHandler('swizzlelog.txt','w')
16+
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
17+
hdlr.setFormatter(formatter)
18+
logger.addHandler(hdlr)
19+
logger.setLevel(logging.DEBUG)
20+
logger.debug('logging started')
821
def swizzlenop(cls,method):
9-
'''swizzles instance method of cls to print args, then call original.
22+
'''unswizzles instance method of cls to print args, then call original.
1023
cls is an ObjCClass. method is selector name, including :'s
1124
'''
1225
from objc_util import ObjCInstance,parse_types
1326
def swizzled(self,sel,*args):
1427
return None
1528
swizzle.swizzle(cls,method,swizzled)
29+
from threading import Lock
1630

31+
def clsptr(c):
32+
try:
33+
return ObjCClass(c).ptr
34+
except:
35+
return None
36+
allclasses=[clsptr(c) for c in ObjCClass.get_names()]
37+
def isclass(obj):
38+
ptr=ctypes.cast(obj,ctypes.POINTER(c_int))
39+
if ptr[0] in allclasses:
40+
return True
1741
def swizzlelog(cls,method):
1842
'''swizzles instance method of cls to print args, then call original.
1943
cls is an ObjCClass. method is selector name, including :'s
2044
'''
2145
from objc_util import ObjCInstance,parse_types
2246
import time,ui
47+
logger.debug('{} swizzled'.format(method))
2348
def swizzled(self,sel,*args):
24-
print('{}:{} called'.format(time.ctime(),method))
25-
print (args)
26-
argtypes=parse_types(ObjCInstanceMethod(ObjCInstance(self), method).encoding)[1][2:]
27-
newargs=[]
28-
for a,ty in zip(args,argtypes):
29-
if a is not None and ty is c_void_p:
30-
def p():
31-
print (ObjCInstance(a))
32-
ui.delay(p,1)
33-
newargs.append(a)
49+
with Lock():
50+
logger.debug('# # # # # {} # # # # #'.format(method))
51+
logger.debug(' self:{}'.format(self))
52+
logger.debug(' args:{}'.format(args))
53+
argtypes=parse_types(
54+
ObjCInstanceMethod(
55+
ObjCInstance(self),
56+
method).encoding
57+
)[1][2:]
58+
newargs=[]
59+
argidx=0
60+
for a,ty in zip(args,argtypes):
61+
argidx+=1
62+
if a is not None and ty is c_void_p:
63+
logger.debug(' {}\n {}\n {}'.format(argidx,ObjCInstance(a),ty))
64+
newargs.append(ObjCInstance(a))
65+
elif a is not None and ty is ObjCBlock:
66+
def block_logger(_cmd,requestid,matches):
67+
logger.debug('__logger_block: call to {}({}). args: {}, {}'.format(ObjCInstance(a),_cmd,requestid,matches))
68+
69+
#logger.debug('{}'.format(signature))
70+
#invoke=cast(bb.ptr,POINTER(block_literal)).contents.invoke
71+
#invoke(_cmd, requestid, matches)
72+
blk=ObjCBlock(block_logger, restype=None,argtypes=[c_void_p, c_int,c_void_p])
73+
newargs.append(blk)
74+
else:
75+
logger.debug(' {}\n {}\n {}'.format(argidx,(a),ty))
76+
#ui.delay(p,1)
77+
newargs.append(a)
78+
selfinstance=ObjCInstance(self)
79+
logger.debug(('self=',selfinstance))
80+
try:
81+
originalmethod=ObjCInstanceMethod(ObjCInstance(self), 'original'+method)
82+
#logger.debug(originalmethod)
83+
except AttributeError:
84+
import console
85+
console.hud_alert(method)
86+
logger.debug(' attrib error, returning none')
87+
return None
88+
if originalmethod:
89+
logger.debug((' newargs',newargs))
90+
returnval=originalmethod(*newargs)
91+
logger.debug((' =====>',returnval))
92+
if isinstance(returnval,ObjCInstance):
93+
return returnval.ptr
3494
else:
35-
def p():
36-
print(a)
37-
ui.delay(p,1)
38-
newargs.append(a)
39-
returnval= ObjCInstanceMethod(ObjCInstance(self), 'original'+method)(*newargs)
40-
print('returnval',returnval)
41-
if isinstance(returnval,ObjCInstance):
42-
return returnval.ptr
43-
else:
44-
return returnval
95+
return returnval
4596
swizzle.swizzle(cls,method,swizzled,type_encoding=None,debug=True)
4697
def unswizzle(cls,method):
4798
swizzle.unswizzle(cls,method)
4899
def is_swizzled(cls,method):
49100
return swizzle.is_swizzled(cls,method)
50-
101+
unswizzle=swizzlenop
51102

52103

53104
#swizzlelog(ObjCClass("OMProgressHUD_PY3"),'showWithMessage:icon:duration:blockInteraction:')

tableview_rowheight.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ def tableView_heightForRowAtIndexPath_(_self,_sel,tv,path):
2626
else:
2727
return tv_py.row_height
2828
except Exception as e:
29-
print(e)
29+
import traceback
30+
traceback.print_exc()
3031
return 44
3132
# set up the swizzle.. only needs to be do e once
3233
def setup_tableview_swizzle(override=False):

0 commit comments

Comments
 (0)