Ejemplo n.º 1
0
 def votedown(self, sender):
     glv.PARSER.vote_comment(self.apikey, self.apiuid, self.gid, self.token, self.comment['comment_id'], '-1')
     if sender.tint_color == ui.parse_color('black'):
         sender.tint_color = 'blue'
     elif sender.tint_color == ui.parse_color('blue'):
         sender.tint_color = 'black'
     self['button_voteup'].tint_color = 'black'
Ejemplo n.º 2
0
    def console(self, webview_index=0):
        webview = WKWebView.webviews[webview_index]
        theme = WKWebView.Theme.get_theme()

        print('Welcome to WKWebView console.')
        print('Evaluate javascript in any active WKWebView.')
        print('Special commands: list, switch #, load <url>, quit')
        console.set_color(*ui.parse_color(theme.tint)[:3])
        while True:
            value = input('js> ').strip()
            self.console_view.history().insertObject_atIndex_(
                ns(value + '\n'), 0)
            if value == 'quit':
                break
            if value == 'list':
                for i in range(len(WKWebView.webviews)):
                    wv = WKWebView.webviews[i]
                    print(i, '-', wv.name, '-', wv.eval_js('document.title'))
            elif value.startswith('switch '):
                i = int(value[len('switch '):])
                webview = WKWebView.webviews[i]
            elif value.startswith('load '):
                url = value[len('load '):]
                webview.load_url(url)
            else:
                print(webview.eval_js(value))
        console.set_color(*ui.parse_color(theme.default_text)[:3])
Ejemplo n.º 3
0
def change_color(sender):
    if sender.background_color != ui.parse_color('white'):
        sender.background_color = 'white'
        sender.chosen = False
    else:
        sender.background_color = '#ff48c2'
        sender.chosen = True
Ejemplo n.º 4
0
    def draw(self):
        r = ui.Rect(*self.bounds).inset(*self.circle_inset)

        oval = ui.Path.oval(r.x, r.y, r.width, r.height)
        c = ui.parse_color(self.circle_color)
        nc = (c[0], c[1], c[2], self.circle_alpha)  # color with alpha
        pattern = '9' * len(self.text)

        text_rect = ui.Rect(0, 0, r.width * .8, r.height * .6)
        text_rect.center(r.center())
        fs = self.get_max_fontsize(text_rect, pattern, self.font_name,
                                   self.inset_rect)

        with ui.GState():
            ui.set_color(nc)
            oval.fill()
            ui.draw_string(self.text,
                           rect=text_rect,
                           font=(self.font_name, fs),
                           color=self.text_color,
                           alignment=ui.ALIGN_CENTER,
                           line_break_mode=ui.LB_TRUNCATE_TAIL)
            j = ui.Path.rect(*text_rect)
            ui.set_color((0, 0, 0, .5))
            j.fill()
Ejemplo n.º 5
0
 def initialize(self, parent, color='#fff'):
     self.color = ui.parse_color(color)
     self.parent = parent
     r, g, b, a = self.color
     self.cpr.value = r * 255
     self.cpg.value = g * 255
     self.cpb.value = b * 255
Ejemplo n.º 6
0
def set_shadow(view, color='black'):
    layer = view.objc_instance.layer()
    layer.setShadowOpacity_(0.8)
    layer.setShadowColor_(
        UIColor.colorWithRed_green_blue_alpha_(
            *ui.parse_color(color)).CGColor())
    layer.setShadowRadius_(10)
