Exemple #1
0
def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-s',
                      '--show-hide',
                      dest='show_hide',
                      action='store_true',
                      default=False,
                      help=_('Toggles the visibility of the terminal window'))

    parser.add_option('-p',
                      '--preferences',
                      dest='show_preferences',
                      action='store_true',
                      default=False,
                      help=_('Shows Guake preference window'))

    parser.add_option('-a',
                      '--about',
                      dest='show_about',
                      action='store_true',
                      default=False,
                      help=_('Shows Guake\'s about info'))

    parser.add_option('-q',
                      '--quit',
                      dest='quit',
                      action='store_true',
                      default=False,
                      help=_('Says to Guake go away =('))

    options, args = parser.parse_args()

    bus = dbus.SessionBus()
    try:
        remote_object = bus.get_object('org.gnome.Guake.DBus',
                                       '/DBusInterface')
    except dbus.DBusException:
        return

    if options.show_hide:
        remote_object.show_hide()
        sys.exit(0)

    if options.show_preferences:
        remote_object.show_prefs()
        sys.exit(0)

    if options.show_about:
        remote_object.show_about()
        sys.exit(0)

    if options.quit:
        remote_object.quit()
        sys.exit(0)

    # here we know that guake was called without any parameter and it is
    # already running, so, lets toggle glade visibility and exit!
    remote_object.show_hide()
    sys.exit(0)
Exemple #2
0
 def get_kind_str(self):
     if "SystemBusDeviceNode" in self.nc:
         return _("system bus device")
     elif "PCIExpressDeviceNode" in self.nc:
         return _("PCI(E) function")
     elif "DeviceNode" in self.nc:
         return _("generic device")
Exemple #3
0
    def __init__(self, idvariable, *args, **kw):
        GUIFrame.__init__(self, *args, **kw)

        self.var = idvariable
        self.var.trace_variable("w", self.__on_var_changed__)

        self.grid()

        self.rowconfigure(0, weight=0)
        self.columnconfigure(0, weight=0)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=0)

        self.kind_cb = cb = VarCombobox(self,
                                        values=[
                                            _("PCI class code"),
                                            _("Vendor ID"),
                                            _("Device ID"),
                                            _("Not specified")
                                        ],
                                        state="readonly")
        cb.grid(row=0, column=0, sticky="NEWS")
        cb.bind("<<ComboboxSelected>>", self.__on_kind_changed__, "+")

        self.cb_name = cb = Combobox(self, state="readonly")
        cb.grid(row=0, column=1, sticky="NEWS")
        cb.bind("<<ComboboxSelected>>", self.__on_name_changed__, "+")

        self.cb_id = cb = Combobox(self, state="readonly")
        cb.grid(row=0, column=2, sticky="NEWS")
        cb.bind("<<ComboboxSelected>>", self.__on_id_changed__, "+")

        self.after_idle(self.__refresh__)
Exemple #4
0
    def rebuild_cache(self):
        try:
            qvd = qvd_get(self.proj.build_path,
                          version=self.proj.target_version)
        except BadBuildPath as e:
            showerror(
                title=_("Cache rebuilding is impossible").get(),
                message=(_("Selected Qemu build path is bad. Reason: %s") %
                         (e.message)).get())
            return

        # if 'reload_build_path_task' is not failed
        if hasattr(self.pw, 'reload_build_path_task'):
            # reload_build_path_task always run at program start that is why
            # it's in process when it's not in finished_tasks and not failed
            if self.pw.reload_build_path_task not in self.pw.tm.finished_tasks:
                ans = askyesno(self,
                               title=_("Cache rebuilding"),
                               message=_("Cache building is already \
in process. Do you want to start cache rebuilding?"))
                if not ans:
                    return

        qvd.remove_cache()
        self.pw.reload_build_path()
Exemple #5
0
    def __init__(self):
        GUITk.__init__(self)
        self.title(_("Text Viewer"))

        self.columnconfigure(0, weight = 1)
        self.columnconfigure(1, weight = 0)

        row = 0
        self.rowconfigure(row, weight = 1)

        self._text = text = TextCanvas(self)
        text.grid(row = row, column = 0, sticky = "NESW")

        add_scrollbars_native(self, text, row = row)
        row += 1 # horizontal scroll bar

        row += 1; self.rowconfigure(row, weight = 0)
        sb = Statusbar(self)
        sb.grid(row = row, column = 0, sticky = "NESW")

        Sizegrip(self).grid(row = row, column = 1, sticky = "NESW")

        sb.right(_("%s/%s") % (text._var_lineno, text._var_total_lines))

        self._file_name = None

        text.focus_set()
Exemple #6
0
    def __init__(self, *args, **kw):
        QOMDescriptionSettingsWidget.__init__(self, *args, **kw)

        self.mw = None

        self.var_tabs = v = BooleanVar()
        self.buttons_fr.columnconfigure(2, weight=0)
        chb = VarCheckbutton(self.buttons_fr, text=_("Use tabs"), variable=v)
        chb.grid(row=0, column=2, sticky="NEWS")
        v.trace_variable("w", self.__on_tabs__)

        # mesh step seleection
        self.buttons_fr.columnconfigure(3, weight=0)
        self.buttons_fr.columnconfigure(4, weight=0)
        self.buttons_fr.columnconfigure(5, weight=0)

        Separator(self.buttons_fr, orient=VERTICAL).grid(row=0,
                                                         column=3,
                                                         sticky="NEWS")

        l = VarLabel(self.buttons_fr, text=_("Mesh step:"))
        l.grid(row=0, column=4, sticky="NEWS")

        self.var_mesh_step = v = StringVar()
        v.trace_variable("w", self.__on_mesh_step)
        self.mesh_step_sb = sb = Spinbox(self.buttons_fr,
                                         from_=MIN_MESH_STEP,
                                         to=MAX_MESH_STEP,
                                         textvariable=v,
                                         width=len(str(MAX_MESH_STEP)))
        sb.grid(row=0, column=5, sticky="NEWS")

        self.var_tabs.set(True)
Exemple #7
0
    def __init__(self, gui_project_history_tracker, *args, **kw):
        kw["columns"] = ["description"]

        VarTreeview.__init__(self, *args, **kw)

        TreeviewWidthHelper.__init__(self, ["#0"] + kw["columns"])

        self.guipht = gui_project_history_tracker

        self.sequence_ml = ml = _("Sequence")
        self.heading("#0", text=ml)
        self.__sequence_ml = ml.trace_variable("w",
                                               self.__on_heading_changed__)
        # width = 0 - columns will be expanded after __invalidate__
        self.column("#0", stretch=False, width=0)

        self.description_ml = ml = _("Operation description")
        self.heading("description", text=ml)
        self.__description_ml = ml.trace_variable("w",
                                                  self.__on_heading_changed__)
        self.column("description", stretch=False, width=0)

        self.guipht.watch_changed(self.__on_operation__)

        self.bind("<Destroy>", self.__on_destroy__, "+")

        self.tag_configure("undone", foreground="grey")

        self.bind("<<TreeviewOpen>>", self.__on_open_or_close__, "+")
        self.bind("<<TreeviewClose>>", self.__on_open_or_close__, "+")

        self.__invalidate__()
Exemple #8
0
    def __init__(self, master, filetypes=None, title=None):
        super(CrossOpenDialog, self).__init__(master)

        self.title = _("Open file") if title is None else title

        self.filetypes = [(_("All files"), '.*')] if filetypes is None \
            else filetypes
Exemple #9
0
def get_pci_id_kind_str(pci_id):
    if type(pci_id) is PCIVendorId:
        return _("vendor")
    elif type(pci_id) is PCIDeviceId:
        return _("device")
    elif type(pci_id) is PCIClassId:
        return _("class")
Exemple #10
0
    def __init__(self, *args, **kw):
        DeviceSettingsWidget.__init__(self, *args, **kw)

        for row, mio in enumerate([("mmio", _("MMIO Mappings")),
                                   ("pmio", _("PMIO Mappings"))], 2):
            lf = VarLabelFrame(self, text=mio[1])
            lf.pack(fill=BOTH, expand=False)
            lf.columnconfigure(0, weight=1)

            fr = GUIFrame(lf)
            fr.grid(row=0, column=0, sticky="NEWS")
            lf.rowconfigure(0, weight=1)
            fr.columnconfigure(0, weight=0)
            fr.columnconfigure(1, weight=1)

            bt_fr = GUIFrame(lf)
            bt_fr.grid(row=1, column=0, sticky="NEWS")
            lf.rowconfigure(1, weight=0)

            bt_add = VarButton(bt_fr,
                               text=_("Add"),
                               command=getattr(self, "on_add_" + mio[0]))
            bt_add.grid(row=0, column=0, sticky="NES")

            bt_del = VarButton(bt_fr,
                               text=_("Delete"),
                               command=getattr(self, "on_del_" + mio[0]))
            bt_del.grid(row=0, column=1, sticky="NES")
            bt_del.config(state="disabled")

            setattr(self, mio[0] + "_fr", fr)
            setattr(self, "bt_del_" + mio[0], bt_del)
            setattr(self, mio[0] + "_rows", [])
