Пример #1
0
    def reload_path(self, path):
        index = None
        for idx, item in enumerate(self.items):
            if item['path'] == path:
                index = idx
                break

        if index is None:
            issue('drag_and_drop.py: unable to item in reload_path')
            return

        item = self.items[index]
        node = item['node']
        node.invalidate_children()

        tv_objc = ObjCInstance(self.tableview)

        if node.path in self._expanded_node_paths:
            # Folder expanded, reload the whole section
            self._items = None
            index_set = NSIndexSet.alloc().initWithIndex_(self._folder_section)
            tv_objc.reloadSections_withRowAnimation_(ns(index_set), 0)
        else:
            # Not expanded, just reload folder row, so the triangle is expanded
            index_paths = []
            index_paths.append(
                NSIndexPath.indexPathForRow_inSection_(index,
                                                       self._folder_section))
            tv_objc.reloadRowsAtIndexPaths_withRowAnimation_(
                ns(index_paths), 0)
Пример #2
0
def load_comic(view, num):
    if num == 404:
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num / latest
        view.comic = None
        objc_util.ObjCInstance(view.navigation_view).navigationController(
        ).topViewController().title = objc_util.ns('404 - Not Found')
        return
    console.show_activity()
    comic = get_info(num)
    if comic:
        if num in faves:
            view['fav'].image = ui.Image('iob:ios7_heart_32')
        else:
            view['fav'].image = ui.Image('iob:ios7_heart_outline_32')
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num / latest
        view.comic = comic

        #view['comic'].image = get_comic(view.comic['img'])
        view['wv'].load_url(get_comic(view.comic['img']))
        objc_util.ObjCInstance(view.navigation_view).navigationController(
        ).topViewController().title = objc_util.ns(view.comic['title'])

    console.hide_activity()
Пример #3
0
    def __init__(self, tableView, filterData, *args, **kwargs):
        ui.View.__init__(self, *args, **kwargs)
        frame = CGRect(CGPoint(0, 0), CGSize(self.width, self.height))
        self.tv = tableView
        self.tableView = ObjCInstance(self.tv)
        flex_width, flex_height = (1 << 1), (1 << 4)
        self.tableView.setAutoresizingMask_(flex_width | flex_height)
        sd = createSearchDelegateClass()
        self.searchDelegate = sd.alloc().init().autorelease()
        self.searchDelegate.filt = filterData
        searchBar = UISearchBar.alloc().init()
        searchBar.setPlaceholder_(ns('Search'))
        searchBar.setDelegate_(self.searchDelegate)
        #searchBar.setShowsBookmarkButton_(ns(True))
        searchBar.setShowsCancelButton_(ns(True))
        #searchBar.setShowsSearchResultsButton_(ns(True))
        #searchBar.setScopeButtonTitles_(ns(['test1','hi']))
        #searchBar.setShowsScopeBar(ns(True))

        self.tableView.setTableHeaderView_(searchBar)
        searchBar.sizeToFit()

        self_objc = ObjCInstance(self)
        self_objc.addSubview_(self.tableView)
        self.tableView.release()