Ejemplo n.º 7
0
def SymbolImage(name,
                point_size=None,
                weight=None,
                scale=None,
                color=None,
                rendering_mode=ui.RENDERING_MODE_AUTOMATIC):
    ''' Create a ui.Image from an SFSymbol name. Optional parameters:
        * `point_size` - Integer font size
        * `weight` - Font weight, one of ULTRALIGHT, THIN, LIGHT, REGULAR, MEDIUM, SEMIBOLD, BOLD, HEAVY, BLACK
        * `scale` - Size relative to font size, one of SMALL, MEDIUM, LARGE 
        
    Run the file to see a symbol browser.'''
    objc_image = ObjCClass('UIImage').systemImageNamed_(name)
    conf = UIImageSymbolConfiguration.defaultConfiguration()
    if point_size is not None:
        conf = conf.configurationByApplyingConfiguration_(
            UIImageSymbolConfiguration.configurationWithPointSize_(point_size))
    if weight is not None:
        conf = conf.configurationByApplyingConfiguration_(
            UIImageSymbolConfiguration.configurationWithWeight_(weight))
    if scale is not None:
        conf = conf.configurationByApplyingConfiguration_(
            UIImageSymbolConfiguration.configurationWithScale_(scale))
    objc_image = objc_image.imageByApplyingSymbolConfiguration_(conf)

    image = ui.Image.from_data(
        nsdata_to_bytes(ObjCInstance(UIImagePNGRepresentation(
            objc_image)))).with_rendering_mode(rendering_mode)
    if color:
        image = image.imageWithTintColor_(
            UIColor.colorWithRed_green_blue_alpha_(*ui.parse_color(color)))
    return image
Ejemplo n.º 8
0
 def __init__(self,
              duration=None,
              crossFadeWithDuration=None,
              doorsCloseHorizontalWithDuration=None,
              doorsCloseVerticalWithDuration=None,
              doorsOpenHorizontalWithDuration=None,
              doorsOpenVerticalWithDuration=None,
              doorwayWithDuration=None,
              fadeWithColor=None,
              fadeWithDuration=None,
              flipHorizontalWithDuration=None,
              flipVerticalWithDuration=None,
              moveInWithDirection=None,
              pushWithDirection=None,
              revealWithDirection=None,
              ID=None):
     if crossFadeWithDuration is not None:
         self.ID = SKTransition.crossFadeWithDuration_(
             crossFadeWithDuration)
     elif doorsCloseHorizontalWithDuration is not None:
         self.ID = SKTransition.doorsCloseHorizontalWithDuration_(
             doorsCloseHorizontalWithDuration)
     elif doorsCloseVerticalWithDuration is not None:
         self.ID = SKTransition.doorsCloseVerticalWithDuration_(
             doorsCloseVerticalWithDuration)
     elif doorsOpenHorizontalWithDuration is not None:
         self.ID = SKTransition.doorsOpenHorizontalWithDuration_(
             doorsOpenHorizontalWithDuration)
     elif doorsOpenVerticalWithDuration is not None:
         self.ID = SKTransition.doorsOpenVerticalWithDuration_(
             doorsOpenVerticalWithDuration)
     elif doorwayWithDuration is not None:
         self.ID = SKTransition.doorwayWithDuration_(doorwayWithDuration)
     elif fadeWithColor is not None:
         r, g, b, a = parse_color(fadeWithColor)
         self.ID = SKTransition.fadeWithColor_duration_(
             ObjCClass('UIColor').color(red=r, green=g, blue=b, alpha=a),
             duration)
     elif fadeWithDuration is not None:
         self.ID = SKTransition.fadeWithDuration_(FadeWithDuration)
     elif flipHorizontalWithDuration is not None:
         self.ID = SKTransition.flipHorizontalWithDuration_(
             FlipHorizontalWithDuration)
     elif flipVerticalWithDuration is not None:
         self.ID = SKTransition.flipVerticalWithDuration_(
             FlipVerticalWithDuration)
     elif moveInWithDirection is not None:
         self.ID = SKTransition.moveInWithDirection_duration_(
             MoveInWithDirection, duration)
     elif pushWithDirection is not None:
         self.ID = SKTransition.pushWithDirection_duration_(
             PushWithDirection, duration)
     elif revealWithDirection is not None:
         self.ID = SKTransition.revealWithDirection_duration_(
             RevealWithDirection, duration)
     elif ID is not None:
         self.ID = ID
     else:
         self.ID = None
Ejemplo n.º 9
0
 def highlight_color(self, value):
     value = ui.parse_color(value)
     self._highlight_color = value
     if hasattr(self, 'dropbox'):
         self.dropbox.data_source.highlight_color = value
         self.dropbox.data_source.reload_cells()
         self.dropbox.reload()
         self.dropbox.selected_row = self.selected_index
