Exemple #1
0
class TrayIcon(tkinter.BaseWidget, tkinter.Wm):
    def __init__(self, icon, master=None, cnf={}, **kw):
        '''
            Create a new icon for the system tray. The application managing the
            system tray is notified about the new icon. It normally results in the
            icon being added to the tray. If there is no system tray at the icon
            creation time, the icon will be invisible. When a new system tray appears,
            the icon will be added to it. Since tktray 1.3, if the tray crashes and
            destroys your icon, it will be recreated on a new system tray when it's
            available.
            OPTIONS:
                class   WM_CLASS attribute for icon window. Tray manager may use class
                        name to remember icon position or other attributes. This name
                        may be used for event binding as well. For now, real icon
                        window is distinct from the user-specified widget: it may be
                        recreated and destroyed several times during icon lifetime,
                        when a system tray crashes, terminates, disappears or appears.
                        However, tktray tries to forward click and motion events from
                        this inner window to user widget, so event bindings on widget
                        name should work as they used to. This option applies to a real
                        icon window, not to a user-visible widget, so don't rely on it
                        to set widget defaults from an option database: the standard
                        "TrayIcon" class name is used for it.
                docked  boolean indicating whether the real icon window should be
                        embedded into a tray when it exists. Think of it as a heavier
                        version of -visible option: there is a guarantee that no place
                        for icon will be reserved on any tray.
                image   image to show in the system tray. Since tktray 1.3, image type
                        "photo" is not mandatory anymore. Icon will be automatically
                        redrawn on any image modifications. For Tk, deleting an image
                        and creating an image with the same name later is a kind of
                        image modification, and tktray follows this convention. Photo
                        image operations that modify existing image content are another
                        example of events triggering redisplay. Requested size for icon
                        is set according to the image's width and height, but obeying
                        (or disobeying) this request is left for the tray.
                shape   used to put a nonrectangular shape on an icon window. Ignored
                        for compatibility.
                visible boolean value indicating whether the icon must be visible.
                        The system tray manager continues to manage the icon whether
                        it is visible or not. Thus when invisible icon becomes visible,
                        its position on the system tray is likely to remain the same.
                        Tktray currently tries to find a tray and embed into it as
                        soon as possible, whether visible is true or not. _XEMBED_INFO
                        property is set for embedded window: a tray should show or
                        hide an icon depending on this property. There may be, and
                        indeed are, incomplete tray implementations ignoring
                        _XEMBED_INFO (ex. docker). Gnome-panel "unmaps" an icon by
                        making it one pixel wide, that might to be what you expect.
                        For those implementations, the place for an icon will be
                        reserved but no image will be displayed: tktray takes care of
                        it. Tktray also blocks mouse event forwarding for invisible
                        icons, so you may be confident that no<Button> bindings will
                        be invoked at this time.
            WINDOW MANAGEMENT
                Current implementation of tktray is designed to present an interface
                of a usual toplevel window, but there are some important differences
                (some of them may come up later). System Tray specification is based
                on XEMBED protocol, and the later has a problem: when the embedder
                crashes, nothing can prevent embedded windows from destruction. Since
                tktray 1.3, no explicit icon recreation code is required on Tcl level.
                The widget was split in two: one represented by a caller-specified name,
                and another (currently $path.inner) that exists only when a tray is
                available (and dies and comes back and so on). This solution has some
                disadvantages as well. User-created widget is not mapped at all, thus
                it can't be used any more as a parent for other widgets, showing them
                instead of an image. A temporal inner window, however, may contain
                widgets.
                This version (1.3.9) introduces three virtual events: <<IconCreate>>
                <<IconConfigure>> and <<IconDestroy>>. <<IconCreate>> is generated
                when docking is requesting for an icon. <<IconConfigure>> is generated
                when an icon window is resized or changed in some other way.
                <<IconDestroy>> is generated when an icon is destroyed due to panel
                crash or undocked with unsetting -docked option.
        '''

        if not master:
            if tkinter._support_default_root:
                if not tkinter._default_root:
                    tkinter._default_root = tkinter.Tk()
                master = tkinter._default_root
        self.TktrayVersion = master.tk.call('package', 'require', 'tktray')

        self.icon = PhotoImage(master=master, file=icon)
        kw['image'] = self.icon

        # stolen from tkinter.Toplevel
        if kw:
            cnf = tkinter._cnfmerge((cnf, kw))
        extra = ()
        for wmkey in ['screen', 'class_', 'class', 'visible', 'colormap']:
            if wmkey in cnf:
                val = cnf[wmkey]
                # TBD: a hack needed because some keys
                # are not valid as keyword arguments
                if wmkey[-1] == '_':
                    opt = '-' + wmkey[:-1]
                else:
                    opt = '-' + wmkey
                extra = extra + (opt, val)
                del cnf[wmkey]
        tkinter.BaseWidget.__init__(self, master, 'tktray::icon', cnf, {},
                                    extra)
        self.protocol("WM_DELETE_WINDOW", self.destroy)

        self.menu = tkinter.Menu(self, tearoff=0)
        self.bind('<Button-3>', self._popupmenu)

    def bbox(self):
        return self._getints(self.tk.call(self._w, 'bbox')) or None

    def _popupmenu(self, event):
        w, h = self.menu.winfo_reqwidth(), self.menu.winfo_reqheight()
        x0, y0, x1, y1 = self.bbox()
        # get the coords for the popup menu; we want it to the mouse pointer's
        # left and above the pointer in case the taskbar is on the bottom of the
        # screen, else below the pointer; add 1 pixel towards the pointer in each
        # dimension, so the pointer is '*inside* the menu when the button is being
        # released, so the menu will not unpost on the initial button-release event
        if y0 > self.winfo_screenheight() / 2:
            # assume the panel is at the bottom of the screen
            x, y = event.x_root - w + 1, event.y_root - h + 1
        else:
            x, y = event.x_root - w + 1, event.y_root - 1
        # make sure that x is not outside the screen
        if x < 5:
            x = 5
        self.menu.tk_popup(x, y)

    def add_menu_separator(self):
        self.menu.add_separator()

    def add_menu_item(self, label="", command=None):
        self.menu.add_command(label=label, command=command)

    def change_icon(self, icon, desc):
        self.icon.configure(file=icon)
        self.update()

    def loop(self, tk_window):
        # no need to update since it is part of the tk mainloop
        self.update_idletasks()
        tk_window.loop_id = tk_window.after(10, self.loop, tk_window)

    def get_item_label(self, item):
        return self.menu.entrycget(item, 'label')

    def set_item_label(self, item, label):
        self.menu.entryconfigure(item, label=label)

    def disable_item(self, item):
        self.menu.entryconfigure(item, state='disabled')

    def enable_item(self, item):
        self.menu.entryconfigure(item, state='normal')

    def bind_left_click(self, command):
        self.bind('<1>', lambda e: command())
