Пример #1
0
def StyleFromPref(prefname):

    try:
        stylepref = pref(prefname)

        if isinstance(stylepref, basestring):
            style = dict(Font=makeFont(stylepref))
        else:
            style = dict(stylepref)
    except Exception:
        print_exc()
        style = {}

    if type(style['Font']) is tuple:
        try:
            font = TupleToFont(style['Font'])
        except Exception:
            print_exc()
            font = try_this(lambda: makeFont('Arial 10'), default_font())
    else:
        font = style['Font']
    fgc = try_this(lambda: wx.Colour(*style['TextColour']),
                   None) or wx.BLACK  #@UndefinedVariable
    bgc = try_this(lambda: wx.Colour(*style['BackgroundColour']),
                   None) or wx.WHITE  #@UndefinedVariable

    return wx.TextAttr(fgc, bgc, font)
Пример #2
0
def load_pref_style(prefname):

    try:
        stylepref = pref(prefname)

        if isinstance(stylepref, basestring):
            style = Storage(Font = makeFont(stylepref))
        else:
            style = Storage(stylepref)
    except Exception:
        print_exc()
        style = {}

    if type(style.Font) is tuple:
        try:
            font = tuple_to_font(style.Font)
        except Exception:
            print_exc()
            font = default_msg_font()
    else:
        font = style.Font
    fgc  = try_this(lambda: wx.Colour(*style.TextColour), None) or wx.BLACK
    bgc  = try_this(lambda: wx.Colour(*style.BackgroundColour), None) or wx.WHITE

    return font, fgc, bgc
Пример #3
0
    def setskin(prefname = None, val = None):
        with p.Frozen():
            variant_sizer.Clear(True)

            if val is None:
                i = try_this(lambda: [s.name for s in skins].index(pref('appearance.skin')), 0)
                j = try_this(lambda: [v.path.namebase for v in skins[i].variants].index(pref('appearance.variant'))+1, 0)
                val = skins[i]

            variants = list(val.variants)

            if prefname is not None:
                mark_pref('appearance.skin',    val.name)
                mark_pref('appearance.variant', ('%s' % variants[0].path) if variants else None)
                wx.CallAfter(skin.reload)

            vchoices = [(None, val.novariant_alias)]
            if variants:
                vchoices += [(v.path.namebase, v.alias) for v in variants]

            choice = Choice('appearance.variant', vchoices, '',
                            callback = lambda *a: wx.CallAfter(skin.reload))(p)

            if prefname is None:
                skin_choice.SetSelection(i)
                choice.SetSelection(j)

            variant_sizer.Add(choice, 1, wx.EXPAND)
            choice.Enable(bool(variants))

            sz.Layout()
Пример #4
0
def StyleFromPref(prefname):

    try:
        stylepref = pref(prefname)

        if isinstance(stylepref, basestring):
            style = dict(Font = makeFont(stylepref))
        else:
            style = dict(stylepref)
    except Exception:
        print_exc()
        style = {}

    if type(style['Font']) is tuple:
        try:
            font = TupleToFont(style['Font'])
        except Exception:
            print_exc()
            font = try_this(lambda: makeFont('Arial 10'), default_font())
    else:
        font = style['Font']
    fgc  = try_this(lambda: wx.Colour(*style['TextColour']), None) or wx.BLACK #@UndefinedVariable
    bgc  = try_this(lambda: wx.Colour(*style['BackgroundColour']), None) or wx.WHITE #@UndefinedVariable

    return wx.TextAttr(fgc, bgc, font)
Пример #5
0
def signin(identity):
    global profile

    if profile is not None:
        try_this(lambda: profile.connection.observers.clear(), None)
        profile = None

    if profile is None:
        profile = DigsbyProfile(identity)