Exemple #11
0
    def __init__(self, pht, runtime):
        GUITk.__init__(self, wait_msec=1)

        self.title(_("QEmu Watcher"))

        self.pht = pht
        self.rt = runtime

        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        self._killed = False
        self.task_manager.enqueue(self.co_rsp_poller())

        self.hk = hk = HotKey(self)
        hk.add_bindings([
            HotKeyBinding(self._on_save,
                          key_code=39,
                          description=_("Save machine"),
                          symbol="S")
        ])

        menubar = VarMenu(self)
        self.config(menu=menubar)

        filemenu = VarMenu(menubar, tearoff=False)
        menubar.add_cascade(label=_("File"), menu=filemenu)

        filemenu.add_command(label=_("Save machine"),
                             command=self._on_save,
                             accelerator=hk.get_keycode_string(self._on_save))
        self._exiting = False
        self.protocol("WM_DELETE_WINDOW", self._on_wm_delete_window)

        pht.watch_changed(self._on_changed)
Exemple #12
0
    def reload_build_path(self):
        if self.tm:
            # If task manager is available then use background task
            try:
                self.tm.remove(self.reload_build_path_task)
            except AttributeError:
                pass
            else:
                del self.reload_build_path_task

            try:
                self.reload_build_path_task = ReloadBuildPathTask(self)
            except BadBuildPath as bbpe:
                showerror(_("Bad build path").get(), str(bbpe))
            else:
                self.tm.enqueue(self.reload_build_path_task)
        else:
            """ If no task manager is available then account build path right
            now. It will cause GUI to freeze but there are no more options. """

            try:
                qvd = qvd_load_with_cache(self.p.build_path)
            except BadBuildPath as bbpe:
                showerror(_("Bad build path").get(), str(bbpe))
            else:
                qvd.use()
                self.pht.all_pci_ids_2_objects()
Exemple #13
0
    def __init__(self, node, machine, *args, **kw):
        GUIFrame.__init__(self, *args, **kw)

        try:
            self.mht = self.winfo_toplevel().mht
        except AttributeError:
            # snapshot mode
            self.mht = None

        if self.mht is not None:
            self.mht.watch_changed(self.on_changed)

        self.node = node
        self.mach = machine

        self.node_fr = fr = GUIFrame(self)
        fr.pack(fill = BOTH, expand = False)
        fr.columnconfigure(0, weight = 0)
        fr.columnconfigure(1, weight = 1)

        # variable name base editing
        fr.rowconfigure(0, weight = 0)
        VarLabel(fr,
            text = _("Variable name base")
        ).grid(
            row = 0,
            column = 0,
            sticky = "NSW"
        )

        self.v_var_base = v = StringVar()
        HKEntry(fr,
            textvariable = v
        ).grid(
            row = 0,
            column = 1,
            sticky = "NESW"
        )

        fr.rowconfigure(1, weight = 0)
        VarLabel(fr,
            text = _("Name of variable")
        ).grid(
            row = 1,
            column = 0,
            sticky = "NSW"
        )

        HKEntry(fr,
            text = machine.node_id2var_name[node.id],
            state = "readonly"
        ).grid(
            row = 1,
            column = 1,
            sticky = "NESW"
        )

        self.refresh_after = self.after(0, self.__refresh_single__)

        self.bind("<Destroy>", self.__on_destroy__)
Exemple #14
0
 def _description(self):
     if self._new is None:
         return _("Forget project build path value '%s'") % self._old
     elif self._old is None:
         return _("Specify project build path value '%s'") % self._new
     else:
         return _("Change project build path value '%s' to '%s'") % (
             self._old, self._new)
Exemple #15
0
 def __description__(self):
     if self.new_path is None:
         return _("Forget project build path value '%s'") % self.old_path
     elif self.old_path is None:
         return _("Specify project build path value '%s'") % self.new_path
     else:
         return _("Change project build path value '%s' to '%s'") % (
             self.old_path, self.new_path)
Exemple #16
0
    def __init__(self, guakeinstance):
        super(PrefsDialog, self).__init__(common.gladefile('prefs.glade'),
                                          root='config-window')

        self.guake = guakeinstance
        self.client = gconf.client_get_default()

        # images
        ipath = common.pixmapfile('guake.png')
        self.get_widget('image_logo').set_from_file(ipath)
        ipath = common.pixmapfile('tabdown.svg')
        self.get_widget('image1').set_from_file(ipath)
        ipath = common.pixmapfile('tabup.svg')
        self.get_widget('image2').set_from_file(ipath)

        # the first position in tree will store the keybinding path in gconf,
        # and the user doesn't worry with this, lest hide that =D
        model = gtk.TreeStore(str, str, str, bool)
        treeview = self.get_widget('treeview-keys')
        treeview.set_model(model)
        treeview.set_rules_hint(True)

        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn('keypath', renderer, text=0)
        column.set_visible(False)
        treeview.append_column(column)

        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_('Action'), renderer, text=1)
        column.set_property('expand', True)
        treeview.append_column(column)

        renderer = gtk.CellRendererText()
        renderer.set_data('column', 1)
        renderer.connect('edited', self.on_key_edited, model)
        column = gtk.TreeViewColumn(_('Shortcut'),
                                    renderer,
                                    text=2,
                                    editable=3)
        column.set_property('expand', False)
        treeview.append_column(column)

        self.populate_shell_combo()
        self.populate_keys_tree()
        self.load_configs()
        self.get_widget('config-window').hide()

        # Preview when selecting a bgimage
        self.selection_preview = gtk.Image()
        self.file_filter = gtk.FileFilter()
        self.file_filter.add_pattern("*.jp[e]?g")
        self.file_filter.add_pattern("*.png")
        self.file_filter.add_pattern("*.svg")
        self.bgfilechooser = self.get_widget('bgimage-filechooserbutton')
        self.bgfilechooser.set_preview_widget(self.selection_preview)
        self.bgfilechooser.set_filter(self.file_filter)
        self.bgfilechooser.connect('update-preview', self.update_preview_cb,
                                   self.selection_preview)
Exemple #17
0
    def _description(self):
        return _("Replace %s '%s' of IRQ line %d with value '%s'.\
" ) % (
            _("source end-point") if "src" in self.attr \
                else _("destination end-point"),
            self.gen_id_str(self.old_val),
            self.node_id,
            self.gen_id_str(self.new_val)
        )
Exemple #18
0
    def on_save_as(self):
        fname = asksaveas(self,
                          [(_("QDC GUI Project defining script"), ".py")],
                          title=_("Save project"))

        if not fname:
            return

        self.try_save_project_to_file(fname)
Exemple #19
0
    def on_load(self):
        if not self.check_unsaved():
            return

        fname = askopen(self, [(_("QDC GUI Project defining script"), ".py")],
                        title=_("Load project"))

        if fname:
            self._do_load(fname)
Exemple #20
0
 def show_notification(self, text):
     if self.client.get_bool(KEY('/general/use_popup')):
         notification = pynotify.Notification(
             _('Guake!'),
             _(text +
               '\nPress <b>%s</b> to use it.') % 
             self.notification_label, 
             self.notification_pixmapfile)
         notification.show()
Exemple #21
0
 def get_kind_str(self):
     return (_("machine draft")
             if "MachineNode" in self.nc
         else _("system bus device template")
             if "SysBusDeviceDescription" in self.nc
         else _("PCI bus device template")
             if "PCIExpressDeviceDescription" in self.nc
         else _("an auto generated code")
     )
Exemple #22
0
 def reload_globals(self, client, connection_id, entry, data):
     """Unbind all global hotkeys and rebind the show_hide
     method. If more global hotkeys should be added, just connect
     the gconf key to the watch system and add.
     """
     self.guake.hotkeys.unbind_all()
     key = entry.get_value().get_string()
     if not self.guake.hotkeys.bind(key, self.guake.show_hide):
         raise ShowableError(_("key binding error"), _("Unable to bind global <b>%s</b> key") % key, -1)
