Ejemplo n.º 1
0
def setup_tableview_swizzle(override=False):
    t = ui.TableView()
    t_o = ObjCInstance(t)
    encoding = t_o.rowHeight.encoding[0:1] + b'@:@@'
    if hasattr(t_o, 'tableView_heightForRowAtIndexPath_') and not override:
        return
    swizzle.swizzle(ObjCClass(t_o._get_objc_classname()),
                    ('tableView:heightForRowAtIndexPath:'),
                    tableView_heightForRowAtIndexPath_, encoding)
Ejemplo n.º 2
0
def setup_tableview_swizzle(override=False):
	t=ui.TableView()
	t_o=ObjCInstance(t)
	encoding=t_o.rowHeight.encoding[0:1]+b'@:@@'
	if hasattr(t_o,'tableView_heightForRowAtIndexPath_') and not override:
		return
	swizzle.swizzle(ObjCClass(t_o._get_objc_classname()),
								('tableView:heightForRowAtIndexPath:'),
								tableView_heightForRowAtIndexPath_,encoding)
Ejemplo n.º 3
0
def swizzlenop(cls, method):
    '''swizzles instance method of cls to print args, then call original.
	cls is an ObjCClass.    method is selector name, including :'s
	'''
    from objc_util import ObjCInstance, parse_types

    def swizzled(self, sel, *args):
        return None

    swizzle.swizzle(cls, method, swizzled)
	def setup_tableview_swizzle(self,override=False):
		#it doesn't seem to matter whether we set this to our tableview, or to a new tableviewinstance....
		#t=ui.TableView()
		t = self.tableView
		#t = ui.TableView()
		t_o=ObjCInstance(t)
	
		encoding=ObjCInstanceMethod(t_o,'rowHeight').encoding[0:1]+b'@:@@'
		if hasattr(t_o,'tableView_heightForRowAtIndexPath_') and not override:
			return
		swizzle.swizzle(ObjCClass(t_o._get_objc_classname()),
									('tableView:heightForRowAtIndexPath:'),
									self.tableView_heightForRowAtIndexPath_,encoding)
Ejemplo n.º 5
0
def setup_tableview_swizzle(override=False):
    t = ui.TableView()
    t_o = ObjCInstance(t)

    encoding = ObjCInstanceMethod(t_o, "rowHeight").encoding[0:1] + b"@:@@"
    if hasattr(t_o, "tableView_heightForRowAtIndexPath_") and not override:
        return
    swizzle.swizzle(
        ObjCClass(t_o._get_objc_classname()),
        ("tableView:heightForRowAtIndexPath:"),
        tableView_heightForRowAtIndexPath_,
        encoding,
    )
Ejemplo n.º 6
0
def setup_tableview_swizzle(override=False):
	t=ui.TableView()
	t_o=ObjCInstance(t)

	encoding=ObjCInstanceMethod(t_o,'rowHeight').encoding[0:1]+b'@:@@'
	if hasattr(t_o,'tableView_heightForRowAtIndexPath_') and not override:
		return
	swizzle.swizzle(ObjCClass(t_o._get_objc_classname()),
								('tableView:heightForRowAtIndexPath:'),
								tableView_heightForRowAtIndexPath_,encoding)

	encoding=b'v@:@@i'
	swizzle.swizzle(ObjCClass(t_o._get_objc_classname()),
		('tableView:willDisplayHeaderView:forSection:'),
		tableView_willDisplayHeaderView_forSection_,encoding)
Ejemplo n.º 7
0
def swizzlelog(cls, method):
    '''swizzles instance method of cls to print args, then call original.
	cls is an ObjCClass.    method is selector name, including :'s
	'''
    from objc_util import ObjCInstance, parse_types
    import time, ui

    def swizzled(self, sel, *args):
        print('{}:{} called'.format(time.ctime(), method))
        print(args)
        argtypes = parse_types(
            ObjCInstanceMethod(ObjCInstance(self), method).encoding)[1][2:]
        newargs = []
        for a, ty in zip(args, argtypes):
            if a is not None and ty is c_void_p:

                def p():
                    print(ObjCInstance(a))

                ui.delay(p, 1)
                newargs.append(a)
            else:

                def p():
                    print(a)

                ui.delay(p, 1)
                newargs.append(a)
        returnval = ObjCInstanceMethod(ObjCInstance(self),
                                       'original' + method)(*newargs)
        print('returnval', returnval)
        if isinstance(returnval, ObjCInstance):
            return returnval.ptr
        else:
            return returnval

    swizzle.swizzle(cls, method, swizzled, type_encoding=None, debug=True)