Пример #6
0
    def _notify_since(self, when):
        to_notify = filter(lambda x: x.updated_parsed > when, reversed(self.combined_feed()))
        self_user = self.user_from_id(self.userid)
        to_notify = filter(lambda x: self.user_from_id(x.author_id) is not self_user, to_notify)

        default_icon = gui.skin.get('BuddiesPanel.BuddyIcons.NoIcon', None)


        for thing in to_notify:
            if getattr(thing, 'acct', None) is None:
                thing.acct = weakref.ref(self)
            if getattr(thing, 'icon', None) is not None:
                continue

            user = self.user_from_id(thing.author_id)
            url = getattr(user, 'thumbnailUrl', None)
            thing.icon = imageloader.LazyWebKitImage(url, default_icon)

        log.info_s("myspace notifying: %r", to_notify)
        if to_notify:
            common.fire('myspace.newsfeed',
                        title = _("MySpace Newsfeed"),
                        items = to_notify,
                        conn = self,
                        onclick = lambda item: getattr(item, 'url',
                                                       util.try_this(lambda:getattr(self.user_from_activity(item), 'webUri', None) or
                                                                            getattr(self.user_from_activity(item), 'profileUrl', None),
                                                                     None)),
                        popupid = '%r.myspace' % self,
                        update = 'paged',
                        util = util,
                        badge = gui.skin.get('serviceicons.myspace', None),
                        buttons = self.get_popup_buttons)
Пример #7
0
    def _send_email_ajax(self,to, subject, body, cc, bcc, callback = None):
        if not hasattr(self.HM, 'SendMessage_ec'):
            return callback.error("Sending email with AJAX call is not supported for build %r",
                                  util.try_this(lambda:self.HM.app_info['BUILD'], "unknown"))

        self.HM.SendMessage_ec(
                               to,                 # to
                               self.name,          # from
                               '',                 # cc
                               '',                 # bcc
                               0,                  # priority
                               subject,            # subject
                               body,               # message
                               [],                 # attachments
                               None,               # draftId
                               str(uuid.UUID(int=folderids.drafts)),   # draftFolderId
                               None,               # originalMessageId
                               None,               # rfc822MessageId
                               None,               # rfc822References
                               None,               # rfc822InReplyTo
                               0,                  # sentState
                               True,               # sendByPlainTextFormat
                               [],                 # ignoredWordsFromSpellCheck
                               None,               # hipAnswer
                               'audio',            # hipMode
                               None,               # meetingIcalId
                               callback,
                               )
Пример #8
0
    def OnComposeEmail(self, to='', subject='', body='', cc='', bcc='', callback = None):
        import hooks; hooks.notify('digsby.statistics.email.compose')
        for name in ('to','subject', 'body', 'cc', 'bcc'):
            assert isinstance(vars()[name], basestring), (name, type(vars()[name]), vars()[name])

        if self.mailclient and try_this(lambda: self.mailclient.startswith('file:'), False):
            os.startfile(self.mailclient[5:])

        elif self.mailclient == 'sysdefault':
            kw = {}
            for name in ('subject', 'body', 'cc',  'bcc'):
                if vars()[name]:
                    kw[name] = vars()[name]

            query = UrlQuery('mailto:' + quote(to), **kw)
            log.info('OnComposeEmail is launching query: %s' % query)
            try:
                os.startfile(query)
            except WindowsError:
                # WindowsError: [Error 1155] No application is associated with the specified file for this operation: 'mailto:'
                mailclient_error()
                raise

        elif self.mailclient == '__urls__':
            url = self.custom_compose_url
            if url is not None: launch_browser(url)

        else:
            url = self.compose(to, subject, body, cc, bcc)
            if url:
                launch_browser(url)

        callback.success()
Пример #9
0
 def Tooltip(self):
     c = self.count_string
     if c == 'X':
         return _(u'{account.offline_reason} ({account.name})').format(account=self.acct)
     else:
         return try_this(lambda: ngettext(u'{count} new alert ({account.name})',
                                          u'{count} new alerts ({account.name})').format(count=c, account=self.acct), '')
Пример #10
0
    def OnSelection(self,item):
        """
        Item selected 'event'
        calls the Selection Callback if availible
        then throws a EVT_COMBOBOX to parent
        """
        if self.selection is item:
            return
        else:
            self.selection = item

        if isinstance(item,int):
            item = self.menu.spine.items[item]

        self.display.SetFocus()
        self.display.SelectAll()

        if self.selectioncallback:
            self.selectioncallback(item)
        else:
            self.display.SetValue(item)

        event = wx.CommandEvent(10020, self.GetId())
        event.SetInt(try_this(lambda: self.menu.spine.items.index(item), -1))
        self.Parent.AddPendingEvent(event)
