예제 #1
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()
예제 #2
0
 def responseHandlerBlock(self, _cmd, data, response, error):
     if error is not None:
         self.error = objc_util.ObjCInstance(error)
     else:
         response = objc_util.ObjCInstance(response)
         data = objc_util.ObjCInstance(data)
         self.data = objc_util.nsdata_to_bytes(data)
예제 #3
0
 def responseHandlerBlock(self, _cmd, data, response, error):
     if error is not None:
         error = objc_util.ObjCInstance(error)
         print(error)
         return
     response = objc_util.ObjCInstance(response)
     data = objc_util.ObjCInstance(data)
     self.data = (str(objc_util.nsdata_to_bytes(data)))
예제 #4
0
def create_sync_button():
	btn_container = ui.View(frame=(0, 0, 32, 44))
	btn = ui.Button(image=ui.Image.named('iob:loop_256'))
	btn.frame = (0, 0, 32, 44)
	btn.action = lambda sender: sync_songs_and_tunes()
	btn_container.add_subview(btn)
	btn_item = ui.ButtonItem()
	btn_item_objc = objc_util.ObjCInstance(btn_item)
	btn_item_objc.customView = objc_util.ObjCInstance(btn_container)
	return btn_item
예제 #5
0
파일: observer.py 프로젝트: slyboots/ui3
 def observeValueForKeyPath_ofObject_change_context_(
         _self, _cmd, _path, _obj, _change, _ctx):
     self = objc_util.ObjCInstance(_self)
     objc_target = objc_util.ObjCInstance(_obj).delegate()
     try:
         target_view = self.targets.get(objc_target)
         if target_view:
             for callback in self.callbacks.get(objc_target, []):
                 callback(target_view)
     except Exception as e:
         print('observeValueForKeyPath:', self, type(e), e)
예제 #6
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)
예제 #7
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))
예제 #8
0
def screenDidConnectNotification_(self, cmd, note):
    global _screen
    _logger.debug('External screen connected')
    _screen = objc_util.ObjCInstance(note).object()

    for handler in _connected_handlers:
        handler()
 def handler(exc_pointer):
     exc = objc_util.ObjCInstance(exc_pointer)
     
     name = exc.name()
     reason = exc.reason()
     user_info = exc.userInfo()
     
     call_stack_symbols = exc.callStackSymbols()
     
     with io.open(os.path.join(LOGDIR, EXCEPTIONLOGNAME_DEFAULT), "wb") as f:
         try:
             f.write(b"Objective-C exception details:\n\n")
             
             if reason is None:
                 f.write(str(name).encode("utf-8") + b"\n")
             else:
                 f.write(str(name).encode("utf-8") + b": " + str(reason).encode("utf-8") + b"\n")
             
             if user_info is not None:
                 f.write(str(user_info).encode("utf-8") + b"\n")
             
             f.write(b"\nStack trace:\n\n")
             
             for sym in call_stack_symbols:
                 f.write(str(sym).encode("utf-8") + b"\n")
             
             f.write(b"\nEnd of exception details.\n")
         except Exception as err:
             import traceback
             f.write(b"I messed up! Python exception:\n")
             f.write(traceback.format_exc().encode("utf-8"))
             raise
예제 #10
0
    def setAttribs(self):
        import objc_util
        tv = self.text_view
        tvo = objc_util.ObjCInstance(tv)

        tvo.setAllowsEditingTextAttributes_(True)
        tvo.setAttributedText_(self.str_object)
        if self.auto_scroll:
            tvo.scrollRangeToVisible_((len(self.all_text), 0))
예제 #11
0
    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)

        self._view = objc_util.ObjCClass("MKMapView").new()
        self._view.setFrame_(
            objc_util.CGRect(objc_util.CGPoint(0, 0),
                             objc_util.CGSize(self.width, self.height)))
        self._view.setAutoresizingMask_(18)  # W+H
        objc_util.ObjCInstance(self).addSubview_(self._view)

        self.animated = True