Exemple #23
0
    def __init__(self, root, *args, **kw):
        GUIDialog.__init__(self, master=root, *args, **kw)
        self.qom_type_var = root.qom_type_var

        self.title(_("Device Tree"))
        self.grid()

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.columnconfigure(2, minsize=200)

        self.attributes("-topmost", 1)
        geom = "+" + str(int(root.winfo_rootx())) \
             + "+" + str(int(root.winfo_rooty()))
        self.geometry(geom)

        self.focus()

        self.device_tree = VarTreeview(self)
        self.device_tree["columns"] = ("Macros")

        self.device_tree.heading("#0", text=_("Devices"))
        self.device_tree.heading("Macros", text=_("Macros"))

        self.device_tree.bind("<ButtonPress-1>", self.on_b1_press_dt)

        self.device_tree.grid(row=0, column=0, sticky="NEWS")

        #Add Scrollbar
        ysb = Scrollbar(self,
                        orient="vertical",
                        command=self.device_tree.yview)
        xsb = Scrollbar(self,
                        orient="horizontal",
                        command=self.device_tree.xview)
        self.device_tree['yscroll'] = ysb.set
        self.device_tree['xscroll'] = xsb.set
        ysb.grid(row=0, column=1, sticky="NS")
        xsb.grid(row=1, column=0, sticky="EW")

        self.add_button = VarButton(self,
                                    text=_("Select"),
                                    command=self.on_select_qom_type)
        self.add_button.grid(row=1, column=2, sticky="WE")
        self.add_button.config(state="disabled")

        self.fr = VarLabelFrame(self, text=_("Select QOM type"))
        self.fr.grid(row=0, column=2, sticky="SEWN")

        # Check exception before __init__ call.
        bp = root.mach.project.build_path
        qvd = qvd_get_registered(bp)
        # the QOM type of roots[0] is "device"
        roots = qvd.qvc.device_tree[0]["children"]
        self.qom_create_tree("", roots)
Exemple #24
0
 def __description__(self, p):
     # Assume that the operation is not used to change Qemu target version
     # from None to None.
     if self._old is None:
         return _("Set target Qemu version '%s'" % self._new)
     elif self._new is None:
         return _("Forget target Qemu version '%s'" % self._old)
     else:
         return _("Change target Qemu version '%s' to '%s'" %
                  (self._old, self._new))
Exemple #25
0
 def __description__(self):
     if self.prev_layouts is None:
         return _("Set layout for '%s' description representation.") % \
             self.desc_name
     elif self.new_layout is None:
         return _("Remove layouts of '%s' description representation.") % \
             self.desc_name
     else:
         return _("Replace layout of '%s' description representation.") % \
             self.desc_name
Exemple #26
0
    def test_format_with_unicode(self):
        """ Under Py2 formatting a `str` which contains encoded unicode with an
explicit `unicode` value results in an `UnicodeDecodeError`.
        """
        fmt = _("Create %s (%d) of type '%s'.")
        kind = _("system bus device")
        _id = 0xdeadbeef
        qtype = u"something"

        fmt % (kind, _id, qtype)
Exemple #27
0
    def __askDestination(self):
        self.drives = self.partutils.returnDrives()
        if len(self.drives) == 1:
            # FIX ME: If disk is unmounted, you should mount it before return process!
            # It returns mount point directory.
            device = self.drives.keys()[0]

        else:
            drive_no = 0

            self.utils.cprint(_("Devices:"), "brightwhite")

            for drive in self.drives:
                drive_no += 1

                # FIX ME: Bad coding..
                self.utils.cprint("%d) %s:" % (drive_no, drive), "brightgreen")
                self.utils.cprint("    %s:" % _("Label"), "green", True)
                print(self.drives[drive]["label"])

                self.utils.cprint("    %s:" % _("Parent"), "green", True)
                print(str(self.drives[drive]["parent"]))

                self.utils.cprint("    %s:" % _("Mount Point"), "green", True)
                mount_dir = self.drives[drive]["mount"]
                if not mount_dir:
                    print("%s (%s)" % (MOUNT_ISO,  _("not mounted")))
                else:
                    print(mount_dir)

                self.utils.cprint("    %s:" % _("Unmount"), "green", True)
                print(str(self.drives[drive]["unmount"]))

                self.utils.cprint("    UUID:", "green", True)
                print(self.drives[drive]["uuid"])

                self.utils.cprint("    %s:" % _("File System Version"), "green", True)
                print(self.drives[drive]["fsversion"])

                self.utils.cprint("    %s:" % _("File System Type"), "green", True)
                print("%s\n" % self.drives[drive]["fstype"])

            try:
                part_number = int(raw_input("%s " % _("USB devices or partitions have found more than one. Please choose one:")))

                device = self.drives.keys()[part_number - 1]

            except ValueError:
               self.cprint(_("You must enter a number between 0 - %d." % drive_no + 1), "red")

               return False

        destination = self.drives[device]["mount"]

        return device, destination
Exemple #28
0
 def _description(self):
     if self.new_bus_id < 0:
         return _("Detach %s from %s.") % (self.gen_id_str(
             self.node_id), self.gen_id_str(self.old_bus_id))
     elif self.old_bus_id < 0:
         return _("Attach %s to %s.") % (self.gen_id_str(
             self.node_id), self.gen_id_str(self.new_bus_id))
     else:
         return _("Move %s from %s to %s.") % (self.gen_id_str(
             self.node_id), self.gen_id_str(
                 self.old_bus_id), self.gen_id_str(self.new_bus_id))
Exemple #29
0
 def _description(self):
     name = self.find_desc().name
     if self.old_val is None:
         return _("Set '%s' of '%s' to %s") % (self.attr, name,
                                               gen_pci_id_str(self.val))
     elif self.val is None:
         return _("Reset '%s' of '%s'.") % (self.attr, name)
     else:
         return _("Change '%s' of '%s' from %s to %s") % (
             self.attr, name, gen_pci_id_str(
                 self.old_val), gen_pci_id_str(self.val))
Exemple #30
0
    def __init__(self, parent, running_procs):
        super(PromptQuitDialog, self).__init__(
            parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO
        )

        self.set_keep_above(True)
        self.set_markup(_("Do you really want to quit Guake!?"))
        if running_procs == 1:
            self.format_secondary_markup(_("<b>There is one process still running.</b>"))
        elif running_procs > 1:
            self.format_secondary_markup(_("<b>There are %d processes running.</b>" % running_procs))
Exemple #31
0
    def __init__(self,
                 node,
                 machine,
                 machine_history_tracker=None,
                 *args,
                 **kw):
        """ Toplevel.__init__ calls `title` which requires the attribute `node`
        to be initialized already. """
        self.node = node

        GUIToplevel.__init__(self, *args, **kw)

        self.mach = machine
        self.mht = machine_history_tracker

        self.grid()

        self.columnconfigure(0, weight=1)

        self.rowconfigure(0, weight=1)
        # to be set by child class constructor
        self.sw = None

        self.rowconfigure(1, weight=0)

        fr = GUIFrame(self)
        fr.grid(row=1, column=0, sticky="NES")
        fr.rowconfigure(0, weight=1)
        fr.columnconfigure(0, weight=1)
        fr.columnconfigure(1, weight=1)
        fr.columnconfigure(2, weight=1)

        VarButton(fr, text=_("Refresh"), command=self.refresh).grid(row=0,
                                                                    column=0,
                                                                    sticky="S")

        VarButton(fr, text=_("Apply"), command=self.apply).grid(row=0,
                                                                column=1,
                                                                sticky="S")

        VarButton(fr, text=_("OK"),
                  command=self.apply_and_quit).grid(row=0,
                                                    column=2,
                                                    sticky="S")

        # Makes settings window always on top.
        # Is there more pythonic interface?
        # http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.attributes-method
        self.attributes("-topmost", 1)

        self.bind("<Escape>", self.on_escape, "+")

        self.after(100, self.__init_geometry)
Exemple #32
0
    def __description__(self):
        mach = self.find_desc()
        dev = mach.id2node[self.node_id]

        return _("Replace %s '%s' of IRQ line %d with value '%s'.\
" ) % (
            _("source end-point") if "src" in self.attr \
                else _("destination end-point"),
            self.gen_id_str(self.old_val),
            self.node_id,
            self.gen_id_str(self.new_val)
        )
Exemple #33
0
 def get_kind_str(self):
     if "SystemBusNode" in self.nc:
         return _("system bus")
     elif "PCIExpressBusNode" in self.nc:
         return _("PCI(E) bus")
     elif "ISABusNode" in self.nc:
         return _("ISA bus")
     elif "IDEBusNod" in self.nc:
         return _("IDE bus")
     elif "I2CBusNode" in self.nc:
         return _("I2C bus")
     elif "BusNode" in self.nc:
         return "generic bus"