Пример #11
0
def rounded_corners(corner_size=1, rounded_imgs={}):
    if not isinstance(corner_size, int):
        import util
        corner_size = util.try_this(lambda: int(bool(corner_size)), 1)
    else:
        corner_size = max(0, min(corner_size, 3))

    try:
        return rounded_imgs[corner_size]
    except KeyError:
        pass

    imgs = []

    from gui import skin
    rounded_img = Image.open(
        skin.resourcedir() /
        ('corner' + str(corner_size) + '.gif')).convert('L')

    for name, rotation in CORNERS:
        mask = rounded_img.transpose(
            rotation) if rotation is not None else rounded_img
        imgs.append(mask)

    return rounded_imgs.setdefault(corner_size, imgs)
Пример #12
0
    def OnSelection(self, item):
        """
        Item selected 'event'
        calls the Selection Callback if availible
        then throws a EVT_COMBOBOX to parent
        """
        if self.selection is item:
            return
        else:
            self.selection = item

        if isinstance(item, int):
            item = self.menu.spine.items[item]

        self.display.SetFocus()
        self.display.SelectAll()

        if self.selectioncallback:
            self.selectioncallback(item)
        else:
            self.display.SetValue(item)

        event = wx.CommandEvent(10020, self.GetId())
        event.SetInt(try_this(lambda: self.menu.spine.items.index(item), -1))
        self.Parent.AddPendingEvent(event)
Пример #13
0
    def _send_email_ajax(self, to, subject, body, cc, bcc, callback=None):
        if not hasattr(self.HM, 'SendMessage_ec'):
            return callback.error(
                "Sending email with AJAX call is not supported for build %r",
                util.try_this(lambda: self.HM.app_info['BUILD'], "unknown"))

        self.HM.SendMessage_ec(
            to,  # to
            self.name,  # from
            '',  # cc
            '',  # bcc
            0,  # priority
            subject,  # subject
            body,  # message
            [],  # attachments
            None,  # draftId
            str(uuid.UUID(int=folderids.drafts)),  # draftFolderId
            None,  # originalMessageId
            None,  # rfc822MessageId
            None,  # rfc822References
            None,  # rfc822InReplyTo
            0,  # sentState
            True,  # sendByPlainTextFormat
            [],  # ignoredWordsFromSpellCheck
            None,  # hipAnswer
            'audio',  # hipMode
            None,  # meetingIcalId
            callback,
        )
Пример #14
0
    def construct(self, is_new):
        self.construct_common(is_new)
        getattr(self, 'construct_' + self.formtype, getattr(self, 'construct_default'))()

        # after all textboxes have been constructed, bind to their KeyEvents so
        # that we can disable the Save button when necessary

        # Make sure textboxes have values.
        txts = [self.name]

        for textbox in self.get_required_textboxes(all = True):
            textbox.Bind(wx.EVT_TEXT, lambda e: self.check_warnings())

        if self.protocolinfo.get('needs_smtp', False):
            self.Bind(wx.EVT_RADIOBUTTON, lambda e: (e.Skip(), self.check_warnings()))

        # A small arrow for expanding the dialog to show advanced options.
        from gui.chevron import Chevron
        self.expand = Chevron(self, 'Advanced')
        self.expand.Bind(wx.EVT_CHECKBOX, self.on_expand)
        self.expanded = False

        self.AffirmativeId = wx.ID_SAVE
        self.save   = wx.Button(self, wx.ID_SAVE,   _('&Save'))
        self.save.Bind(wx.EVT_BUTTON, self.on_save)
        self.save.SetDefault()
        if is_new or try_this(lambda: self.password.Value, None) == '': self.save.Enable(False)

        self.cancel = wx.Button(self, wx.ID_CANCEL, _('&Cancel'))
        self.cancel.Bind(wx.EVT_BUTTON, self.on_cancel)
Пример #15
0
    def construct(self, is_new):
        self.construct_common(is_new)
        getattr(self, "construct_" + self.formtype, getattr(self, "construct_default"))()

        # after all textboxes have been constructed, bind to their KeyEvents so
        # that we can disable the Save button when necessary

        # Make sure textboxes have values.
        txts = [self.name]

        for textbox in self.get_required_textboxes(all=True):
            textbox.Bind(wx.EVT_TEXT, lambda e: self.check_warnings())

        if self.protocolinfo.get("needs_smtp", False):
            self.Bind(wx.EVT_RADIOBUTTON, lambda e: (e.Skip(), self.check_warnings()))

        # A small arrow for expanding the dialog to show advanced options.
        from gui.chevron import Chevron

        self.expand = Chevron(self, "Advanced")
        self.expand.Bind(wx.EVT_CHECKBOX, self.on_expand)
        self.expanded = False

        self.AffirmativeId = wx.ID_SAVE
        self.save = wx.Button(self, wx.ID_SAVE, _("&Save"))
        self.save.Bind(wx.EVT_BUTTON, self.on_save)
        self.save.SetDefault()
        if is_new or try_this(lambda: self.password.Value, None) == "":
            self.save.Enable(False)

        self.cancel = wx.Button(self, wx.ID_CANCEL, _("&Cancel"))
        self.cancel.Bind(wx.EVT_BUTTON, self.on_cancel)
