def makeBorder(borderdesc): vals = borderdesc.split() if not vals: return wx.TRANSPARENT_PEN if vals[0].lower() == 'border': vals = vals[1:] d = S() for elem in vals: elem = elem.lower() if elem.endswith('px') and isint(elem[:-2]): d.size = int(elem[:-2]) elif isint(elem): d.size = int(elem) else: penstyle = penstyle_aliases.get(elem, elem) if penstyle in penstyles: d.style = penstyle else: try: d.color = colorfor(elem) except ValueError: pass return _pen_from_dict(d)
def test_isint(self): self.assert_(isint('5')) self.assert_(isint('123')) self.assert_(isint('-2321')) self.assert_(not isint('1.5')) self.assert_(not isint('.')) self.assert_(not isint('')) self.assert_(not isint(' ')) self.assert_(not isint('foo')) self.assert_(not isint('5 foo')) self.assert_(not isint('foo 5'))
def __getitem__(self, buddy): ''' This is where the magic happens -- if the buddy does not exist, then a new 'blank' buddy will be returned with only the name and protocol set. @param buddy the name to use for the buddy ''' if not buddy: raise NameError if (util.is_email(buddy) and self in (self.protocol.buddies, self.protocol.circle_buddies)): try: return dict.__getitem__(self, buddy) except KeyError: return self.setdefault(str(buddy), self.DefaultClass(name=buddy, msn=self.protocol)) else: is_sms = validate_sms(buddy) is_int = funcs.isint(buddy) if (is_sms or is_int) and self is self.protocol.m_buddies: try: return dict.__getitem__(self, buddy) except KeyError: return dict.setdefault(self, str(buddy), self.DefaultClass(name=buddy, msn=self.protocol)) log.critical('Unknown buddy was requested: %r, %r', type(buddy), buddy) raise KeyError(buddy)
def from_net(cls, data, is_payload = None): if is_payload is None: is_payload = is_payload_command(data.split(' ', 1)) if is_payload: cmdline, payload = data.split('\r\n',1) else: cmdline, payload = data, None cmdline = cmdline.strip('\r\n ') dlist = cmdline.split(' ') cmd = dlist.pop(0) if dlist and isint(dlist[0]): trid = int(dlist.pop(0)) else: trid = 0 if is_payload: try: l = dlist.pop() except IndexError: # oops, the TrID was the payload length l,trid = trid, 0 try: assert isint(l) and int(l) == len(payload), (cmdline, len(payload)) except AssertionError: assert cmd in ('ADL', 'RML') and (not isint(l) or len(payload) == int(l)), (cmdline, dlist, l, len(payload)) dlist.append(l) payload = payload.strip() or None args = list(dlist) if cmd == 'MSG': ctype = MsgPayload(payload).get('content-type', '').split(';')[0] subcmd = msn.util.msgtypes.get(ctype, '') cls = globals().get(cmd+subcmd, MSG) else: cls = globals().get(cmd, cls) return cls(cmd, trid=trid, payload=payload, *args)
def __init__(self, code, *args): if isinstance(code, basestring): try: code = int(code) except (ValueError,): code = 100 elif isinstance(code, message): code = code.error_code assert not args else: from util.primitives.funcs import isint assert isint(code) msg = error_codes.get(code, 'Unknown') Exception.__init__(self, code, msg, *args)
def __init__(self, code, *args): if isinstance(code, basestring): try: code = int(code) except (ValueError, ): code = 100 elif isinstance(code, message): code = code.error_code assert not args else: from util.primitives.funcs import isint assert isint(code) msg = error_codes.get(code, 'Unknown') Exception.__init__(self, code, msg, *args)
def send_fqy(self, n, flags): 'FQY 10 51\r\n<ml l="1"><d n="yahoo.com"><c n="synae" /></d></ml>' 'FQY 17 53\r\n<ml l="2"><d n="yahoo.com"><c n="digbsy04" /></d></ml>' u, d = n.split('@') ml = xml_tag.tag('ml') ml.d['n']=d ml.d.c['n']=u if not isint(flags): d = dict(f=1, a=2, b=4, r=8, p=16) if isinstance(flags, basestring): flags = [flags] flags = sum(d[f[0].lower()] for f in flags) if flags == 1: flags = 2 ml['l']=flags xml = ml._to_xml(pretty=False) self.socket.send(Message('FQY', payload=xml), trid=True, callback=sentinel)
def send_fqy(self, n, flags): 'FQY 10 51\r\n<ml l="1"><d n="yahoo.com"><c n="synae" /></d></ml>' 'FQY 17 53\r\n<ml l="2"><d n="yahoo.com"><c n="digbsy04" /></d></ml>' u, d = n.split("@") ml = xml_tag.tag("ml") ml.d["n"] = d ml.d.c["n"] = u if not isint(flags): d = dict(f=1, a=2, b=4, r=8, p=16) if isinstance(flags, basestring): flags = [flags] flags = sum(d[f[0].lower()] for f in flags) if flags == 1: flags = 2 ml["l"] = flags xml = ml._to_xml(pretty=False) self.socket.send(Message("FQY", payload=xml), trid=True, callback=sentinel)
def makeFont(fontdesc, defaultFace=None, defaultSize=None): ''' Returns a wxFont for the following skin syntax: Arial 12 bold Underline or Comic Sans MS 14 italic strikethrough ''' from gui.skin import font_multiply_factor system_font = default_font() if not fontdesc: return system_font elif isinstance(fontdesc, int): system_font.SetPointSize(int(fontdesc)) return system_font # arguments to wx.Font constructor opts = dict(faceName=defaultFace if defaultFace is not None else system_font.FaceName, pointSize=defaultSize if defaultSize is not None else system_font.PointSize, style=wx.FONTSTYLE_NORMAL, weight=wx.FONTWEIGHT_NORMAL, underline=False, family=wx.FONTFAMILY_DEFAULT) fontdesc = fontdesc.strip() elems = fontdesc.split() # find the last number -- that will be the size. everything before becomes # the face name, and everything after is treated as flags. lastsize = -1 for i, elem in enumerate(elems[::-1]): if isint(elem): lastsize = len(elems) - i - 1 # since the indices are reversed break if lastsize == -1: flagi = -1 for i, elem in enumerate(elems): if elem in fontweights or elem in fontstyles or elem in ( 'underline', 'underlined'): flagi = i break size = defaultSize if defaultSize is not None else system_font.PointSize if flagi != -1: splitpoint = fontdesc.rfind(elems[flagi]) facename = fontdesc[:splitpoint].strip() flags = fontdesc[splitpoint:].strip() else: facename = fontdesc.strip() flags = '' else: splitpoint = fontdesc.rfind(elems[lastsize]) facename = fontdesc[:splitpoint].strip() size = int(elems[lastsize]) flags = fontdesc[splitpoint + len(elems[lastsize]):] if facename: opts['faceName'] = facename opts['pointSize'] = int(size) # parse remaining flags for elem in flags.split(): elem = elem.lower() if elem in fontweights: opts['weight'] = getattr(wx, 'FONTWEIGHT_' + elem.upper()) elif elem in fontstyles: opts['style'] = getattr(wx, 'FONTSTYLE_' + elem.upper()) elif elem in ('underline', 'underlined'): opts['underline'] = True o = opts return wx.Font(o['pointSize'], o['family'], o['style'], o['weight'], o['underline'], o['faceName'])
def makeBrush(brushdesc): ''' Makes a rectangular skin brush given strings like red red white blue vertical green white red rounded red rounded 10 blue shadow 0xffffee 0x123456 ''' if isinstance(brushdesc, list): return SkinStack(makeBrush(e) for e in brushdesc) elif isinstance(brushdesc, int): return SkinColor(colorfor(brushdesc)) elif brushdesc is None: return None elems = brushdesc.split() try: b = elems.index('border') except ValueError: border = None else: border = makeBorder(' '.join(elems[b:])) elems = elems[:b] first = elems[0] if any(first.endswith(e) for e in image_exts): return makeImage(brushdesc) shadow = highlight = rounded = False colors = [] direction = 'vertical' for i, elem in enumerate(elems): elem = elem.lower() if elem in ('h', 'v', 'horizontal', 'vertical'): direction = {'h': 'horizontal', 'v': 'vertical'}.get(elem, elem) elif elem == 'rounded': if len(elems) > i + 1 and isint(elems[i + 1]): rounded = float(elems[i + 1]) else: rounded = DEFAULT_ROUNDED_RADIUS elif elem == 'highlight': highlight = True elif elem == 'shadow': shadow = True elif elem.endswith('%') and isint(elem[:-1]) and colors: # replace the last wxColor in colors with the same color and # a new alpha value, so strings like "blue red 40%" produce # [wx.Colour(0, 0, 255, 255), wx.Colour(255, 0, 0, 102)] # # (I know there is a wxColour.Set method but it didn't work for me) alpha_value = clamp(float(elem[:-1]) / 100.00 * 255.0, 0, 255) rgba = tuple(colors[-1])[:3] + (alpha_value, ) colors[-1] = wx.Colour(*rgba) else: try: colors.append(colorfor(elem)) except ValueError: pass kwargs = dict(rounded=rounded, shadow=shadow, highlight=highlight, border=border) if len(colors) == 0: raise SkinException('no colors specified in "%s"' % brushdesc) elif len(colors) == 1: # one color -> SkinColor return SkinColor(colors[0], **kwargs) else: # multiple colors -> SkinGradient return SkinGradient(direction, colors, **kwargs)
def makeImage(imagedesc): 'Parses an image description, returning a SolidImage or SplitImage4.' imagedesc = imagedesc.strip() if not imagedesc: return None # use the image extension as the "split" point between the filename # and the options, so that spaces in image filenames are possible # without quotes. i = max(imagedesc.find('.' + ext) for ext in imageExts) if i == -1: raise SkinException('images end in %r' % (imageExts, )) i = imagedesc.find(' ', i) if i == -1: # just "image.png" -- return a SolidImage. return solid_si4(imagedesc) filename, options = imagedesc[:i], imagedesc[i + 1:] imgdict = S(source=filename) options = options.split() if options: # one-liner: image with cuts if isint(options[0]): # numbers...must be a splitimage n = len(options) for i, opt in enumerate(options): if not isint(opt): n = i break splits, options = options[:n], options[n:] if not splits: solid_si4(imgdict['source']) # parsing rules for splits are same as framesizes imgdict.update(izip(('x1', 'y1', 'x2', 'y2'), Margins(splits))) hstyle = vstyle = regionTypes.stretch align = None posSpecified = False offset = [] for option in options: if option.startswith('h_'): if option in ('h_right', 'h_center', 'h_left'): hstyle = regionTypes.static if align is None: align = regionAlignments[option] else: align |= regionAlignments[option] else: hstyle = regionTypes[option[2:]] elif option.startswith('v_'): if option in ('v_top', 'v_center', 'v_bottom'): vstyle = regionTypes.static if align is None: align = regionAlignments[option] else: align |= regionAlignments[option] else: vstyle = regionTypes[option[2:]] elif option == 'tile': hstyle = vstyle = regionTypes.tile elif isint(option): offset += [int(option)] else: log.warning('unknown skin option "%s"') if len(offset) == 0: # no offsets given: use (0, 0) offset = [0, 0] elif len(offset) == 1: # one offset: means it is used for both X and Y offset = offset * 2 else: # more than two: use the last two numbers found offset = offset[-2:] if align is None: align = wx.ALIGN_CENTER for a in SIREGIONS: imgdict[a] = S(extend=[], hstyle=hstyle, vstyle=vstyle, align=align, offset=wx.Point(*offset)) return si4(imgdict) else: return solid_si4(imgdict['source'])
def makeBrush(brushdesc): ''' Makes a rectangular skin brush given strings like red red white blue vertical green white red rounded red rounded 10 blue shadow 0xffffee 0x123456 ''' if isinstance(brushdesc, list): return SkinStack(makeBrush(e) for e in brushdesc) elif isinstance(brushdesc, int): return SkinColor(colorfor(brushdesc)) elif brushdesc is None: return None elems = brushdesc.split() try: b = elems.index('border') except ValueError: border = None else: border = makeBorder(' '.join(elems[b:])) elems = elems[:b] first = elems[0] if any(first.endswith(e) for e in image_exts): return makeImage(brushdesc) shadow = highlight = rounded = False colors = [] direction = 'vertical' for i, elem in enumerate(elems): elem = elem.lower() if elem in ('h','v', 'horizontal', 'vertical'): direction = {'h': 'horizontal', 'v': 'vertical'}.get(elem, elem) elif elem == 'rounded': if len(elems) > i + 1 and isint(elems[i+1]): rounded = float(elems[i+1]) else: rounded = DEFAULT_ROUNDED_RADIUS elif elem == 'highlight': highlight = True elif elem == 'shadow': shadow = True elif elem.endswith('%') and isint(elem[:-1]) and colors: # replace the last wxColor in colors with the same color and # a new alpha value, so strings like "blue red 40%" produce # [wx.Colour(0, 0, 255, 255), wx.Colour(255, 0, 0, 102)] # # (I know there is a wxColour.Set method but it didn't work for me) alpha_value = clamp(float(elem[:-1])/100.00 * 255.0, 0, 255) rgba = tuple(colors[-1])[:3] + (alpha_value,) colors[-1] = wx.Colour(*rgba) else: try: colors.append(colorfor(elem)) except ValueError: pass kwargs = dict(rounded = rounded, shadow = shadow, highlight = highlight, border = border) if len(colors) == 0: raise SkinException('no colors specified in "%s"' % brushdesc) elif len(colors) == 1: # one color -> SkinColor return SkinColor(colors[0], **kwargs) else: # multiple colors -> SkinGradient return SkinGradient(direction, colors, **kwargs)
def makeFont(fontdesc, defaultFace = None, defaultSize = None): ''' Returns a wxFont for the following skin syntax: Arial 12 bold Underline or Comic Sans MS 14 italic strikethrough ''' from gui.skin import font_multiply_factor system_font = default_font() if not fontdesc: return system_font elif isinstance(fontdesc, int): system_font.SetPointSize(int(fontdesc)) return system_font # arguments to wx.Font constructor opts = dict(faceName = defaultFace if defaultFace is not None else system_font.FaceName, pointSize = defaultSize if defaultSize is not None else system_font.PointSize, style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL, underline = False, family = wx.FONTFAMILY_DEFAULT) fontdesc = fontdesc.strip() elems = fontdesc.split() # find the last number -- that will be the size. everything before becomes # the face name, and everything after is treated as flags. lastsize = -1 for i, elem in enumerate(elems[::-1]): if isint(elem): lastsize = len(elems) - i - 1 # since the indices are reversed break if lastsize == -1: flagi = -1 for i, elem in enumerate(elems): if elem in fontweights or elem in fontstyles or elem in ('underline', 'underlined'): flagi = i break size = defaultSize if defaultSize is not None else system_font.PointSize if flagi != -1: splitpoint = fontdesc.rfind(elems[flagi]) facename = fontdesc[:splitpoint].strip() flags = fontdesc[splitpoint:].strip() else: facename = fontdesc.strip() flags = '' else: splitpoint = fontdesc.rfind(elems[lastsize]) facename = fontdesc[:splitpoint].strip() size = int(elems[lastsize]) flags = fontdesc[splitpoint + len(elems[lastsize]):] if facename: opts['faceName'] = facename opts['pointSize'] = int(size) # parse remaining flags for elem in flags.split(): elem = elem.lower() if elem in fontweights: opts['weight'] = getattr(wx, 'FONTWEIGHT_' + elem.upper()) elif elem in fontstyles: opts['style'] = getattr(wx, 'FONTSTYLE_' + elem.upper()) elif elem in ('underline', 'underlined'): opts['underline'] = True o = opts return wx.Font(o['pointSize'], o['family'], o['style'], o['weight'], o['underline'], o['faceName'])
def is_trid(self): return bool(isint(self.trid) and int(self.trid))
def makeImage(imagedesc): 'Parses an image description, returning a SolidImage or SplitImage4.' imagedesc = imagedesc.strip() if not imagedesc: return None # use the image extension as the "split" point between the filename # and the options, so that spaces in image filenames are possible # without quotes. i = max(imagedesc.find('.' + ext) for ext in imageExts) if i == -1: raise SkinException('images end in %r' % (imageExts,)) i = imagedesc.find(' ', i) if i == -1: # just "image.png" -- return a SolidImage. return solid_si4(imagedesc) filename, options = imagedesc[:i], imagedesc[i+1:] imgdict = S(source = filename) options = options.split() if options: # one-liner: image with cuts if isint(options[0]): # numbers...must be a splitimage n = len(options) for i, opt in enumerate(options): if not isint(opt): n = i break splits, options = options[:n], options[n:] if not splits: solid_si4(imgdict['source']) # parsing rules for splits are same as framesizes imgdict.update(izip(('x1', 'y1', 'x2', 'y2'), Margins(splits))) hstyle = vstyle = regionTypes.stretch align = None posSpecified = False offset = [] for option in options: if option.startswith('h_'): if option in ('h_right', 'h_center', 'h_left'): hstyle = regionTypes.static if align is None: align = regionAlignments[option] else: align |= regionAlignments[option] else: hstyle = regionTypes[option[2:]] elif option.startswith('v_'): if option in ('v_top', 'v_center', 'v_bottom'): vstyle = regionTypes.static if align is None: align = regionAlignments[option] else: align |= regionAlignments[option] else: vstyle = regionTypes[option[2:]] elif option == 'tile': hstyle = vstyle = regionTypes.tile elif isint(option): offset += [int(option)] else: log.warning('unknown skin option "%s"') if len(offset) == 0: # no offsets given: use (0, 0) offset = [0, 0] elif len(offset) == 1: # one offset: means it is used for both X and Y offset = offset * 2 else: # more than two: use the last two numbers found offset = offset[-2:] if align is None: align = wx.ALIGN_CENTER for a in SIREGIONS: imgdict[a] = S(extend = [], hstyle = hstyle, vstyle = vstyle, align = align, offset = wx.Point(*offset)) return si4(imgdict) else: return solid_si4(imgdict['source'])