Пример #4
0
    def tableview_did_select(self, tv, section, row):
        tv_objc = ObjCInstance(tv)
        index_path = tv_objc.indexPathForSelectedRow()

        if section == self._file_section:
            tv_objc.deselectRowAtIndexPath_animated_(index_path, True)
            return

        item = self.items[row]
        node = item.get('node', None)

        if node.path == self._root_node.path or not node.children:
            tv_objc.deselectRowAtIndexPath_animated_(index_path, True)
            return

        tv_objc.beginUpdates()
        start_index = row + 1
        try:
            self._expanded_node_paths.remove(node.path)

            index_paths = []
            for index, item in enumerate(self._items[start_index:]):
                if item['node'].path.startswith(node.path):
                    index_paths.append(
                        NSIndexPath.indexPathForRow_inSection_(
                            start_index + index, section))
                else:
                    break

            if index_paths:
                self._items[start_index:start_index + len(index_paths)] = []
                tv_objc.deleteRowsAtIndexPaths_withRowAnimation_(
                    ns(index_paths), 3)

        except KeyError:
            self._expanded_node_paths.add(node.path)
            child_items = self._generate_node_children_items(node)

            index_paths = []
            for i in range(start_index, start_index + len(child_items)):
                index_paths.append(
                    NSIndexPath.indexPathForRow_inSection_(i, section))

            self._items[start_index:start_index] = child_items
            tv_objc.insertRowsAtIndexPaths_withRowAnimation_(
                ns(index_paths), 3)

        tv_objc.reloadRowsAtIndexPaths_withRowAnimation_(ns([index_path]), 5)
        tv_objc.endUpdates()
        self._update_path_items()
Пример #5
0
def add(action, index=-1):
    assert isinstance(action, dict), "The new action should be a dictionary"
    assert action["scriptName"], "The new action must contain a script to run"

    script_name = action["scriptName"]
    icon = action.get("iconName", "python")
    iconColor = action.get("iconColor", None)
    arguments = action.get("arguments", None)
    title = action.get("title", os.path.split(script_name)[1])

    new_action = {
        "scriptName": script_name,
        "iconName": icon,
        "arguments": arguments,
        "iconColor": iconColor,
        "title": title
    }

    if new_action["iconColor"] is None: del new_action["iconColor"]
    if new_action["arguments"] is None: del new_action["arguments"]

    current_actions = defaults.get("EditorActionInfos").mutableCopy()
    if index == -1:
        _index = current_actions.count()
    else:
        _index = index
    current_actions.insert(Object=objc_util.ns(new_action), atIndex=_index)
    defaults.set("EditorActionInfos", current_actions)
Пример #6
0
def load_custom_font(file):
    #https://marco.org/2012/12/21/ios-dynamic-font-loading
    font_url = CFURLCreateWithString(None, objc_util.ns(file), None)

    error = ctypes.c_void_p(None)
    success = CTFontManagerRegisterFontsForURL(
        objc_util.ObjCInstance(font_url), 0, ctypes.byref(error))
    def scantree(path):
        """Recursively yield DirEntry objects for given directory."""
        for entry in os.scandir(path):
            if entry.is_dir(follow_symlinks=False):
                scantree(entry.path)
            else:
                fpath = entry.path
                if os.path.splitext(entry.path)[-1].lower() != ".py":
                    continue

    #for root, dirs, files in os.walk(path):
    #	for f in files:
    #		fpath = os.path.join(root, f)
    #		if os.path.splitext(fpath)[-1].lower() in [".py"]:
                with open(fpath, mode='rt', encoding='utf-8',
                          errors='ignore') as fil:
                    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
                    }))
Пример #8
0
def _blackmamba_keyCommands(_self, _cmd):
    """Swizzled version of keyCommands(). It calls original method to
    get Pythonista shortcuts and then appends custom ones."""
    obj = ObjCInstance(_self)
    commands = list(obj.originalkeyCommands() or [])
    commands.extend(_key_commands)
    return ns(commands).ptr