Пример #16
0
        def unauthorized(e):
            log.info("unauthorized: %r", e)

            if not (
                (getattr(e, 'oauth_problem', None) == 'permission_denied') or
                (getattr(e, 'oauth_problem', None) == 'signature_invalid') or
                (getattr(e, 'code', 0) == 401 and util.try_this(
                    lambda: e.headers['x-opensocial-error'], None) is not None)
                    or
                (getattr(e, 'code', 0) == 401
                 and util.try_this(lambda: "Invalid digital signature" in e.
                                   document.get('statusDescription', ''))) or
                (isinstance(e, Unauthorized))):
                return callback.error(e)

            etxt = None
            if hasattr(e, 'read'):
                etxt = e.read()
            if not etxt:
                etxt = repr(e)
            log.error('Error accessing resource %r: %r', self.endpoint, etxt)

            if not client.allow_authenticate():
                return

            client.authenticate_start()

            client.fetch_request_token(
                error=auth_error,
                success=lambda results:
                (client.request_token_fetched(results),
                 client.authorize_token(
                     error=auth_error,
                     success=lambda results:
                     (client.token_authorized(results),
                      client.fetch_access_token(
                          error=auth_error,
                          success=lambda results:
                          (client.access_token_fetched(results),
                           client.request(url,
                                          method=method,
                                          data=data,
                                          error=callback.error,
                                          success=lambda resp: callback.
                                          success(resp.document),
                                          **kw)))))))
Пример #17
0
    def info(self):
        "Returns a Storage containing the attributes edited by this dialog."

        info = Storage(name=self.name.Value, protocol=self.protocol_name)

        info.protocol, info.name = strip_acct_id(info.protocol, info.name)

        if hasattr(self, "password"):
            info.password_len = len(self.password.Value)
            try:
                info.password = profile.crypt_pw(self.password.Value)
            except UnicodeEncodeError:
                # the database has corrupted the password.
                log.warning("corrupted password")
                info.password = ""
                self.password.Value = ""
                import hub

                hub.get_instance().on_error(
                    "This account's password has been corrupted somehow. Please report it immediately."
                )

        if hasattr(self, "host"):
            info.server = (self.host.Value, int(self.port.Value) if self.port.Value else "")

        if hasattr(self, "remote_alias"):
            info.remote_alias = self.remote_alias.Value

        if hasattr(self, "autologin"):
            info.autologin = bool(self.autologin.Value)

        if hasattr(self, "resource"):
            info.update(
                resource=self.resource.Value,
                priority=try_this(lambda: int(self.priority.Value), DEFAULT_JABBER_PRIORITY),
            )
        #                        ,
        #                        confserver = self.confserver.Value
        if hasattr(self, "dataproxy"):
            info.update(dataproxy=self.dataproxy.Value)

        for d in getattr(self.protocolinfo, "more_details", []):
            attr = d["store"]
            ctrl = getattr(self, attr)
            info[attr] = ctrl.Value

        getattr(self, "info_" + self.formtype, lambda *a: {})(info)

        for info_cb in self.info_callbacks:
            info_cb(info)

        defaults = self.protocolinfo.get("defaults", {})
        for k in defaults:
            if k not in info:
                info[k] = getattr(self.account, k, defaults.get(k))

        return info
Пример #18
0
 def Tooltip(self):
     c = self.count_string
     if c == 'X':
         return _(u'{account.offline_reason} ({account.name})').format(
             account=self.acct)
     else:
         return try_this(
             lambda: ngettext(u'{count} new alert ({account.name})',
                              u'{count} new alerts ({account.name})').
             format(count=c, account=self.acct), '')