Exemple #34
0
    def __init__(self, irq, *args, **kw):
        SettingsWidget.__init__(self, irq, *args, **kw)

        self.irq = irq

        for pfx, txt in [
            ("src_", _("Source")),
            ("dst_", _("Destination"))
        ]:
            lf = VarLabelFrame(self, text = txt)
            lf.pack(fill = BOTH, expand = False)

            lf.columnconfigure(0, weight = 0)
            lf.columnconfigure(1, weight = 1)

            for row in xrange(0, 3):
                lf.rowconfigure(row, weight = 1)

            l = VarLabel(lf, text = _("Node"))
            l.grid(row = 0, column = 0, sticky = "NE")

            node_var = StringVar()
            node_var.trace_variable("w", self.on_node_text_changed)
            node_cb = Combobox(lf,
                textvariable = node_var,
                values = [],
                state = "readonly"
            )
            node_cb.grid(row = 0, column = 1, sticky = "NEW")

            irq_idx_l = VarLabel(lf, text = _("GPIO index"))
            irq_idx_l.grid(row = 1, column = 0, sticky = "NE")

            irq_idx_var = StringVar()
            irq_idx_e = HKEntry(lf, textvariable = irq_idx_var)
            irq_idx_e.grid(row = 1, column = 1, sticky = "NEW")

            irq_name_l = VarLabel(lf, text = _("GPIO name"))
            irq_name_l.grid(row = 2, column = 0, sticky = "NE")

            irq_name_var = StringVar()
            irq_name_e = HKEntry(lf, textvariable = irq_name_var)
            irq_name_e.grid(row = 2, column = 1, sticky = "NEW")

            for v in ["lf", "node_var", "node_cb",
                      "irq_idx_l", "irq_idx_e", "irq_idx_var",
                      "irq_name_l", "irq_name_e", "irq_name_var"]:
                setattr(self, pfx + v, locals()[v])

        self.__auto_var_base_cbs = None
        self.v_var_base.trace_variable("w", self.__on_var_base)
Exemple #35
0
    def verifyIsoChecksum(self, src):
        import hashlib

        checksum = hashlib.md5()
        isofile = file(src, "rb")
        size = self.bytes
        total = 0

        while size:
            data = isofile.read(size)
            checksum.update(data)
            size = len(data)
            total += size
            digit  = total / self.bytes
            self.fProgressbar(self.wheel, self.tour, digit)

        print("\b\b%s." % _("Finished"))

        src_md5 = checksum.hexdigest()

        for release in releases:
            if src_md5 in release['md5']:
                return release['name'], release['md5'], release['url']

        return False
Exemple #36
0
    def on_rename_activate(self, *args):
        """Shows a dialog to rename the current tab.
        """
        entry = gtk.Entry()
        entry.set_text(self.selected_tab.get_label())
        entry.set_property("can-default", True)
        entry.show()

        vbox = gtk.VBox()
        vbox.set_border_width(6)
        vbox.show()

        dialog = gtk.Dialog(
            _("Rename tab"),
            self.window,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT),
        )

        dialog.set_size_request(300, -1)
        dialog.vbox.pack_start(vbox)
        dialog.set_border_width(4)
        dialog.set_has_separator(False)
        dialog.set_default_response(gtk.RESPONSE_ACCEPT)
        dialog.add_action_widget(entry, gtk.RESPONSE_ACCEPT)
        entry.reparent(vbox)

        response = dialog.run()
        dialog.destroy()

        if response == gtk.RESPONSE_ACCEPT:
            self.selected_tab.set_label(entry.get_text())

        self.set_terminal_focus()
Exemple #37
0
    def __createImage(self, src, dst):
        createUSBDirs(dst)

        self.utils.cprint(_("Creating boot manager..."), "yellow")
        if createSyslinux(dst):
            self.utils.cprint(_("Could not create boot manager."), "red")

            return False

        self.__copyImage(self.iso_dir, dst)

        self.utils.cprint(_("Unmounting image and USB disk..."), "green")
        unmountDirs()

        self.utils.cprint(_("USB disk is ready. Now you can install or run Pardus from your USB disk."), "brightgreen")

        return True
Exemple #38
0
    def __checkSource(self, src):
        if not os.path.isfile(src):
            self.utils.cprint(_("The path is invalid, please specify an image path."), "red")

            return False

        self.utils.cprint(_("Calculating checksum..."), "green")

        try:
            (name, md5, url) = self.progressbar.verifyIsoChecksum(src)

            self.utils.cprint(_("Source Informations:"), "brightgreen")
            self.utils.cprint("    %s:" % _("Image Path"), "green", True)
            print(src)
            self.utils.cprint("    %s:" % _("Name"), "green", True)
            print(name)
            self.utils.cprint("    Md5sum:", "green", True)
            print(md5)
            self.utils.cprint("    %s:" % _("Download URL"), "green", True)
            print(url)

            return True

        # FIX ME: Bad Code..
        except TypeError:
            self.utils.cprint(_("The checksum of the source cannot be validated. Please specify a correct source or be sure that you have downloaded the source correctly."), "red")

            return False
Exemple #39
0
    def __createImage(self, src, dst):
        createUSBDirs(dst)

        self.utils.cprint(_("Creating boot manager..."), "yellow")
        if createSyslinux(dst):
            self.utils.cprint(_("Could not create boot manager."), "red")

            return False

        self.__copyImage(MOUNT_ISO, dst)

        self.utils.cprint(_("Unmounting image..."), "green")
        cmd = "fusermount -u %s" % MOUNT_ISO

        if runCommand(cmd):
            self.utils.cprint(_("Could not unmounted image."), "red")

            return False

        if dst == MOUNT_USB:
            self.utils.cprint(_("Unmounting USB disk..."), "green")
            cmd = "umount %s" % MOUNT_USB

            if runCommand(cmd):
                self.utils.cprint(_("Could not unmounted USB disk."), "red")

                return False

        self.utils.cprint(_("USB disk is ready. Now you can install or run Pardus from your USB disk."), "brightgreen")

        return True
    def find_glade(self, basepath, glade_filename):
        """This method is based on the load_glade_file() function in VirTaal's virtaal/main_window.py."""
        for glade_dir in GLADE_DIRS:
            path = glade_dir + [glade_filename]
            file = os.path.join(basepath or os.path.dirname(__file__), *path)

            if os.path.exists(file):
                return file

        raise Exception(_('Could not find Glade file: ') + glade_filename)
Exemple #41
0
    def __init__(self, src, dst):
        self.utils = Utils()
        self.progressbar = ProgressBar(src)
        self.iso_dir = tempfile.mkdtemp(suffix="_isoPuding")

        if not dst:
            self.partutils = PartitionUtils()

            if not self.partutils.detectRemovableDrives():
                self.utils.cprint(_("USB device not found."), "red")
                sys.exit()

            else:
                device, dst = self.__askDestination()

                # FIX ME: You should not use it.
                if not dst:
                    dst = tempfile.mkdtemp(suffix="_usbPuding")
                    cmd = "mount -t vfat %s %s" % (device, dst)
                    self.utils.cprint(_("Mounting USB device..."), "green")
                    runCommand(cmd)

        self.utils.cprint(_("Mounting image..."), "green")
        cmd = "fuseiso %s %s" % (src, self.iso_dir)
        if runCommand(cmd):
            self.utils.cprint(_("Could not mounted image."), "red")

            sys.exit(1)

        if self.__checkSource(src) and self.__checkDestination(dst):
            from pardusTools import Main

            tools = Main(self.iso_dir, dst)
            if self.__checkDiskInfo(dst, tools.getTotalSize()):
                self.__createImage(src, dst)

        else:
            self.utils.cprint(_("The path you have typed as second argument is invalid. Please check the USB directory."), "red")
            unmountDirs()

            sys.exit(1)
Exemple #42
0
    def __copyImage(self, src, dst):
        # FIX ME: Now, Puding supports only Pardus..
        from pardusTools import Main

        tools = Main(src, dst)
        file_list = tools.file_list

        for path in file_list:
            file_name = os.path.split(path)[-1]
            self.utils.cprint("%s:" % _("Copying"), "green", True)
            self.utils.cprint(file_name, "brightyellow")
            tools.copyFile(path)
Exemple #43
0
    def __init__(self, src, dst):
        self.utils = Utils()
        self.progressbar = ProgressBar(src)

        if dst == None:
            self.partutils = PartitionUtils()

            if not self.partutils.detectRemovableDrives():
                self.utils.cprint(_("USB device not found."), "red")
                sys.exit()

            else:
                device, dst = self.__askDestination()

                # FIX ME: You should not use it.
                if not dst:
                    cmd = "mount -t vfat %s %s" % (device, MOUNT_USB)
                    self.utils.cprint(_("Mounting USB device..."), "green")
                    runCommand(cmd)
                    dst = MOUNT_USB

        self.utils.cprint(_("Mounting image..."), "green")
        cmd = "fuseiso %s %s" % (src, MOUNT_ISO)
        if runCommand(cmd):
            self.utils.cprint(_("Could not mounted image."), "red")

            sys.exit(1)

        if self.__checkSource(src) and self.__checkDestination(dst):
            from pardusTools import Main

            tools = Main(MOUNT_ISO, dst)
            if self.__checkDiskInfo(dst, tools.getTotalSize()):
                self.__createImage(src, dst)

        else:
            self.utils.cprint(_("The path you have typed is invalid. If you think the path is valid, make sure you have mounted USB stick to the path you gave. To check the path, you can use: mount | grep %s" % dst), "red")

            sys.exit(1)
