Example #1
0
    def set_hidden_messages(self, n):
        '''
        n can be

         -1: show bubble with no count, and no flashing
          0: show just the digsby head
         >0: flash between digsby head and bubble with count, which is n
        '''

        status = profile.status
        digsby_head = self.status_tray_icon(status)

        if pref(UNREADPREF + 'flash_only_count', False):
            from gui import skin
            message_icon = skin.get('AppDefaults.TaskbarIcon')
        else:
            message_icon = None

        if n == -1:
            icons = [generate_hidden_message_icon(None)]
        elif n == 0:
            icons = [digsby_head]
        else:
            count = n if pref(UNREADPREF + 'show_count', True) else None
            unread_icon = generate_hidden_message_icon(count, message_icon)
            icons = [digsby_head, unread_icon]

        intervalms = pref(UNREADPREF + 'flash_interval_ms', default=1000)

        self.icons = [to_icon(i) for i in icons]
        self.delays = [intervalms] * len(self.icons)
        self.UpdateAnimation(status_tooltip(status))
Example #2
0
    def _rebuild_panels(self):
        trayaccts = []
        if pref('buddylist.show_email_as', 'panel') in ('systray', 'both'):
            trayaccts += [a for a in profile.emailaccounts]
        if pref('buddylist.show_social_as', 'panel') in ('systray', 'both'):
            trayaccts += [a for a in profile.socialaccounts]

        with self.Frozen():
            if trayaccts:
                shown = [a for (a, icon) in self.tray_icons]
                enabled = [a for a in trayaccts if a.enabled]
                icons = dict(self.tray_icons)
                e, s = set(enabled), set(shown)

                # remove tray icons no longer needed
                do(icons.pop(acct).Destroy() for acct in s - e)

                # add new ones, indexed by their positions in the accounts list
                for acct in sorted(e - s,
                                   key=lambda a: enabled.index(a),
                                   reverse=True):
                    try:
                        icons[acct] = AccountTrayIcon.create(
                            acct, self.infobox)
                    except Exception:
                        print_exc()

                self.tray_icons = icons.items()
            else:
                # destroy all tray icons
                do(icon.Destroy() for acct, icon in self.tray_icons)
                self.tray_icons = {}

            wx.CallAfter(self.gui_layout)
Example #3
0
    def set_hidden_messages(self, n):
        '''
        n can be

         -1: show bubble with no count, and no flashing
          0: show just the digsby head
         >0: flash between digsby head and bubble with count, which is n
        '''

        status = profile.status
        digsby_head = self.status_tray_icon(status)

        if pref(UNREADPREF + 'flash_only_count', False):
            from gui import skin
            message_icon = skin.get('AppDefaults.TaskbarIcon')
        else:
            message_icon = None

        if n == -1:
            icons = [generate_hidden_message_icon(None)]
        elif n == 0:
            icons = [digsby_head]
        else:
            count = n if pref(UNREADPREF + 'show_count', True) else None
            unread_icon = generate_hidden_message_icon(count, message_icon)
            icons = [digsby_head, unread_icon]

        intervalms = pref(UNREADPREF + 'flash_interval_ms', default=1000)

        self.icons = [to_icon(i) for i in icons]
        self.delays = [intervalms] * len(self.icons)
        self.UpdateAnimation(status_tooltip(status))
Example #4
0
    def _rebuild_panels(self):
        trayaccts = []
        if pref('buddylist.show_email_as', 'panel') in ('systray', 'both'):
            trayaccts += [a for a in profile.emailaccounts]
        if pref('buddylist.show_social_as', 'panel') in ('systray', 'both'):
            trayaccts += [a for a in profile.socialaccounts]

        with self.Frozen():
            if trayaccts:
                shown   = [a for (a, icon) in self.tray_icons]
                enabled = [a for a in trayaccts if a.enabled]
                icons = dict(self.tray_icons)
                e, s = set(enabled), set(shown)

                # remove tray icons no longer needed
                do(icons.pop(acct).Destroy() for acct in s - e)

                # add new ones, indexed by their positions in the accounts list
                for acct in sorted(e - s, key = lambda a: enabled.index(a), reverse = True):
                    try:
                        icons[acct] = AccountTrayIcon.create(acct, self.infobox)
                    except Exception:
                        print_exc()

                self.tray_icons = icons.items()
            else:
                # destroy all tray icons
                do(icon.Destroy() for acct, icon in self.tray_icons)
                self.tray_icons = {}

            wx.CallAfter(self.gui_layout)
Example #5
0
    def on_error(self, task=None):
        '''
        Called when an error occurs. task is a callable that can be used to make another attempt
        at whatever caused the error (if error_count is less than max_error).
        '''
        self.error_count += 1

        log.error('%r\'s error count is now: %d',self, self.error_count)
        log.error('on_error called from %s', get_func_name(2))

        if self.error_count < pref('email.err_max_tolerance', self.error_max):
            if task is None:
                task = self.update_now
            log.error('error count is under, calling %r now', task)

            if not callable(task):
                # If it was an exception assume that update_now was called. (the account type
                # probably just hasn't been fixed yet
                task = self.update_now
            util.call_later(pref('email.err_retry_time', type=int, default=2), task)
        else:
            log.error('assuming the connection has died')
            self.set_offline(self.Reasons.CONN_FAIL)
            self.error_count = 0

        del self.emails[:]
Example #6
0
def get_cpu_percent(chassis_percent=None):
    #if the chassis recommended % is less than the default, limit to that.
    #^ will be true for laptops.  If, for example, we switch desktops to be limited to 80%, but the default is 75, they will default to 75.
    #however, anything less than 75% will be limited to that level.
    if chassis_percent is None:
        chassis_percent = Driver.chassis_desired_cpuUsage()
    import common
    try:
        return int(common.profile.localprefs['research.cpu_percent'])
    except (KeyError, AttributeError) as _e:
        chassis_percent = float(chassis_percent)
        chassis_percent *= 100
        try:
            if chassis_percent < common.profile.defaultprefs.get(
                    'research.cpu_percent', chassis_percent):
                return min(chassis_percent,
                           common.pref('research.cpu_percent',
                                       chassis_percent,
                                       type=float))  #default for this chasis
            else:
                return common.pref('research.cpu_percent',
                                   chassis_percent,
                                   type=float)
        except AttributeError as _e2:
            return common.pref('research.cpu_percent',
                               chassis_percent,
                               type=float)