Ejemplo n.º 10
0
 def text_color(self, value):
     value = ui.parse_color(value)
     self._text_color = value
     if hasattr(self, 'selected_label'):
         self.selected_label.text_color = value
     if hasattr(self, 'dropbox'):
         self.dropbox.data_source.text_color = value
         self.dropbox.data_source.reload_cells()
         self.dropbox.reload()
         self.dropbox.selected_row = self.selected_index
Ejemplo n.º 11
0
    def __init__(self, color, *args, **kwargs):
        # TODO add parameter to set startvalue of color
        ui.View.__init__(self, *args, **kwargs)
        self.history = []  #future...keep track of recent colors

        r, g, b, a = ui.parse_color(color)
        h, s, v = colorsys.rgb_to_hsv(r, g, b)
        self.current = (h, s, v)
        self.N = 16  # grid for hue and saturation
        self.Nb = 16  # grid for value
        self.__debugprint = True
Ejemplo n.º 12
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     blur = offset = color = None
     for key in self.node.attrs.keys():
         try:
             blur = float(key)
         except ValueError:
             try:
                 value = ast.literal_eval(key)
                 if (type(value) is tuple
                         and all(map(lambda x: x - 0 == x, value))):
                     if len(value) == 2:
                         offset = value
                     else:
                         color = ui.parse_color(value)
             except:
                 color = ui.parse_color(key)
     self.blur = blur or 3.0
     self.offset = offset or (2, 2)
     self.color = color or 'grey'
Ejemplo n.º 13
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     line_style = 0
     line_color = None
     for key in self.node.attrs.keys():
         if key in self.styles:
             line_style |= self.styles[key]
         else:
             line_color = ui.parse_color(key)
     self.line_style = line_style or 1
     self.color = line_color or 'black'
Ejemplo n.º 14
0
def color_prop(self, attribute, *value):
  if value:
    value = ui.parse_color(value[0])
    setattr(self.node, attribute, UIColor.color(red=value[0], green=value[1], blue=value[2], alpha=value[3]))
  else:
    color = getattr(self.node, attribute)()
    return (
      color.red,
      color.green,
      color.blue,
      color.alpha
    )
Ejemplo n.º 15
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     assert len(self.node.attrs
                ) <= 2, f'Give at most color and a width: {self.node}'
     outline_color = None
     outline_width = None
     for key in self.node.attrs.keys():
         try:
             outline_width = float(key)
         except ValueError:
             outline_color = ui.parse_color(key)
     self.outline_width = outline_width or 3.0
     self.color = outline_color or 'black'
def contentFromPy(aPContent):
    def isImage(aPContent):
        return isinstance(aPContent, Image)

    def isImageArray(aPContent):
        if isinstance(aPContent, Iterable):
            for aPContentElement in aPContent:
                if not isImage(aPContentElement): return False
            return True
        return False

    def isNumber(aPContent):
        return isinstance(aPContent, float) or isinstance(aPContent, int)

    def isURL(aPContent):
        if isinstance(aPContent, str):
            if ' ' in aPContent: return False
            if len(
                    aPContent
            ) > 8 or ':' in aPContent or '/' in aPContent or '.' in aPContent:
                return True
        return False

    def isColor(aPContent):
        try:
            r, g, b, a = parse_color(aPContent)
            return True
        except:
            return False

    if isImage(aPContent):
        aPng = aPContent.to_png()
        return ObjCClass('UIImage').imageWithData_(aPng)
    elif isImageArray(aPContent):
        imageList = []
        for anImage in aPContent:
            aPng = anImage.to_png()
            imageList.append(ObjCClass('UIImage').imageWithData_(aPng))
        return imageList
    elif isNumber(aPContent):
        return ns(aPContent)
    elif isURL(aPContent):
        return nsurl(aPContent)
    elif isColor(aPContent):
        r, g, b, a = parse_color(
            aPContent
        )  #parse_color accepts anything, might result in random colors
        return UIColor.color(red=r, green=g, blue=b, alpha=a)
    else:
        return aPContent