Exemple #44
0
    def add_tab(self, directory=None):
        """Adds a new tab to the terminal notebook.
        """
        box = GuakeTerminalBox()
        box.terminal.grab_focus()
        box.terminal.connect('button-press-event', self.show_context_menu)
        box.terminal.connect('child-exited', self.on_terminal_exited, box)
        box.terminal.connect('window-title-changed', self.on_terminal_title_changed, box)
        box.show()

        self.term_list.append(box.terminal)

        # We can choose the directory to vte launch. It is important
        # to be used by dbus interface. I'm testing if directory is a
        # string because when binded to a signal, the first param can
        # be a button not a directory.
        default_params = {}
        if isinstance(directory, basestring):
            default_params['directory'] = directory

        final_params = self.get_fork_params(default_params)
        pid = box.terminal.fork_command(**final_params)
        self.pid_list.append(pid)

        self.vte_titlings.append(False) 

        # Adding a new radio button to the tabbar
        label = _('Terminal %s') % self.tab_counter
        tabs = self.tabs.get_children()
        parent = tabs and tabs[0] or None

        bnt = gtk.RadioButton(group=parent, label=label)
        bnt.set_property('can-focus', False)
        bnt.set_property('draw-indicator', False)
        bnt.connect('button-press-event', self.show_tab_menu)
        bnt.connect('button-press-event', self.show_rename_dialog)
        bnt.connect('clicked',
                    lambda *x: self.notebook.set_current_page(
                        self.notebook.page_num(box)
                    ))
        bnt.show()

        self.tabs.pack_start(bnt, expand=False, padding=1)
        self.tab_counter += 1

        self.notebook.append_page(box, None)
        self.notebook.set_current_page(self.notebook.page_num(box))
        self.load_config()
Exemple #45
0
    def on_rename_activate(self, *args):
        """Shows a dialog to rename the current tab.
        """
        pagepos = self.notebook.get_current_page()

        entry = gtk.Entry()
        entry.set_text(self.selected_tab.get_label())
        entry.set_property('can-default', True)
        entry.show()

        check = gtk.CheckButton("Use terminal title")
        check.set_active(self.vte_titlings[pagepos])
        check.show()

        vbox = gtk.VBox()
        vbox.set_border_width(6)
        vbox.show()

        dialog = gtk.Dialog(_("Rename tab"),
                            self.window,
                            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                             gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))

        dialog.set_size_request(300, -1)
        dialog.vbox.pack_start(vbox)
        dialog.set_border_width(4)
        dialog.set_has_separator(False)
        dialog.set_default_response(gtk.RESPONSE_ACCEPT)
        dialog.add_action_widget(entry, gtk.RESPONSE_ACCEPT)
        dialog.action_area.pack_end(check)
        entry.reparent(vbox)
        check.reparent(vbox)

        self.disable_losefocus_hiding = True
        response = dialog.run()
        self.disable_losefocus_hiding = False

        if response == gtk.RESPONSE_ACCEPT:
            self.selected_tab.set_label(entry.get_text())
            self.vte_titlings[pagepos] = check.get_active()
            self.on_terminal_title_changed(self.term_list[pagepos], self.notebook.get_nth_page(pagepos))

        dialog.destroy()
        self.set_terminal_focus()
Exemple #46
0
    def __checkDiskInfo(self, dst, total_size):
        (capacity, available, used) = getDiskInfo(str(dst))
        if available < total_size:
            self.utils.cprint(_("There is not enough space left on your USB stick for the image."), "red")

            self.utils.cprint(_("Unmounting image..."), "red")
            runCommand("fusermount -u %s" % MOUNT_ISO)

            return False

        self.utils.cprint(_("USB disk informations:"), "brightgreen")
        self.utils.cprint("    %s:" % _("Capacity"), "green", True)
        print("%dMB" % capacity)

        self.utils.cprint("    %s:" % _("Available"), "green", True)
        print("%dMB" % available)

        self.utils.cprint("    %s:" % _("Used"), "green", True)
        print("%dMB" % used)

        print(_("\nPlease double check your path information. If you don't type the path to the USB stick correctly, you may damage your computer. Would you like to continue?"))

        answer = raw_input("%s " % _("Please type CONFIRM to continue:"))
        if answer in (_('CONFIRM'), _('confirm')):
            self.utils.cprint(_("Writing image data to USB stick!"), "green")

            return True

        self.utils.cprint(_("You did not type CONFIRM. Exiting.."), "red")

        return False
Exemple #47
0
    with open("%s/feeds" % root, "wb") as file:
        file.write(feeds)
    # Create a backup of it too.
    with open("%s/feeds.bak" % root, "wb") as file:
        file.write(feeds)
    # Update file with new-article count.
    # This must be done only whilst the feed-list file is locked.
    with open("%s/status" % root, "wb") as file:
        file.write(status)


# Load feeds, and possiblity do more with it.
feeds = None
with touch("%s/feeds" % root) as feeds_flock:
    # Read file, with a lock on it as short as possible.
    flock(feeds_flock, False, _("Feed database is locked by another process, waiting..."))
    with open("%s/feeds" % root, "rb") as file:
        feeds = file.read()
    unflock(feeds_flock)
    # Decode and parse file.
    feeds = feeds.decode("utf-8", "strict")
    feeds = [] if len(feeds) == 0 else eval(feeds)
    # --update, --repair, --status
    if update or repair or status:
        # Get affected group.
        group = None
        for arg in args:
            if not arg.startswith("-"):
                group = arg
                break
        ### --update (fetch new articles) ###
Exemple #48
0
    def __init__(self):
        super(Guake, self).__init__(gladefile("guake.glade"))
        self.client = gconf.client_get_default()

        # setting global hotkey and showing a pretty notification =)
        globalhotkeys.init()

        # trayicon!
        img = pixmapfile("guake-tray.png")
        self.tray_icon = gtk.status_icon_new_from_file(img)
        self.tray_icon.set_tooltip(_("Guake Terminal"))
        self.tray_icon.connect("popup-menu", self.show_menu)
        self.tray_icon.connect("activate", self.show_hide)

        # adding images from a different path.
        ipath = pixmapfile("guake.png")
        self.get_widget("image1").set_from_file(ipath)
        ipath = pixmapfile("add_tab.png")
        self.get_widget("image2").set_from_file(ipath)

        # important widgets
        self.window = self.get_widget("window-root")
        self.notebook = self.get_widget("notebook-teminals")
        self.tabs = self.get_widget("hbox-tabs")
        self.toolbar = self.get_widget("toolbar")
        self.mainframe = self.get_widget("mainframe")
        self.resizer = self.get_widget("resizer")

        # check and set ARGB for real transparency
        screen = self.window.get_screen()
        colormap = screen.get_rgba_colormap()
        if colormap != None and screen.is_composited():
            self.window.set_colormap(colormap)
            self.has_argb = True
        else:
            self.has_argb = False

        # List of vte.Terminal widgets, it will be useful when needed
        # to get a widget by the current page in self.notebook
        self.term_list = []

        # This is the pid of shells forked by each terminal. Will be
        # used to kill the process when closing a tab
        self.pid_list = []

        # It's intended to know which tab was selected to
        # close/rename. This attribute will be set in
        # self.show_tab_menu
        self.selected_tab = None

        # holds the number of created tabs. This counter will not be
        # reset to avoid problems of repeated tab names.
        self.tab_counter = 0

        # holds fullscreen status
        self.fullscreen = False

        # holds the timestamp of the losefocus event
        self.losefocus_time = 0

        # double click stuff
        def double_click(hbox, event):
            """Handles double clicks on tabs area and when receive
            one, calls add_tab.
            """
            if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
                self.add_tab()

        evtbox = self.get_widget("event-tabs")
        evtbox.connect("button-press-event", double_click)

        # Flag to prevent guake hide when window_losefocus is true and
        # user tries to use the context menu.
        self.showing_context_menu = False

        def hide_context_menu(menu):
            """Turn context menu flag off to make sure it is not being
            shown.
            """
            self.showing_context_menu = False

        self.get_widget("context-menu").connect("hide", hide_context_menu)
        self.get_widget("tab-menu").connect("hide", hide_context_menu)
        self.window.connect("focus-out-event", self.on_window_losefocus)

        # this line is important to resize the main window and make it
        # smaller.
        self.window.set_geometry_hints(min_width=1, min_height=1)

        # resizer stuff
        self.resizer.connect("motion-notify-event", self.on_resizer_drag)

        # adding the first tab on guake
        self.add_tab()

        # loading and setting up configuration stuff
        GConfHandler(self)
        GConfKeyHandler(self)
        self.hotkeys = globalhotkeys.GlobalHotkey()
        self.load_config()

        key = self.client.get_string(GKEY("show_hide"))
        keyval, mask = gtk.accelerator_parse(key)
        label = gtk.accelerator_get_label(keyval, mask)
        filename = pixmapfile("guake-notification.png")

        if not self.hotkeys.bind(key, self.show_hide):
            notification = pynotify.Notification(
                _("Guake!"),
                _(
                    "A problem happened when binding <b>%s</b> key.\n"
                    "Please use Guake Preferences dialog to choose another "
                    "key (The trayicon was enabled)"
                )
                % label,
                filename,
            )
            self.client.set_bool(KEY("/general/use_trayicon"), True)
            notification.show()

        elif self.client.get_bool(KEY("/general/use_popup")):
            # Pop-up that shows that guake is working properly (if not
            # unset in the preferences windows)
            notification = pynotify.Notification(
                _("Guake!"), _("Guake is now running,\n" "press <b>%s</b> to use it.") % label, filename
            )
            notification.show()