Example #7
0
    def OnMouseEnter(self, event):
        """
            When mouse enters the tab captures it and sets focus to true
            if another tab doesn't have capture and the mouse is within the
            cliptangle if there is one
        """
        cliptangle = RectS(self.Size)
        sy = self.Rect.y
        sw, sh = cliptangle.Size
        ph = self.Parent.Size.height-16
        if sy + sh > ph and pref('tabs.side_tabs', False):
            cliptangle = Rect(0, 0, sw, ph - sy)

        if cliptangle.Contains(event.Position):
            #TODO tactiveover conditioning
            if not self.HasCapture():
                self.CaptureMouse()
            if not event.LeftIsDown():
                self.focus=True
                self.state=2 if not self.active else 3

                if pref('tabs.style',2) == 2:
                    self.closebutton.Show(True)

                self.Refresh(False)
Example #8
0
    def OnMouseLeave(self, event=None):
        """
            Unfocus tab and if mouse was dragged out starts dragging tabs
        """
        #if draging mouse out of tab and not from button
        cliptangle = RectS(self.Size)
        sy = self.Rect.y
        sw, sh = self.Size
        ph = self.Parent.Size.height-16
        if sy + sh > ph and pref('tabs.side_tabs', False):
            cliptangle = Rect(0, 0, sw, ph-sy)

        # Make sure the mouse isn't just over the close button
        if (not hasattr(self, 'closebutton') or not event or not self.closebutton.Rect.Contains(event.Position)) or not cliptangle.Contains(event.Position):

            self.ReleaseAllCapture()
            # if the left button was down and mouse draged out starts drag mode
            if not self.Parent.dragorigin and event and self.focus and event.LeftIsDown() and (not self.closebutton or not self.closebutton.hovered):
                # go into drag mode by notifying drag
                wx.CallAfter(self.Parent.OnDragStart, self)

            # if mouse out but not dragging, unfocus tab
            elif self.focus:
                self.focus=False

                self.state=1 if self._active else 0

                if pref('tabs.style', 2) == 2:
                    self.closebutton.Show(False)

        self.mark = None

        self.Refresh(False)
Example #9
0
    def establish_out_dc(self, message='<HTML>', extratlvs=[]):
        # Pull IP and port from preferences.
        info('message = %r, extratlvs = %r', message, extratlvs)
        local_ip      = pref('oscar.peer.local_ip', '')
        if not local_ip:
            local_ip = ''
        incoming_port = pref('oscar.peer.incoming_port', 0)
        info('local_ip = %r, incoming_port = %r', local_ip, incoming_port)

        # Are we proxying by default?
        proxy = pref('oscar.peer.always_proxy', None)
        if proxy:
            default_proxy = 'ars.oscar.aol.com'
            if self.protocol.icq:
                default_proxy = 'ars.icq.com'
            proxy = pref('oscar.peer.proxy_server', default_proxy)
        info('proxy = %r', proxy)
        # send first outgoing ch2 rendezvous request message
        self.newsocket().tryaccept((local_ip, incoming_port),
                                   self.incoming_conn,
                                   lambda: info('failed direct connection'),
                                   timeout = 0)

        ip = myip()
        __, port = self.socket.getsockname()

        info('sending channel 2 request asking the receiver to connect to %s:%d', ip_from_bytes(ip), port)
        self.send_ch2request(1, port, ip, proxy=proxy, message=message,
                             extratlvs=extratlvs)
Example #10
0
    def on_call_fire(self, opts, id=None, buttons=None, onclick=None):
        from common import fire, pref
        from gui import skin

        # stringify keys, so that they can be keywords.
        # also turn dicts into storages
        opts = to_storage(dict((str(k), v)
                    for k, v in opts.iteritems()))

        if pref('twitter.popups.user_icons', default=True):
            from gui.browser.webkit.imageloader import LazyWebKitImage
            twitter_icon = skin.get('serviceicons.twitter', None)
            for tweet in opts.tweets:
                tweet.icon = LazyWebKitImage(tweet.user.profile_image_url, twitter_icon)

        def buttons_cb(item):
            if hasattr(item.tweet, 'sender_id'):
                return self.direct_buttons
            else:
                return self.tweet_buttons

        opts.update(onclick=onclick or self.on_popup_click,
                    popupid='twitter20_' + self.username + str(opts.get('popupid_postfix', '')),
                    buttons=buttons or buttons_cb,
                    max_lines=10)

        if pref('twitter.popups.mark_as_read', default=True):
            opts.update(mark_as_read=self.mark_as_read)

        opts.update(badge=skin.get('serviceicons.twitter', None))

        fire(**opts)
Example #11
0
    def _got_friend_activities(self, f_acts, from_cache = False):
        if f_acts is None:
            return

        if not from_cache:
            activities = []

            entries = getattr(f_acts, 'entry', [])
            for entry in entries:
                activity = objects.Activity()
                try:
                    activity.populate(entry, objects.InputType.XML)
                except Exception:
                    log.error('Error processing this activity: %r', etree.tostring(entry))
                    raise

                if activity.title == (activity.author_name + ' '):
                    continue

                self.fix_title(activity)
                activities.append(activity)

            log.info("got %r activities", len(activities))
            activities = util.removedupes(activities + self.activities, key = lambda x: x.id)
            self._cache('friend_activities', activities[:common.pref('myspace.newsfeed.maxlength', type = int, default = 200)])
        else:
            activities = f_acts

        if self.activities != activities:
            log.info('Got new activities')
            self.activities = activities[:common.pref('myspace.max_activities', type = int, default = 200)]
            self._feed_invalidated()