Пример #19
0
    def UpdateSkin(self):
        key = self.skinkey
        s = lambda k, default=sentinel: skin.get('%s.%s' % (key, k), default)

        self.SetSashSize(try_this(lambda: int(s('Thickness')), 4))

        self.icon = s('Icon', None)
        self.bg = s('Backgrounds.Normal')
        self.bghover = s('Backgrounds.Hover', lambda: self.normalbg)
        self.bgactive = s('Backgrounds.Active', lambda: self.hoverbg)
Пример #20
0
    def info(self):
        'Returns a Storage containing the attributes edited by this dialog.'

        info = Storage(name = self.name.Value,
                       protocol = self.protocol_name)

        info.protocol, info.name = strip_acct_id(info.protocol, info.name)

        if hasattr(self, 'password'):
            info.password_len = len(self.password.Value)
            try:
                info.password = profile.crypt_pw(self.password.Value)
            except UnicodeEncodeError:
                # the database has corrupted the password.
                log.warning('corrupted password')
                info.password = ''
                self.password.Value = ''
                import hub
                hub.get_instance().on_error('This account\'s password has been corrupted somehow. Please report it immediately.')

        if hasattr(self, 'host'):
            info.server = (self.host.Value, int(self.port.Value) if self.port.Value else '')

        if hasattr(self, 'remote_alias'):
            info.remote_alias = self.remote_alias.Value

        if hasattr(self, 'autologin'):
            info.autologin = bool(self.autologin.Value)

        if hasattr(self, 'resource'):
            info.update(resource = self.resource.Value,
                        priority = try_this(lambda: int(self.priority.Value), DEFAULT_JABBER_PRIORITY))
#                        ,
#                        confserver = self.confserver.Value
        if hasattr(self, 'dataproxy'):
            info.update(dataproxy = self.dataproxy.Value)

        for d in getattr(self.protocolinfo, 'more_details', []):
            attr = d['store']
            ctrl = getattr(self, attr)
            info[attr] = ctrl.Value

        getattr(self, 'info_' + self.formtype, lambda *a: {})(info)

        for info_cb in self.info_callbacks:
            info_cb(info)

        defaults = self.protocolinfo.get('defaults', {})
        for k in defaults:
            if k not in info:
                info[k] = getattr(self.account, k, defaults.get(k))

        return info
Пример #21
0
        def unauthorized(e):
            log.info("unauthorized: %r", e)

            if not ((getattr(e, 'oauth_problem', None) == 'permission_denied') or
                    (getattr(e, 'oauth_problem', None) == 'signature_invalid') or
                    (getattr(e, 'code', 0) == 401 and util.try_this(lambda: e.headers['x-opensocial-error'], None) is not None) or
                    (getattr(e, 'code', 0) == 401 and util.try_this(lambda: "Invalid digital signature" in e.document.get('statusDescription', ''))) or
                    (isinstance(e, Unauthorized))
                    ):
                return callback.error(e)

            etxt = None
            if hasattr(e, 'read'):
                etxt = e.read()
            if not etxt:
                etxt = repr(e)
            log.error('Error accessing resource %r: %r', self.endpoint, etxt)

            if not client.allow_authenticate():
                return

            client.authenticate_start()

            client.fetch_request_token(
                 error = auth_error,
                 success = lambda results: (
            client.request_token_fetched(results),
            client.authorize_token(
                  error = auth_error,
                  success = lambda results: (
            client.token_authorized(results),
            client.fetch_access_token(
                  error = auth_error,
                  success = lambda results: (
            client.access_token_fetched(results),
            client.request(url,
                           method = method, data = data,
                           error = callback.error,
                           success = lambda resp: callback.success(resp.document),
                           **kw)))))))
Пример #22
0
    def setskin(prefname=None, val=None):
        with p.Frozen():
            variant_sizer.Clear(True)

            if val is None:
                i = try_this(
                    lambda: [s.name
                             for s in skins].index(pref('appearance.skin')), 0)
                j = try_this(
                    lambda: [v.path.namebase for v in skins[i].variants].index(
                        pref('appearance.variant')) + 1, 0)
                val = skins[i]

            variants = list(val.variants)

            if prefname is not None:
                mark_pref('appearance.skin', val.name)
                mark_pref('appearance.variant',
                          ('%s' % variants[0].path) if variants else None)
                wx.CallAfter(skin.reload)

            vchoices = [(None, val.novariant_alias)]
            if variants:
                vchoices += [(v.path.namebase, v.alias) for v in variants]

            choice = Choice('appearance.variant',
                            vchoices,
                            '',
                            callback=lambda *a: wx.CallAfter(skin.reload))(p)

            if prefname is None:
                skin_choice.SetSelection(i)
                choice.SetSelection(j)

            variant_sizer.Add(choice, 1, wx.EXPAND)
            choice.Enable(bool(variants))

            sz.Layout()