Exemple #49
0
def load_feed(id):
    '''
    Load the feeds
    
    @param   id:str                                    The ID of the feed
    @return  :(entries:itr<dict<str, int|str|↑>>,      Feed entries
               years:dict<str|int, int|str|↑|itr<↑>>,  Mapping for dates to branches in `entries`,
                                                       `years[2014][11][25]['inner']` lists all feeds entries
                                                       for 2014-(11)Nov-25.
               have:set<str>,                          A set of all ID:s of the leaves in `entries`
               unread:set<str>)                        A set of all ID:s of the read leaves in `entries`
    '''
    next_id = 0
    entries = []
    years = {}
    have, unread = set(), set()
    with touch('%s/%s' % (root, id)) as feed_flock:
        # Read files.
        flock(feed_flock, False, _('The feed is locked by another process, waiting...'))
        feed_info, feed_data = None, None
        if os.access('%s/%s' % (root, id), os.F_OK):
            with open('%s/%s' % (root, id), 'rb') as file:
                feed_info = file.read()
            if os.access('%s/%s-content' % (root, id), os.F_OK):
                with open('%s/%s-content' % (root, id), 'rb') as file:
                    feed_data = file.read()
            unflock(feed_flock)
        
        # Decode and parse metadata file.
        feed_info = feed_info.decode('utf-8', 'strict')
        feed_info = eval(feed_info) if len(feed_info) > 0 else {}
        have   = set() if 'have'   not in feed_info else feed_info['have']
        unread = set() if 'unread' not in feed_info else feed_info['unread']
        
        # Construct tree.
        if feed_data is not None:
            feed_data = eval(feed_data.decode('utf-8', 'strict'))
            for entry in feed_data:
                entry['id'] = entry['guid']
                # Set new-article-count on the article itself.
                entry['new'] = 1 if entry['guid'] in unread else 0
                # Get publication/retrieval time.
                pubdate = entry['pubdate']
                entry['time'] = (pubdate[3] * 60 + pubdate[4]) * 100 + pubdate[5]
                # Get title.
                entry['realtitle'] = entry['title']
                title = entry['title'].split('\n')[0]
                entry['title'] = '(%02i:%02i:%02i) %s' % (pubdate[3], pubdate[4], pubdate[5], title)
                # Year branch.
                if pubdate[0] not in years:
                    year_entry = {}
                    years[pubdate[0]] = year_entry
                    entries.append(year_entry)
                    year_entry['year'] = pubdate[0]
                    year_entry['title'] = _('Year %i') % pubdate[0]
                    year_entry['inner'] = []
                    year_entry['id'] = next_id
                    next_id += 1
                # Month branch.
                months = years[pubdate[0]]
                if pubdate[1] not in months:
                    month_entry = {}
                    months[pubdate[1]] = month_entry
                    months['inner'].append(month_entry)
                    month_entry['year'] = pubdate[0]
                    month_entry['month'] = pubdate[1]
                    month_entry['title'] = MONTHS[pubdate[1]] if pubdate[1] in MONTHS else str(pubdate[1])
                    month_entry['inner'] = []
                    month_entry['id'] = next_id
                    next_id += 1
                # Day branch.
                days = months[pubdate[1]]
                if pubdate[2] not in days:
                    day_entry = {}
                    days[pubdate[2]] = day_entry
                    days['inner'].append(day_entry)
                    day_entry['year'] = pubdate[0]
                    day_entry['month'] = pubdate[1]
                    day_entry['day'] = pubdate[2]
                    title =  MONTHS[pubdate[1]][:3] if pubdate[1] in MONTHS else ''
                    title = '%03i-(%02i)%s-%02i' % (pubdate[0], pubdate[1], title, pubdate[2])
                    day_entry['title'] = title
                    day_entry['inner'] = []
                    day_entry['id'] = next_id
                    next_id += 1
                # Add article to day branch.
                days[pubdate[2]]['inner'].append(entry)
                # Colour nodes.
                ancestors = [year_entry, month_entry, day_entry]
                colour = entry['colour'] if 'colour' in entry else ...
                colour_propagation(ancestors, colour, None)
    
    # Sort the tree.
    entries.sort(key = lambda x : -(x['year']))
    for year in entries:
        year['inner'].sort(key = lambda x : -(x['month']))
        for month in year['inner']:
            month['inner'].sort(key = lambda x : -(x['day']))
            for day in month['inner']:
                day['inner'].sort(key = lambda x : -(x['time']))
    
    return (entries, years, have, unread)