Exemple #2
0
class Config(Toplevel):
    """ Configuration dialog to set times and language. """

    def __init__(self, master):
        Toplevel.__init__(self, master, class_="CheckMails")
        self.title(_("Preferences"))

        style = Style(self)
        style.map("TCombobox",
                  fieldbackground=[('readonly', 'white')],
                  selectbackground=[('readonly', 'white')],
                  selectforeground=[('readonly', 'black')],
                  foreground=[('readonly', 'black')])

        # validation of the entries : only numbers are allowed
        self._validate_entry_nb = self.register(self.validate_entry_nb)

        # --- Times
        Label(self,
              text=_("Time between two checks")).grid(row=0, column=0,
                                                      padx=(10, 4), pady=(10, 4),
                                                      sticky="e")
        Label(self, justify="right",
              text=_("Maximum time allowed for login or check\n\
(then the connection is reset)")).grid(row=1, column=0, padx=(10, 4), pady=4, sticky="e")
        self.time_entry = Entry(self, width=5, justify="center",
                                validate="key",
                                validatecommand=(self._validate_entry_nb, "%P"))
        self.time_entry.grid(row=0, column=1, padx=(4, 0), pady=(10, 4))
        self.time_entry.insert(0, "%g" % (CONFIG.getint("General", "time") / 60000))
        self.timeout_entry = Entry(self, width=5, justify="center",
                                   validate="key",
                                   validatecommand=(self._validate_entry_nb, "%P"))
        self.timeout_entry.grid(row=1, column=1, padx=(4, 0), pady=4)
        self.timeout_entry.insert(0, "%g" % (CONFIG.getint("General", "timeout") / 60000))
        Label(self, text="min").grid(row=0, column=2, padx=(0, 10), pady=(10, 4))
        Label(self, text="min").grid(row=1, column=2, padx=(0, 10), pady=4)

        frame = Frame(self)
        frame.grid(row=2, columnspan=3, padx=6, pady=(0, 6))

        # --- Language
        Label(frame, text=_("Language")).grid(row=0, column=0,
                                              padx=8, pady=4, sticky="e")
        lang = {"fr": "Français", "en": "English"}
        self.lang = StringVar(self, lang[CONFIG.get("General", "language")])
        menu_lang = Menu(frame, tearoff=False)
        Menubutton(frame, menu=menu_lang, width=9,
                   textvariable=self.lang).grid(row=0, column=1,
                                                padx=8, pady=4, sticky="w")
        menu_lang.add_radiobutton(label="English", value="English",
                                  variable=self.lang, command=self.translate)
        menu_lang.add_radiobutton(label="Français", value="Français",
                                  variable=self.lang, command=self.translate)
        # --- gui toolkit
        Label(frame,
              text=_("GUI Toolkit for the system tray icon")).grid(row=1, column=0,
                                                                   padx=8, pady=4,
                                                                   sticky="e")
        self.gui = StringVar(self, CONFIG.get("General", "trayicon").capitalize())
        menu_gui = Menu(frame, tearoff=False)
        Menubutton(frame, menu=menu_gui, width=9,
                   textvariable=self.gui).grid(row=1, column=1,
                                               padx=8, pady=4, sticky="w")
        for toolkit, b in TOOLKITS.items():
            if b:
                menu_gui.add_radiobutton(label=toolkit.capitalize(),
                                         value=toolkit.capitalize(),
                                         variable=self.gui,
                                         command=self.change_gui)
        # --- Font
        self.preview_path = tempfile.mktemp(".png", "checkmails_preview")
        w = max([len(f) for f in TTF_FONTS])
        self.fonts = sorted(TTF_FONTS)
        self.font = Combobox(frame, values=self.fonts, width=(w * 2) // 3,
                             exportselection=False, state="readonly")
        current_font = CONFIG.get("General", "font")
        if current_font in self.fonts:
            i = self.fonts.index(current_font)
        else:
            i = 0
        self.font.current(i)
        self.img_prev = PhotoImage(master=self, file=IMAGE)
        Label(frame, text=_("Font")).grid(row=2, column=0,
                                          padx=8, pady=4, sticky="e")
        self.font.grid(row=2, column=1, padx=8, pady=4, sticky="w")
        self.prev = Label(frame, image=self.img_prev)
        self.prev.grid(row=2, column=2, padx=8, pady=4)
        self.update_preview()
        self.font.bind('<<ComboboxSelected>>', self.update_preview)
        self.font.bind_class("ComboboxListbox", '<KeyPress>', self.key_nav)

        # --- Ok/Cancel
        frame_button = Frame(self)
        frame_button.grid(row=3, columnspan=3, padx=6, pady=(0, 6))
        Button(frame_button, text="Ok",
               command=self.ok).grid(row=2, column=0, padx=8, pady=4)
        Button(frame_button, text=_("Cancel"),
               command=self.destroy).grid(row=2, column=1, padx=4, pady=4)

    def update_preview(self, event=None):
        self.font.selection_clear()
        nb = "0"
        im = Image.open(IMAGE)
        draw = ImageDraw.Draw(im)
        font_name = self.font.get()
        font_path = TTF_FONTS[font_name]
        W, H = im.size
        try:
            font = ImageFont.truetype(font_path, FONTSIZE)
            w, h = draw.textsize(nb, font=font)
            draw.text(((W - w) / 2, (H - h) / 2), nb, fill=(255, 0, 0),
                      font=font)
        except OSError:
            w, h = draw.textsize(nb)
            draw.text(((W - w) / 2, (H - h) / 2), nb, fill=(255, 0, 0))
        if W > 48:
            im.resize((48, 48), Image.ANTIALIAS).save(self.preview_path)
        else:
            im.save(self.preview_path)
        self.img_prev.configure(file=self.preview_path)
        self.prev.configure(image=self.img_prev)
        self.prev.update_idletasks()

    def key_nav(self, event):
        char = event.char.upper()
        if char:
            i = 0
            n = len(self.fonts)
            while i < n and self.fonts[i] < char:
                i += 1
            if i < n:
                self.tk.eval("%s selection clear 0 end" % (event.widget))
                self.tk.eval("%s see %i" % (event.widget, i))
                self.tk.eval("%s selection set %i" % (event.widget, i))
                self.tk.eval("%s activate %i" % (event.widget, i))

    def ok(self):
        time = float(self.time_entry.get()) * 60000
        timeout = float(self.timeout_entry.get()) * 60000
        CONFIG.set("General", "time", "%i" % time)
        CONFIG.set("General", "timeout", "%i" % timeout)
        CONFIG.set("General", "language", self.lang.get().lower()[:2])
        CONFIG.set("General", "font", self.font.get())
        CONFIG.set("General", "trayicon", self.gui.get().lower())
        save_config()
        self.destroy()

    def translate(self):
        showinfo("Information",
                 _("The language setting will take effect after restarting the application"),
                 parent=self)

    def change_gui(self):
        showinfo("Information",
                 _("The GUI Toolkit setting will take effect after restarting the application"),
                 parent=self)

    @staticmethod
    def validate_entry_nb(P):
        """ Allow only to enter numbers"""
        parts = P.split(".")
        b = len(parts) < 3 and P != "."
        for p in parts:
            b = b and (p == "" or p.isdigit())
        return b

    def destroy(self):
        remove(self.preview_path)
        Toplevel.destroy(self)