Пример #23
0
    def add_group(self, name, callback=None):
        if self.groups.values():
            new_position = max(util.try_this(lambda: int(x.Position), 0) for x in self.groups.values()) + 1
        else:
            new_position = 0

        def success(sent, recvd):

            def new_group_listener(g_info):
                if g_info.get('GroupName') == name:
                    callback.success(self.get_group(name))
                    self.api.unbind('got_group', new_group_listener)

            self.api.bind('got_group', new_group_listener)
            self.request_group_list()

        self.api.set_group_details(id=None, name=name.encode('utf8'), flag=0, position=new_position, success=success,
                                   error=callback.error)
Пример #24
0
    def start_client_email(self, email=None):
        log.info('mailclient: %s', self.mailclient)
        import os.path

        if self.mailclient == 'sysdefault':
            launch_sysdefault_email(email)

        elif self.mailclient == '__urls__':
            url = self.custom_inbox_url
            if url is not None: launch_browser(url)

        elif try_this(lambda: self.mailclient.startswith('file:'), False):
            filename = self.mailclient[5:]

            if os.path.exists(filename):
                os.startfile(filename)
            else:
                log.warning('cannot find %s', filename)
Пример #25
0
    def start_client_email(self, email=None):
        log.info('mailclient: %s', self.mailclient)
        import os.path

        if self.mailclient == 'sysdefault':
            launch_sysdefault_email(email)

        elif self.mailclient == '__urls__':
            url = self.custom_inbox_url
            if url is not None: launch_browser(url)

        elif try_this(lambda:self.mailclient.startswith('file:'), False):
            filename = self.mailclient[5:]

            if os.path.exists(filename):
                os.startfile(filename)
            else:
                log.warning('cannot find %s', filename)
Пример #26
0
    def OnComposeEmail(self,
                       to='',
                       subject='',
                       body='',
                       cc='',
                       bcc='',
                       callback=None):
        import hooks
        hooks.notify('digsby.statistics.email.compose')
        for name in ('to', 'subject', 'body', 'cc', 'bcc'):
            assert isinstance(vars()[name],
                              basestring), (name, type(vars()[name]),
                                            vars()[name])

        if self.mailclient and try_this(
                lambda: self.mailclient.startswith('file:'), False):
            os.startfile(self.mailclient[5:])

        elif self.mailclient == 'sysdefault':
            kw = {}
            for name in ('subject', 'body', 'cc', 'bcc'):
                if vars()[name]:
                    kw[name] = vars()[name]

            query = UrlQuery('mailto:' + quote(to), **kw)
            log.info('OnComposeEmail is launching query: %s' % query)
            try:
                os.startfile(query)
            except WindowsError:
                # WindowsError: [Error 1155] No application is associated with the specified file for this operation: 'mailto:'
                mailclient_error()
                raise

        elif self.mailclient == '__urls__':
            url = self.custom_compose_url
            if url is not None: launch_browser(url)

        else:
            url = self.compose(to, subject, body, cc, bcc)
            if url:
                launch_browser(url)

        callback.success()
Пример #27
0
def rounded_corners(corner_size = 1, rounded_imgs = {}):
    if not isinstance(corner_size, int):
        import util
        corner_size = util.try_this(lambda: int(bool(corner_size)), 1)
    else:
        corner_size = max(0, min(corner_size, 3))

    try: return rounded_imgs[corner_size]
    except KeyError: pass

    imgs = []

    from gui import skin
    rounded_img = Image.open(skin.resourcedir() / ('corner' + str(corner_size) + '.gif')).convert('L')

    for name, rotation in CORNERS:
        mask = rounded_img.transpose(rotation) if rotation is not None else rounded_img
        imgs.append(mask)

    return rounded_imgs.setdefault(corner_size, imgs)