Example #12
0
    def connect_stream(self):
        try:  #protection against None stream
            self.hash = self.j.s5bserver.conn_id(self.sid, self.j.stream.me,
                                                 self.jid)
        except AttributeError:
            self.event("stream_connect_failed")
            return
        self.j.s5bserver.add_hash(self.hash)

        i = Iq(to_jid=self.jid, stanza_type='set')
        b = ByteStreams(sid=self.sid)
        if pref('jabber.use_direct_ft'):
            if not pref('jabber.use_faulty_localhost_ips'):
                [
                    b.add_host(self.j.stream.me, h[0], h[1])
                    for h in self.j.s5bserver.hosts
                ]
            else:
                [
                    b.add_host(self.j.stream.me, h[0].replace("192", "129"),
                               h[1]) for h in self.j.s5bserver.hosts
                ]
        if pref('jabber.use_proxy_ft'):
            b.hosts.extend(
                set(h for hosts in self.j.known_s5b_proxies.values()
                    for h in hosts))
            if pref('jabber.use_jabber_org_proxy', True):
                b.add_host("proxy.jabber.org", "208.245.212.98", 7777)
        b.as_xml(i.get_node())

        self.j.send_cb(i,
                       success=self.handle_ready,
                       error=self.handle_error,
                       timeout=self.timed_out)
Example #13
0
    def on_call_fire(self, opts, id=None, buttons=None, onclick=None):
        from common import fire, pref
        from gui import skin

        # stringify keys, so that they can be keywords.
        # also turn dicts into storages
        opts = to_storage(dict((str(k), v) for k, v in opts.iteritems()))

        if pref('twitter.popups.user_icons', default=True):
            from gui.browser.webkit.imageloader import LazyWebKitImage
            twitter_icon = skin.get('serviceicons.twitter', None)
            for tweet in opts.tweets:
                tweet.icon = LazyWebKitImage(tweet.user.profile_image_url,
                                             twitter_icon)

        def buttons_cb(item):
            if hasattr(item.tweet, 'sender_id'):
                return self.direct_buttons
            else:
                return self.tweet_buttons

        opts.update(onclick=onclick or self.on_popup_click,
                    popupid='twitter20_' + self.username +
                    str(opts.get('popupid_postfix', '')),
                    buttons=buttons or buttons_cb,
                    max_lines=10)

        if pref('twitter.popups.mark_as_read', default=True):
            opts.update(mark_as_read=self.mark_as_read)

        opts.update(badge=skin.get('serviceicons.twitter', None))

        fire(**opts)
Example #14
0
    def on_error(self, task=None):
        '''
        Called when an error occurs. task is a callable that can be used to make another attempt
        at whatever caused the error (if error_count is less than max_error).
        '''
        self.error_count += 1

        log.error('%r\'s error count is now: %d', self, self.error_count)
        log.error('on_error called from %s', get_func_name(2))

        if self.error_count < pref('email.err_max_tolerance', self.error_max):
            if task is None:
                task = self.update_now
            log.error('error count is under, calling %r now', task)

            if not callable(task):
                # If it was an exception assume that update_now was called. (the account type
                # probably just hasn't been fixed yet
                task = self.update_now
            util.call_later(pref('email.err_retry_time', type=int, default=2),
                            task)
        else:
            log.error('assuming the connection has died')
            self.set_offline(self.Reasons.CONN_FAIL)
            self.error_count = 0

        del self.emails[:]
Example #15
0
    def CreateEngine(self, lang_override=None):
        '''
            Create an Aspell engine from the values in prefs. Optional lang_override allows for creating an engine in a different
            language.

            http://aspell.net/man-html/The-Options.html

            TODO: take lots of kwargs and use them to override the options going into the Aspell engine

            Returns the new Aspell object if it was created.
            Returns None if the requested language was not found.

            Raises all unknown errors.
        '''

        if (not self._pref('enabled')) or \
                pref('messaging.spellcheck.engineoptions.lang') not in self.dict_info:
            return NullSpellEngine()

        #Time to build the args

        #first set of args comes from the prefs
        spellprefs = 'lang encoding keyboard'.split()
        parameters = dict(
            (str(key), str(pref('messaging.spellcheck.engineoptions.' + key)))
            for key in spellprefs)

        #so check is fast
        parameters['sug-mode'] = 'ultra'

        if lang_override is not None:
            parameters['lang'] = lang_override

        lang = parameters['lang']

        #set the directories
        local_dir = LocalAspellDataDir()
        parameters['local-data-dir'] = local_dir.encode('filesys')
        parameters['add-word-list-path'] = local_dir.encode('filesys')

        home_dir = local_dir / profile.username
        if not home_dir.isdir():
            home_dir.makedirs()
        parameters['home-dir'] = home_dir.encode('filesys')

        if not lang.startswith('en'):
            parameters['dict-dir'] = local_dir.encode('filesys')

        #If the digsby dict for this language doesn't exist, make it, mostly just for english the first time you run it
        #other languages should lready have it at this point
        digsby_dict_location = local_dir / ('digsby-%s.rws' % lang)
        if not digsby_dict_location.isfile():
            try:
                MakeDigsbyDict(lang, local_dir)
            except CalledProcessError, e:
                log.error(
                    "failed to create Digsby Dictionary in '%s' at '%s', probable cause: dict not yet downloaded, exception was '%s'",
                    lang, local_dir, e)
                return None