예제 #12
0
    def __init__(self, view_type, *args, **kwargs):
        super().__init__(view_type, *args, **kwargs)
        # Add subject as a subview
        object.__getattribute__(self, "add_subview")(self.__subject__)
        # Turn off clipping of subviews so that the wrapped view is visible.
        ptr = object.__getattribute__(self, "_objc_ptr")

        class ObjCDummy():
            """Used to trick ObjCInstance into working on this proxy class."""
            _objc_ptr = ptr

        objc = objc_util.ObjCInstance(ObjCDummy())
예제 #13
0
def tableView_heightForRowAtIndexPath_(_self,_sel,tv,path):
	try:
		import sys, objc_util, ctypes
		# For some reason, tv returns a NSNumber.  But, our tableview is in _self
		tv_o=objc_util.ObjCInstance(_self)
		# get row and section from the path
		indexPath=objc_util.ObjCInstance(path)
		row=indexPath.row()
		section=indexPath.section()
		# get the pyObject.  get as an opaque pointer, then cast to py_object and deref 
		pyo=tv_o.pyObject(restype=ctypes.c_void_p,argtypes=[])
		tv_py=ctypes.cast(pyo.value,ctypes.py_object).value
		# if the delegate has the right method, call it
		if tv_py.delegate and hasattr(tv_py.delegate,'tableview_height_for_section_row'):
			return tv_py.delegate.tableview_height_for_section_row(tv_py,section,row)
		else:
			return tv_py.row_height
	except Exception as e:
		import traceback
		traceback.print_exc()
		return 44
예제 #14
0
def dismiss(view):
    '''Dismisses view (ui.View) from external screen.
	
	View must be presented on external screen otherwise nothing happens.
	'''
    view_objc = objc_util.ObjCInstance(view)

    if view_objc.superview() == _window:
        view_objc.removeFromSuperview()
        _logger.debug('View dismissed from external screen')
    else:
        _logger.debug(
            'View is not presented on external screen, skipping dismiss')
예제 #15
0
	def to_png(self):
		global depthSource
		ctx = objc_util.ObjCClass('CIContext').context()
		try:
			extent = self.ci_img.extent()
		except:
			if allow_ML:
				raise('The selected portrait photo does not contain a depth map.')
			else:
				print('The selected portrait photo does not contain a depth map.')
				quit()
		m = ctx.outputImageMaximumSize()
		cg_img = ctx.createCGImage_fromRect_(self.ci_img, extent)
		ui_img = objc_util.UIImage.imageWithCGImage_(cg_img)
		png_data = objc_util.uiimage_to_png(objc_util.ObjCInstance(ui_img))
		depthSource = 'Embedded'
		return png_data
예제 #16
0
def show_tv_view(v):
	global tvwin
	
	if UIScreen.screens().count() < 2:
		raise ValueError("No external screen connected")
	
	hide_tv_view()
	
	tv = UIScreen.screens()[1]
	tvwin = UIWindow.alloc().initWithFrame_(tv.bounds())
	tvwin.setScreen_(tv)
	
	vc = UIViewController.alloc().init()
	vc.setView_(objc_util.ObjCInstance(v))
	tvwin.setRootViewController_(vc)
	
	tvwin.setHidden_(False)