Пример #28
0
 def __init__(self, d_or_s='', **k):
     from_string = False
     if isinstance(d_or_s, basestring):
         self._orig = d_or_s
         d = self.parse(d_or_s)
         from_string = True
     else:
         d = d_or_s
     odict.__init__(self, d, **k)
     if from_string:
         for key in ('body', 'msg'):
             if key in self:
                 self[key] = unescape(str(self[key]))
     for key in self:
         if try_this(lambda: '\x1c' in self[key], False) or key == 'body':
             self[key] = msdict(self[key])
         for key in self:
             if isinstance(self[key], basestring):
                 try:
                     self[key] = eval(self[key], {}, {})
                 except Exception:
                     pass
Пример #29
0
    def _notify_since(self, when):
        to_notify = filter(lambda x: x.updated_parsed > when,
                           reversed(self.combined_feed()))
        self_user = self.user_from_id(self.userid)
        to_notify = filter(
            lambda x: self.user_from_id(x.author_id) is not self_user,
            to_notify)

        default_icon = gui.skin.get('BuddiesPanel.BuddyIcons.NoIcon', None)

        for thing in to_notify:
            if getattr(thing, 'acct', None) is None:
                thing.acct = weakref.ref(self)
            if getattr(thing, 'icon', None) is not None:
                continue

            user = self.user_from_id(thing.author_id)
            url = getattr(user, 'thumbnailUrl', None)
            thing.icon = imageloader.LazyWebKitImage(url, default_icon)

        log.info_s("myspace notifying: %r", to_notify)
        if to_notify:
            common.fire('myspace.newsfeed',
                        title=_("MySpace Newsfeed"),
                        items=to_notify,
                        conn=self,
                        onclick=lambda item: getattr(
                            item, 'url',
                            util.try_this(
                                lambda: getattr(self.user_from_activity(
                                    item), 'webUri', None) or getattr(
                                        self.user_from_activity(item),
                                        'profileUrl', None), None)),
                        popupid='%r.myspace' % self,
                        update='paged',
                        util=util,
                        badge=gui.skin.get('serviceicons.myspace', None),
                        buttons=self.get_popup_buttons)
Пример #30
0
    def add_group(self, name, callback=None):
        if self.groups.values():
            new_position = max(
                util.try_this(lambda: int(x.Position), 0)
                for x in self.groups.values()) + 1
        else:
            new_position = 0

        def success(sent, recvd):
            def new_group_listener(g_info):
                if g_info.get('GroupName') == name:
                    callback.success(self.get_group(name))
                    self.api.unbind('got_group', new_group_listener)

            self.api.bind('got_group', new_group_listener)
            self.request_group_list()

        self.api.set_group_details(id=None,
                                   name=name.encode('utf8'),
                                   flag=0,
                                   position=new_position,
                                   success=success,
                                   error=callback.error)
Пример #31
0
    def link_logging(self, src, key, *a, **k):
        n = 'logging'
        if not isinstance(key, basestring) or not key.startswith(n):
            return
        logname = key[len(n):] or None
        if logname is not None:
            logname = logname.strip('.')
        newlevel = try_this(lambda: int(get(src, key)), 0)
        logging.log(100, 'Setting %s to level %d', logname or 'root', newlevel)

        import main
        if not hasattr(main, 'full_loggers'):
            return  # logging system not setup

        # don't bother modifying console handlers if we never setup any
        if not getattr(main, 'logging_to_stdout', False):
            return

        if not logname:
            logger = logging.getLogger('')
            s_handlers = [h for  h in logger.handlers if (h.__class__ is console_handler_class) and h not in main.full_loggers]
            s_handlers[0].setLevel(newlevel)
        else:
            rootlogger = logging.getLogger('')
            root_handlers = [h for  h in rootlogger.handlers if (h.__class__ is not console_handler_class) or h in main.full_loggers]
            handler = self.consolehandlers[newlevel]
            handler.setLevel(newlevel)

            from main import ConsoleFormatter
            formatter = ConsoleFormatter()

            handler.setFormatter(formatter)
            root_handlers.append(handler)
            new_logger = logging.getLogger(logname)
            new_logger.propagate = False
            new_logger.handlers[:] = root_handlers
Пример #32
0
 def idle_after_changed(self, minutes):
     from common import pref
     minutes = try_this(lambda: float(minutes),
               try_this(lambda: float(pref('messaging.idle_after', 10)), 10))
     if pref('messaging.become_idle', True):
         self.idle_timer.reset(minutes * IDLE_UNIT)
Пример #33
0
 def value_transform(self, v):
     import util
     return {'none': None,
             'true': True,
             'false': False}.get(util.try_this(lambda: v.lower(), None), v)