Пример #9
0
def _register_key_command(input, modifier_flags, function, title=None):
    if not UIApplication.sharedApplication().respondsToSelector_(
            sel('originalkeyCommands')):
        swizzle('UIApplication', 'keyCommands', _blackmamba_keyCommands)

    selector_name = _key_command_selector_name(input, modifier_flags)
    selector = sel(selector_name)
    obj = UIApplication.sharedApplication()

    info('Registering key command "{}" ({})'.format(
        _shortcut_name(input, modifier_flags), title
        or 'No discoverability title'))

    if not callable(function):
        error('Skipping, provided function is not callable')
        return False

    if obj.respondsToSelector_(selector):
        error('Skipping, method {} already registered'.format(selector_name))
        return False

    def key_command_action(_sel, _cmd, sender):
        function()

    IMPTYPE = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p)
    imp = IMPTYPE(key_command_action)
    retain_global(imp)

    cls = c.object_getClass(obj.ptr)
    type_encoding = c_char_p('v@:@'.encode('utf-8'))
    did_add = c.class_addMethod(cls, selector, imp, type_encoding)
    if not did_add:
        error('Failed to add key command method {}'.format(selector_name))
        return False

    if isinstance(modifier_flags, UIKeyModifier):
        modifier_flags = modifier_flags.value

    if title:
        kc = UIKeyCommand.keyCommandWithInput_modifierFlags_action_discoverabilityTitle_(
            ns(input), modifier_flags, selector, ns(title))
    else:
        kc = UIKeyCommand.keyCommandWithInput_modifierFlags_action_(
            ns(input), modifier_flags, selector)

    _key_commands.append(kc)
    return True
def setSearchResults_(_self, _sel, _search_results):
    from objc_util import ObjCInstance, ns
    import os
    global search_term
    self = ObjCInstance(_self)  # PA2QuickHelpViewController
    #print(dir(self))
    search_term = str(self.searchTerm())
    search_results = ObjCInstance(_search_results)
    #print(search_results)
    new_search_results = []

    # if Pythonista help also needed
    for elem in search_results:
        new_search_results.append(ns(elem))

    path = os.path.expanduser('~/Documents')
    tx = '/Pythonista3/Documents/'
    se = search_term.lower()

    # search all .py. Tests show that os.scandir is quicker than os.walk
    def scantree(path):
        """Recursively yield DirEntry objects for given directory."""
        for entry in os.scandir(path):
            if entry.is_dir(follow_symlinks=False):
                scantree(entry.path)
            else:
                fpath = entry.path
                if os.path.splitext(entry.path)[-1].lower() != ".py":
                    continue

    #for root, dirs, files in os.walk(path):
    #	for f in files:
    #		fpath = os.path.join(root, f)
    #		if os.path.splitext(fpath)[-1].lower() in [".py"]:
                with open(fpath, mode='rt', encoding='utf-8',
                          errors='ignore') as fil:
                    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)
Пример #11
0
 def _create_objc(self):
     self._scene_objc = SCNView.alloc().initWithFrame_options_(
         ((0, 0), (100, 100)), ns({'SCNViewOptionPreferredRenderingAPI':
                                   1})).autorelease()
     self._scene_objc.setAutoresizingMask_(18)  # Fill superview
     self._scene_objc.setNeedsDisplayOnBoundsChange_(True)  # fill on change
     self._scene_ref = None
     self._pointOfView_ref = Node(self._scene_objc.pointOfView())
Пример #12
0
 def save_to_file(self, file_name):
     if SUPPORTED_FORMATS.match(path.rsplit('.', 1)[-1]):
         options = ns({'SCNSceneExportDestinationURL': nsurl(path)})
         file = nsurl(file_name)
         
         return self._objc.writeToURL_options_(url, options)
     else:
         raise TypeError('Not a supported export type')
Пример #13
0
    def save_to_file(self, file_name):
        if SUPPORTED_FORMATS.match(path.rsplit('.', 1)[-1]):
            options = ns({'SCNSceneExportDestinationURL': nsurl(path)})
            file = nsurl(file_name)

            return self._objc.writeToURL_options_(url, options)
        else:
            raise TypeError('Not a supported export type')