예제 #17
0
	def __init__(self, chosen_pic):
		self.MLModel = objc_util.ObjCClass('MLModel')
		self.VNCoreMLModel = objc_util.ObjCClass('VNCoreMLModel')
		self.VNCoreMLRequest = objc_util.ObjCClass('VNCoreMLRequest')
		self.VNImageRequestHandler = objc_util.ObjCClass('VNImageRequestHandler')
		
		result = self.classify_asset(chosen_pic)
		if result:
			resultString = str(result)
			resultWidth = int(resultString[resultString.find('width=') + 6:resultString.find(' ', resultString.find('width=') + 6)])
			resultHeight = int(resultString[resultString.find('height=') + 7:resultString.find(' ', resultString.find('height=') + 7)])
			CIImage = objc_util.ObjCClass('CIImage')
			pixelBuffer = result.pixelBuffer
			ci_img = CIImage.imageWithCVPixelBuffer_(pixelBuffer())		
			ctx = objc_util.ObjCClass('CIContext').context()
			cg_img = ctx.createCGImage_fromRect_(ci_img, objc_util.CGRect(objc_util.CGPoint(0, 0), objc_util.CGSize(resultWidth, resultHeight)))
			ui_img = objc_util.UIImage.imageWithCGImage_(cg_img)
			self.png_data = objc_util.uiimage_to_png(objc_util.ObjCInstance(ui_img))
예제 #18
0
    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)
        self._objc = objc_util.ObjCInstance(self)

        # Set up the camera device
        self._session = AVCaptureSession.new()
        camera_type = ctypes.c_void_p.in_dll(objc_util.c, "AVMediaTypeVideo")
        device = AVCaptureDevice.defaultDeviceWithMediaType(camera_type)
        input = AVCaptureDeviceInput.deviceInputWithDevice_error_(device, None)
        if input:
            self._session.addInput(input)
        else:
            raise UnsupportedDeviceError("Failed to connect to camera.")

        # Add the camera preview layer
        self._layer = self._objc.layer()
        self._camera_layer = AVCaptureVideoPreviewLayer.layerWithSession(
            self._session)
        self._layer.addSublayer(self._camera_layer)

        self._auto_rotating = True
예제 #19
0
def present(view):
    '''Presents view (ui.View) on external screen.
	
	Returns True if view was presented or False if external screen is not
	available.
	'''
    window = _configure_window()
    if window is None:
        _logger.debug(
            'Unable to present view, external screen is not available')
        return False

    view.flex = 'WH'
    view_objc = objc_util.ObjCInstance(view)
    view_objc.setFrame(window.bounds())

    window.subviews().makeObjectsPerformSelector(
        objc_util.sel('removeFromSuperview'))
    window.addSubview(view_objc)

    _logger.debug('View presented on external screen')
    return True
# https://forum.omz-software.com/topic/4183/how-to-add-a-new-line-in-a-button-title/3

import objc_util
import ui

NSLineBreakByWordWrapping = 0
NSLineBreakByCharWrapping = 1
NSLineBreakByClipping = 2
NSLineBreakByTruncatingHead = 3
NSLineBreakByTruncatingTail = 4
NSLineBreakByTruncatingMiddle = 5  # Default for button labels.

b = ui.Button(
)  # Your button (doesn't need to be created here, can come from somewhere else, like a UI file).
objc_util.ObjCInstance(b).button().titleLabel().setLineBreakMode(
    NSLineBreakByWordWrapping
)  # You can use any of the line break modes listed above.
예제 #21
0
#!python2

import tableview_rowheight, ui, objc_util
# create a tableview and delegate and datasource, per usual
#tableview_rowheight.setup_tableview_swizzle(False)
t = ui.TableView(frame=(0, 0, 200, 576))
d = ui.ListDataSource([str(x) for x in range(100)])
t.data_source = t.delegate = d

t.row_height = -1


# here i will just create height that grows then shrinks again
def tableview_height_for_section_row(tv, section, row):
    return 10 + (row / 5)**2 if row < 50 else 10 + ((100 - row) / 5)**2


d.tableview_height_for_section_row = tableview_height_for_section_row

# this is optional, but speeds up initial display and scrolling
# set to nominal or average height
t_o = objc_util.ObjCInstance(t)
t_o.estimatedRowHeight = 44

t.present('sheet')
예제 #22
0
# coding: utf-8

# https://github.com/jsbain/objc_hacks/blob/master/objcstuff.py