Exemple #50
0
def open_feed(feed_node, callback):
    '''
    Inspect a feed
    
    @param   feed_node:dict<str, _|str>  The node in the feed tree we the feed we are inspecting
    @param   callback:(:int)→void        Notify the previous tree about an update, the parameter
                                         specifies how much should be added to ['new']
    @return  :bool                       Whether the entire program should exit
    '''
    id = feed_node['id']
    (entries, years, have, unread) = load_feed(id)
    tree = Tree(feed_node['title'], entries)
    
    def get_nodes(node, qualifier):
        '''
        List all node inside, directly or indirectly, a node,
        that passes a test
        
        @param   node:dict<str, _|list<↑>>?       Node from which to start enumeration
        @param   qualifier:(dict<str, _|↑>)→bool  Should return truth for nodes to return
        @return  :list<dict<str, _|↑>>            Found nodes that qualified
        '''
        nodes = []
        # At leaf.
        if (node is not None) and ('inner' not in node):
            # List node if it qualifies
            if qualifier(node):
                nodes.append(node)
        # At root or branch?
        else:
            # Visit children.
            inners = node['inner'] if node is not None else entries
            for inner in inners:
                nodes += get_nodes(inner, qualifier)
        return nodes
    
    def read_unread(mod, nodes):
        '''
        Mark nodes and their children as either read or unread
        
        @param  mod:`-1`|`+1`              -1 to mark as read, +1 to mark as unread
        @param  nodes:itr<dict<str, _|↑>>  Nodes to mark as read or unread
        '''
        # Get GUID:s of articles to update.
        guids = [node['guid'] for node in nodes]
        # Calls a given for all nodes that qualifies.
        def update(f, qualifer):
            [f(guid) for guid in guids if qualifer(guid)]
        # Mark as unread?
        if mod == 1:
            # Update tree.
            updated = update_entries(id, lambda _, unread : update(unread.add, lambda g : g not in unread))
            # Update 'unread'-set.
            [unread.add(guid) for guid in guids if guid not in unread]
        # Mark as read?
        elif mod == -1:
            # Update tree.
            updated = update_entries(id, lambda _, unread : update(unread.remove, lambda g : g in unread))
            # Update 'unread'-set.
            [unread.remove(guid) for guid in guids if guid in unread]
        else:
            # Never reached.
            return
        # Update new-article-counter for thee feed (root).
        tree.count += mod * len(guids)
        # Update nodes.
        for node in nodes:
            # Find ancestors.
            pubdate = node['pubdate']
            ancestors = [years[pubdate[0]]]
            while len(ancestors) < 3:
                ancestors.append(ancestors[-1][pubdate[len(ancestors)]])
            ancestors.append(node) # ... and the nodes themself.
            # Things will have to be redrawn.
            for node in ancestors:
                node['new'] += mod # Update new-artice-counter for all ancestors.
                node['draw_line'] = -1
            tree.redraw_root = True
        # Save changes to the feed tree, and feed list file.
        if updated:
            callback(mod * len(guids))
    
    # Session.
    while True:
        # Get input command from user.
        (action, node) = tree.interact()
        # Exit.
        if action == 'quit':
            return True
        # Back to the first page.
        elif action == 'back':
            return False
        # Edit article.
        elif action == 'edit':
            if (node is None) or ('inner' in node):
                # We can only edit articles, not the root or year-, month- or date-branches.
                continue
            table = {'Title' : node['realtitle'].split('\n')[0]}
            values = {}
            saved = False
            # Callback-function, for the editor, used to retrieve the changes.
            def saver():
                nonlocal table, saved, values
                values['title'] = table['Title']
                saved = True
                return True
            # Open editor.
            text_area = TextArea(['Title'], table)
            text_area.initialise(False)
            print('\033[?25h\033[?9l', end = '', flush = True)
            text_area.run(saver)
            print('\033[?9h\033[?25l', end = '', flush = True)
            text_area.close()
            # Restore locale, if editor change it.
            gettext.textdomain('@PKGNAME@')
            # Any changes?
            if saved:
                # Apply them.
                node['realtitle'] = values['title']
                pubdate = node['pubdate']
                pubdate = '%02i:%02i:%02i' % (pubdate[3], pubdate[4], pubdate[5])
                node['title'] = '(%s) %s' % (pubdate, values['title'])
                modify_entry(id, {node['guid'] : values})
            # Redraw the screen, now that there is not editor open anymore.
            print('\033[H\033[2J', end = '', flush = True)
            tree.draw_force = True
        # Read article.
        elif action == 'open':
            if (node is None) or ('inner' in node):
                # We can only read articles, not the root or year-, month- or date-branches.
                continue
            # Get link and description (content) of article.
            description = ''
            if 'link' in node:
                description += '%s<br><br>' % (_('Link: %s') % node['link'])
            if 'description' in node:
                description += node['description']
            description = description.encode('utf-8')
            # Convert from HTML to pony-readable format.
            proc = ['html2text'] ## Well that (markdown (in new versions)) isn't really readable, but we will soon do something about that.
            if ('FEATHERWEIGHT_HTML' in os.environ) and (not os.environ['FEATHERWEIGHT_HTML'] == ''):
                proc = ['sh', '-c', os.environ['FEATHERWEIGHT_HTML']]
            proc = Popen(proc, stdin = PIPE, stdout = PIPE, stderr = sys.stderr)
            description = proc.communicate(description)[0]
            # Get pager.
            pager = os.environ['PAGER'] if 'PAGER' in os.environ else None
            pager = None if pager == '' else pager
            # No pager specified?
            if pager is None:
                # That's okay, just search PATH for one.
                path = os.environ['PATH'] if 'PATH' in os.environ else None
                if path is not None:
                    path = path.split(':')
                    for pg in ['less', 'more', 'most', 'pg']:
                        for p in path:
                            if os.access('%s/%s' % (p, pg), os.X_OK):
                                pager = pg
                                break
                        if pager is not None:
                            break
            # Do we have a pager?
            if pager is not None:
                # Use the pager.
                print('\033[H\033[2J\033[?9l\033[?25h\033[?1049l', end = '', flush = True)
                proc = Popen(['sh', '-c', pager], stdin = PIPE, stdout = sys.stdout, stderr = sys.stderr)
                proc.communicate(description)
                print('\033[?1049h\033[?25l\033[?9h\033[H\033[2J', end = '', flush = True)
            # No pager?
            else:
                # Act as a dumb pager.
                print('\033[H\033[2J\033[?9l', end = '', flush = True)
                sys.stdout.buffer.write(description)
                sys.stdout.buffer.flush()
                while sys.stdin.read(1)[0] != '\n':
                    pass
                print('\033[?9h\033[H\033[2J', end = '', flush = True)
            # Redraw the screen, now that there is not an article on it anymore.
            tree.draw_force = True
        # Add node.
        elif action == 'add':
            # “Add”, add what?
            pass
        # Move node upward, downward, outward, or inward.
        elif action in ('up', 'down', 'out', 'in'):
            # Cannot reorder nodes, they are sorted.
            pass
        # Delete node.
        elif action == 'delete':
            if node is None:
                # Cannot delete root here, go to the previous page for that.
                continue
            # Confirm action.
            Popen(['stty', 'echo', 'icanon'], stdout = PIPE, stderr = PIPE).communicate()
            print('\033[H\033[2J\033[?25h\033[?9l%s' % (_('Are you sure you to delete %s?') % double_quote(node['title'])))
            print(_('Type %s, if you are sure.') % quote(_('yes')))
            delete = sys.stdin.readline().replace('\n', '') == _('yes')
            Popen(['stty', '-echo', '-icanon'], stdout = PIPE, stderr = PIPE).communicate()
            print('\033[?25l\033[?9h', end = '', flush = True)
            print('\033[H\033[2J', end = '', flush = True)
            # Redraw the screen, now that there is no dialogue on it.
            tree.draw_force = True
            # Did the user change her mind?
            if not delete:
                continue
            # Mark everything in the node read. (To keep track of new-article-count.)
            read_unread(-1, get_nodes(node, lambda n : n['new'] == 1))
            # Get articles to delete.
            guids = [n['guid'] for n in get_nodes(node, lambda _ : True)]
            # Delete articles.
            delete_entry_content(id, set(guids))
            def delete_node(nodes, node_id):
                for i in range(len(nodes)):
                    # Is is this node?
                    if nodes[i]['id'] == node_id:
                        # Delete it, and pop the selection stack.
                        del nodes[i]
                        tree.select_stack.pop()
                        return True
                    # Is this a branch?
                    elif 'inner' in nodes[i]:
                        # Visit children.
                        if delete_node(nodes[i]['inner'], node_id):
                            # Found it.
                            # Did the parent become childless?
                            if len(nodes[i]['inner']) == 0:
                                # Delete it and pop the stack.
                                del nodes[i]
                                tree.select_stack.pop()
                            return True
                # No luck. Search next child.
                return False
            delete_node(entries, node['id'])
        # Mark node, and its children, as read.
        elif action == 'read':
            read_unread(-1, get_nodes(node, lambda n : n['new'] == 1))
        # Mark node, and its children, as unread.
        elif action == 'unread':
            read_unread(+1, get_nodes(node, lambda n : n['new'] == 0))
        # Colour node.
        elif action in '012345678':
            if (node is None) or ('inner' in node):
                # Cannot colour root, or branch directly.
                continue
            # Get desired and current colour.
            action = ... if action == '0' else (int(action) % 8)
            old_colour = node['colour'] if 'colour' in node else ...
            if old_colour is None: # Who knows that the user may do.
                old_colour = '...'
            if action == old_colour:
                # Why continue if the colour will not change?
                continue
            # Apply colour.
            modify_entry(id, {node['guid'] : {'colour' : action}})
            if action == ...:
                del node['colour']
            else:
                node['colour'] = action
            # Request redraw of node.
            node['draw_line'] = -1
            # List ancestors.
            pubdate = node['pubdate']
            ancestors = [years[pubdate[0]]]
            while len(ancestors) < 3:
                ancestors.append(ancestors[-1][pubdate[len(ancestors)]])
            # Propagate colour ancestors, as appropriate.
            colour_propagation(ancestors, colour, old_colour)
Exemple #51
0
def main():
    """Parses the command line parameters and decide if dbus methods
    should be called or not. If there is already a guake instance
    running it will be used and a True value will be returned,
    otherwise, false will be returned.
    """
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-t', '--toggle-visibility', dest='show_hide',
            action='store_true', default=False,
            help=_('Toggles the visibility of the terminal window'))

    parser.add_option('-p', '--preferences', dest='show_preferences',
            action='store_true', default=False,
            help=_('Shows Guake preference window'))

    parser.add_option('-a', '--about', dest='show_about',
            action='store_true', default=False,
            help=_('Shows Guake\'s about info'))

    parser.add_option('-n', '--new-tab', dest='new_tab',
            action='store', default='',
            help=_('Add a new tab'))

    parser.add_option('-s', '--select-tab', dest='select_tab',
            action='store', default='',
            help=_('Select a tab'))

    parser.add_option('-g', '--selected-tab', dest='selected_tab',
            action='store_true', default=False,
            help=_('Return the selectd tab index.'))

    parser.add_option('-e', '--execute-command', dest='command',
            action='store', default='',
            help=_('Execute an arbitrary command in the selected tab.'))

    parser.add_option('-r', '--rename-tab', dest='rename_tab',
            action='store', default='',
            help=_('Rename the selected tab.'))

    parser.add_option('-q', '--quit', dest='quit',
            action='store_true', default=False,
            help=_('Says to Guake go away =('))

    options = parser.parse_args()[0]

    # Trying to get an already running instance of guake. If it is not
    # possible, lets create a new instance. This function will return
    # a boolean value depending on this decision.
    try:
        bus = dbus.SessionBus()
        remote_object = bus.get_object(DBUS_NAME, DBUS_PATH)
        already_running = True
    except dbus.DBusException:
        instance = Guake()
        remote_object = DbusManager(instance)
        already_running = False

    called_with_param = False

    if options.show_hide:
        remote_object.show_hide()
        called_with_param = True

    if options.show_preferences:
        remote_object.show_prefs()
        called_with_param = True

    if options.new_tab:
        remote_object.add_tab(options.new_tab)
        called_with_param = True

    if options.select_tab:
        selected = int(options.select_tab)
        remote_object.select_tab(selected)
        called_with_param = True

    if options.selected_tab:
        selected = remote_object.get_selected_tab()
        sys.stdout.write('%d\n' % selected)
        called_with_param = True

    if options.command:
        remote_object.execute_command(options.command)
        called_with_param = True

    if options.rename_tab:
        remote_object.rename_current_tab(options.rename_tab)
        called_with_param = True

    if options.show_about:
        remote_object.show_about()
        called_with_param = True

    if options.quit:
        remote_object.quit()
        called_with_param = True

    if not called_with_param and already_running:
        # here we know that guake was called without any parameter and
        # it is already running, so, lets toggle its visibility.
        remote_object.show_hide()

    return already_running
