def extract_profile_ids(stream): ret = set() for post in stream['posts']: """(SELECT viewer_id FROM #posts)""" """(SELECT actor_id FROM #posts)""" """(SELECT target_id FROM #posts)""" """(SELECT source_id FROM #posts)""" for key in POST_ID_NAMES: with traceguard: try_this(lambda: ret.add(post[key]), ignore=IGNORED) """(SELECT likes.sample FROM #posts)""" with traceguard: try_this(lambda: ret.update(post['likes']['sample']), ignore=IGNORED) """(SELECT likes.friends FROM #posts)""" with traceguard: try_this(lambda: ret.update(post['likes']['friends']), ignore=IGNORED) """(SELECT fromid FROM #comments)""" for post_comments in stream['comments'].values(): for comment in post_comments: with traceguard: try_this(lambda: ret.add(comment['fromid']), ignore=IGNORED) """(SELECT sender_id FROM #notifications)""" for notification in stream.get('notifications', []): with traceguard: try_this(lambda: ret.add(notification['sender_id']), ignore=IGNORED) return ret
def extract_profile_ids(stream): ret = set() for post in stream['posts']: """(SELECT viewer_id FROM #posts)""" """(SELECT actor_id FROM #posts)""" """(SELECT target_id FROM #posts)""" """(SELECT source_id FROM #posts)""" for key in POST_ID_NAMES: with traceguard: try_this(lambda: ret.add(post[key]), ignore = IGNORED) """(SELECT likes.sample FROM #posts)""" with traceguard: try_this(lambda: ret.update(post['likes']['sample']), ignore = IGNORED) """(SELECT likes.friends FROM #posts)""" with traceguard: try_this(lambda: ret.update(post['likes']['friends']), ignore = IGNORED) """(SELECT fromid FROM #comments)""" for post_comments in stream['comments'].values(): for comment in post_comments: with traceguard: try_this(lambda: ret.add(comment['fromid']), ignore = IGNORED) """(SELECT sender_id FROM #notifications)""" for notification in stream.get('notifications', []): with traceguard: try_this(lambda: ret.add(notification['sender_id']), ignore = IGNORED) return ret
def UpdateSkin(self): """ Updates all the local skin references """ key = self.skinkey s = lambda k, default=sentinel: skin.get(key + '.' + k, default) mode = try_this(lambda: str(s('mode', '')), '') if config.platformName != "mac" and key and mode.lower() != 'native': self.native = False self.repeat = try_this(lambda: str(s('style', '')).lower(), '') == 'repeat' self.padding = s('padding', 0) self.Font = s('font', lambda: default_font()) self.bg = s('backgrounds.normal', None) self.fg = s('backgrounds.fill', lambda: SkinColor(wx.BLUE)) self.normalfc = s('fontcolors.normal', wx.BLACK) self.fillfc = s('fontcolors.fill', wx.WHITE) else: self.native = True self.OnSize()
def UpdateSkin(self): """ Updates all the local skin references """ key = self.skinkey s = lambda k, default = sentinel: skin.get(key + '.' + k, default) mode = try_this(lambda: str(s('mode', '')), '') if config.platformName != "mac" and key and mode.lower() != 'native': self.native=False self.repeat = try_this(lambda: str(s('style', '')).lower(), '') == 'repeat' self.padding = s('padding', 0) self.Font = s('font', lambda: default_font()) self.bg = s('backgrounds.normal', None) self.fg = s('backgrounds.fill', lambda: SkinColor(wx.BLUE)) self.normalfc = s('fontcolors.normal', wx.BLACK) self.fillfc = s('fontcolors.fill', wx.WHITE) else: self.native = True self.OnSize()
def test_try_this(self): 'Ensure try_this squashes exceptions' def raise_it(e): raise e self.assert_equal(5, try_this(lambda: 1/0, 5)) self.assert_equal('foo', try_this(lambda: raise_it(AssertionError), 'foo')) if not python_debug_build: self.assert_raises(RuntimeError, rabbithole) self.assert_equal('bar', try_this(rabbithole, 'bar'))
def test_try_this(self): 'Ensure try_this squashes exceptions' def raise_it(e): raise e self.assert_equal(5, try_this(lambda: 1 / 0, 5)) self.assert_equal('foo', try_this(lambda: raise_it(AssertionError), 'foo')) if not python_debug_build: self.assert_raises(RuntimeError, rabbithole) self.assert_equal('bar', try_this(rabbithole, 'bar'))
def rearrange(self, clist_obj, area, to_group, drop_to): 'Rearranges manual ordering.' with traceguard: log.info('moving %s %s %s', clist_obj, area, drop_to) self._update_order_from_sorter() # get the list of ordered keys for a group grp_key = to_group.groupkey() # HACK: effectively, groups that share a name with the fake root group do not exist. # side effect: if you rename the fake root group w/o being logged into another account that # has a group which shares it's name, the ordering for that group is lost. if grp_key.lower() == pref('buddylist.fakeroot_name', default=_('Contacts')).lower(): grp_key = FAKE_ROOT_GROUP_KEY # end HACK. order = self.order['contacts'][grp_key] # rearrange a Contact, using it's idstr obj = clist_obj.idstr() # index of the thing you're moving, otherwise end i = try_this(lambda: order.index(obj), len(order)) # index of where to insert if drop_to is self.DROP_BEGINNING: j = 0 elif drop_to is self.DROP_END: j = len(order) else: j = try_this(lambda: order.index(drop_to.idstr()) + (1 if area == 'below' else 0), 0) #if destination is farther than current position, #we will leave a hole, account for it. if j > i: j -= 1 with traceguard: log.info('rearranging buddies in %s (groupkey=%s): %d -> %d', to_group.name, grp_key, i, j) if i != len(order): order.pop(i) order.insert(j, obj) self._info_changed() self.update_order() self.rebuild_now()
def from_xml(xml, filter_html=True): if not xml or not xml.strip(): return [] results = lxml.etree.fromstring(xml) ns = results.nsmap.get(None, '') if ns: ns = '{%s}' % ns find = lambda s: results.find(ns + s) return NewsItemList( version = find('version'), time = try_this(lambda: int(find('time').text), 0), max_age = try_this(lambda: int(find('max-age').text), 1800), items = (NewsItem_from_xml(ns, e, filter_html=filter_html) for e in find('featured-result-list')))
def Draw( self, dc, rect, selected, obj, depth, expanded, index, hover ): s = self.skin # apply margins rect = rect.AddMargins(wx.Rect(*s.margins)).AddMargins(wx.Rect(0, s.padding.y, 0, s.padding.y)) # Group font is drawn with the same as the buddies. fontface = self.font_face font = safefont(fontface, try_this(lambda: int(self.font_size), 10), bold = True) dc.SetFont( font ) # indent for depth rect = rect.Subtract(left = self.group_indent * depth) # Expander triangles. if isiterable( obj ): triangle = self.get_expander(selected, expanded, hover) if triangle is not None: dc.DrawBitmap(triangle, rect.x, rect.VCenter(triangle), True) rect = rect.Subtract(left = triangle.Width + s.padding.x) # decide on a foreground text color if selected: fg = s.fontcolors.groupselected elif hover: fg = s.fontcolors.grouphover else: fg = s.fontcolors.group dc.SetTextForeground( fg ) # the actual text label dc.DrawTruncatedText(obj.display_string, rect, alignment = lmiddle)
def mobile_changed(self, *args): # Returning from this method early as it is no longer used, # but might come back in the future # see ticket #1534 return if not self: return log.critical('mobile_changed is an unregistered observer!') val = try_this(lambda: self.acct.connection.self_buddy.enable_mobile, False) assert type(val) is bool, (val, type(val)) self.Freeze() self.online_components.Hide(self.mob_sz[not val], recursive=True) if self.acct.is_connected: f = self.online_components.Show else: f = self.online_components.Hide f(self.mob_sz[val], recursive=True) # self.mob_sz[not val].Show(False, recursive=True) # self.mob_sz[val].Show(True, recursive=True) self.Thaw() self.Fit() self.Layout()
def UpdateSkin(self): Renderer.UpdateSkin(self) self.drawseqs = {} self._lastcalc = [] s, g = self.skin, skin.get self.statusicons = g('statusicons') s.margins = g('BuddiesPanel.BuddyMargins') s.icon_frame = g('BuddiesPanel.BuddyIcons.Frame', None) s.icon_frame_size = Margins(g('BuddiesPanel.BuddyIcons.FrameSize', (0, 0, 0, 0))) s.round_corners = try_this(lambda: int(g('BuddiesPanel.BuddyIcons.Rounded', 1)), 1) f, g = s.fontcolors, lambda k, default: skin.get('BuddiesPanel.FontColors.' + k, default) f.buddy = g('Buddy', lambda: syscol(wx.SYS_COLOUR_WINDOWTEXT)) f.buddyoffline = g('BuddyOffline', lambda: syscol(wx.SYS_COLOUR_GRAYTEXT)) f.buddyselected = g('BuddySelected', lambda: syscol(wx.SYS_COLOUR_HIGHLIGHTTEXT)) f.buddyhover = g('BuddyHover', lambda: f.buddy) f.status = g('Status', lambda: f.buddy) f.statushover = g('StatusHover', lambda: f.buddyhover) f.statusselected = g('StatusSelected', lambda: f.buddyselected) f.idletime = g('IdleTime', lambda: syscol(wx.SYS_COLOUR_GRAYTEXT)) f.idletimehover = g('IdleTimeHover', lambda: syscol(wx.SYS_COLOUR_GRAYTEXT)) f.idletimeselected = g('IdleTimeSelected', lambda: syscol(wx.SYS_COLOUR_HIGHLIGHTTEXT)) # icons to be drawn self.calcsizes()
def rearrange_group(self, group, area, togroup): ''' Move a group above or below another group. area should be "above" or "below" ''' if not isinstance(group, DisplayGroup) or not isinstance(togroup, DisplayGroup): raise TypeError('group and togroup must be DisplayGroups: %r %r' % (group, togroup)) order = self.order['groups'] try: i = order.index(groupkey(group)) except ValueError: found = False else: found = True #index of where to insert j = try_this(lambda: order.index(groupkey(togroup)) + (1 if area == 'below' else 0), 0) if found and j > i: j -= 1 #log.info('moving group %r from %r to %r', group, i, j) if found: popped = order.pop(i) else: popped = groupkey(group) order.insert(j, popped) self._info_changed() self.update_order() self.rebuild_now()
def calcsizes(self): s = self.skin p = self.getpref self.padding = p('padding') self.mainfont = safefont(p('name_font_face', None), try_this(lambda: int(p('name_font_size')), 10)) self.mainfont_height = self.mainfont.LineHeight self.cell_height = (max(self.icon_height, self.mainfont_height) + s.margins.top + s.margins.bottom + self.padding * 2)
def from_xml(xml, filter_html=True): if not xml or not xml.strip(): return [] results = lxml.etree.fromstring(xml) ns = results.nsmap.get(None, '') if ns: ns = '{%s}' % ns find = lambda s: results.find(ns + s) return NewsItemList(version=find('version'), time=try_this(lambda: int(find('time').text), 0), max_age=try_this(lambda: int(find('max-age').text), 1800), items=(NewsItem_from_xml(ns, e, filter_html=filter_html) for e in find('featured-result-list')))
def status_messages_start(self): cbs = dict(success = self.status_messages_success, error = self.status_messages_repeat) if self.status_messages: self.api.query('select uid, status from user where uid in (SELECT uid2 FROM friend WHERE uid1 = me()) and status.time > %d'\ % max(self.status_messages, key=lambda s: try_this(lambda: (s.get('status', {}) or {}).get('time', 0), 0)), **cbs ) else: self.api.query('select uid, status from user where uid in (SELECT uid2 FROM friend WHERE uid1 = me())', **cbs )
def status_messages_start(self): cbs = dict(success=self.status_messages_success, error=self.status_messages_repeat) if self.status_messages: self.api.query('select uid, status from user where uid in (SELECT uid2 FROM friend WHERE uid1 = me()) and status.time > %d'\ % max(self.status_messages, key=lambda s: try_this(lambda: (s.get('status', {}) or {}).get('time', 0), 0)), **cbs ) else: self.api.query( 'select uid, status from user where uid in (SELECT uid2 FROM friend WHERE uid1 = me())', **cbs)
def calcsizes(self): p = self.getpref margins = self.skin.margins padding = self.skin.padding # Main Font: contact's name self.mainfont = safefont(p('name_font_face', None), try_this(lambda: int(p('name_font_size')), 10)) self.mainfont_height = self.mainfont.LineHeight # group_height is reported via OnMeasureItem to VListBox self.group_height = int(self.mainfont_height) + margins.top + margins.bottom + (padding.y * 2) self.depth_indent = p('indent', 5)
def status_messages_success(self, result): try: if isinstance(result, list): results = db_rows_to_dict(result, 'uid') self.status_messages.update(results) except Exception: traceback.print_exc() else: #timing is a little weird, just update them all for uid, status in self.status_messages.iteritems(): msg = try_this(lambda: (status.get('status', {}) or {}).get('message', ''), '') self.get_buddy(str(uid)).set_status_message(msg) finally: self.status_messages_repeat()
def status_messages_success(self, result): try: if isinstance(result, list): results = db_rows_to_dict(result, 'uid') self.status_messages.update(results) except Exception: traceback.print_exc() else: #timing is a little weird, just update them all for uid, status in self.status_messages.iteritems(): msg = try_this( lambda: (status.get('status', {}) or {}).get('message', ''), '') self.get_buddy(str(uid)).set_status_message(msg) finally: self.status_messages_repeat()
def get_dropdown_contacts(self, prefix=None): val = prefix.lower() if prefix is not None else '' #print '-'*80 #from pprint import pprint #pprint(self.contacts) filtered_contacts = [] contacts_inviting = set(self.model.contacts) is_self = lambda b: try_this(lambda: b is b.protocol.self_buddy, False) for contact in sorted(self.contacts.itervalues(), key=self.buddy_sort): if contact not in contacts_inviting and not is_self(contact) and getattr(contact, 'supports_group_chat', False): # search "name" and "alias" fields n, a = contact.name.lower(), contact.alias.lower() if n.startswith(val) or a.startswith(val): filtered_contacts.append(contact) return filtered_contacts
def get_dropdown_contacts(self, prefix=None): val = prefix.lower() if prefix is not None else '' #print '-'*80 #from pprint import pprint #pprint(self.contacts) filtered_contacts = [] contacts_inviting = set(self.model.contacts) is_self = lambda b: try_this(lambda: b is b.protocol.self_buddy, False) for contact in sorted(self.contacts.itervalues(), key=self.buddy_sort): if contact not in contacts_inviting and not is_self( contact) and getattr(contact, 'supports_group_chat', False): # search "name" and "alias" fields n, a = contact.name.lower(), contact.alias.lower() if n.startswith(val) or a.startswith(val): filtered_contacts.append(contact) return filtered_contacts
def __init__(self, parent=None): SimplePanel.__init__(self, parent) self.Sizer = wx.BoxSizer(wx.VERTICAL) link = profile.prefs.link #@UndefinedVariable # setup and layout GUI self.tray_icons = [] self.gui_construct() rebuild = self.rebuild_panels rebuild() # Watch always on top changes def ontop_changed(val): docker = wx.GetTopLevelParent(self).docker if docker.docked and docker.AutoHide: return p = wx.GetTopLevelParent(self) if val: p.WindowStyle = p.WindowStyle | wx.STAY_ON_TOP else: p.WindowStyle = p.WindowStyle & ~wx.STAY_ON_TOP self.unlinkers = [ link(*a) for a in [( 'buddylist.always_on_top', ontop_changed, True, self ), ('buddylist.order', lambda v: self.gui_layout(), False, self), ('buddylist.show_status', rebuild, False), ( 'buddylist.show_email_as', rebuild, False), ('buddylist.show_social_as', rebuild, False), ('buddylist.show_menubar', lambda v: self.gui_layout(), False, self), ('social.display_attr', rebuild, False), ('email.display_attr', rebuild, False), ('buddylist.show_in_taskbar', lambda val: wx.CallAfter(lambda: setattr( self.Top, 'OnTaskbar', val)), True, self)] ] # link docking preferences link = profile.localprefs.link docker = wx.GetTopLevelParent(self).docker self.unlinkers += [ link(*a) for a in [ ('buddylist.dock.autohide', lambda v: docker.SetAutoHide(bool(v)), True, docker), ('buddylist.dock.enabled', lambda v: docker.SetEnabled(bool(v)), True, docker), ('buddylist.dock.revealms', lambda v: setattr( docker, 'RevealDurationMs', try_this(lambda: int(v), 300)), True, docker), ] ] self.unlinkers.append( profile.prefs.link( 'buddylist.dock.slide_velocity', lambda v: wx.CallAfter(docker.SetVelocity, int(v)), obj=docker)) #@UndefinedVariable self.unlinkers.append( Storage(unlink=profile.emailaccounts.add_list_observer( rebuild, rebuild, 'enabled').disconnect)) self.unlinkers.append( Storage(unlink=profile.socialaccounts.add_list_observer( rebuild, rebuild, 'enabled').disconnect)) # don't ever let this control take focus self.Bind(wx.EVT_SET_FOCUS, lambda e: self.blist.SetFocus())
def get_fault(exc): return try_this(lambda: exc.fault.detail[0], None)
def __init__( self, parent = None ): SimplePanel.__init__(self, parent) self.Sizer = wx.BoxSizer(wx.VERTICAL) link = profile.prefs.link #@UndefinedVariable # setup and layout GUI self.tray_icons = [] self.gui_construct() rebuild = self.rebuild_panels rebuild() # Watch always on top changes def ontop_changed(val): docker = wx.GetTopLevelParent(self).docker if docker.docked and docker.AutoHide: return p = wx.GetTopLevelParent(self) if val: p.WindowStyle = p.WindowStyle | wx.STAY_ON_TOP else: p.WindowStyle = p.WindowStyle & ~wx.STAY_ON_TOP self.unlinkers = [link(*a) for a in [ ('buddylist.always_on_top', ontop_changed, True, self), ('buddylist.order', lambda v: self.gui_layout(), False, self), ('buddylist.show_status', rebuild, False), ('buddylist.show_email_as', rebuild, False), ('buddylist.show_social_as', rebuild, False), ('buddylist.show_menubar', lambda v: self.gui_layout(), False, self), ('social.display_attr', rebuild, False), ('email.display_attr', rebuild, False), ('buddylist.show_in_taskbar', lambda val: wx.CallAfter(lambda: setattr(self.Top, 'OnTaskbar', val)), True, self) ]] # link docking preferences link = profile.localprefs.link docker = wx.GetTopLevelParent(self).docker self.unlinkers += [link(*a) for a in [ ('buddylist.dock.autohide', lambda v: docker.SetAutoHide(bool(v)), True, docker), ('buddylist.dock.enabled', lambda v: docker.SetEnabled(bool(v)), True, docker), ('buddylist.dock.revealms', lambda v: setattr(docker, 'RevealDurationMs', try_this(lambda: int(v), 300)), True, docker), ]] self.unlinkers.append(profile.prefs.link('buddylist.dock.slide_velocity', lambda v: wx.CallAfter(docker.SetVelocity,int(v)), obj = docker)) #@UndefinedVariable self.unlinkers.append(Storage(unlink = profile.emailaccounts.add_list_observer (rebuild, rebuild, 'enabled').disconnect)) self.unlinkers.append(Storage(unlink = profile.socialaccounts.add_list_observer(rebuild, rebuild, 'enabled').disconnect)) # don't ever let this control take focus self.Bind(wx.EVT_SET_FOCUS, lambda e:self.blist.SetFocus())
def __repr__(self): return '<%s %s: status=%r, message=%r, idletime=%r>' % (type(self).__name__, try_this(lambda:key(safe_deref(self.buddy)), None), self.status, getattr(safe_deref(self.buddy), 'stripped_msg', ''), self.idle_time)
def icon(self): from gui import skin from util import try_this return try_this(lambda: skin.get('serviceicons.%s' % self.protocol), None)
def __repr__(self): return '<%s %s: status=%r, message=%r, idletime=%r>' % ( type(self).__name__, try_this(lambda: key(safe_deref(self.buddy)), None), self.status, getattr(safe_deref(self.buddy), 'stripped_msg', ''), self.idle_time)