Example #16
0
    def CreateEngine(self, lang_override=None):
        """
            Create an Aspell engine from the values in prefs. Optional lang_override allows for creating an engine in a different
            language.

            http://aspell.net/man-html/The-Options.html

            TODO: take lots of kwargs and use them to override the options going into the Aspell engine

            Returns the new Aspell object if it was created.
            Returns None if the requested language was not found.

            Raises all unknown errors.
        """

        if (not self._pref("enabled")) or pref("messaging.spellcheck.engineoptions.lang") not in self.dict_info:
            return NullSpellEngine()

        # Time to build the args

        # first set of args comes from the prefs
        spellprefs = "lang encoding keyboard".split()
        parameters = dict((str(key), str(pref("messaging.spellcheck.engineoptions." + key))) for key in spellprefs)

        # so check is fast
        parameters["sug-mode"] = "ultra"

        if lang_override is not None:
            parameters["lang"] = lang_override

        lang = parameters["lang"]

        # set the directories
        local_dir = LocalAspellDataDir()
        parameters["local-data-dir"] = local_dir.encode("filesys")
        parameters["add-word-list-path"] = local_dir.encode("filesys")

        home_dir = local_dir / profile.username
        if not home_dir.isdir():
            home_dir.makedirs()
        parameters["home-dir"] = home_dir.encode("filesys")

        if not lang.startswith("en"):
            parameters["dict-dir"] = local_dir.encode("filesys")

        # If the digsby dict for this language doesn't exist, make it, mostly just for english the first time you run it
        # other languages should lready have it at this point
        digsby_dict_location = local_dir / ("digsby-%s.rws" % lang)
        if not digsby_dict_location.isfile():
            try:
                MakeDigsbyDict(lang, local_dir)
            except CalledProcessError, e:
                log.error(
                    "failed to create Digsby Dictionary in '%s' at '%s', probable cause: dict not yet downloaded, exception was '%s'",
                    lang,
                    local_dir,
                    e,
                )
                return None
Example #17
0
    def Calcumalate(self):
        'Tab layout calculations, sets cursor positions for the label, the icon, and the button.'

        #Create a DC for use as calculation reference
        dc = ClientDC(self)
        dc.Font=self.font[self.mode]

        #curent Horizantal placement position
        xpad     = self.padding[self.mode].x
        xcurser  = xpad + self.margins[self.mode].left
        ypad     = self.padding[self.mode].y
        flip     = pref('tabs.flip', False)
        style    = pref('tabs.style', 2)
        icon     = self.Icon
        iconsize = self.iconsize[self.mode]

        #determine tab height

        label1 = self.label1
        if isinstance(label1, str):
            label1 = label1.decode('fuzzy utf8')

        txtwh = dc.GetTextExtent(label1)[0]
        ycurser = self.txtht = dc.Font.Height#sum([txtexts[1],txtexts[2],txtexts[3]])
        if (icon or style) and ycurser < iconsize:
            ycurser=iconsize
        ycurser += 2 * ypad + self.margins[self.mode].y


        #Icon and button placement if on the left
        if not flip: self.iconcurser=Point(xcurser, (ycurser-self.margins[self.mode].y)/2+self.margins[self.mode].top-iconsize/2)
        #icon and
        #else: self.iconcurser = 0
        if (style == 2 and not flip) or (style==1 and flip):
            self.closebutton.Size = Size(iconsize,iconsize)
            self.buttoncurser=self.iconcurser or Point(xcurser, (ycurser-self.margins[self.mode].y)/2+self.margins[self.mode].top-iconsize/2)

        if (icon and not flip) or (style==2 and not flip) or (style==1 and flip):
            xcurser +=iconsize + xpad

        #Label placement
        self.label1curser=Point(xcurser, (ycurser-self.margins[self.mode].y)/2+self.margins[self.mode].top-self.txtht/2)
        xcurser += txtwh + xpad

        #adding space for right hand elements to be placed during painting
        if (icon and flip) or (style==1 and not flip) or (style==2 and flip): xcurser+=iconsize + xpad
        xcurser+=self.margins[self.mode].right
        #setting tabs to just fit contents

        maxwidth = self.maxtabwidth
        if maxwidth and maxwidth < xcurser: xcurser=maxwidth
        self.gensize = (xcurser, ycurser)
        self.SetMinSize(self.gensize)
        #self.Parent.Generate()

        #print 'hey look, the close button is shown is a',(style==1),'statement'
        self.closebutton.Show(style==1 or (style==2 and self.Rect.Contains(self.Parent.ScreenToClient(GetMousePosition()))))
Example #18
0
    def resort(self, mock = False):
        assert on_thread('sorter').now

        rootgroups = [display_copy(g) for g in self.rootgroups if isinstance(g, GroupTypes)]
        self.personalities = self.track_personalities(rootgroups)

        metacontacts = self.safe_metacontacts(rootgroups)

        # Always collect metacontacts, but exit early here if sorting is paused.
        if self.sorting_paused:# or not profile.prefs_loaded:
            return

        metrics.event('Buddylist Sort')

        self._setup_blist_sorter()

        # invalidate all sorter knowledge of contacts.
        # results in more CPU usage, but until we put metacontact combining into the sorter
        # this might be necessary.
        self.new_sorter.removeAllContacts()

        newroots = rootgroups[:] + [metacontacts]
        for i, root in enumerate(newroots):
            root.name = "Root" + str(i)
            root._root = True
        root = DGroup('none', [], [], newroots)
        if mock: self.mock_root = make_mocklist(root)
        self.new_sorter.set_root(root)

        view = get_view_from_sorter(self.new_sorter)

        if getattr(self, '_search_by', ''):
            if len(view) > 0:
                contacts_group = view[0]

                # don't allow renaming, etc of the search "Contacts" group
                contacts_group._disallow_actions = True
                num_contacts = len(contacts_group)
            else:
                num_contacts = -1

            self._search_results = self._search_results[1], num_contacts
        else:
            if pref('buddylist.hide_offline_dependant', False, bool):
                hide_offline_groups = not pref('buddylist.show_offline') and pref('buddylist.hide_offline_groups')
            else:
                hide_offline_groups = pref('buddylist.hide_offline_groups')
            if hide_offline_groups:
                view[:] = filter((lambda g: not offline_nonempty_group_re.match(g.display_string)), view)

        for g in view: remove_duplicate_contacts(g)

        self.add_search_entries(view)

        hooks.notify('buddylist.sorted', view)

        return view