Ejemplo n.º 8
0
def swizzlelog(cls, method):
    '''swizzles instance method of cls to print args, then call original.
	cls is an ObjCClass.    method is selector name, including :'s
	'''
    from objc_util import ObjCInstance, parse_types
    import time, ui
    logger.debug('{} swizzled'.format(method))

    def swizzled(self, sel, *args):
        with Lock():
            logger.debug('# # # # # {} # # # # #'.format(method))
            logger.debug('   self:{}'.format(self))
            logger.debug('   args:{}'.format(args))
            argtypes = parse_types(
                ObjCInstanceMethod(ObjCInstance(self), method).encoding)[1][2:]
            newargs = []
            argidx = 0
            for a, ty in zip(args, argtypes):
                argidx += 1
                if a is not None and ty is c_void_p:
                    logger.debug('    {}\n       {}\n      {}'.format(
                        argidx, ObjCInstance(a), ty))
                    newargs.append(ObjCInstance(a))
                elif a is not None and ty is ObjCBlock:

                    def block_logger(_cmd, requestid, matches):
                        logger.debug(
                            '__logger_block: call to {}({}). args: {}, {}'.
                            format(ObjCInstance(a), _cmd, requestid, matches))

                        #logger.debug('{}'.format(signature))
                        #invoke=cast(bb.ptr,POINTER(block_literal)).contents.invoke
                        #invoke(_cmd, requestid, matches)

                    blk = ObjCBlock(block_logger,
                                    restype=None,
                                    argtypes=[c_void_p, c_int, c_void_p])
                    newargs.append(blk)
                else:
                    logger.debug('    {}\n       {}\n     {}'.format(
                        argidx, (a), ty))
                    #ui.delay(p,1)
                    newargs.append(a)
            selfinstance = ObjCInstance(self)
            logger.debug(('self=', selfinstance))
            try:
                originalmethod = ObjCInstanceMethod(ObjCInstance(self),
                                                    'original' + method)
                #logger.debug(originalmethod)
            except AttributeError:
                import console
                console.hud_alert(method)
                logger.debug('     attrib error, returning none')
                return None
            if originalmethod:
                logger.debug(('     newargs', newargs))
                returnval = originalmethod(*newargs)
                logger.debug(('  =====>', returnval))
            if isinstance(returnval, ObjCInstance):
                return returnval.ptr
            else:
                return returnval

    swizzle.swizzle(cls, method, swizzled, type_encoding=None, debug=True)
Ejemplo n.º 9
0
	g=ObjCInstance(gr)
	o=ObjCInstance(ogr)
	ispinch=g._get_objc_classname()==b'UIPinchGestureRecognizer'
	ispan=g._get_objc_classname()==b'UIPanGestureRecognizer'
	istap=g._get_objc_classname()==b'UITapGestureRecognizer'
	if (ispinch or ispan or istap) and (g.view()==o.view()) :
		return True
	else:
		return False
def gestureRecognizer_shouldRequireFailureOfGestureRecognizer_(
	_self,_sel,gr,othergr):
	console.hud_alert('aaa')
	return True
	
cls=ObjCClass(UIApplication.sharedApplication()._rootViewControllers()[0]._get_objc_classname())
swizzle.swizzle(cls,
								'gestureRecognizer:shouldRequireFailureOfGestureRecognizer:',gestureRecognizer_shouldRequireFailureOfGestureRecognizer_,'c@:@@')
								