import objc_util, ui

v = ui.View()

vv = objc_util.ObjCInstance(v._objc_ptr)

wnd = objc_util.ObjCClass('UIWindow').alloc()
r = objc_util.CGRect(objc_util.CGPoint(0, 0), objc_util.CGSize(100, 100))

wnd.initWithFrame_(r)
예제 #23
0
 def position(self):
     """ Current position """
     pos = objc_util.ObjCInstance(self.p).currentPoint()
     return pos.x, pos.y
예제 #24
0
def userNotificationCenter_didReceiveNotificationResponse_withCompletionHandler_(self, _cmd, unc, response, handler):
	print(objc_util.ObjCInstance(response))
예제 #25
0
def errorhandler_imp(_cmd, error):
	if error is None:
		print("No errors!")
	else:
		print("Error!")
		print(objc_util.ObjCInstance(error))
예제 #26
0
	quit()

# This might break on non-English iOS. Too lazy to test.
for album in photos.get_smart_albums():
	if album.title == 'Portrait':
		my_album = album
		break

# Again using iOS API to get the photo's proper filename
try:
	if allow_ML:
		chosen_pic = photos.pick_asset(assets = photos.get_assets(), title = 'Select a photo')
		# chosen_pic = photos.pick_image(show_albums=True, include_metadata=False, original=True, raw_data=False, multi=False)
	else:
		chosen_pic = photos.pick_asset(assets = my_album.assets, title = 'Select a portrait photo')
	filename, file_extension = os.path.splitext(str(objc_util.ObjCInstance(chosen_pic).originalFilename()))
	assert filename != 'None'
	output_filename = 'Holo_' + filename + '.png'
except:
	quit()

try:
	chosen_pic_image = chosen_pic.get_image(original = False)
except:
	print('Image format (' + file_extension[1:] + ') not supported.')
	quit()
chosen_pic_data = chosen_pic.get_image_data(original = False).getvalue()

# Extract a depth map
try:
	chosen_pic_depth = CImage(objc_util.ns(chosen_pic_data)).to_png()
예제 #27
0
파일: richlabel.py 프로젝트: slyboots/ui3
 def apply(self, attr_str):
     self.attr_str = attr_str
     objc_style = objc_util.ObjCInstance(
         ctypes.c_void_p.in_dll(objc_util.c, self.style))
     font = UIFont.preferredFontForTextStyle_(objc_style)
     self.set('NSFont', font)
예제 #28
0
	def remove(self,sender):
		import objc_util
		objc_util.ObjCInstance(self).removeFromSuperview()
		self.process_events(self.EVENT_CLOSE)
예제 #29
0
def tableView_willDisplayHeaderView_forSection_(_self,_sel,tv, v,section):
	tv_o=objc_util.ObjCInstance(_self)
	pyo=tv_o.pyObject(restype=c_void_p,argtypes=[])
	tv_py=ctypes.cast(pyo.value,ctypes.py_object).value
	if tv_py.delegate and hasattr(tv_py.delegate,'will_display_header'):
			tv_py.delegate.will_display_header(v,section)
예제 #30
0

def load_view():
    return ui.load_view()


# Code for the main.py:

import ui
import hdmi
import objc_util

v = ui.load_view()
v.present('sheet')

UIScreen = objc_util.ObjCClass('UIScreen')
if len(UIScreen.screens()) > 1:
    second_screen = UIScreen.screens()[1]

    bounds = second_screen.bounds()

    UIWindow = objc_util.ObjCClass('UIWindow')
    second_window = UIWindow.alloc().initWithFrame_(bounds)
    second_window.setScreen(second_screen)
    second_window.setHidden(False)

    hdmi_view = hdmi.load_view()
    hdmi_view_objc = objc_util.ObjCInstance(hdmi_view)
    hdmi_view_objc.setFrame(second_window.bounds())
    second_window.addSubview(hdmi_view_objc)