Example #19
0
    def UpdateSkin(self):
        key = self.skinkey
        s = lambda k, default = sentinel,mode=0: skin.get('%s%s.%s' % ('side'*mode,key, k), default)

        self.mode = pref('tabs.side_tabs',False)

        self.maxtabwidth = s('maxwidth',pref('tabs.max_width',100))#TODO: Completly remove pref?

        padd = s('padding', lambda: Point(0, 0))
        marg = s('margins', lambda: Margins([0,0,0,0]))
        icsz = s('iconsize', 16)
        font = s('font', lambda: default_font())
        spad = s('padding', padd, 1)
        smar = s('margins', marg, 1)
        sico = s('iconsize', icsz, 1)
        sfnt = s('font', font, 1)

        self.padding = (padd,spad)
        self.margins = (marg,smar)
        self.iconsize = (icsz,sico)
        self.font = (font,sfnt)

        states = self.states
        states[0][0] = s('backgrounds.normal')
        states[0][1] = s('backgrounds.active')
        states[0][2] = s('backgrounds.hover',       states[0][0])
        states[0][3] = s('backgrounds.activehover', states[0][2])
        states[0][4] = s('backgrounds.notify',      states[0][0])

        states[1][0] = s('backgrounds.normal',      states[0][0],1)
        states[1][1] = s('backgrounds.active',      states[0][1],1)
        states[1][2] = s('backgrounds.hover',       states[0][2],1)
        states[1][3] = s('backgrounds.activehover', states[0][3],1)
        states[1][4] = s('backgrounds.notify',      states[0][4],1)

        fc = self.fontcolors
        fc[0][0] = s('fontcolors.normal',      BLACK)
        fc[0][1] = s('fontcolors.active',      BLACK)
        fc[0][2] = s('fontcolors.hover',       fc[0][0])
        fc[0][3] = s('fontcolors.activehover', fc[0][2])
        fc[0][4] = s('fontcolors.notify',      fc[0][0])

        fc[1][0] = s('fontcolors.normal',      fc[0][0],1)
        fc[1][1] = s('fontcolors.active',      fc[0][1],1)
        fc[1][2] = s('fontcolors.hover',       fc[1][0],1)
        fc[1][3] = s('fontcolors.activehover', fc[1][2],1)
        fc[1][4] = s('fontcolors.notify',      fc[1][0],1)

        if pref('tabs.style', 2) and not hasattr(self, 'closebutton'):
            self.GenCloseButton()

        if hasattr(self, 'closebutton'):
            self.closebutton.SetSkinKey(self.Parent.closebuttonskin)
            self.closebutton.SetIcon(self.Parent.closeicon)

        self.Calcumalate()
        self.Refresh(False)
Example #20
0
def reload():
    'Reloads the active skin.'

    t = time.clock()
    from common import pref
    global _css_fonts
    _css_fonts = None
    set_active(pref('appearance.skin'), pref('appearance.variant'), True)
    log.info('skin reloaded in %ss', (time.clock() - t))
Example #21
0
def tag_status(message, protocol, status=None):
    if pref('digsby.status.promote_tag.enabled', default=True) and \
       (pref('digsby.status.promote_tag.upgrade_response', default=None) is not None):
        if protocol == 'msim':
            protocol = 'myspaceim'
        if not message and status:
            message = status
        return message + " - I use " + url_append_for_protocol(protocol)
    else:
        return message
Example #22
0
 def allowed(self):
     'notifications.enable_%s'
     cname = type(self).__name__.lower()
     try:
         away = profile.status.away
     except AttributeError:
         return True
     else:
         return bool(pref('notifications.enable_%s' % cname, True) and
                 not (away and pref('messaging.when_away.disable_%s' % cname, False)))
Example #23
0
def tag_status(message, protocol, status=None):
    if pref('digsby.status.promote_tag.enabled', default=True) and \
       (pref('digsby.status.promote_tag.upgrade_response', default=None) is not None):
        if protocol == 'msim':
            protocol = 'myspaceim'
        if not message and status:
            message = status
        return message + " - I use " + url_append_for_protocol(protocol)
    else:
        return message
Example #24
0
    def revar(name=None, first=False):
        from common import pref
        if name is None:
            name = pref(PFX + 'theme')

        themes = get_themes()
        found = None
        for theme in themes:
            if theme.theme_name == name:
                found = theme

        if found is None:
            found = themes[0] if themes else None

        if found is not None:
            vars = found.variants
            if vars:
                vchoices = [((v, v) if v is not None else
                             (None, found.novariant_name)) for v in vars]
            else:
                vchoices = [(None, found.novariant_name)]
        else:
            vchoices = []
            vars = []

        p.Freeze()
        vsizer.Clear(True)

        if not first:
            mark_pref(PFX + 'variant', found.variant or '')
        choice = Choice(PFX + 'variant', vchoices, '')(p)

        vsizer.Add(choice, 1, EXPAND)
        if not vars:
            #choice.SetSelection(vars.index(found.variant))
            choice.Enable(False)

        if found is not None:
            allow_colors = found.allow_text_colors if found is not None else True
            allow_header = bool(found.header)
        else:
            allow_colors = True
            allow_header = True

        # "Show Message Colors" checkbox is disabled and unchecked if the theme does not
        # support colors.
        colors_checkbox.Enable(allow_colors)
        colors_checkbox.SetValue(allow_colors
                                 and pref(PFX + 'show_message_colors'))

        header_check.Enable(allow_header)
        header_check.SetValue(allow_header and pref(PFX + 'show_header'))

        sz.Layout()
        p.Thaw()