Пример #34
0
def preLoadWindowPos(windowName, uniqueId="", position_only = False, defaultPos = None, defaultSize = None):
    # save based on classname, and any unique identifier that is specified
    section = windowId(windowName, uniqueId)

    if defaultPos is not None:
        doCenter = defaultPos == 'center'
        hasDefPos = not doCenter
    else:
        hasDefPos = False
        doCenter = False


    size = defaultSize if defaultSize is not None else wx.DefaultSize#(450, 400)
    pos  = defaultPos  if hasDefPos else wx.DefaultPosition
    style = 0

    try:
        cfg = local_settings()
        hassection = cfg.has_section(section)
    except Exception:
        print_exc()
        hassection = False

    placement = None
    if wxMSW:
        if hassection:
            import util
            with util.traceguard:
                placement = json.loads(cfg.get(section, 'placement'))

                if position_only:
                    placement_set_size(placement, size)

    if hassection and not position_only:
        try:
            size = Size(cfg.getint(section, "w"), cfg.getint(section, "h"))
        except Exception:
            pass
            #TODO: this isn't expected to work anymore with IM windows, needs to
            #be removed once everything else is moved to use SetPalcement
            #print_exc()

    if doCenter:
        mon = Monitor.GetFromRect(wx.RectPS(wx.Point(0, 0), size)) #@UndefinedVariable
        pos = wx.Point(*mon.ClientArea.CenterPoint(size))

    if hassection:
        try:
            pos = Point(cfg.getint(section, "x"), cfg.getint(section, "y"))
        except Exception:
            pass
            #TODO: this isn't expected to work anymore with IM windows, needs to
            #be removed once everything else is moved to use SetPalcement
            #print_exc()

    import util
    max = util.try_this(lambda: cfg.getboolean(section, "maximized"), False) if hassection else False

    if max:
        style |= wx.MAXIMIZE

    return dict(style = style, size = size, pos = pos), placement
Пример #35
0
 def icon(self):
     from gui import skin
     from util import try_this
     return try_this(lambda: skin.get('serviceicons.%s' % self.protocol),
                     None)
Пример #36
0
def default_msg_font():
    return try_this(lambda: makeFont('Arial 10'), default_font())
Пример #37
0
def StorageToStyle(s):
    font, fgc, bgc = StorageToFont(s)
    fgc = try_this(lambda: wx.Colour(*fgc), None) or wx.BLACK
    bgc = try_this(lambda: wx.Colour(*bgc), None) or wx.WHITE
    return wx.TextAttr(fgc, bgc, font)
Пример #38
0
 def icon(self):
     from gui import skin
     from util import try_this
     return try_this(lambda: skin.get('serviceicons.%s' % self.protocol), None)
Пример #39
0
 def display_name(self):
     return try_this(lambda: getattr(self, pref('social.display_attr')), self.username)
Пример #40
0
 def _get_state(self):
     return try_this(lambda: self.connection.state, StateMixin.Statuses.OFFLINE)
Пример #41
0
 def display_name(self):
     return try_this(lambda: getattr(self, pref('email.display_attr')), self.email_address)
Пример #42
0
 def display_name(self):
     return try_this(lambda: getattr(self, self.prefs['account.display_attr']), self.username)
Пример #43
0
 def display_name(self):
     return try_this(lambda: getattr(self, pref('social.display_attr')),
                     self.username)
Пример #44
0
def textattr_from_storage(s):
    font, fgc, bgc = font_attrs_from_storage(s)
    fgc  = try_this(lambda: wx.Colour(fgc), None) or wx.BLACK
    bgc  = try_this(lambda: wx.Colour(bgc), None) or wx.WHITE
    return wx.TextAttr(fgc, bgc, font)
Пример #45
0
def StorageToStyle(s):
    font, fgc, bgc = StorageToFont(s)
    fgc  = try_this(lambda: wx.Colour(*fgc), None) or wx.BLACK
    bgc  = try_this(lambda: wx.Colour(*bgc), None) or wx.WHITE
    return wx.TextAttr(fgc, bgc, font)
Пример #46
0
 def display_name(self):
     from common import pref
     return try_this(lambda: getattr(self, pref('profile.display_attr')), self.username)
Пример #47
0
 def display_name(self):
     return try_this(lambda: getattr(self, pref('email.display_attr')),
                     self.email_address)