Ejemplo n.º 17
0
 def load_images(self):
     self.puff_images = {}
     for color in self.colors:
         p_color = ui.parse_color(color)
         self.puff_images[p_color] = []
         for i in range(25):
             with io.BytesIO(
                     ui.Image(self.puff_image_name +
                              str(i).zfill(2)).to_png()) as fp:
                 orig_puff = pilImage.open(fp)
                 gray_img = orig_puff.convert('L')
                 color_puff = ImageOps.colorize(gray_img, 'black', color)
                 with io.BytesIO() as fp2:
                     color_puff.save(fp2, 'PNG')
                     self.puff_images[p_color].append(
                         ui.Image.from_data(fp2.getvalue()))
Ejemplo n.º 18
0
 def background_color(self, value):
     self._background_color = value
     r, g, b, a = ui.parse_color(value)
     self.tvo.setBackgroundColor_(UIColor.colorWithRed_green_blue_alpha_(r, g, b, 1))
Ejemplo n.º 19
0
 def filter(self, name, **params):
     CIFilter = ObjCClass('CIFilter')
     CIVector = ObjCClass('CIVector')
     CIColor = ObjCClass('CIColor')
     filter = CIFilter.filterWithName_(name)
     if not filter:
         raise ValueError('Invalid filter name')
     filter.setDefaults()
     input_keys = [str(k) for k in filter.inputKeys()]
     attrs = filter.attributes()
     input_key_types = {
         str(k): str(attrs[k]['CIAttributeClass'])
         for k in input_keys
     }
     supported_types = {
         'CIImage': CImage,
         'CIVector': tuple,
         'CIColor': (tuple, numbers.Number, str),
         'NSNumber': numbers.Number,
         'NSData': (bytes, str),
         'NSString': str
     }
     if 'inputImage' in input_keys:
         filter.setValue_forKey_(self.ci_img, 'inputImage')
     for key, value in params.items():
         if key not in input_keys:
             key = 'input' + key[0].upper() + key[1:]
         if key not in input_keys:
             raise ValueError('"%s" is not a valid parameter for %s' %
                              (key, name))
         param_type = input_key_types[key]
         if param_type not in supported_types:
             raise TypeError('Parameters of type %s are not supported' %
                             param_type)
         expected_type = supported_types[param_type]
         type_matches = isinstance(value, expected_type)
         if not type_matches:
             raise TypeError(
                 'Incorrect type for %s parameter (expected %s, got %s)' %
                 (key, expected_type, type(value)))
         if param_type == 'CIColor':
             if isinstance(value, numbers.Number):
                 value = (value, value, value, 1.0)
             elif isinstance(value, str):
                 value = ui.parse_color(value)
             if not all(isinstance(n, numbers.Number) for n in value):
                 raise TypeError('All color components must be numbers')
             if len(value) == 3:
                 ci_color = CIColor.colorWithRed_green_blue_(*value)
             elif len(value) == 4:
                 ci_color = CIColor.colorWithRed_green_blue_alpha_(*value)
             else:
                 raise TypeError(
                     'Color must be a tuple with 3 or 4 RGB(A) values')
             filter.setValue_forKey_(ci_color, key)
         elif param_type == 'CIImage':
             filter.setValue_forKey_(value.ci_img, key)
         elif param_type == 'CIVector':
             arr = (CGFloat * len(value))(*value)
             vector = CIVector.vectorWithValues_count_(arr, len(value))
             filter.setValue_forKey_(vector, key)
         elif param_type == 'NSData' and isinstance(value, str):
             filter.setValue_forKey_(value.encode('utf-8'), key)
         else:
             filter.setValue_forKey_(value, key)
     out_img = filter.valueForKey_('outputImage')
     return CImage(out_img)
Ejemplo n.º 20
0
 def _objc_color(self, color):
     return UIColor.colorWithRed_green_blue_alpha_(*ui.parse_color(color))