Example #25
0
 def stop_notify(win=win):
     if win:
         try:
             win.Unnotify()
         except wx.PyDeadObjectError:
             pass
         else:
             if not win.Top.AnyNotified and pref('conversation_window.notify_flash'):
                 win.Top.StopFlashing()
     if hidden and pref('messaging.popups.close_dismisses_hidden', False):
         _remove_hidden_message(bud, msg)
Example #26
0
 def get_css(self, script):
     from common import pref
     skin_tuple = getattr(self, 'skin_tuple', None)
     new_skin_tuple = pref('appearance.skin'), pref('appearance.variant')
     if skin_tuple != new_skin_tuple:
         self.skin_tuple = new_skin_tuple
         import gui
         print 'new css'
         gen_css = gui.skin.get_css()
         script = ('''$('#gen_css').html(%s);''' % simplejson.dumps(gen_css)) + script
     return script
Example #27
0
def get_research_enabled():
    import wx
    from common import pref
    had_prefs = wx.GetApp().local_settings_exist_at_startup
    if had_prefs:
        value = pref('research.enabled', default=True)
    else:
        value = pref('research.last_known_local', default=False)
    _set_research_pref(value)

    return value
Example #28
0
def get_research_enabled():
    import wx
    from common import pref
    had_prefs = wx.GetApp().local_settings_exist_at_startup
    if had_prefs:
        value = pref('research.enabled', default = True)
    else:
        value = pref('research.last_known_local', default = False)
    _set_research_pref(value)

    return value
Example #29
0
def status_factory():
    '''
    Yes, a factory.
    '''
    import common
    if common.pref('social.use_global_status', default=False, type=bool):
        return

    start_status = pref(PROMOTE_STATUS_PREF, 'available')
    if start_status == 'idle':
        start_status = 'available'
    return PromoteStatus(status=start_status)
Example #30
0
    def message(self, messageobj):
        if not self.inited:
            self.inited = True
            theme, variant = pref('appearance.conversations.theme'), pref('appearance.conversations.variant')
            buddy = messageobj.buddy

            # initialize the message area, not showing history
            self.message_area.init_content(get_theme_safe(theme, variant),
                                           buddy.name, buddy, show_history = False)
                                           #prevent_align_to_bottom=True) # disable until all skins look correct with this option

        self.message_area.format_message(messageobj.type, messageobj)
Example #31
0
 def allowed(self):
     'notifications.enable_%s'
     cname = type(self).__name__.lower()
     try:
         away = profile.status.away
     except AttributeError:
         return True
     else:
         return bool(
             pref('notifications.enable_%s' % cname, True)
             and not (away and pref(
                 'messaging.when_away.disable_%s' % cname, False)))
Example #32
0
def status_factory():
    '''
    Yes, a factory.
    '''
    import common
    if common.pref('social.use_global_status', default = False, type = bool):
        return

    start_status = pref(PROMOTE_STATUS_PREF, 'available')
    if start_status == 'idle':
        start_status = 'available'
    return PromoteStatus(status = start_status)
Example #33
0
    def show_history(self, buddy):
        num_lines = max(0, pref('conversation_window.num_lines', 5, int))

        if num_lines > 0:
            logsource = buddy
            if pref('conversation_window.merge_metacontact_history', False):
                from common import profile
                metacontact = profile.metacontacts.forbuddy(buddy)
                if metacontact: logsource = list(metacontact).pop()

            msgobjs   = reversed(list(takemany(num_lines, logsource.history)))
            self.replay_messages(msgobjs, buddy)
Example #34
0
    def on_view_show(_m):
        sortstatus = pref('buddylist.sortby').startswith('*status')

        showoffline = pref('buddylist.show_offline')
        hidegroups = pref('buddylist.hide_offline_groups')
        groupoff =  pref('buddylist.group_offline')

        groupoffline.Enable(not sortstatus and showoffline)
        groupoffline.Check(groupoff and (not sortstatus and showoffline))

        hideoffline.Enable(not sortstatus)
        hideoffline.Check((sortstatus and not showoffline)
                          or (not sortstatus and hidegroups))
Example #35
0
    def on_view_show(_m):
        sortstatus = pref('buddylist.sortby').startswith('*status')

        showoffline = pref('buddylist.show_offline')
        hidegroups = pref('buddylist.hide_offline_groups')
        groupoff = pref('buddylist.group_offline')

        groupoffline.Enable(not sortstatus and showoffline)
        groupoffline.Check(groupoff and (not sortstatus and showoffline))

        hideoffline.Enable(not sortstatus)
        hideoffline.Check((sortstatus and not showoffline)
                          or (not sortstatus and hidegroups))
Example #36
0
    def revar(name = None, first = False):
        from common import pref
        if name is None:
            name = pref(PFX + 'theme')

        themes = get_themes()
        found = None
        for theme in themes:
            if theme.theme_name == name:
                found = theme

        if found is None:
            found = themes[0] if themes else None

        if found is not None:
            vars = found.variants
            if vars: vchoices = [((v, v) if v is not None else (None, found.novariant_name)) for v in vars]
            else:    vchoices = [(None, found.novariant_name)]
        else:
            vchoices = []
            vars = []

        p.Freeze()
        vsizer.Clear(True)

        if not first:
            mark_pref(PFX + 'variant', found.variant or '')
        choice = Choice(PFX + 'variant',  vchoices, '')(p)

        vsizer.Add(choice, 1, EXPAND)
        if not vars:
            #choice.SetSelection(vars.index(found.variant))
            choice.Enable(False)

        if found is not None:
            allow_colors = found.allow_text_colors if found is not None else True
            allow_header = bool(found.header)
        else:
            allow_colors = True
            allow_header = True

        # "Show Message Colors" checkbox is disabled and unchecked if the theme does not
        # support colors.
        colors_checkbox.Enable(allow_colors)
        colors_checkbox.SetValue(allow_colors and pref(PFX + 'show_message_colors'))

        header_check.Enable(allow_header)
        header_check.SetValue(allow_header and pref(PFX + 'show_header'))

        sz.Layout()
        p.Thaw()