Пример #14
0
 def keyCommands(_self, _cmd):
     key_commands = [
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('C',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('D',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('P',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('N',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('K',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('U',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('A',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('E',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('W',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('L',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('Z',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('[',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_(']',
                                                                CTRL_KEY_FLAG,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('UIKeyInputUpArrow',
                                                                0,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('UIKeyInputDownArrow',
                                                                0,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('UIKeyInputLeftArrow',
                                                                0,
                                                                'kcDispatcher:'),
         UIKeyCommand.keyCommandWithInput_modifierFlags_action_('UIKeyInputRightArrow',
                                                                0,
                                                                'kcDispatcher:'),
     ]
     commands = ns(key_commands)
     return commands.ptr
Пример #15
0
def _get_custom_commands():
    existing_custom_commands = objc_getAssociatedObject(
        _utils._application, associated_obj_key)
    try:
        # This is a terrible solution, but it's the only way I could come up with
        # to check if the object is `nil` (not empty!)
        # checking if it's None wont work, no idea why.
        # The idea is that this will fail since the __str__ method will try to load
        # the description, which of course is nil, since the object itself is nil
        s = objc_util.ObjCInstance(existing_custom_commands).__str__()
    except:
        existing_custom_commands = objc_util.ns([])
    return objc_util.ObjCInstance(existing_custom_commands)
Пример #16
0
def _drop_file(data_ptr, path):
    try:
        if os.path.exists(path):
            console.alert('{} exists'.format(os.path.basename(path)),
                          'Do you want to replace existing file?', 'Replace')
        data = ObjCInstance(data_ptr)

        if not data.writeToFile_atomically_(ns(path), True):
            console.hud_alert('Failed to write file', 'error')
            return

        console.hud_alert('{} dropped'.format(os.path.basename(path)))

    except KeyboardInterrupt:
        pass
Пример #17
0
def get_bookmark_paths():
    if not os.path.isfile(_BOOKMARKS_FILE):
        return None

    with open(_BOOKMARKS_FILE, 'rb') as input:
        content = plistlib.readPlist(input)

        if not content:
            return None

        paths = []
        for data in content:
            url = NSURL.URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(
                ns(data.data), 1 << 8, None, None, None)
            if url and url.isFileURL():
                paths.append(str(url.path()))

        return paths
Пример #18
0
def _load_data_imp(_cmd, _block_ptr):
    global _dragged_item_path
    handler = runtime.ObjCBlockPointer(
        _block_ptr, argtypes=[ctypes.c_void_p, ctypes.c_bool, ctypes.c_void_p])

    if _dragged_item_path:
        NSURL = ObjCClass('NSURL')
        url = NSURL.fileURLWithPath_isDirectory_(
            ns(_dragged_item_path), os.path.isdir(_dragged_item_path))

        _dragged_item_path = None
    else:
        url = None

    if not url:
        error = NSError.errorWithDomain_code_userInfo_(
            'com.robertvojta.blackmamba', 1, None)
        handler(None, None, error)
    else:
        handler(url.ptr, False, None)
Пример #19
0
def nsDicToPyDic(nsDic):
    pyDic = {}
    for k in nsDic.allKeys():
        v = nsDic[k]
        if v.isKindOfClass_(NSString):
            v = str(v)
        elif v.isKindOfClass_(NSBoolean):
            v = bool(v)
        elif v.isKindOfClass_(NSNumber):
            vs = v.stringValue()
            if vs.rangeOfString_(ns(".")).length > 0:
                v = float(str(vs))
            else:
                v = v.intValue()
        elif v.isKindOfClass_(NSData):
            v = nsdata_to_bytes(v)
        elif v.isKindOfClass_(NSDictionary):
            v = nsDicToPyDic(v)
        pyDic[str(k)] = v
    return pyDic
Пример #20
0
def tableView_itemsForBeginningDragSession_atIndexPath_(
        _self, _cmd, tv_ptr, session_ptr, index_path_ptr):
    global _dragged_item_path

    if not _path_items:
        return ns([]).ptr

    section = ObjCInstance(index_path_ptr).section()
    row = ObjCInstance(index_path_ptr).row()

    if section >= 0 and section < len(_path_items) and row >= 0 and row < len(
            _path_items[section]):
        path = _path_items[section][row]

        type_identifier = _type_identifier(path)
        if not type_identifier:
            error('Failed to provide data, file does not exists?')
            return ns([]).ptr

        suggested_name = _suggested_name(path)

        provider = NSItemProvider.alloc().init()
        provider.registerFileRepresentationForTypeIdentifier_fileOptions_visibility_loadHandler_(
            type_identifier, 0, 0, _load_data)

        if not provider:
            error('Failed to create item provider.')
            return ns([]).ptr

        if suggested_name:
            provider.setSuggestedName(suggested_name)

        item = UIDragItem.alloc().initWithItemProvider_(provider)
        if not item:
            error('Failed to create drag item.')
            return ns([]).ptr

        _dragged_item_path = path
        return ns([item]).ptr

    return ns([]).ptr
def classify_image(img):
    buffer = io.BytesIO()
    img.save(buffer, 'JPEG')
    img_data = ns(buffer.getvalue())
    return _classify_img_data(img_data)
Пример #22
0
def showShareSheet(*params):
    vc = UIActivityViewController.alloc().initWithActivityItems_applicationActivities_(ns(list(params)), None)
    rootVC = UIApplication.sharedApplication().keyWindow().rootViewController()
    while rootVC.presentedViewController():
        rootVC = rootVC.presentedViewController()
    rootVC.presentViewController_animated_completion_(vc, True, None)
Пример #23
0
def load_scene(file):
    url = ns(file)
    s = SCNScene.sceneWithURL_options_(url, ns({}))
    return Scene(s)
Пример #24
0
def load_scene(file):
    url = ns(file)
    s = SCNScene.sceneWithURL_options_(url, ns({}))
    return Scene(s)
Пример #25
0
# ObjC classes
UIColor = ObjCClass('UIColor')
UIPickerView = ObjCClass('UIPickerView')
UIFont = ObjCClass('UIFont')
NSAttributedString = ObjCClass('NSAttributedString')


# Default attributes, no need to recreate them again and again
def _str_symbol(name):
    return ObjCInstance(c_void_p.in_dll(c, name))


_default_attributes = {
    _str_symbol('NSFontAttributeName'):
    UIFont.fontWithName_size_(ns('Courier'), 16),
    _str_symbol('NSForegroundColorAttributeName'):
    UIColor.blackColor(),
    _str_symbol('NSBackgroundColorAttributeName'):
    UIColor.whiteColor()
}


# Data source & delegate methods
def pickerView_attributedTitleForRow_forComponent_(self, cmd, picker_view, row,
                                                   component):
    tag = ObjCInstance(picker_view).tag()
    return NSAttributedString.alloc().initWithString_attributes_(
        ns(_data[tag - 1][row]), ns(_default_attributes)).ptr

Пример #26
0
def set_route(route, pw):
    MRMediaRemoteSetPickedRouteWithPassword = c.MRMediaRemoteSetPickedRouteWithPassword
    MRMediaRemoteSetPickedRouteWithPassword.argtypes = [c_void_p, c_void_p]
    MRMediaRemoteSetPickedRouteWithPassword(ns(route).ptr, ns(pw).ptr)
Пример #27
0
 def _create_objc(self):
     self._scene_objc = SCNView.alloc().initWithFrame_options_(((0, 0),(100, 100)), ns({'SCNViewOptionPreferredRenderingAPI': 1})).autorelease()
     self._scene_objc.setAutoresizingMask_(18) # Fill superview
     self._scene_objc.setNeedsDisplayOnBoundsChange_(True) # fill on change
     self._scene_ref = None
     self._pointOfView_ref = Node(self._scene_objc.pointOfView())
Пример #28
0
def load_comic(view, num):
    if num == 404:
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num/latest
        view.comic = None
        objc_util.ObjCInstance(view.navigation_view).navigationController().topViewController().title = objc_util.ns('404 - Not Found')
        return 
    console.show_activity()
    comic = get_info(num)
    if comic:
        if num in faves:
            view['fav'].image = ui.Image('iob:ios7_heart_32')
        else:
            view['fav'].image = ui.Image('iob:ios7_heart_outline_32')
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num/latest
        view.comic = comic
        
        #view['comic'].image = get_comic(view.comic['img'])
        view['wv'].load_url(get_comic(view.comic['img']))
        objc_util.ObjCInstance(view.navigation_view).navigationController().topViewController().title = objc_util.ns(view.comic['title'])
    
    console.hide_activity()
Пример #29
0
 def items (self, items):
     self._objc_set(ns(items))
Пример #30
0
	def __init__(self, tableView, filterData, selectCallBack, theme_manager, soofflineSelectCallBack, *args, **kwargs):
		ui.View.__init__(self, *args, **kwargs)
		self.width, self.height = ui.get_screen_size()
		frame = CGRect(CGPoint(0, 0), CGSize(self.width, self.height))
		theme_manager_g = theme_manager
		self.theme_manager = theme_manager
		bkg_view = ui.View()
		bkg_view.background_color = self.theme_manager.currentTheme.backgroundColour
		self.tv = tableView
		self.tv.width = self.width
		self.tv.height = self.height
		self.tableView = ObjCInstance(self.tv)
		self.tableView.setBackgroundView(bkg_view)
		flex_width, flex_height = (1<<1), (1<<4)
		self.tableView.setAutoresizingMask_(flex_width|flex_height)
		self.selectCallBack = selectCallBack
		self.soofflineSelectCallBack = soofflineSelectCallBack
		v = UITableViewController.alloc().init().autorelease()
		tvd = createTableViewDelegateClass(theme_manager)
		self.tb_ds = tvd.alloc().init().autorelease()

		v.tableView().setDataSource_(self.tb_ds)
		v.tableView().setDelegate_(self.tb_ds)
		v.tableView().dataSource().data = []
		v.tableView().dataSource().selectCallBack = self.performSelectCallBack
		self.searchController = UISearchController.alloc().initWithSearchResultsController_(v)
		self.searchController.resultController = v
		self.searchController.firstRun = True
		
		sd = createSearchDelegateClass()
		self.searchDelegate = sd.alloc().init().autorelease()
		self.searchDelegate.filter = filterData
		self.searchDelegate.resultController = v
		self.tableView.extendedLayoutIncludesOpaqueBars = True
		self.searchController.searchResultsUpdater = self.searchDelegate
		self.searchController.dimsBackgroundDuringPresentation = True
		self.searchController.hidesNavigationBarDuringPresentation = True
		self.searchController.searchBar().delegate = self.searchDelegate
		self.searchController.searchBar().setPlaceholder_(ns('Search'))
		self.tableView.tableHeaderView =self.searchController.searchBar();
		self.searchController.searchBar().sizeToFit();		
		tColour = tuple(int(self.theme_manager.currentTheme.searchTintColour.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4))
		bTColour = tuple(int(self.theme_manager.currentTheme.searchBackgroundColour.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4))
		tColour = (tColour[0]/255, tColour[1]/255, tColour[2]/255)
		bTColour = (bTColour[0]/255, bTColour[1]/255, bTColour[2]/255)
		searchTintColour = UIColor.colorWithRed_green_blue_alpha_(tColour[0], tColour[1], tColour[2], 1)
		self.searchController.searchBar().tintColor = searchTintColour
		searchBackgroundTintColour = UIColor.colorWithRed_green_blue_alpha_(bTColour[0], bTColour[1], bTColour[2], 1)
		self.searchController.searchBar().tintColor = searchTintColour
		self.searchController.searchBar().barTintColor = searchBackgroundTintColour


		# self.tb_ds.textColour = searchTColour
		self.tv.border_color = self.theme_manager.currentTheme.borderColour
		self.tv.background_color = self.theme_manager.currentTheme.backgroundColour
		self.tv.bg_color = self.theme_manager.currentTheme.backgroundColour		
		self.tv.tint_color = self.theme_manager.currentTheme.tintColour
		self.tv.separator_color = self.theme_manager.currentTheme.separatorColour
		bk_view = ui.View()
		bk_view.background_color = self.theme_manager.currentTheme.backgroundColour
		v.tableView().setBackgroundView(bk_view)
		
		self_objc = ObjCInstance(self)
		self_objc.addSubview_(self.tableView)
		self.tableView.release()
Пример #31
0
def pickerView_titleForRow_forComponent_(self, cmd, picker_view, row,
                                         component):
    tag = ObjCInstance(picker_view).tag()
    return ns(_data[tag - 1][row]).ptr
Пример #32
0
def pickerView_attributedTitleForRow_forComponent_(self, cmd, picker_view, row,
                                                   component):
    tag = ObjCInstance(picker_view).tag()
    return NSAttributedString.alloc().initWithString_attributes_(
        ns(_data[tag - 1][row]), ns(_default_attributes)).ptr
Пример #33
0
def songlist_to_array(songs):
    objcitems = []
    for i in songs:
        objcitems += [i._objc]
    return ns(objcitems)
def classify_asset(asset):
    img_data = ns(asset.get_image_data().getvalue())
        
    req = VNDetectTextRectanglesRequest.alloc().init()
    req.reportCharacterBoxes = True
    
    handler = VNImageRequestHandler.alloc().initWithData_options_(img_data, None).autorelease()
    success = handler.performRequests_error_([req], None)
    if success:
        im = ui.ImageView()
        pil_image = asset.get_image()
        print(pil_image.size)
        ui_image = asset.get_ui_image()
        wim,him = ui_image.size
        im.frame = (0,0,400,400*him/wim)
        #im.frame = (0,0,141,64)
        wi = im.width
        hi = im.height
        im.image = ui_image
        im.content_mode = 1 #1
        im.present()
        for i in range(0,len(req.results())):
            observation = req.results()[i]  
            box = observation.boundingBox()
            xb=box.origin.x
            yb=box.origin.y
            wb=box.size.width
            hb=box.size.height
            #print('x=',xb)
            #print('y=',y )
            #print('width=',w )
            #print('height=',hb)
            l = ui.Label()
            l.frame = (xb*wi,yb*hi,wb*wi,hb*hi)
            #print(l.frame)
            #l.border_width = 1
            #l.border_color = 'red'
            im.add_subview(l)
            #print(dir(observation))
            confidence = observation.confidence()
            #print('confidence', confidence)
            for i_ch in range(0,len(observation.characterBoxes())):
              ch_box = observation.characterBoxes()[i_ch]
              box = ch_box.boundingBox()
              x=box.origin.x
              y=box.origin.y
              w=box.size.width
              h=box.size.height
              #print('x=',x)
              #print('y=',y)
              #print('width=',w)
              #print('height=',h)
              l = ui.Label()
              l.frame = (x*wi,yb*hi,w*wi,hb*hi)
              #print(l.frame)
              l.border_width = 1
              l.border_color = 'blue'
              im.add_subview(l)
              print((int(x*wim),int(yb*him),int(w*wim),int(hb*him)))
              pil_char = pil_image.crop((int(x*wim)-1,int(yb*him)-1,int((x+w)*wim)+1,int((yb+hb)*him)+8))
              pil_char.show()
              print(classify_image(pil_char))
              #print(dir(ch_box))
              #break
        print('ok')
    else:
        print('error')
Пример #35
0
 def open_url(self, url):
     UIApplication = ObjCClass('UIApplication')
     sharedApplication = UIApplication.sharedApplication()
     internalurl = NSURL.URLWithString_(ns(url))
     sharedApplication.openURL_(internalurl)
Пример #36
0
 def set(self, key, value):
     self.attr_str.addAttribute_value_range_(
         objc_util.ns(key), value,
         objc_util.NSRange(self.start, self.end - self.start))