Exemple #52
0
        called_with_param = True

    if options.rename_tab:
        remote_object.rename_current_tab(options.rename_tab)
        called_with_param = True

    if options.show_about:
        remote_object.show_about()
        called_with_param = True

    if options.quit:
        remote_object.quit()
        called_with_param = True

    if not called_with_param and already_running:
        # here we know that guake was called without any parameter and
        # it is already running, so, lets toggle its visibility.
        remote_object.show_hide()

    return already_running


if __name__ == "__main__":
    if not test_gconf():
        raise ShowableError(
            _("Guake can not init!"), _("Gconf Error.\n" "Have you installed <b>guake.schemas</b> properlly?")
        )

    if not main():
        gtk.main()
Exemple #53
0
    def __init__(self):
        super(Guake, self).__init__(gladefile('guake.glade'))
        self.client = gconf.client_get_default()

        # setting global hotkey and showing a pretty notification =)
        globalhotkeys.init()

        # trayicon!
        img = pixmapfile('guake-tray.png')
        self.tray_icon = gtk.status_icon_new_from_file(img)
        self.tray_icon.set_tooltip(_('Guake-Terminal'))
        self.tray_icon.connect('popup-menu', self.show_menu)
        self.tray_icon.connect('activate', self.show_hide)

        # adding images from a different path.
        ipath = pixmapfile('guake.png')
        self.get_widget('image1').set_from_file(ipath)
        ipath = pixmapfile('add_tab.png')
        self.get_widget('image2').set_from_file(ipath)

        # important widgets
        self.window = self.get_widget('window-root')
        self.notebook = self.get_widget('notebook-teminals')
        self.tabs = self.get_widget('hbox-tabs')
        self.toolbar = self.get_widget('toolbar')
        self.mainframe = self.get_widget('mainframe')
        self.resizer = self.get_widget('resizer')

        # check and set ARGB for real transparency
        screen = self.window.get_screen()
        colormap = screen.get_rgba_colormap()
        if colormap != None and screen.is_composited():
            self.window.set_colormap(colormap)
            self.has_argb = True
        else:
            self.has_argb = False

        # List of vte.Terminal widgets, it will be useful when needed
        # to get a widget by the current page in self.notebook
        self.term_list = []

        # This is the pid of shells forked by each terminal. Will be
        # used to kill the process when closing a tab
        self.pid_list = []

        # It's intended to know which tab was selected to
        # close/rename. This attribute will be set in
        # self.show_tab_menu
        self.selected_tab = None

        # holds the number of created tabs. This counter will not be
        # reset to avoid problems of repeated tab names.
        self.tab_counter = 0

        # holds fullscreen status
        self.fullscreen = False

        # holds the timestamp of the losefocus event
        self.losefocus_time = 0

        # double click stuff
        def double_click(hbox, event):
            """Handles double clicks on tabs area and when receive
            one, calls add_tab.
            """
            if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
                self.add_tab()
        evtbox = self.get_widget('event-tabs')
        evtbox.connect('button-press-event', double_click)

        # Flag to prevent guake hide when window_losefocus is true and
        # user tries to use the context menu.
        self.showing_context_menu = False
        def hide_context_menu(menu):
            """Turn context menu flag off to make sure it is not being
            shown.
            """
            self.showing_context_menu = False
        self.get_widget('context-menu').connect('hide', hide_context_menu)
        self.get_widget('tab-menu').connect('hide', hide_context_menu)
        self.window.connect('focus-out-event', self.on_window_losefocus)

        # this line is important to resize the main window and make it
        # smaller.
        self.window.set_geometry_hints(min_width=1, min_height=1)

        # resizer stuff
        self.resizer.connect('motion-notify-event', self.on_resizer_drag)

        # loading and setting up configuration stuff
        GConfHandler(self)
        GConfKeyHandler(self)
        self.hotkeys = globalhotkeys.GlobalHotkey()
        self.load_config()

        key = self.client.get_string(GKEY('show_hide'))
        keyval, mask = gtk.accelerator_parse(key)
        self.notification_label = gtk.accelerator_get_label(keyval, mask)
        self.notification_pixmapfile = pixmapfile('guake-notification.png')

        if not self.hotkeys.bind(key, self.show_hide):
            self.show_notification('A problem happened when binding <b>%s</b> key.\n'
                  'Please use Guake Preferences dialog to choose another '
                  'key (The trayicon was enabled)')
            self.client.set_bool(KEY('/general/use_trayicon'), True)
            
        # add tabs remembered from last session
        try:
            guake_tabs = open(os.path.expanduser('~/.guake_tabs'), 'r')
            for line in guake_tabs:
                tname, tdir = line.rstrip('\n').split('\t')
                self.add_tab(tdir, tname)
            guake_tabs.close()
        except:
            # not there? not readable? add failed?
            pass
        
        if not self.term_list:
            self.add_tab()
Exemple #54
0
        remote_object.execute_command(options.command)
        called_with_param = True

    if options.rename_tab:
        remote_object.rename_current_tab(options.rename_tab)
        called_with_param = True

    if options.show_about:
        remote_object.show_about()
        called_with_param = True

    if options.quit:
        remote_object.quit()
        called_with_param = True

    if not called_with_param and already_running:
        # here we know that guake was called without any parameter and
        # it is already running, so, lets toggle its visibility.
        remote_object.show_hide()

    return already_running

if __name__ == '__main__':
    if not test_gconf():
        raise ShowableError(_('Guake can not init!'),
            _('Gconf Error.\n'
              'Have you installed <b>guake.schemas</b> properlly?'))

    if not main():
        gtk.main()
Exemple #55
0
def main():
    """Parses the command line parameters and decide if dbus methods
    should be called or not. If there is already a guake instance
    running it will be used and a True value will be returned,
    otherwise, false will be returned.
    """
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option(
        "-t",
        "--toggle-visibility",
        dest="show_hide",
        action="store_true",
        default=False,
        help=_("Toggles the visibility of the terminal window"),
    )

    parser.add_option(
        "-p",
        "--preferences",
        dest="show_preferences",
        action="store_true",
        default=False,
        help=_("Shows Guake preference window"),
    )

    parser.add_option(
        "-a", "--about", dest="show_about", action="store_true", default=False, help=_("Shows Guake's about info")
    )

    parser.add_option("-n", "--new-tab", dest="new_tab", action="store", default="", help=_("Add a new tab"))

    parser.add_option("-s", "--select-tab", dest="select_tab", action="store", default="", help=_("Select a tab"))

    parser.add_option(
        "-g",
        "--selected-tab",
        dest="selected_tab",
        action="store_true",
        default=False,
        help=_("Return the selectd tab index."),
    )

    parser.add_option(
        "-e",
        "--execute-command",
        dest="command",
        action="store",
        default="",
        help=_("Execute an arbitrary command in the selected tab."),
    )

    parser.add_option(
        "-r", "--rename-tab", dest="rename_tab", action="store", default="", help=_("Rename the selected tab.")
    )

    parser.add_option(
        "-q", "--quit", dest="quit", action="store_true", default=False, help=_("Says to Guake go away =(")
    )

    options = parser.parse_args()[0]

    # Trying to get an already running instance of guake. If it is not
    # possible, lets create a new instance. This function will return
    # a boolean value depending on this decision.
    try:
        bus = dbus.SessionBus()
        remote_object = bus.get_object(DBUS_NAME, DBUS_PATH)
        already_running = True
    except dbus.DBusException:
        instance = Guake()
        remote_object = DbusManager(instance)
        already_running = False

    called_with_param = False

    if options.show_hide:
        remote_object.show_hide()
        called_with_param = True

    if options.show_preferences:
        remote_object.show_prefs()
        called_with_param = True

    if options.new_tab:
        remote_object.add_tab(options.new_tab)
        called_with_param = True

    if options.select_tab:
        selected = int(options.select_tab)
        remote_object.select_tab(selected)
        called_with_param = True

    if options.selected_tab:
        selected = remote_object.get_selected_tab()
        sys.stdout.write("%d\n" % selected)
        called_with_param = True

    if options.command:
        remote_object.execute_command(options.command)
        called_with_param = True

    if options.rename_tab:
        remote_object.rename_current_tab(options.rename_tab)
        called_with_param = True

    if options.show_about:
        remote_object.show_about()
        called_with_param = True

    if options.quit:
        remote_object.quit()
        called_with_param = True

    if not called_with_param and already_running:
        # here we know that guake was called without any parameter and
        # it is already running, so, lets toggle its visibility.
        remote_object.show_hide()

    return already_running