Example #37
0
    def _get_email_body(self):

        body = self._emailpanel.email_input_area.Value
        if pref("email.signature.enabled", type=bool, default=False):
            footer = u"\r\n" + pref(
                "email.signature.value",
                type=unicode,
                default=u"\r\n_______________________________________________________________"
                "\r\nSent using Digsby - http://email.digsby.com",
            )
        else:
            footer = ""

        return body + footer
Example #38
0
    def _get_email_body(self):

        body = self._emailpanel.email_input_area.Value
        if pref('email.signature.enabled', type=bool, default=False):
            footer = u'\r\n' + pref(
                'email.signature.value',
                type=unicode,
                default=
                u'\r\n_______________________________________________________________'
                '\r\nSent using Digsby - http://email.digsby.com')
        else:
            footer = ''

        return body + footer
Example #39
0
    def handle_ready(self, stanza):
        log.info(stanza.serialize())
        try:
            b = ByteStreams(stanza.get_query())
            used_jid = b.host_used
        except:
            #cleanup
            self.kill_socket_hash()
            self.event("stream_connect_failed")
            return
        #debug:
        if not pref('jabber.use_proxy_ft'): assert used_jid == self.j.stream.me
        if not pref('jabber.use_direct_ft'):
            assert used_jid != self.j.stream.me
        #        assert used_jid != self.j.stream.me
        if used_jid == self.j.stream.me:
            self.conn = self.j.s5bserver.retrieve_hash(self.hash)
            if self.conn not in (False, None):
                self.socket_connected()
                self.event("stream_connected")
            else:
                self.event("stream_connect_failed")
                #cleanup?
        else:
            #cleanup socket server
            self.kill_socket_hash()

            hosts = set(h for hosts in self.j.known_s5b_proxies.values()
                        for h in hosts)

            if not (used_jid in [h.jid for h in hosts]):
                self.event("stream_connect_failed")
                return

            streamhost = [h for h in hosts if h.jid == used_jid]
            if len(streamhost) != 1:
                self.event("stream_connect_failed")
                return
            self.streamhost = streamhost = streamhost[0]

            #start proxy here:
            #same as s5bsocket
            self.conn = S5B_proxyConnect((streamhost.host, streamhost.port),
                                         self.hash, streamhost)
            self.conn.bind_event("connected", self.handle_proxy_connect)
            self.conn.bind_event("connection_failed", self.socket_failed)
            self.conn.get_connect()

        log.info('handle_ready done')
Example #40
0
    def setcontent(*a):
        convo_panel.Freeze()
        sz.Clear(True)
        
        theme = pref(CONVO_THEME_PREF)
        themeName = pref('appearance.conversations.theme')
        theme     = get_theme_safe(themeName, pref('appearance.conversations.variant'))
        log.info('showing message style %r', themeName)

        pref_panel.msgarea = msgarea = build_example_message_area(convo_panel, theme)
        sz.Add(msgarea, 1, EXPAND)
        sz.Layout()

        parent._thawtimer = CallLater(150, lambda: convo_panel.Thaw())
        return msgarea
Example #41
0
    def file_check_complete(self, updater):
        assert updater is self.updater

        if not (updater.update_files or updater.delete_files):
            self.cancel()
            return

        self.downloader = downloader.Downloader(updater)

        auto_download = common.pref("digsby.updater.auto_download",
                                    type=bool,
                                    default=True)
        res = []

        def after_popup():
            if auto_download:
                self.start_downloader()
            elif (not res) or res[0] is None:  # No popup was fired.

                def dialog_cb(ok):
                    if ok:
                        self.start_downloader()
                    else:
                        self.stop_timer()

                diag = gui.toolbox.SimpleMessageDialog(
                    None,
                    title=_('Update Available'),
                    message=
                    _("A Digsby update is available to download.\nWould you like to begin downloading it now?"
                      ),
                    icon=gui.skin.get('serviceicons.digsby').Resized(32),
                    ok_caption=_('Yes'),
                    cancel_caption=_('No'),
                    wrap=450)
                diag.OnTop = True
                diag.ShowWithCallback(dialog_cb)

        def do_popup():
            res.append(
                gui.toast.popup(
                    icon=gui.skin.get("serviceicons.digsby"),
                    header=_("Update Available"),
                    minor=
                    _("A Digsby update is available to download.\nWould you like to begin downloading it now?"
                      ),
                    sticky=True,
                    buttons=[(_("Yes"), lambda *a: self.start_downloader()),
                             (_("No"), self.stop_timer)],
                    size=util.nicebytecount(updater.expected_download_size),
                    onclose=self._download_popup_closed,
                    #                                       popupid = 'digsby.update',
                ))

            wx.CallAfter(after_popup)

        if not auto_download:
            wx.CallAfter(do_popup)
        else:
            wx.CallAfter(after_popup)
Example #42
0
    def next_file(self):
        if self.cancelling:
            return

        if sys.DEV and not sys.opts.force_update:
            self.unchecked_files = []
            self.delete_files, self.update_files = dev_integrity_check(self.local_dir)
            self.files_processed()
            return

        if self.unchecked_files:
            if self.fast_mode:
                while self.fast_mode and self.unchecked_files and not self.cancelling:
                    self._check_file()
            else:
                self._check_file()

            import common
            interval = common.pref('digsby.updater.file_integrity_interval', type = int, default = 0.01)
            if interval == 0:
                interval = 0.01

            t = util.Timer(interval, self.next_file)
            t._verbose = False
            t.start()
        else:
            self.files_processed()
Example #43
0
def chatlogdir():
    import wx, gui.native
    gui.native.extendStdPaths()

    import stdpaths
    from common import pref
    return pref('log.outputdir') or stdpaths.documents