def math_eval(expr):
	import math
	import re
	whitelist = '|'.join(
	# oprators, digits
	['-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '\d+' ])

	if re.match(whitelist,expr):
		return eval(expr)
	else:
		return 1.0
																									
class RoomAreaView(ui.View):
	''' top level container, consisting of an imageview and an overlay	.  
Ejemplo n.º 10
0
        #sugg=ns([Suggestion(),])

        if 0:
            sugg = ns(
                complete(
                    str(ObjCInstance(tv).text())[0:position], c_void_p(_self)))
            if sugg:
                completion_block(completion, requestid, sugg.ptr)
        else:
            complete_later(completion, requestid)
        logger.debug('   done orig')


swizzle.swizzle(
    ObjCClass('PA2ConsoleCompletionProvider'),
    'suggestCompletionsForPosition:inTextView:requestID:completion:',
    suggestCompletionsForPosition_inTextView_requestID_completion_,
    type_encoding=None,
    debug=True)


def matchedRangesForPattern_inString_(_self, _sel, pattern, string):
    with Lock():
        #logger.debug(NSThread.currentThread())
        try:
            #logger.debug('     pattern: {}  string:{}'.format(ObjCInstance(pattern), ObjCInstance(string)))
            originalmethod = ObjCInstanceMethod(
                ObjCInstance(_self),
                'original' + 'matchedRangesForPattern:inString:')
            returnval = originalmethod(c_void_p(pattern), c_void_p(string))
            return returnval.ptr
        except Exception as e:
Ejemplo n.º 11
0
		x_callback_info.source_app = str(ObjCInstance(source_app))
		
		query = NSURLComponents.componentsWithURL_resolvingAgainstBaseURL_(nsurl(url_str), False)
		x_callback_info.parameters = dict()
		for queryItem in query.queryItems():
			x_callback_info.parameters[str(queryItem.name())] = str(queryItem.value())
			
		if not _handler == None:
			_handler(x_callback_info)
		return True



# Do the swizzling
cls = ObjCInstance(c.object_getClass(appDelegate.ptr))
swizzle.swizzle(cls, 'application:openURL:sourceApplication:annotation:', application_openURL_sourceApplication_annotation_)




if __name__ == '__main__':
	import console
	console.clear()
	
	draft_uuid = '9B0A1EF8-B2D8-4050-8EE4-B6D8AC0F229B'
	url = 'drafts4://x-callback-url/get?uuid={}&x-success=pythonista://'.format(draft_uuid)
	
	def my_handler(info):
		print(info.full_url)
		print(info.parameters['text'])
	
Ejemplo n.º 12
0
def writeNv(f, SRGB, n, numImages, numBlocks):
    width, height, format_, fourcc, dataSize, compSel, numMips, data = dds.readDDS(f, SRGB)

    if 0 in [width, dataSize] and data == []:
        print("")
        if n != (numImages - 1):
            print("Continuing in 5 seconds...")
            time.sleep(5)
            return b''
        else:
            print("Exiting in 5 seconds...")
            time.sleep(5)
            sys.exit(1)

    if format_ not in formats:
        print("")
        print("Unsupported DDS format!")
        print("")
        if n != (numImages - 1):
            print("")
            print("Continuing in 5 seconds...")
            time.sleep(5)
            return b''
        else:
            print("Exiting in 5 seconds...")
            time.sleep(5)
            sys.exit(1)

    if numMips > 16:
        print("")
        print("Invalid number of mipmaps for " + f)
        print("")
        if n != (numImages - 1):
            print("")
            print("Continuing in 5 seconds...")
            time.sleep(5)
            return b''
        else:
            print("Exiting in 5 seconds...")
            time.sleep(5)
            sys.exit(1)

    imageData = data[:dataSize]
    mipData = data[dataSize:]
    numMips += 1

    bpp = bpps[format_]

    alignment = 512

    if numMips - 1:
        print("")
        print("Processing " + str(numMips - 1) + " mipmaps:")

    swizzled_data = bytearray()
    offset = 0
    mipOffsets = []
    for i in range(numMips):
        if not i:
            data = imageData
        else:
            print(str(i) + ": " + str(max(1, width >> i)) + "x" + str(max(1, height >> i)))

            mipOffset, dataSize = get_curr_mip_off_size(width, height, bpp, i, format_ in BCn_formats)

            data = mipData[mipOffset:mipOffset+dataSize]

        mipOffsets.append(offset)

        offset += len(data)

        swizzled_data += swizzle.swizzle(max(1, width >> i), max(1, height >> i), format_, data)

    print("")
    print("// ----- NvTextureHeader Info ----- ")
    print("  imageSize       = " + str(offset))
    print("  alignment       = " + str(alignment))
    print("  width           = " + str(width))
    print("  height          = " + str(height))
    print("  depth           = 1")
    print("  target          = 1")
    print("  format          = " + formats[format_])
    print("  numMips         = " + str(numMips))
    print("  sliceSize       = " + str(offset))
    print("")
    print("  bits per pixel  = " + str(bpp * 8))
    print("  bytes per pixel = " + str(bpp))

    if format_ == 1:
        if compSel not in [[0, 0, 0, 5], [0, 5, 5, 5]]:
            warn_color()

    elif format_ == 0xd:
        if compSel not in [[0, 0, 0, 1], [0, 5, 5, 1]]:
            warn_color()

    elif format_ == 0x3c:
        if compSel != [0, 1, 2, 5]:
            warn_color()

    else:
        if compSel != [0, 1, 2, 3]:
            warn_color()

    block_head_struct = NvBlockHeader()
    tex_blk_head = block_head_struct.pack(0x4E764248, 0x24, 0x78, 0x24, 2, numBlocks, 0)

    numBlocks += 1

    tex_head_struct = NvTextureHeader()
    tex_head = tex_head_struct.pack(offset, alignment, width, height, 1, 1, format_, numMips, offset)

    image_blk_head = block_head_struct.pack(0x4E764248, 0x24, offset, 0x154, 3, numBlocks, 0)

    numBlocks += 1

    align_blk = b'\x00' * 0x130

    output = tex_blk_head + tex_head

    i = 0
    for offset in mipOffsets:
        output += offset.to_bytes(4, 'little')
        i += 1
    for z in range(17 - i):
        output += 0 .to_bytes(4, 'little')

    output += 0x700000004.to_bytes(12, 'little')
    output += image_blk_head
    output += align_blk
    output += swizzled_data

    return output, numBlocks
Ejemplo n.º 13
0
					b.invoke(c_void_p(completion),c_short(_requestid),c_void_p(completiondict))
				except Exception as e:
					logger.error(e)
					logger.error(e.__traceback__)
		blk=ObjCBlock(completion_block,
			restype=None,
			argtypes=[c_void_p, c_int, c_void_p])
		#originalmethod=ObjCInstanceMethod(ObjCInstance(_self), 'original'+'suggestCompletionsForPosition:inTextView:requestID:completion:')
		#logger.debug('   calling orig({},{},{},{})'.format(position, cast(tv,c_void_p), requestid,cast(completion,c_void_p)))
		#originalmethod(position, cast(tv,c_void_p), requestid,blk)
		#sugg=ns([Suggestion(),])
		sugg=ns(complete(str(ObjCInstance(tv).text())[0:position], c_void_p(_self)))
		if sugg:
			completion_block(completion,requestid, sugg.ptr)
		logger.debug('   done orig')
swizzle.swizzle(ObjCClass('PA2ConsoleCompletionProvider'),'suggestCompletionsForPosition:inTextView:requestID:completion:'
,suggestCompletionsForPosition_inTextView_requestID_completion_,type_encoding=None,debug=True)

def matchedRangesForPattern_inString_(_self,_sel,pattern, string):
	with Lock():
		#logger.debug(NSThread.currentThread())
		try:
			#logger.debug('     pattern: {}  string:{}'.format(ObjCInstance(pattern), ObjCInstance(string)))
			originalmethod=ObjCInstanceMethod(ObjCInstance(_self), 'original'+'matchedRangesForPattern:inString:')
			returnval= originalmethod(c_void_p(pattern),c_void_p(string))
			return returnval.ptr
		except Exception as e:
			logger.error(e)
			return None
			
#swizzle.swizzle(ObjCClass('PA2ConsoleCompletionProvider'),	'matchedRangesForPattern:inString:',	matchedRangesForPattern_inString_,	type_encoding=None,debug=True)
Ejemplo n.º 14
0
    objc_setAssociatedObject(_utils._application, associated_obj_key, commands,
                             1)


def _add_custom_command(command):
    existing_custom_commands = _get_custom_commands()
    existing_custom_commands.addObject_(command)
    save_custom_commands(existing_custom_commands)


def keyCommands(_self, _sel):
    commands = _get_custom_commands()
    commands.addObjectsFromArray_(_utils._application.originalkeyCommands())
    return commands.ptr


# Even though the script will be imported multiple times, we should swizzle only once
if not "originalkeyCommands" in dir(_utils._application):
    app = _utils._application
    cls = objc_util.ObjCInstance(objc_util.c.object_getClass(app.ptr))
    swizzle.swizzle(cls, 'keyCommands', keyCommands)

if __name__ == "__main__":

    def handler(_self, _cmd):
        print("ACTION")

    c = register("cmd+option+U", handler, "ACTION")
    print(_get_custom_commands())
    #deregister(c)
Ejemplo n.º 15
0
	g=ObjCInstance(gr)
	o=ObjCInstance(ogr)
	ispinch=g._get_objc_classname()==b'UIPinchGestureRecognizer'
	ispan=g._get_objc_classname()==b'UIPanGestureRecognizer'
	istap=g._get_objc_classname()==b'UITapGestureRecognizer'
	if (ispinch or ispan or istap) and (g.view()==o.view()) :
		return True
	else:
		return False
def gestureRecognizer_shouldRequireFailureOfGestureRecognizer_(
	_self,_sel,gr,othergr):
	console.hud_alert('aaa')
	return True
	
cls=ObjCClass(UIApplication.sharedApplication()._rootViewControllers()[0]._get_objc_classname())
swizzle.swizzle(cls,
								'gestureRecognizer:shouldRequireFailureOfGestureRecognizer:',gestureRecognizer_shouldRequireFailureOfGestureRecognizer_,'c@:@@')
								
def math_eval(expr):
	import math
	import re
	whitelist = '|'.join(
	# oprators, digits
	['-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '\d+' ])

	if re.match(whitelist,expr):
		return eval(expr)
	else:
		return 1.0
																									
class RoomAreaView(ui.View):
	''' top level container, consisting of an imageview and an overlay	.  
Ejemplo n.º 16
0
        query = NSURLComponents.componentsWithURL_resolvingAgainstBaseURL_(
            nsurl(url_str), False)
        x_callback_info.parameters = dict()
        for queryItem in query.queryItems():
            x_callback_info.parameters[str(queryItem.name())] = str(
                queryItem.value())

        if _handler:
            _handler(x_callback_info)
        return True


# Do the swizzling
cls = ObjCInstance(c.object_getClass(appDelegate.ptr))
swizzle.swizzle(cls, 'application:openURL:sourceApplication:annotation:',
                application_openURL_sourceApplication_annotation_)

if __name__ == '__main__':
    import console
    console.clear()

    draft_uuid = '9B0A1EF8-B2D8-4050-8EE4-B6D8AC0F229B'
    url = 'drafts4://x-callback-url/get?uuid={}&x-success=pythonista://'.format(
        draft_uuid)

    def my_handler(info):
        print((info.full_url))
        print((info.parameters['text']))

    open_url(url, my_handler)
                    content = fil.read().lower()
                    if se not in content:
                        continue
                # segmentation error crash if url or title contains a blank,
                # even if contains %20 instead of blank
                # thus replace blank by ~ (allowed character in url)
                # url is zip:///...myfile:///...#title
                my_path = 'myfile://' + fpath.replace(' ', '~')  # temporary
                i = fpath.find(tx) + len(tx)
                t = fpath[i:]
                t = t.replace(' ', '~')
                typ = 'mod'  # mod,exception,attribute,method,class,function,data
                new_search_results.append(
                    ns({
                        'path': my_path,
                        'rank': 10,
                        'title': t,
                        'type': typ
                    }))
    scantree(path)

    #print('search:',self.searchTerm(),'results=',new_search_results)
    self.originalsetSearchResults_(new_search_results)


cls = ObjCClass('PA2QuickHelpContentViewController')
swizzle.swizzle(cls, 'initWithURL:', initWithURL_)

cls2 = ObjCClass('PA2QuickHelpViewController')
swizzle.swizzle(cls2, 'setSearchResults:', setSearchResults_)
Ejemplo n.º 18
-1
def swizzlelog(cls,method):	
	'''swizzles instance method of cls to print args, then call original.
	cls is an ObjCClass.    method is selector name, including :'s
	'''
	from objc_util import ObjCInstance,parse_types
	import time,ui
	def swizzled(self,sel,*args):
		print('{}:{} called'.format(time.ctime(),method))
		print (args)
		argtypes=parse_types(ObjCInstanceMethod(ObjCInstance(self), method).encoding)[1][2:]
		newargs=[]
		for a,ty in zip(args,argtypes):
			if a is not None and ty is c_void_p:
				def p():
					print (ObjCInstance(a))
				ui.delay(p,1)
				newargs.append(a)
			else:
				def p():
					print(a)
				ui.delay(p,1)
				newargs.append(a)
		returnval= ObjCInstanceMethod(ObjCInstance(self), 'original'+method)(*newargs)
		print('returnval',returnval)
		if isinstance(returnval,ObjCInstance):
			return returnval.ptr
		else:
			return returnval
	swizzle.swizzle(cls,method,swizzled,type_encoding=None,debug=True)
Ejemplo n.º 19
-1
def swizzlenop(cls,method):	
	'''swizzles instance method of cls to print args, then call original.
	cls is an ObjCClass.    method is selector name, including :'s
	'''
	from objc_util import ObjCInstance,parse_types
	def swizzled(self,sel,*args):
		return None
	swizzle.swizzle(cls,method,swizzled)