Ejemplo n.º 21
0
def text_in_circle(r,
                            text,
                            text_color = 'white',
                            circle_color = 'teal',
                            circle_alpha = 1.0,
                            font_name = 'Arial Rounded MT Bold',
                            inset_percent = 0):

	'''
	text_in_circle - * denotes a param
	==============
	*r-ui.Rect or tuple (0, 0, 0, 0) - the bounding rect for the circle.
	
	*text-text to draw in the circle
	
	*text_color-color of the text drawn inside the circle
	
	*circle_color-color of the circle
	
	*circle_alpha-alpha setting applied to circle color. Note, did this
	for a reason. easier to use string names for colors!
	
	*font_name-the font used to render the *text
	
	*inset_percent-reduces *r by a percentage for l,t,w,h for possible
	better placement of the text inside the circle. a.k.a margin
	
	RETURNS - a rendered uiImage
	
	'''
	
	# this inner function does not need to be here, was just to keep it
	# all together
	def get_max_fontsize(r, text, font_name, inset_rect = ui.Rect()):
		r1 = ui.Rect(*r).inset(*inset_rect)
		for i in xrange(5, 1000):
			w, h = ui.measure_string(text, max_width=0,
			font=(font_name, i), alignment=ui.ALIGN_LEFT,
			line_break_mode=ui.LB_TRUNCATE_TAIL)
			
			if w > r1.width or h > r1.height:
				return (i - 1, ui.Rect(r1.x, r1.y, w, h))
				
	# tuple or Rect? tried issubclass but had problems
	if not type(r) is ui.Rect:
		r = ui.Rect(*r)
		
	inset_rect = ui.Rect(r.x * inset_percent, r.y * inset_percent,
	r.width * inset_percent, r.height * inset_percent)
	
	with ui.ImageContext(r.width, r.height) as ctx:
		oval = ui.Path.oval(r.x, r.y, r.width, r.height)
		c = ui.parse_color(circle_color)
		nc = (c[0], c[1], c[2], circle_alpha)       # color with alpha
		fs, dest_r = get_max_fontsize(r, text, font_name, inset_rect = inset_rect)
		dest_r.center(r.center())
		with ui.GState():
			ui.set_color(nc)
			oval.fill()
			ui.draw_string(text, rect=dest_r,
			font=(font_name, fs), color=text_color,
			alignment=ui.ALIGN_LEFT,
			line_break_mode=ui.LB_TRUNCATE_TAIL)
		return ctx.get_image()
Ejemplo n.º 22
0
def objc_color(self, color):
    """ Convert any Pythonista color spec to an ObjC UIColor """
    return objc_util.UIColor.colorWithRed_green_blue_alpha_(
        *ui.parse_color(color))
Ejemplo n.º 23
0
def pil_color(color):
    color = ui.parse_color(color)
    result_color = tuple()
    for band in color:
        result_color += (int(band * 255), )
    return result_color
Ejemplo n.º 24
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     assert len(
         self.node.attrs) == 1, f'Give only one color: {self.node}'
     self.color = ui.parse_color(list(self.node.attrs.keys())[0])
Ejemplo n.º 25
0
    def __init__(self, control, *args, color=(0, 0, 1), **kwargs):
        super().__init__(*args, **kwargs)

        self.control = control
        self.color = ui.parse_color(color)
        self.init_values()
Ejemplo n.º 26
0
 def tint_color(self, value):
     self._tint_color = value
     r, g, b, a = ui.parse_color(value)
     self.tvo.setTintColor_(UIColor.colorWithRed_green_blue_alpha_(r, g, b, 1))
 def isColor(aPContent):
     try:
         r, g, b, a = parse_color(aPContent)
         return True
     except:
         return False
Ejemplo n.º 28
0
def _get_CGColor(color):
    """Get a CGColor from a wide range of formats."""
    return UIColor.colorWithRed_green_blue_alpha_(
        *ui.parse_color(color)).CGColor()
Ejemplo n.º 29
0
def get_css_color(color_name, alpha=1.0):
    '''
		A simple util to return a tuple (RGBA) given a css name
	'''
    c = ui.parse_color(color_name)
    return (c[0], c[1], c[2], alpha)
Ejemplo n.º 30
0
 def objc_color(self):
     return objc_util.UIColor.colorWithRed_green_blue_alpha_(
         *ui.parse_color(self.color))
Ejemplo n.º 31
0
 def background_color(self, color):
     rgba = parse_color(color)
     self.status.setBackgroundColor_(
         UIColor.colorWithRed_green_blue_alpha_(*rgba)
     )