Example #44
0
    def Generate(self, val=None):
        self.navi.closebutton.Show(pref("tabs.tabbar_x", False))

        if self.side_tabs:
            self.ReVgenerate(True)
        else:
            self.Regenerate()
Example #45
0
def show_research_popup_once():
    from common import pref, setpref

    if not pref('research.showed_notification', default=False, type=bool):
        show_research_popup()

    setpref('research.showed_notification', True)
Example #46
0
    def download_error(self, error_files, success_files):
        log.error("Update incomplete. %d successful files, %d errored files",
                  len(success_files), len(error_files))
        for f in error_files:
            log.error("\t%r", f.path)

        self.cancel()
        hooks.notify('digsby.updater.update_failed')

        auto_download = common.pref("digsby.updater.auto_download",
                                    type=bool,
                                    default=True)

        if not auto_download:
            popup = gui.toast.popup(
                icon=gui.skin.get('serviceicons.digsby'),
                header=_("Update Failed"),
                minor=
                _("Digsby was unable to complete the download. This update will be attempted again later."
                  ),
                sticky=True,
                buttons=[(_("Manual Update"), lambda: wx.LaunchDefaultBrowser(
                    "http://install.digsby.com")),
                         (_("Close"), lambda: popup.cancel())],
                #                popupid = 'digsby.update',
            )
Example #47
0
    def GetEmotibox(self):
        'Shares the emoticon box between all instances of this class.'

        b = None
        old_name, new_name = getattr(self, '_emotipack_name', None), pref('appearance.conversations.emoticons.pack', type = unicode, default = u'default')
        self._emotipack_name = new_name

        try:
            b = self.__class__.emotibox
            if not wx.IsDestroyed(b):
                if old_name != new_name:
                    b.Destroy()
                elif b.Parent is not self:
                    b.Reparent(self)

        except AttributeError:
            pass

        if b is None or wx.IsDestroyed(b):
            from gui.imwin.emoticons import get_emoticon_bitmaps
            b = self.__class__.emotibox = UberEmotiBox(self, get_emoticon_bitmaps(self._emotipack_name), self.textctrl, maxwidth = 12)
        else:
            b.SetTextCtrl(self.textctrl)

        return b
Example #48
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()
Example #49
0
    def search(self, e=None):
        if not pref('search.buddylist.enabled', True):
            if e is not None: e.Skip()
            return

        key, backspace = self._interpret_char_event(e)

        def size_like(img, i):
            img = img.ResizedSmaller(max(i.Width, i.Height)).PIL
            return img.ResizeCanvas(i.Width, i.Height).WXB

        icon = skin.get('StatusPanel.SearchIcon')
        self.ForceTextFieldBackground = True
        self.cbutton.SetIcon(size_like(icon, self._button_icon))
        self.DropDownButton.SetIcon(skin.get('StatusPanel.CancelSearchIcon'))
        self.searching = True
        if not hasattr(self, 'search_timer'):
            self.search_timer = wx.PyTimer(self.on_search_timer)
        self.search_timer.Start(500)

        self.display.TypeField()

        # emulate a keypress if one started the search
        self.TextField.ChangeValue(profile.blist.search_string)

        if key is not None:
            self.TextField.AppendText(key)
        if backspace:
            # emulate a backspace
            size = self.TextField.LastPosition
            self.TextField.Remove(size - 1, size)

        self.OnActivateSearch()
Example #50
0
    def OnButton(self, event):
        """
            Handels all events for any button clciked in the navi
        """
        if event.GetId()==CLOSEID:
            self.Parent.Parent.pagecontainer.active.tab.Close()
        elif event.GetId()==PREVID:
            if self.Parent.tabindex>0:
                self.Parent.tabindex-=1
                self.Parent.Regenerate(True)
        elif event.GetId()==NEXTID:
            endex=self.Parent.tabendex
            if endex<self.Parent.GetTabCount()-1:
                while self.Parent.tabendex==endex:
                    self.Parent.tabindex+=1
                    self.Parent.Regenerate(True)
        elif event.GetId()==UPID:
            if self.Parent.rowindex>0:
                self.Parent.rowindex-=1
                self.Parent.Regenerate(True)
        elif event.GetId()==DOWNID:
            if self.Parent.rowindex<len(self.Parent.rows)-pref('tabs.rows',2):#self.Parent.visible:
                self.Parent.rowindex+=1
                self.Parent.Regenerate(True)
        self.Enabler()

#        SmokeAndMirrorsBomb(self,[self.prevb,self.nextb,self.upb,self.downb,self.closebutton])

        self.Parent.Refresh()

        self.Parent.UpdateNotify()
Example #51
0
    def handle_error(self, e=None):
        import traceback
        traceback.print_exc()
        t, v = sys.exc_info()[:2]
        if t is not None:
            msg = get(get(v.args, 0, 'say what?'), 'message', '')
            if msg.startswith('bad write retry'):
                assert False
                self.__logger.error(
                    'Got that weird-ass "bad write retry" message in jabber socket'
                )
#                return

        sslzero_closes = pref('jabber.ssl_error_zero.should_close',
                              type=bool,
                              default=True)
        if t is SSLError and get(v.args, 0, sentinel) == 0:
            self.__logger('SSL error 0!')
            if not sslzero_closes:
                self.__logger('\tnot closing')
                return

        self.__logger.debug('handle_error in %r', self)
        async_chat.close(self)
        if not self.killed:
            self.killed = True
            self.on_error()
Example #52
0
    def Generate(self, val=None):
        self.navi.closebutton.Show(pref('tabs.tabbar_x', False))

        if self.side_tabs:
            self.ReVgenerate(True)
        else:
            self.Regenerate()
Example #53
0
 def edit_status(self):
     if common.pref('social.use_global_status', default=False, type=bool):
         import wx
         wx.GetApp().SetStatusPrompt([self])
     else:
         from myspacegui.editstatus import get_new_status
         get_new_status(success=self.set_web_status)