コード例 #1
0
    def _export_protocol(self):
        app = get_app()

        filter_ = gtk.FileFilter()
        filter_.set_name(' MicroDrop protocols (*.json)')
        filter_.add_pattern("*.json")

        dialog = gtk.FileChooserDialog(
            title="Export protocol",
            action=gtk.FILE_CHOOSER_ACTION_SAVE,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,
                     gtk.RESPONSE_OK))
        dialog.add_filter(filter_)
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_current_name(app.protocol.name)
        dialog.set_current_folder(
            os.path.join(app.get_device_directory(), app.dmf_device.name,
                         "protocols"))
        response = dialog.run()
        try:
            if response == gtk.RESPONSE_OK:
                filename = ph.path(dialog.get_filename())
                if filename.ext.lower() != '.json':
                    filename = filename + '.json'
                logger = _L()  # use logger with method context
                try:
                    with open(filename, 'w') as output:
                        protocol_dict_to_json(upgrade_protocol(app.protocol),
                                              ostream=output,
                                              validate=False,
                                              json_kwargs={'indent': 2})
                except md.protocol.SerializationError, exception:
                    plugin_exception_counts = Counter(
                        [e['plugin'] for e in exception.exceptions])
                    logger.info('%s: `%s`', exception, exception.exceptions)
                    result = yesno(
                        'Error exporting data for the following '
                        'plugins: `%s`\n\n'
                        'Would you like to exclude this data and '
                        'export anyway?' %
                        ', '.join(sorted(plugin_exception_counts.keys())))
                    if result == gtk.RESPONSE_YES:
                        # Delete plugin data that is causing serialization
                        # errors.
                        protocol = copy.deepcopy(app.protocol)
                        protocol.remove_exceptions(exception.exceptions,
                                                   inplace=True)
                        with open(filename, 'w') as output:
                            protocol_dict_to_json(upgrade_protocol(
                                app.protocol),
                                                  ostream=output,
                                                  validate=False,
                                                  json_kwargs={'indent': 2})
                    else:
                        # Abort export.
                        logger.warn('Export cancelled.')
                        return
                logger.info('exported protocol to %s', filename)
                app = get_app()
                parent_window = app.main_window_controller.view
                message = 'Exported protocol to:\n\n%s' % filename
                ok_dialog = gtk.MessageDialog(parent=parent_window,
                                              message_format=message,
                                              type=gtk.MESSAGE_OTHER,
                                              buttons=gtk.BUTTONS_OK)
                # Increase default dialog size.
                ok_dialog.set_size_request(450, 150)
                ok_dialog.props.title = 'Export complete'
                ok_dialog.props.use_markup = True
                ok_dialog.run()
                ok_dialog.destroy()
        finally:
            dialog.destroy()
コード例 #2
0
    def _on_button_save_clicked(self, widget):
        log.debug("_on_button_save_clicked")
        if len(self.files_treestore) == 0:
            return

        is_remote = self.files_treestore[0][1] == gtk.STOCK_NETWORK
        if is_remote:
            # This is a remote path
            dialog = self.glade.get_widget("remote_save_dialog")
            dialog_save_path = self.glade.get_widget("entry_save_path")
            dialog_save_path.set_text(
                self.files_treestore[0][0].rstrip("\\/") + ".torrent")
            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                result = dialog_save_path.get_text()
            else:
                dialog.hide()
                return
            dialog.hide()
        else:
            # Setup the filechooserdialog
            chooser = gtk.FileChooserDialog(
                _("Save .torrent file"),
                self.dialog,
                gtk.FILE_CHOOSER_ACTION_SAVE,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,
                         gtk.RESPONSE_OK))

            chooser.set_transient_for(self.dialog)
            chooser.set_select_multiple(False)
            chooser.set_property("skip-taskbar-hint", True)

            # Add .torrent and * file filters
            file_filter = gtk.FileFilter()
            file_filter.set_name(_("Torrent files"))
            file_filter.add_pattern("*." + "torrent")
            chooser.add_filter(file_filter)
            file_filter = gtk.FileFilter()
            file_filter.set_name(_("All files"))
            file_filter.add_pattern("*")
            chooser.add_filter(file_filter)

            chooser.set_current_name(
                os.path.split(self.files_treestore[0][0])[-1] + ".torrent")
            # Run the dialog
            response = chooser.run()

            if response == gtk.RESPONSE_OK:
                result = chooser.get_filename()
            else:
                chooser.destroy()
                return
            chooser.destroy()

        # Fix up torrent filename
        if len(result) < 9:
            result += ".torrent"
        elif result[-8:] != ".torrent":
            result += ".torrent"

        # Get the path
        path = self.files_treestore[0][0]
        # Get a list of trackers
        trackers = []
        if not len(self.trackers_liststore):
            tracker = None
        else:
            # Create a list of lists [[tier0, ...], [tier1, ...], ...]
            tier_dict = {}
            for tier, tracker in self.trackers_liststore:
                tier_dict.setdefault(tier, []).append(tracker)

            trackers = [tier_dict[tier] for tier in sorted(tier_dict)]
            # Get the first tracker in the first tier
            tracker = trackers[0][0]

        # Get a list of webseeds
        webseeds = []
        b = self.glade.get_widget("textview_webseeds").get_buffer()
        lines = b.get_text(b.get_start_iter(),
                           b.get_end_iter()).strip().split("\n")
        import deluge.common
        for l in lines:
            if deluge.common.is_url(l):
                webseeds.append(l)
        # Get the piece length in bytes
        combo = self.glade.get_widget("combo_piece_size")
        piece_length = \
            self.parse_piece_size_text(combo.get_model()[combo.get_active()][0])
        num_pieces = self.files_treestore[0][2] / piece_length

        author = self.glade.get_widget("entry_author").get_text()
        comment = self.glade.get_widget("entry_comments").get_text()
        private = self.glade.get_widget("chk_private_flag").get_active()
        add_to_session = self.glade.get_widget(
            "chk_add_to_session").get_active()

        if is_remote:
            client.core.create_torrent(path, tracker, piece_length, comment,
                                       result, webseeds, private, author,
                                       trackers, add_to_session)

        else:
            # Setup progress dialog
            self.glade.get_widget("progress_dialog").set_transient_for(
                component.get("MainWindow").window)
            self.glade.get_widget("progress_dialog").show_all()

            def hide_progress(result):
                self.glade.get_widget("progress_dialog").hide_all()

            deferToThread(self.create_torrent, path.decode('utf-8'), tracker,
                          piece_length,
                          self._on_create_torrent_progress, comment,
                          result.decode('utf-8'), webseeds, private, author,
                          trackers, add_to_session).addCallback(hide_progress)

        self.dialog.destroy()
コード例 #3
0
    def newChannel(self):
        self.enableDisable()

        method = MethodSelector().show()
        if not method:
            return

        editor = ChannelEditor()

        path = None
        removable = []

        if method == "manual":

            type = TypeSelector().show()
            if not type:
                return

            newchannel = {"type": type}
            if editor.show(None, newchannel, editalias=True):
                alias = newchannel["alias"]
                del newchannel["alias"]
                sysconf.set(("channels", alias),
                            parseChannelData(newchannel))
                self._changed = True
                if newchannel.get("removable"):
                    removable.append(alias)

        elif method in ("descriptionpath", "descriptionurl"):

            if method == "descriptionpath":
                if gtk.pygtk_version > (2,4,0):
                    dia = gtk.FileChooserDialog(
                        action=gtk.FILE_CHOOSER_ACTION_OPEN,
                        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                 gtk.STOCK_OK, gtk.RESPONSE_OK))
                                 
                else:
                    dia = gtk.FileSelection(_("Select Channel Description"))
                    dia.hide_fileop_buttons()
                response = dia.run()
                filename = dia.get_filename()
                dia.destroy()
                if response != gtk.RESPONSE_OK:
                    return
                if not os.path.isfile(filename):
                    iface.error(_("File not found: %s") % filename)
                    return
                file = open(filename)
                data = file.read()
                file.close()
            elif method == "descriptionurl":
                url = iface.askInput(_("Description URL"))
                if not url:
                    return
                ctrl = iface.getControl()
                succ, fail = ctrl.downloadURLs([url], _("channel description"))
                if fail:
                    iface.error(_("Unable to fetch channel description: %s")
                                % fail[url])
                    return
                file = open(succ[url])
                data = file.read()
                file.close()
                if succ[url].startswith(sysconf.get("data-dir")):
                    os.unlink(succ[url])
            
            newchannels = parseChannelsDescription(data)
            for alias in newchannels:
                newchannel = newchannels[alias]
                if editor.show(alias, newchannel, editalias=True):
                    alias = newchannel["alias"]
                    del newchannel["alias"]
                    sysconf.set(("channels", alias),
                                parseChannelData(newchannel))
                    self._changed = True
                    if newchannel.get("removable"):
                        removable.append(alias)

        elif method in ("detectmedia", "detectpath"):

            if method == "detectmedia":
                path = MountPointSelector().show()
                if not path:
                    return
            elif method == "detectpath":
                if gtk.pygtk_version > (2,4,0):
                    dia = gtk.FileChooserDialog(
                        action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                 gtk.STOCK_OK, gtk.RESPONSE_OK))
                                 
                else:
                    dia = gtk.FileSelection(_("Select Path"))
                    dia.hide_fileop_buttons()
                response = dia.run()
                path = dia.get_filename()
                dia.destroy()
                if response != gtk.RESPONSE_OK:
                    return
                if not os.path.isdir(path):
                    iface.error(_("Directory not found: %s") % path)
                    return

            sysconf.set("default-localmedia", path, soft=True)

            foundchannel = False
            for newchannel in detectLocalChannels(path):
                foundchannel = True
                if editor.show(newchannel.get("alias"), newchannel,
                               editalias=True):
                    alias = newchannel["alias"]
                    del newchannel["alias"]
                    sysconf.set(("channels", alias),
                                parseChannelData(newchannel))
                    self._changed = True
                    if newchannel.get("removable"):
                        removable.append(alias)
            
            if not foundchannel:
                iface.error(_("No channels detected!"))
                return

        if removable:
            ctrl = iface.getControl()
            ctrl.rebuildSysConfChannels()
            channels = [x for x in ctrl.getChannels()
                        if x.getAlias() in removable]
            iface.updateChannels(channels=channels)

        if path:
            sysconf.remove("default-localmedia", soft=True)

        if self._changed:
            self.fill()
コード例 #4
0
#!/usr/bin/env python

import gtk
import os
import gettext
import locale

home = os.path.expanduser("~")
gettext.install("*****@*****.**", home + "/.local/share/locale")

dialogO = gtk.FileChooserDialog(
    _("Select your PDF..."), None, gtk.FILE_CHOOSER_ACTION_OPEN,
    (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialogO.set_default_response(gtk.RESPONSE_OK)
dialogO.set_select_multiple(True)

dialogE = gtk.FileChooserDialog(
    _("Save as..."), None, gtk.FILE_CHOOSER_ACTION_SAVE,
    (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
dialogE.set_default_response(gtk.RESPONSE_OK)
dialogE.set_do_overwrite_confirmation(True)
dialogE.set_current_name("*.pdf")

filter = gtk.FileFilter()
filter.set_name(_("PDF Files"))
filter.add_pattern("*.pdf")
dialogO.add_filter(filter)
dialogE.add_filter(filter)

if dialogO.run() == gtk.RESPONSE_OK:
    dialogO.hide()
コード例 #5
0
def menuAction(self, w):
    m = w.get_name()
    if m == "New":
        #self.runcmd("agooey &");
        os.system('agooey &')
    elif m == "Open":
        chooser = gtk.FileChooserDialog(
            title=None,
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))
        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            filename = chooser.get_filename()
            if os.path.splitext(filename)[-1] == ".set":
                self.runcmd("cd " + os.path.dirname(filename))
                self.runcmd("settings load " + filename)
            else:
                dialogs.error(
                    str('%s does not appear to be an ADORE settings file.' %
                        filename))
        chooser.destroy()
        return
    elif m == "Connect":
        response, param = dialogs.parameters(
            "<b>Connect</b>",
            labels=("URI", "Agooey Temporary File"),
            parameters=('*****@*****.**', self.setFile),
            titleString="Connect to remote server")
        if response == gtk.RESPONSE_OK:
            #      self.runcmd(str('ssh -Y %s -t "bash -c adore -g %s"' % (param[0], param[1])))
            self.setFile = param[1]
            self.runcmd(
                str('ssh -Y %s -t \'bash -i -c "adore -i -g %s"\' ' %
                    (param[0], param[1])))
        return
    elif m == "demLoad":
        chooser = gtk.FileChooserDialog(
            title=None,
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))
        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            filename = chooser.get_filename()
            self.runcmd("dem load " + filename)
    #    elif response == gtk.RESPONSE_CANCEL:
        chooser.destroy()
        return
    elif m == "demMake":
        response, param = dialogs.parameter(
            "<b>dem make</b>", "SRTM1/SRTM3 extraBufferPercentage name",
            "SRTM3 20 dem", "Enter parameters for...")
        if response == gtk.RESPONSE_OK:
            self.runcmd("dem make " + param)
        return
    elif m == "ShowAbout":
        #os.system("echo ADORE-GUI")#self.answer_label.set_label( "Created by Beda Kosata")
        self.readSet()
        about = gtk.AboutDialog()
        about.set_program_name("ADORE-GOOEY")
        about.set_version(
            open(
                self.set.get('adore', 'ADOREFOLDER').strip('\'"') + "/version",
                'r').read())
        about.set_copyright("(c) Batuhan Osmanoglu 2009-2012")
        about.set_license(
            open(
                self.set.get('adore', 'ADOREFOLDER').strip('\'"') +
                "/license.txt", 'r').read())
        about.set_comments("""
    Automated Doris Environment
    SHELL PID: {}
    """.format(self.vPid))
        about.set_website("http://code.google.com/p/adore-doris/")
        about.set_logo(
            gtk.gdk.pixbuf_new_from_file(
                self.set.get('adore', 'ADOREFOLDER').strip('\'"') +
                "/gui/adore-doris-gui-icon-256px.png"))
        about.run()
        about.destroy()
        return
    elif m == "toolsPythonCmd":
        response, param = dialogs.parameter("<b>Python Command</b>",
                                            "Please enter your command", "",
                                            "")
        if response == gtk.RESPONSE_OK:
            self.v.feed(str(eval(param)))
            self.v.feed('\n')
        return
コード例 #6
0
ファイル: dialogs.py プロジェクト: hsavolai/vmlab
def open(title='',
         parent=None,
         patterns=None,
         folder=None,
         filter=None,
         with_file_chooser=False):
    """Displays an open dialog.
    @param title: the title of the folder, defaults to 'Select folder'
    @param parent: parent gtk.Window or None
    @param patterns: a list of pattern strings ['*.py', '*.pl'] or None
    @param folder: initial folder or None
    @param filter: a filter to use or None, is incompatible with patterns
    """

    ffilter = filter
    if patterns and ffilter:
        raise TypeError("Can't use patterns and filter at the same time")

    filechooser = gtk.FileChooserDialog(title or _('Open'), parent,
                                        gtk.FILE_CHOOSER_ACTION_OPEN,
                                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                         gtk.STOCK_OPEN, gtk.RESPONSE_OK))

    if patterns or ffilter:
        if not ffilter:
            ffilter = gtk.FileFilter()
            for pattern in patterns:
                ffilter.add_pattern(pattern)
        if type(ffilter) != list:
            ffilter = [ffilter]
        for f in ffilter:
            filechooser.add_filter(f)
    filechooser.set_default_response(gtk.RESPONSE_OK)

    if folder:
        filechooser.set_current_folder(folder)

    response = filechooser.run()
    if response != gtk.RESPONSE_OK:
        if with_file_chooser:
            return None, filechooser
        filechooser.destroy()
        return

    path = filechooser.get_filename()
    if path and os.access(path, os.R_OK):
        if with_file_chooser:
            return path, filechooser
        filechooser.destroy()
        return path

    abspath = os.path.abspath(path)

    error(
        _('Could not open file "%s"') % abspath,
        _('The file "%s" could not be opened. '
          'Permission denied.') % abspath)

    if with_file_chooser:
        return None, filechooser
    filechooser.destroy()
    return
コード例 #7
0
def browse_local(parent, dialog_name, conn, start_folder=None,
                 _type=None, dialog_type=None,
                 confirm_func=None, browse_reason=None,
                 choose_button=None):
    """
    Helper function for launching a filechooser

    @param parent: Parent window for the filechooser
    @param dialog_name: String to use in the title bar of the filechooser.
    @param conn: vmmConnection used by calling class
    @param start_folder: Folder the filechooser is viewing at startup
    @param _type: File extension to filter by (e.g. "iso", "png")
    @param dialog_type: Maps to FileChooserDialog 'action'
    @param confirm_func: Optional callback function if file is chosen.
    @param browse_reason: The vmmConfig.CONFIG_DIR* reason we are browsing.
        If set, this will override the 'folder' parameter with the gconf
        value, and store the user chosen path.

    """
    import gtk

    # Initial setup
    overwrite_confirm = False

    if dialog_type is None:
        dialog_type = gtk.FILE_CHOOSER_ACTION_OPEN
    if dialog_type == gtk.FILE_CHOOSER_ACTION_SAVE:
        if choose_button is None:
            choose_button = gtk.STOCK_SAVE
            overwrite_confirm = True

    if choose_button is None:
        choose_button = gtk.STOCK_OPEN

    fcdialog = gtk.FileChooserDialog(dialog_name, parent,
                                     dialog_type,
                                     (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                      choose_button, gtk.RESPONSE_ACCEPT),
                                      None)
    fcdialog.set_default_response(gtk.RESPONSE_ACCEPT)

    # If confirm is set, warn about a file overwrite
    if confirm_func:
        overwrite_confirm = True
        fcdialog.connect("confirm-overwrite", confirm_func)
    fcdialog.set_do_overwrite_confirmation(overwrite_confirm)

    # Set file match pattern (ex. *.png)
    if _type != None:
        pattern = _type
        name = None
        if type(_type) is tuple:
            pattern = _type[0]
            name = _type[1]

        f = gtk.FileFilter()
        f.add_pattern("*." + pattern)
        if name:
            f.set_name(name)
        fcdialog.set_filter(f)

    # Set initial dialog folder
    if browse_reason:
        start_folder = running_config.get_default_directory(conn,
                                                            browse_reason)

    if start_folder != None:
        if os.access(start_folder, os.R_OK):
            fcdialog.set_current_folder(start_folder)

    # Run the dialog and parse the response
    response = fcdialog.run()
    fcdialog.hide()
    if (response == gtk.RESPONSE_ACCEPT):
        filename = fcdialog.get_filename()
        fcdialog.destroy()
        ret = filename
    else:
        fcdialog.destroy()
        ret = None

    # Store the chosen directory in gconf if necessary
    if ret and browse_reason and not ret.startswith("/dev"):
        running_config.set_default_directory(os.path.dirname(ret),
                                             browse_reason)
    return ret
コード例 #8
0
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.set_size_request(600, 600)

        self.button1 = gtk.Button("EXIT")
        self.button1.connect("clicked", self.destroy)

        self.button2 = gtk.Button("hide")
        self.button2.connect("clicked", self.myhide)
        self.button3 = gtk.Button("show")
        self.button3.connect("clicked", self.myshow)
        self.button4 = gtk.Button("relable")
        self.button4.connect("clicked", self.relable)
        self.button5 = gtk.Button("add to Combo box")
        self.button5.connect("clicked", self.add_combo)
        self.button6 = gtk.Button("About")
        self.button6.connect("clicked", self.about_win)

        self.label1 = gtk.Label("disini dituliskan label")

        self.text1 = gtk.Entry()
        self.text1.connect("changed", self.textbox)

        self.combo = gtk.combo_box_entry_new_text()
        self.combo.connect("changed", self.combo_text)
        self.combo.append_text("Ini tulisan")
        self.combo.append_text("Opsi 1")
        self.combo.append_text("Opsi 2")
        self.combo.append_text("Opsi 3")

        dialog = gtk.FileChooserDialog("Pilih gambar", None,
                                       gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        filter = gtk.FileFilter()
        filter.set_name("gambar bo")
        filter.add_mime_type("image/png")
        filter.add_mime_type("image/jpg")
        filter.add_pattern("*.png")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.jpeg")
        dialog.add_filter(filter)

        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            self.pix = gtk.gdk.pixbuf_new_from_file_at_size(
                dialog.get_filename(), 200, 200)
            self.image = gtk.Image()
            self.image.set_from_pixbuf(self.pix)
        elif response == gtk.RESPONSE_CANCEL:
            print "no file selected"

            #menampilkan error dialog
            em = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT,
                                   gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
                                   "Error Euy \n Teuing kunaon")
            em.run()
            em.destroy()

            #exit dari program
            raise SystemExit
        dialog.destroy()

        self.box1 = gtk.HBox()
        self.box1.pack_start(self.button1)
        self.box1.pack_start(self.button2)
        self.box1.pack_start(self.button3)
        self.box1.pack_start(self.button4)
        self.box1.pack_start(self.button6)

        self.box3 = gtk.HBox()
        self.box3.pack_start(self.text1)
        self.box3.pack_start(self.button5)

        self.box2 = gtk.VBox()
        self.box2.pack_start(self.box1)
        self.box2.pack_start(self.label1)
        self.box2.pack_start(self.box3)
        self.box2.pack_start(self.combo)
        self.box2.pack_start(self.image)

        self.window.add(self.box2)
        self.window.show_all()
        self.window.connect("destroy", self.destroy)
コード例 #9
0
    def add_folder(self, in_new_tab=False):
        chooser = gtk.FileChooserDialog(
            title=_("Choose directory with music"),
            action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        chooser.set_default_response(gtk.RESPONSE_OK)
        chooser.set_select_multiple(True)
        if FCache().last_music_path:
            chooser.set_current_folder(FCache().last_music_path)
        response = chooser.run()

        if response == gtk.RESPONSE_OK:
            paths = chooser.get_filenames()
            chooser.destroy()

            def task():
                path = paths[0]
                FCache().last_music_path = path[:path.rfind("/")]
                tree = self
                number_of_tab = self.controls.tabhelper.page_num(tree.scroll)

                if in_new_tab:
                    tree = NavigationTreeControl(self.controls)
                    tab_name = unicode(path[path.rfind("/") + 1:])
                    self.controls.tabhelper._append_tab(tab_name,
                                                        navig_tree=tree)
                    number_of_tab = self.controls.tabhelper.get_current_page()
                    FCache().music_paths.insert(0, [])
                    FCache().tab_names.insert(0, tab_name)
                    FCache().cache_music_tree_beans.insert(0, [])

                elif tree.is_empty:
                    tab_name = unicode(path[path.rfind("/") + 1:])
                    vbox = gtk.VBox()
                    label = gtk.Label(tab_name + " ")
                    label.set_angle(90)
                    if FC().tab_close_element:
                        vbox.pack_start(
                            self.controls.tabhelper.button(tree.scroll), False,
                            False)
                    vbox.pack_end(label, False, False)
                    event = self.controls.notetabs.to_eventbox(vbox, tree)
                    event = self.controls.tabhelper.tab_menu_creator(
                        event, tree.scroll)
                    event.connect("button-press-event",
                                  self.controls.tabhelper.on_button_press)
                    self.controls.tabhelper.set_tab_label(tree.scroll, event)
                    FCache().tab_names[number_of_tab] = tab_name
                    FCache().music_paths[number_of_tab] = []

                for path in paths:
                    if path in FCache().music_paths[number_of_tab]:
                        pass
                    else:
                        FCache().music_paths[number_of_tab].append(path)
                        self.controls.preferences.on_load()
                        logging.info("New music paths" +
                                     str(FCache().music_paths[number_of_tab]))
                self.controls.update_music_tree(tree, number_of_tab)
                FC().save()

            self.controls.in_thread.run_with_progressbar(task)
        elif response == gtk.RESPONSE_CANCEL:
            logging.info('Closed, no files selected')
            chooser.destroy()
コード例 #10
0
def file_selection(title,
                   filename='',
                   parent=None,
                   action=gtk.FILE_CHOOSER_ACTION_OPEN,
                   preview=True,
                   multi=False,
                   filters=None):
    if action == gtk.FILE_CHOOSER_ACTION_OPEN:
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                   gtk.RESPONSE_OK)
    else:
        buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,
                   gtk.RESPONSE_OK)

    win = gtk.FileChooserDialog(title, None, action, buttons)
    if not parent:
        parent = service.LocalService('gui.main').window
    win.set_transient_for(parent)
    win.set_icon(OPENERP_ICON)
    win.set_current_folder(options['client.default_path'])
    win.set_select_multiple(multi)
    win.set_default_response(gtk.RESPONSE_OK)
    if filters is not None:
        for filter in filters:
            win.add_filter(filter)
    if filename:
        win.set_current_name(filename)

    def update_preview_cb(win, img):
        filename = win.get_preview_filename()
        try:
            pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename, 128, 128)
            img.set_from_pixbuf(pixbuf)
            have_preview = True
        except:
            have_preview = False
        win.set_preview_widget_active(have_preview)
        return

    if preview:
        img_preview = gtk.Image()
        win.set_preview_widget(img_preview)
        win.connect('update-preview', update_preview_cb, img_preview)

    button = win.run()
    if button != gtk.RESPONSE_OK:
        win.destroy()
        return False
    if not multi:
        filepath = win.get_filename()
        if filepath:
            filepath = filepath.decode('utf-8')
            try:
                options['client.default_path'] = os.path.dirname(filepath)
            except:
                pass
        parent.present()
        win.destroy()
        return filepath
    else:
        filenames = win.get_filenames()
        if filenames:
            filenames = [x.decode('utf-8') for x in filenames]
            try:
                options['client.default_path'] = os.path.dirname(filenames[0])
            except:
                pass
        parent.present()
        win.destroy()
        return filenames
コード例 #11
0
ファイル: mediaplayer.py プロジェクト: hellozt/gnome15
    def _open_file(self):
        dialog = gtk.FileChooserDialog("Open..", None,
                                       gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)

        filter = gtk.FileFilter()
        filter.set_name(_("All files"))
        filter.add_pattern("*")
        dialog.add_filter(filter)

        # Video
        filter = gtk.FileFilter()
        filter.set_name(_("Video Files"))

        filter.add_mime_type("application/ogg")

        filter.add_mime_type("video/ogg")
        filter.add_mime_type("video/mpeg")
        filter.add_mime_type("video/quicktime")
        filter.add_mime_type("video/x-la-asf")
        filter.add_mime_type("video/x-ms-asf")
        filter.add_mime_type("video/x-msvideo")
        filter.add_mime_type("video/x-sgi-movie")

        filter.add_pattern("*.ogx")
        filter.add_pattern("*.ogv")
        filter.add_pattern("*.mp2")
        filter.add_pattern("*.mpa")
        filter.add_pattern("*.mpe")
        filter.add_pattern("*.mpeg")
        filter.add_pattern("*.mpg")
        filter.add_pattern("*.mpv2")
        filter.add_pattern("*.mov")
        filter.add_pattern("*.qt")
        filter.add_pattern("*.lsf")
        filter.add_pattern("*.lsx")
        filter.add_pattern("*.asf")
        filter.add_pattern("*.asr")
        filter.add_pattern("*.asx")
        filter.add_pattern("*.avi")
        filter.add_pattern("*.movie")
        dialog.add_filter(filter)

        # Audio
        filter = gtk.FileFilter()
        filter.set_name(_("Audio Files"))

        filter.add_mime_type("audio/ogg")
        filter.add_mime_type("audio/vorbis")
        filter.add_mime_type("audio/flac")
        filter.add_mime_type("audio/x-ogg")
        filter.add_mime_type("audio/x-vorbis")
        filter.add_mime_type("audio/x-flac")
        filter.add_mime_type("audio/basic")
        filter.add_mime_type("audio/mid")
        filter.add_mime_type("audio/mpeg")
        filter.add_mime_type("audio/aiff")
        filter.add_mime_type("audio/x-aiff")
        filter.add_mime_type("audio/x-mpegurl")
        filter.add_mime_type("audio/x-pn-realaudio")
        filter.add_mime_type("audio/x-realaudio")
        filter.add_mime_type("audio/wav")
        filter.add_mime_type("audio/x-wav")
        filter.add_mime_type("audio/x-au")
        filter.add_mime_type("audio/x-midi")
        filter.add_mime_type("audio/x-mpeg")
        filter.add_mime_type("audio/x-mpeg3")
        filter.add_mime_type("audio/x-mpeg-3")
        filter.add_mime_type("audio/midi")
        filter.add_mime_type("audio/x-mid")

        filter.add_pattern("*.flac")
        filter.add_pattern("*.oga")
        filter.add_pattern("*.ogg")
        filter.add_pattern("*.au")
        filter.add_pattern("*.snd")
        filter.add_pattern("*.mid")
        filter.add_pattern("*.rmi")
        filter.add_pattern("*.mp3")
        filter.add_pattern("*.aif")
        filter.add_pattern("*.aifc")
        filter.add_pattern("*.aiff")
        filter.add_pattern("*.m3u")
        filter.add_pattern("*.ra")
        filter.add_pattern("*.ram")
        filter.add_pattern("*.wav")
        dialog.add_filter(filter)

        response = dialog.run()
        while gtk.events_pending():
            gtk.main_iteration(False)
        try:
            if response == gtk.RESPONSE_OK:
                return dialog.get_filename()
        finally:
            dialog.destroy()
コード例 #12
0
    def __init__(self, assistant, project_data, *args):
        """ Init Introduction page of assistant"""

        super(Page_intro, self).__init__(homogeneous=False, spacing=5)
        self.set_name('page_intro')
        self.assistant = assistant
        self.project_data = project_data

        self.pattern_filename = re.compile(r'^\w+$')
        #
        # Initailize widgets for first page
        #

        # A label
        label = gtk.Label(
            _('This assistant will help you on configuration of a new Luciole project.'
              ))
        self.pack_start(child=label, expand=False, fill=False, padding=10)
        # A line separator
        self.pack_start(child=gtk.HSeparator(),
                        expand=False,
                        fill=False,
                        padding=10)
        # A label
        label = gtk.Label(_('Select project name and destination folder.'))
        self.pack_start(child=label, expand=False, fill=False, padding=10)

        # Use a gtk.table to display project/folder chosse
        table = gtk.Table(3, 2, True)

        label_project_name = gtk.Label(_('Project Name'))
        # positionning of label
        label_project_name.set_alignment(
            xalign=0.0, yalign=0.5)  # left justification of label

        # Insert label into the upper left quadrant of the table
        table.attach(label_project_name, 0, 1, 0, 1, xpadding=10)

        self.entry_project_name = gtk.Entry()
        self.entry_project_name.set_text('')
        self.entry_project_name.connect('changed',
                                        self.on_project_name_changed)
        # Insert entry_project_name into the upper right quadrant of the table
        table.attach(self.entry_project_name, 1, 2, 0, 1, xpadding=10)

        label_folder = gtk.Label(_('Folder'))
        # positionning of label
        label_folder.set_alignment(xalign=0.0,
                                   yalign=0.5)  # left justification of label
        # Insert label into the lower left quadrant of the table
        table.attach(label_folder, 0, 1, 1, 2, xpadding=10)

        dialog = gtk.FileChooserDialog(
            title=_('Select a folder'),
            parent=None,
            action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK,
                     gtk.RESPONSE_OK))
        self.fileChooser = gtk.FileChooserButton(dialog)
        self.fileChooser.connect('selection-changed', self.on_dir_is_changed)

        self.fileChooser.set_current_folder(os.path.expandvars('$HOME'))
        self.fileChooser.set_filename(os.path.expandvars('$HOME'))
        # Insert label into the lower right quadrant of the table
        table.attach(self.fileChooser,
                     1,
                     2,
                     1,
                     2,
                     yoptions=gtk.SHRINK,
                     xpadding=10)

        #label for message
        self.message_label = gtk.Label('')
        self.message_label.set_alignment(
            xalign=0.0, yalign=0.5)  # left justification of label
        table.attach(self.message_label,
                     0,
                     2,
                     2,
                     3,
                     yoptions=gtk.FILL,
                     xpadding=10)

        # pack table to main widget
        self.pack_start(child=table, expand=True, fill=True, padding=10)
コード例 #13
0
    def create_enter_data_frame(fields_data):
        entries_list = {}

        objLabelToken = gtk.Label("Admin token")
        objLabelToken.set_usize(150, 25)

        objEntryToken = gtk.Entry()
        objEntryToken.set_text(fields_data["access_token"])
        entries_list.update({"entry_token": objEntryToken})

        objHBoxToken = gtk.HBox()
        objHBoxToken.pack_start(objLabelToken,
                                expand=False, fill=False, padding=0)
        objHBoxToken.pack_start(objEntryToken,
                                expand=True, fill=True, padding=0)

        objLabelDate = gtk.Label("Date")
        objLabelDate.set_usize(150, 25)

        objEntryDateDay = gtk.Entry()
        objEntryDateDay.set_text(fields_data["date"]["day"])
        objEntryDateDay.set_usize(50, 30)
        objEntryDateMonth = gtk.Entry()
        objEntryDateMonth.set_text(fields_data["date"]["month"])
        objEntryDateMonth.set_usize(50, 30)
        objEntryDateYear = gtk.Entry()
        objEntryDateYear.set_text(fields_data["date"]["year"])
        objEntryDateYear.set_usize(75, 30)

        entries_list.update({"entry_date_day": objEntryDateDay})
        entries_list.update({"entry_date_month": objEntryDateMonth})
        entries_list.update({"entry_date_year": objEntryDateYear})

        objHBoxEntriesDate = gtk.HBox()
        objHBoxEntriesDate.pack_start(objEntryDateDay,
                                      expand=False, fill=False, padding=0)
        objHBoxEntriesDate.pack_start(objEntryDateMonth,
                                      expand=False, fill=False, padding=0)
        objHBoxEntriesDate.pack_start(objEntryDateYear,
                                      expand=False, fill=False, padding=0)

        objHBoxDate = gtk.HBox()
        objHBoxDate.pack_start(objLabelDate,
                               expand=False, fill=False, padding=0)
        objHBoxDate.pack_start(objHBoxEntriesDate,
                               expand=False, fill=False, padding=0)

        objLabelPublicURL = gtk.Label("Public URL")
        objLabelPublicURL.set_usize(150, 25)

        objEntryPublicURL = gtk.Entry()
        objEntryPublicURL.set_text(fields_data["public_url"])
        objEntryPublicURL.set_usize(300, 30)
        entries_list.update({"entry_public_url": objEntryPublicURL})

        objHBoxPublicURL = gtk.HBox()
        objHBoxPublicURL.pack_start(objLabelPublicURL,
                                    expand=False, fill=False, padding=0)
        objHBoxPublicURL.pack_start(objEntryPublicURL,
                                    expand=False, fill=False, padding=0)

        objLabelPostsCount = gtk.Label("Posts count")
        objLabelPostsCount.set_usize(150, 25)

        objEntryPostsCount = gtk.Entry()
        objEntryPostsCount.set_text(fields_data["post_count"])
        objEntryPostsCount.set_usize(60, 30)
        entries_list.update({"entry_posts_count": objEntryPostsCount})

        objHBoxPostCount = gtk.HBox()
        objHBoxPostCount.pack_start(objLabelPostsCount,
                                    expand=False, fill=False, padding=0)
        objHBoxPostCount.pack_start(objEntryPostsCount,
                                    expand=False, fill=False, padding=0)

        dialog = gtk.FileChooserDialog(title="Select evaluator template",
                                       action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                       buttons=(gtk.STOCK_CANCEL,
                                                gtk.RESPONSE_CANCEL,
                                                gtk.STOCK_OPEN,
                                                gtk.RESPONSE_OK))
        dict_template_chooser = {
            "dialog": dialog,
            "RESPONSE_OK": gtk.RESPONSE_OK,
            "STOCK_OPEN": gtk.STOCK_OPEN,
            "RESPONSE_CANCEL": gtk.RESPONSE_CANCEL,
            "STOCK_CANCEL": gtk.STOCK_CANCEL,
        }
        entries_list.update({"template_chooser": dict_template_chooser})

        objButtonTemplateChooser = gtk.Button("Select template")
        objButtonTemplateChooser.set_usize(150, 30)
        objButtonTemplateChooser.connect("clicked", buttons_listener.select_template,
                                         entries_list)

        objEntryTemplateChooser = gtk.Entry()
        objEntryTemplateChooser.set_text(fields_data["evaluator_template"])

        entries_list.update({"evaluator_template": objEntryTemplateChooser})

        objHBoxTemplateChooser = gtk.HBox()
        objHBoxTemplateChooser.pack_start(objButtonTemplateChooser,
                                          expand=False, fill=False, padding=0)
        objHBoxTemplateChooser.pack_start(objEntryTemplateChooser,
                                          expand=True, fill=True, padding=0)

        objFrameReackEvaluatorData = gtk.Frame()
        objFrameReackEvaluatorData.set_label("Reach evaluator data")
        objFrameReackEvaluatorData.set_label_align(0.0, 0.0)
        objFrameReackEvaluatorData.add(objHBoxTemplateChooser)

        objTable = gtk.Table(5, 1, False)
        objTable.attach(objHBoxToken, 0, 1, 0, 1)
        objTable.attach(objHBoxDate, 0, 1, 1, 2)
        objTable.attach(objHBoxPublicURL, 0, 1, 2, 3)
        objTable.attach(objHBoxPostCount, 0, 1, 3, 4)
        objTable.attach(objFrameReackEvaluatorData, 0, 1, 4, 5)

        objFrame = gtk.Frame()
        objFrame.set_label("Enter data")
        objFrame.set_label_align(0.0, 0.0)
        objFrame.add(objTable)

        return objFrame, entries_list
コード例 #14
0
def apply_modif(folder, pw2_rom, output_rom='', verbose=True):
    os.environ['PATH'] += ';' + os.getcwd()
    f, pathname, descr = imp.find_module('config', [folder])
    config = imp.load_module('config', f, pathname, descr)
    f.close()
    if output_rom == '':
        output_rom = os.getcwd() + os.sep + config.rom_name + '.nds'
        dlg = gtk.FileChooserDialog(title='Save modified rom to',
                                    action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                    buttons=(gtk.STOCK_CANCEL,
                                             gtk.RESPONSE_CANCEL,
                                             gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        fold, rom = os.path.split(output_rom)
        dlg.set_current_folder(fold)
        dlg.set_current_name(rom)
        response = dlg.run()
        if response == gtk.RESPONSE_OK:
            output_rom = dlg.get_filename()
        else:
            dlg.destroy()
            return
        dlg.destroy()
    if verbose:
        dlg = gtk.Dialog(title='Applying modifications')
        lbl = gtk.Label()
        lbl.set_text('Applying : %s [%s] by %s\n' %
                     (config.name, config.version, config.author))
        dlg.vbox.pack_start(lbl)
        dlg.show_all()
        dlg.present()

        def append_line(s):
            lbl.set_text(lbl.get_text() + s + '\n')
            dlg.queue_draw()
            while gtk.events_pending():
                gtk.main_iteration()

    sys.path.append(folder)
    tempdir = tempfile.mkdtemp()
    scriptsdir = tempdir + os.sep + 'scripts'
    os.mkdir(scriptsdir)
    if verbose:
        append_line('Creating temp directory')
    curpath = os.getcwd()
    if verbose:
        append_line('Extracting rom data')
    if 'winver' in dir(sys):
        ndstool = curpath + os.sep + 'ndstool'
    else:
        ndstool = 'ndstool'
    datadir = tempdir + os.sep + 'data'
    ndstool = '"' + ndstool + '"'
    command = 'temp.nds -9 arm9.bin -7 arm7.bin -y overlay ' + '-data data -h header.bin -t banner.bin ' + '-y7 y7.bin -y9 y9.bin'
    extract = ndstool + ' -x ' + command
    intract = ndstool + ' -c ' + command
    debug = file('debug.txt', 'w')
    debug.write('Running : ' + extract + '\n')
    debug.write('Running : ' + intract + '\n')
    debug.close()
    os.chdir(tempdir)

    def file_copy(fnin, fnout):
        fin = file(fnin, 'rb')
        fout = file(fnout, 'wb')
        fout.write(fin.read())
        fout.close()
        fin.close()

    file_copy(pw2_rom, 'temp.nds')
    os.system(extract)
    if verbose:
        append_line('Extracting scripts')
    os.chdir(curpath)
    mesutils.extract_mes(datadir + os.sep + 'mes_all.bin', scriptsdir)
    for script in config.scripts:
        n = config.scripts[script]
        f = file(folder + os.sep + script, 'r')
        fo = file(scriptsdir + os.sep + 'script-%02d.txt' % n, 'w')
        fo.write(f.read())
        f.close()
        fo.close()

    if verbose:
        append_line('Converting back scripts')
    os.chdir(curpath)
    mesutils.pack_mes_folder(datadir + os.sep + 'mes_all.bin', scriptsdir)
    if verbose:
        append_line('Building the new rom')
    os.chdir(tempdir)
    os.system(intract)
    file_copy('temp.nds', output_rom)
    if verbose:
        append_line('Cleaning up')
    rm_rf(tempdir)
    if verbose:
        dlg.destroy()
    os.chdir(curpath)
コード例 #15
0
 def init_file_chooser(self):
     self.file_chooser = gtk.FileChooserDialog(title="File Chooser",
     parent=self.window, action=gtk.FILE_CHOOSER_ACTION_OPEN,
     buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
         gtk.STOCK_OK, gtk.RESPONSE_ACCEPT), backend=None)
コード例 #16
0
ファイル: background.py プロジェクト: tanktarta/gnome15
    def __init__(self, parent, driver, gconf_client, gconf_key):

        widget_tree = gtk.Builder()
        widget_tree.add_from_file(
            os.path.join(os.path.dirname(__file__), "background.ui"))

        self.gconf_client = gconf_client
        self.gconf_key = gconf_key

        # Widgets
        dialog = widget_tree.get_object("BackgroundDialog")
        dialog.set_transient_for(parent)
        g15uigconf.configure_radio_from_gconf(gconf_client,
                                              gconf_key + "/type",
                                              ["UseDesktop", "UseFile"],
                                              ["desktop", "file"], "desktop",
                                              widget_tree, True)
        g15uigconf.configure_combo_from_gconf(gconf_client,
                                              gconf_key + "/style",
                                              "StyleCombo", "zoom",
                                              widget_tree)
        widget_tree.get_object("UseDesktop").connect("toggled",
                                                     self.set_available,
                                                     widget_tree)
        widget_tree.get_object("UseFile").connect("toggled",
                                                  self.set_available,
                                                  widget_tree)
        g15uigconf.configure_checkbox_from_gconf(
            gconf_client, gconf_key + "/allow_profile_override",
            "AllowProfileOverride", True, widget_tree)
        g15uigconf.configure_adjustment_from_gconf(gconf_client,
                                                   gconf_key + "/brightness",
                                                   "BrightnessAdjustment", 50,
                                                   widget_tree)

        # Currently, only GNOME is supported for getting the desktop background
        if g15desktop.get_desktop() in ["gnome", "gnome-shell"]:
            widget_tree.get_object("UseFile").set_active(True)

        # The file chooser
        chooser = gtk.FileChooserDialog("Open..", None,
                                        gtk.FILE_CHOOSER_ACTION_OPEN,
                                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                         gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        chooser.set_default_response(gtk.RESPONSE_OK)

        filter = gtk.FileFilter()
        filter.set_name("Images")
        filter.add_mime_type("image/png")
        filter.add_mime_type("image/jpeg")
        filter.add_mime_type("image/gif")
        filter.add_pattern("*.png")
        filter.add_pattern("*.jpg")
        filter.add_pattern("*.jpeg")
        filter.add_pattern("*.gif")
        chooser.add_filter(filter)

        filter = gtk.FileFilter()
        filter.set_name("All files")
        filter.add_pattern("*")
        chooser.add_filter(filter)

        chooser_button = widget_tree.get_object("FileChooserButton")
        chooser_button.dialog = chooser
        chooser_button.connect("file-set", self.file_set)
        widget_tree.connect_signals(self)
        bg_img = gconf_client.get_string(gconf_key + "/path")
        if bg_img == None:
            bg_img = ""
        chooser_button.set_filename(bg_img)
        self.set_available(None, widget_tree)
        dialog.run()
        dialog.hide()
コード例 #17
0
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from xml.dom.minidom import parseString
import sys
import os
import gtk

filter = gtk.FileFilter()
filter.add_pattern("*.xml")
filter.set_name(_("Mach configuration files"))
fcd = gtk.FileChooserDialog(
    "Open...", None, gtk.FILE_CHOOSER_ACTION_OPEN,
    (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
fcd.set_current_folder(os.path.expanduser('~/Desktop'))
fcd.add_filter(filter)
response = fcd.run()
if response == gtk.RESPONSE_OK:
    file_name = fcd.get_filename()
    machinename = os.path.splitext(os.path.basename(fcd.get_filename()))[0]
fcd.destroy()
if response == gtk.RESPONSE_CANCEL:
    quit(1)
print file_name
print machinename
file = open(file_name, 'r')
#convert to string:
data = file.read()
コード例 #18
0
    def on_button_save_clicked(self, widget):
        log.debug('on_button_save_clicked')
        if len(self.files_treestore) == 0:
            return

        # Get the path
        path = self.files_treestore[0][0].rstrip('\\/')
        torrent_filename = '%s.torrent' % os.path.split(path)[-1]

        is_remote = self.files_treestore[0][1] == gtk.STOCK_NETWORK

        if is_remote:
            # This is a remote path
            dialog = self.builder.get_object('remote_save_dialog')
            dialog.set_transient_for(self.dialog)
            dialog_save_path = self.builder.get_object('entry_save_path')
            dialog_save_path.set_text(path + '.torrent')
            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                result = dialog_save_path.get_text()
            else:
                dialog.hide()
                return
            dialog.hide()
        else:
            # Setup the filechooserdialog
            chooser = gtk.FileChooserDialog(
                _('Save .torrent file'),
                self.dialog,
                gtk.FILE_CHOOSER_ACTION_SAVE,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,
                         gtk.RESPONSE_OK))

            chooser.set_transient_for(self.dialog)
            chooser.set_select_multiple(False)
            chooser.set_property('skip-taskbar-hint', True)

            # Add .torrent and * file filters
            file_filter = gtk.FileFilter()
            file_filter.set_name(_('Torrent files'))
            file_filter.add_pattern('*.' + 'torrent')
            chooser.add_filter(file_filter)
            file_filter = gtk.FileFilter()
            file_filter.set_name(_('All files'))
            file_filter.add_pattern('*')
            chooser.add_filter(file_filter)

            chooser.set_current_name(torrent_filename)
            # Run the dialog
            response = chooser.run()

            if response == gtk.RESPONSE_OK:
                result = chooser.get_filename()
            else:
                chooser.destroy()
                return
            chooser.destroy()

        # Fix up torrent filename
        if len(result) < 9:
            result += '.torrent'
        elif result[-8:] != '.torrent':
            result += '.torrent'

        # Get a list of trackers
        trackers = []
        if not len(self.trackers_liststore):
            tracker = None
        else:
            # Create a list of lists [[tier0, ...], [tier1, ...], ...]
            tier_dict = {}
            for tier, tracker in self.trackers_liststore:
                tier_dict.setdefault(tier, []).append(tracker)

            trackers = [tier_dict[tier] for tier in sorted(tier_dict)]
            # Get the first tracker in the first tier
            tracker = trackers[0][0]

        # Get a list of webseeds
        textview_buf = self.builder.get_object(
            'textview_webseeds').get_buffer()
        lines = textview_buf.get_text(
            *textview_buf.get_bounds()).strip().split('\n')
        webseeds = []
        for line in lines:
            line = line.replace('\\', '/')  # Fix any mistyped urls.
            if is_url(line):
                webseeds.append(line)
        # Get the piece length in bytes
        combo = self.builder.get_object('combo_piece_size')
        piece_length = self.parse_piece_size_text(
            combo.get_model()[combo.get_active()][0])

        author = self.builder.get_object('entry_author').get_text()
        comment = self.builder.get_object('entry_comments').get_text()
        private = self.builder.get_object('chk_private_flag').get_active()
        add_to_session = self.builder.get_object(
            'chk_add_to_session').get_active()

        if is_remote:

            def torrent_created():
                self.builder.get_object('progress_dialog').hide_all()
                client.deregister_event_handler(
                    'CreateTorrentProgressEvent',
                    on_create_torrent_progress_event)

            def on_create_torrent_progress_event(piece_count, num_pieces):
                self._on_create_torrent_progress(piece_count, num_pieces)
                if piece_count == num_pieces:
                    from twisted.internet import reactor
                    reactor.callLater(0.5, torrent_created)

            client.register_event_handler('CreateTorrentProgressEvent',
                                          on_create_torrent_progress_event)

            client.core.create_torrent(path, tracker, piece_length, comment,
                                       result, webseeds, private, author,
                                       trackers, add_to_session)

        else:

            def hide_progress(result):
                self.builder.get_object('progress_dialog').hide_all()

            deferToThread(self.create_torrent, path.decode('utf-8'), tracker,
                          piece_length,
                          self._on_create_torrent_progress, comment,
                          result.decode('utf-8'), webseeds, private, author,
                          trackers, add_to_session).addCallback(hide_progress)

        # Setup progress dialog
        self.builder.get_object('progress_dialog').set_transient_for(
            component.get('MainWindow').window)
        self.builder.get_object('progress_dialog').show_all()

        self.dialog.destroy()
コード例 #19
0
        def create(widget, other=None):
            theme_name = msg_input(
                '',
                _('Enter your plymouth theme name. eg. Bodhibuilder Theme (please use only alphanumeric characters)'
                  ), _('Name:'), 'Bodhibuilder Theme')
            if theme_name == False or theme_name == None:
                return
            elif theme_name == '':
                msg_error(_("You must specify theme name!"))
                return

            theme_name_fixed = theme_name.replace(' ', '-').replace(
                '/', '-').replace('..', '-').replace('\\', '-')
            theme_dir = "/lib/plymouth/themes/" + theme_name_fixed

            if os.path.exists(theme_dir):
                overwrite = msg_confirm(
                    _('The theme "%s" already exists! Do you want to overwrite it?'
                      ) % theme_name)
                if overwrite:
                    shutil.rmtree(theme_dir)
                else:
                    return

            dialog = gtk.FileChooserDialog(
                title=_("Select 1920x1080 PNG image..."),
                action=gtk.FILE_CHOOSER_ACTION_OPEN,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                         gtk.RESPONSE_OK))
            dialog.set_default_response(gtk.RESPONSE_OK)
            dialog.set_current_folder(self.working_dir)

            filter = gtk.FileFilter()
            filter.set_name(_("PNG Images"))
            filter.add_mime_type("image/png")
            dialog.add_filter(filter)

            filter = gtk.FileFilter()
            filter.set_name(_("All files"))
            filter.add_pattern("*")
            dialog.add_filter(filter)

            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                filename = dialog.get_filename()
                self.working_dir = os.path.dirname(filename)
                dialog.destroy()
                while gtk.events_pending():
                    gtk.main_iteration_do()
                os.makedirs(theme_dir)
                now = datetime.datetime.now()
                theme_pic = os.path.join(theme_dir, os.path.basename(filename))
                shutil.copy(filename, theme_pic)
                shutil.copy(
                    '/etc/bodhibuilder/plymouth/bodhibuilder-theme/progress_bar.png',
                    theme_dir + '/progress_bar.png')
                shutil.copy(
                    '/etc/bodhibuilder/plymouth/bodhibuilder-theme/progress_box.png',
                    theme_dir + '/progress_box.png')
                script_name = "/lib/plymouth/themes/" + theme_name_fixed + "/" + theme_name_fixed + ".script"
                script = open(
                    "/etc/bodhibuilder/plymouth/bodhibuilder-theme/bodhibuilder-theme.script"
                ).read().replace("__THEMEPIC__", os.path.basename(theme_pic))
                open(script_name, 'w+').write(script)

                config_name = "/lib/plymouth/themes/" + theme_name_fixed + "/" + theme_name_fixed + ".plymouth"
                config = open(
                    "/etc/bodhibuilder/plymouth/bodhibuilder-theme/bodhibuilder-theme.plymouth"
                ).read()
                config = config.replace("__THEMENAME__", theme_name)
                config = config.replace("__THEMEDIR__", theme_name_fixed)
                open(config_name, 'w+').write(config)

                os.system(
                    'update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth "%(config_name)s" 80'
                    % ({
                        'config_name': config_name
                    }))
                os.system(
                    'update-alternatives --set default.plymouth "%(config_name)s"'
                    % ({
                        'config_name': config_name
                    }))

                ns.window.get_widget("checkbutton1").set_active(False)

                update_initramfs()

                msg_info(
                    _("Your plymouth theme named %(theme_name)s with the picture %(theme_pic)s has been created."
                      ) % ({
                          'theme_name': theme_name,
                          'theme_pic': theme_pic
                      }))
            else:
                dialog.destroy()
                shutil.rmtree(theme_dir)
            list_themes()
コード例 #20
0
    def __init__(self):
        self.root = os.getcwd()
        self.filemodel = gtk.TreeStore(str, str, bool)
        self.fileview = self.get_view('Files', self.filemodel, 'fileview')
        self.colmodel = gtk.TreeStore(str, str, str)
        self.colview = self.get_view('Collections', self.colmodel, 'colview')

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("Kindelabra v%s" % VERSION)
        self.window.set_default_size(1000, 700)
        self.window.connect("destroy", gtk.main_quit)
        self.accel_group = gtk.AccelGroup()
        self.window.add_accel_group(self.accel_group)
        vbox_main = gtk.VBox()
        filechooserdiag = gtk.FileChooserDialog(
            "Select your Kindle folder", self.window,
            gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK,
             gtk.RESPONSE_ACCEPT))
        filechooserdiag.set_current_folder(os.path.join(self.root, 'system'))
        self.filechooser = gtk.FileChooserButton(filechooserdiag)
        self.filechooser.connect("current-folder-changed", self.load)

        file_toolbar = gtk.HBox()
        file_toolbar.pack_start(self.filechooser, True, True, 2)
        file_toolbar.pack_start(
            self.get_button('gtk-refresh', 'Refresh files', self.refresh),
            False, True, 2)
        file_toolbar.pack_start(
            self.get_button('gtk-open', 'Open collection file',
                            self.open_collection, "O"), False, True, 2)
        file_toolbar.pack_start(gtk.VSeparator(), False, True, 2)
        file_toolbar.pack_start(
            self.get_button('gtk-save', 'Save collection file', self.save,
                            "S"), False, True, 2)

        hbox_main = gtk.HBox()
        filescroll = gtk.ScrolledWindow()
        filescroll.add(self.fileview)
        colscroll = gtk.ScrolledWindow()
        colscroll.add(self.colview)
        col_toolbar = gtk.VBox()
        col_toolbar.pack_start(
            self.get_button('gtk-new', 'Create new collection',
                            self.add_collection, "N"), False, True, 2)
        col_toolbar.pack_start(
            self.get_button('gtk-edit', 'Rename collection',
                            self.rename_collection, "E"), False, True, 2)
        col_toolbar.pack_start(
            self.get_button('gtk-remove', 'Delete collection',
                            self.del_collection), False, True, 2)
        col_toolbar.pack_start(gtk.HSeparator(), False, True, 7)
        col_toolbar.pack_start(
            self.get_button('gtk-go-forward', 'Add book to collection',
                            self.add_file), False, True, 2)
        col_toolbar.pack_start(
            self.get_button('gtk-go-back', 'Remove book from collection',
                            self.del_file), False, True, 2)
        col_toolbar.pack_start(gtk.HSeparator(), False, True, 7)
        col_toolbar.pack_start(
            self.get_button('gtk-revert-to-saved', 'Revert collections',
                            self.revert), False, True, 2)

        hbox_main.add(filescroll)
        hbox_main.pack_start(col_toolbar, False, False, 2)
        hbox_main.add(colscroll)

        self.statusbar = gtk.Statusbar()

        vbox_main.pack_start(file_toolbar, False)
        vbox_main.add(hbox_main)
        vbox_main.pack_start(self.statusbar, False)

        self.window.add(vbox_main)
        self.window.show_all()
        self.status("Select your Kindle's home folder")
        gtk.main()
コード例 #21
0
    def load_from_file(self, widget):
        dialog = gtk.FileChooserDialog("Open..", self.window,
                                       gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)

        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            file_name = dialog.get_filename()
        else:
            file_name = None
        dialog.destroy()

        if file_name is None:
            return

        log = open(file_name, 'r').read()

        m = re.match('\s*Tree before operation\s+=+\s+Tree\s+=+\s+(.*?)=+',
                     log, re.UNICODE | re.DOTALL)
        if m:
            treelines = m.group(1)
            items = [(len(line) - len(line.lstrip()), line.strip())
                     for line in treelines.splitlines()]
            # Filter "root" item and decrease level
            items = [(level, name) for level, name in items[1:]]

            # The "root" items should be at level 0, adjust level to that
            min_level = min(level for level, name in items)
            items = [(level - min_level, name) for level, name in items]

            nodes = list(set([name for level, name in items]))

            relationships = []
            parent_level = {-1: None}

            for level, name in items:
                parent = parent_level[level - 1]
                relationships.append((parent, name))

                for key in list(parent_level.keys()):
                    if key > level:
                        del parent_level[key]

                parent_level[level] = name

            print "Nodes to add:", nodes
            print "Relationships:", "\n".join(str(r) for r in relationships)
            print

            for node_id in nodes:
                task = TaskNode(node_id, random_task_title(node_id),
                                self.view_tree)
                self.tree.add_node(task)

            for parent, child in relationships:
                parent_node = self.tree.get_node(parent)
                parent_node.add_child(child)
        else:
            print "Not matched"
            print "Log: ", log
コード例 #22
0
        if hasattr(button, '_filename') and button._filename:
            button.set_label(_("Wait..."))
            try:
                st=helper.get_statistics(button._filename)
            except AdveneException, e:
                st=_("Error: %s") % unicode(e)
            button.set_label(st)
            button._filename=None
        return True

    preview.connect('clicked', do_preview)

    fs=gtk.FileChooserDialog(title=title,
                             parent=None,
                             action=action,
                             buttons=( button,
                                       gtk.RESPONSE_OK,
                                       gtk.STOCK_CANCEL,
                                       gtk.RESPONSE_CANCEL ))
    fs.set_preview_widget(preview_box)

    # filter may be: 'any', 'advene', 'session', 'video'
    filters={}

    for name, descr, exts in (
        ('any', _("Any type of file"), ( '*', ) ),
        ('advene',
         _("Advene files (.xml, .azp, .apl)"),
         ('*.xml', '*.azp', '*.apl')),
        ('session', _("Advene session (.apl)"), ( '*.apl', ) ),
        ('audio', _("Audio files"), ('*.wav', '*.mp3', '*.ogg')),
コード例 #23
0
def python_export_scaled(img, drawable):
    global percent_e, width_e, height_e, orig_width, orig_height, warning_label
    orig_filename = img.filename

    orig_width = img.width
    orig_height = img.height

    # Do we already have defaults?
    para = img.parasite_find('export-scaled')
    if para:
        [ init_filename, init_percent, init_width, init_height ] = \
            para.data.split('\n')
    else:
        init_filename = orig_filename
        init_percent = 100
        init_width = img.width
        init_height = img.height

    chooser = gtk.FileChooserDialog(title=None,
                                    action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                    buttons=(gtk.STOCK_CANCEL,
                                             gtk.RESPONSE_CANCEL,
                                             gtk.STOCK_SAVE, gtk.RESPONSE_OK))

    if init_filename:
        chooser.set_current_name(os.path.basename(init_filename))
        chooser.set_current_folder(os.path.dirname(init_filename))

    vbox = gtk.VBox(spacing=8)

    hbox = gtk.HBox(spacing=8)

    l = gtk.Label("Export size:")
    l.set_alignment(1, 0)
    l.show()
    hbox.pack_start(l)

    l = gtk.Label("Percent")
    l.set_alignment(1, 0)
    hbox.pack_start(l)
    l.show()
    adj = gtk.Adjustment(float(init_percent), 1, 10000, 1, 10, 0)
    percent_e = gtk.SpinButton(adj)  #, 0, 0)

    #percent_e = gtk.Entry()
    #percent_e.set_width_chars(5)
    #percent_e.set_text("100")   # XXX Later, remember size from last time

    percent_e.connect("changed", entry_changed, 'p')
    percent_e.show()
    hbox.pack_start(percent_e)
    l = gtk.Label("%")
    l.set_alignment(0, 1)
    hbox.pack_start(l)
    l.show()

    l = gtk.Label("Width")
    l.set_alignment(1, 0)
    hbox.pack_start(l)
    l.show()
    adj = gtk.Adjustment(float(init_width), 1, 10000, 1, 10, 0)
    width_e = gtk.SpinButton(adj)
    #width_e = gtk.Entry()
    #width_e.set_width_chars(7)
    #width_e.set_text(str(img.width))
    # XXX Later, remember size from previous run
    width_e.connect("changed", entry_changed, 'w')
    width_e.show()
    hbox.pack_start(width_e)

    l = gtk.Label("Height")
    l.set_alignment(1, 0)
    hbox.pack_start(l)
    l.show()
    adj = gtk.Adjustment(float(init_height), 1, 10000, 1, 10, 0)
    height_e = gtk.SpinButton(adj)
    #height_e = gtk.Entry()
    #height_e.set_width_chars(7)
    #height_e.set_text(str(img.height))
    height_e.connect("changed", entry_changed, 'h')
    hbox.pack_start(height_e)
    height_e.show()

    hbox.show()
    vbox.pack_start(hbox)

    warning_label = gtk.Label("")
    warning_label.show()
    vbox.pack_start(warning_label)

    chooser.set_extra_widget(vbox)

    # Oh, cool, we could have shortcuts to image folders,
    # and maybe remove the stupid fstab shortcuts GTK adds for us.
    #chooser.add_shortcut_folder(folder)
    #chooser.remove_shortcut_folder(folder)

    # Loop to catch errors/warnings:
    while True:
        response = chooser.run()
        if response != gtk.RESPONSE_OK:
            chooser.destroy()
            return

        percent = float(percent_e.get_text())
        width = int(width_e.get_text())
        height = int(height_e.get_text())

        filename = chooser.get_filename()
        if filename == orig_filename:
            warning_label.set_text(
                "Change the name or the directory -- don't overwrite original file!"
            )
            continue

        # Whew, it's not the original filename, so now we can export.

        #print "export from", orig_filename, "to", filename, \
        #    "at", width, "x", height

        # Is there any point to pushing and popping the context?
        #gimp.context_pop()

        newimg = pdb.gimp_image_duplicate(img)

        # If it's XCF, we don't need to flatten or process it further,
        # just scale it:
        base, ext = os.path.splitext(filename)
        ext = ext.lower()
        if ext == '.gz' or ext == '.bz2':
            base, ext = os.path.splitext(base)
            ext = ext.lower()
        if ext != '.xcf':
            newimg.flatten()
            # XXX This could probably be smarter about flattening. Oh, well.

        newimg.scale(width, height)

        # Find any image type settings parasites (e.g. jpeg settings)
        # that got set during save, so we'll be able to use them
        # next time.
        def copy_settings_parasites(fromimg, toimg):
            for pname in fromimg.parasite_list():
                if pname[-9:] == '-settings' or pname[-13:] == '-save-options':
                    para = fromimg.parasite_find(pname)
                    if para:
                        toimg.attach_new_parasite(pname, para.flags, para.data)

        # Copy any settings parasites we may have saved from previous runs:
        copy_settings_parasites(img, newimg)

        # gimp-file-save insists on being passed a valid layer,
        # even if saving to a multilayer format such as XCF. Go figure.
        try:
            # I don't get it. What's the rule for whether gimp_file_save
            # will prompt for jpg parameters? Saving back to an existing
            # file doesn't seem to help.
            # run_mode=RUN_WITH_LAST_VALS is supposed to prevent prompting,
            # but actually seems to do nothing. Copying the -save-options
            # parasites is more effective.
            dpy = chooser.get_display()
            chooser.hide()
            dpy.sync()
            pdb.gimp_file_save(newimg,
                               newimg.active_layer,
                               filename,
                               filename,
                               run_mode=RUN_WITH_LAST_VALS)
        except RuntimeError, e:
            #warning_label.set_text("Didn't save to " + filename
            #                       + ":" + str(e))
            markup = '<span foreground="red" size="larger" weight=\"bold">'
            markup_end = '</span>'
            warning_label.set_markup(markup + "Didn't save to " + filename +
                                     ":" + str(e) + markup_end)
            gimp.delete(newimg)
            chooser.show()
            continue

        chooser.destroy()

        #gimp.context_pop()

        copy_settings_parasites(newimg, img)

        gimp.delete(newimg)
        #gimp.Display(newimg)

        # Save parameters as a parasite, even if saving failed,
        # so we can default to them next time.
        # Save: percent, width, height
        # I have no idea what the flags are -- the doc doesn't say.
        para = img.attach_new_parasite(
            'export-scaled', 0,
            '%s\n%d\n%d\n%d' % (filename, percent, width, height))
        # img.parasite_attach(para)

        return
コード例 #24
0
ファイル: properties.py プロジェクト: jaliste/sanaviron.gtk-3
    def __init__(self, application):
        gtk.ScrolledWindow.__init__(self)

        self.observer = Observer()

        self.objects = dict()

        from canvas import Canvas
        self.canvas = Canvas(application)

        self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)

        properties = gtk.VBox()
        self.add_with_viewport(properties)

        self.group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)

        #---START-------------------------------------------------------
        button = Button(_("General properties"))
        properties.pack_start(button, False, False)

        form = Form("general", self)
        button.add(form)

        form.add_section(_("Units"))

        entry = gtk.combo_box_new_text()
        entry.append_text(CENTIMETERS)
        entry.append_text(MILLIMETERS)
        entry.append_text(DOTS)
        entry.append_text(INCHES)
        entry.set_active(1)

        form.add_entry(_("Preferred linear unit"), entry, "linear-unit")

        entry = gtk.combo_box_new_text()
        entry.append_text(DEGREES)
        entry.append_text(RADIANS)
        entry.set_active(1)

        form.add_entry(_("Preferred angular unit"), entry, "angular-unit")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Document properties"))
        properties.pack_start(button, False, False)

        form = Form("document", self)
        button.add(form)

        form.add_section(_("Size"))

        entry = LinearEntry()
        form.add_entry(_("Width"), entry, "width")

        entry = LinearEntry()
        form.add_entry(_("Height"), entry, "height")

        form.add_section(_("Margins"))

        entry = LinearEntry()
        form.add_entry(_("Top"), entry, "top-margin")

        entry = LinearEntry()
        form.add_entry(_("Bottom"), entry, "bottom-margin")

        entry = LinearEntry()
        form.add_entry(_("Left"), entry, "left-margin")

        entry = LinearEntry()
        form.add_entry(_("Right"), entry, "right-margin")

        form.add_section(_("Config"))

        entry = LinearEntry()
        form.add_entry(_("Grid size"), entry, "grid-size")

        entry = LinearEntry()
        form.add_entry(_("Guides size"), entry, "guides-size")

        entry = gtk.CheckButton(_("Show margins"))
        form.add_entry(None, entry, "margins-active")

        entry = gtk.CheckButton(_("Show guides"))
        form.add_entry(None, entry, "guides-active")

        entry = gtk.CheckButton(_("Show grid"))
        form.add_entry(None, entry, "grid-active")

        entry = gtk.CheckButton(_("Enable snap"))
        form.add_entry(None, entry, "snap")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Line properties"))
        self.objects["Line"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("line", self)
        button.add(form)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Box properties"))
        self.objects["Box"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("box", self)
        button.add(form)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Rounded box properties"))
        self.objects["Rounded"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("rounded", self)
        button.add(form)

        form.add_section(_("Shape"))

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Radius"), entry, "radius")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Text properties"))
        self.objects["Text"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("text", self)
        button.add(form)

        form.add_section(_("Format"))

        entry = gtk.FontButton()
        entry.connect("font-set", self.change_font)
        form.add_entry(_("Font"), entry, "font")

        entry = gtk.CheckButton(_("Preserve aspect"))
        entry.connect("toggled", self.preserve)
        form.add_entry(None, entry, "preserve")

        form.add_section(_("Text"))

        entry = TextPad(application)
        self.disconnect_handler = entry.buffer.connect("changed", self.changed)
        entry.connect("cursor-moved", self.cursor_moved)
        form.add_entry(None, entry, "text")
        #---END---------------------------------------------------------

        #---START--------ARC properties-----------------------------------------------
        button = Button(_("Arc properties"))
        self.objects["Arc"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("arc", self)
        button.add(form)

        form.add_section(_("Angle"))
        self.angle_start = AngularEntry()
        form.add_entry(_("Start Angle"), self.angle_start, "start")
        self.angle_start.spin.connect("value-changed", self.change_angle_start)

        self.angle_stop = AngularEntry()
        form.add_entry(_("Stop Angle"), self.angle_stop, "stop")
        self.angle_stop.spin.connect("value-changed", self.change_angle_stop)

        form.add_section(_("Other"))
        self.closed_btn = gtk.CheckButton()
        form.add_entry(_("Closed Arc"), self.closed_btn, "closed")
        self.closed_btn.connect("toggled", self.close_arc)

        self.closed_at_centre_btn = gtk.CheckButton()
        self.closed_at_centre_btn.set_active(1)
        form.add_entry(_("Closed Arc at Centre"), self.closed_at_centre_btn,
                       "closed-at-centre")
        self.closed_at_centre_btn.connect("toggled", self.close_at_centre_arc)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Table properties"))
        self.objects["Table"] = button
        properties.pack_start(button, False, False)

        form = PositionedObjectForm("table", self)
        button.add(form)

        form.add_section(_("Spacing"))

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Vertical"), entry, "vertical-spacing")

        entry = LinearEntry()
        entry.set_value(0)
        form.add_entry(_("Horizontal"), entry, "horizontal-spacing")

        form.add_section(_("Size"))

        entry = LinearEntry()
        entry.set_value(1)
        entry.connect("value-changed", self.set_table_columns)
        form.add_entry(_("Columns"), entry, "columns")

        entry = LinearEntry()
        entry.set_value(5)
        entry.connect("value-changed", self.set_table_rows)
        form.add_entry(_("Rows"), entry, "rows")

        form.add_section(_("Color"))

        entry = gtk.ColorButton()
        form.add_entry(_("Stroke"), entry, "stroke")

        entry = gtk.ColorButton()
        form.add_entry(_("Fill"), entry, "fill")

        form.add_section(_("Format"))

        entry = gtk.FontButton()
        entry.connect("font-set", self.set_table_font)
        form.add_entry(_("Font"), entry, "font")

        form.add_section(_("Columns"))

        entry = ColumnsEditor()
        entry.add_column()
        entry.connect("width-edited", self.set_table_column_width)
        entry.connect("title-edited", self.set_table_column_title)
        form.add_entry(None, entry, "columns-editor")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Barcode properties"))
        self.objects["BarCode"] = button
        properties.pack_start(button, False, False)

        form = ColorizedObjectForm("barcode", self)
        button.add(form)

        form.add_section(_("Barcode"))

        entry = gtk.combo_box_new_text()
        entry.connect("changed", self.changed_barcode_type)
        for type in sorted(barcodes, key=lambda type: barcodes[type]):
            entry.append_text(type)
        form.add_entry(_("Type"), entry, "type")

        entry = gtk.Entry()
        entry.connect("changed", self.changed_barcode_code)
        form.add_entry(_("Code"), entry, "code")
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Image properties"))
        self.objects["Image"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("image", self)
        button.add(form)

        form.add_section(_("Image"))

        def update_preview(dialog, preview):
            filename = dialog.get_preview_filename()
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(
                    filename, 128, 128)
                preview.set_from_pixbuf(pixbuf)
                have_preview = True
            except:
                have_preview = False
            dialog.set_preview_widget_active(have_preview)

        dialog = gtk.FileChooserDialog(
            title="Source image file",
            #parent = self,
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OPEN,
                     gtk.RESPONSE_ACCEPT),
            backend=None)

        preview = gtk.Image()

        dialog.set_preview_widget(preview)
        dialog.connect("update-preview", update_preview, preview)

        #dialog.set_transient_for(self)
        dialog.set_default_response(gtk.RESPONSE_OK)

        def add_filter(dialog, name, pattern, type=None):
            filter = gtk.FileFilter()
            filter.set_name(name)
            if type:
                filter.add_mime_type(type)
            filter.add_pattern(pattern)
            dialog.add_filter(filter)

        add_filter(dialog, "PNG files", "*.png", "image/png")
        add_filter(dialog, "JPG files", "*.jpg", "image/jpg")
        add_filter(dialog, "All files", "*")

        dialog.connect("file-activated", self.changed_image_file)

        entry = gtk.FileChooserButton(dialog)
        form.add_entry(_("Image file"), entry, "file", True)
        #---END---------------------------------------------------------

        #---START-------------------------------------------------------
        button = Button(_("Chart properties"))
        self.objects["Chart"] = button
        properties.pack_start(button, False, False)

        form = SizedObjectForm("chart", self)
        button.add(form)

        form.add_section(_("Chart"))

        entry = gtk.combo_box_new_text()
        entry.connect("changed", self.changed_chart_type)
        for type in sorted(chart_types, key=lambda type: chart_types[type]):
            entry.append_text(type)
        form.add_entry(_("Type"), entry, "type")
        #---END---------------------------------------------------------

        fill = gtk.Label("\n")
        properties.add(fill)
コード例 #25
0
 def __init__(self, title, parent):
     self.dialog = dialog = \
         gtk.FileChooserDialog(title, parent, self.mode, self.buttons)
コード例 #26
0
def open_file_gui(window_title="Open",
                  set_name=None,
                  add_pattern=None,
                  allow_no_file=True):
    """
    GUI for opening a file with a file browser.

    :param window_title: Window title
    :type window_title: string
    :param set_name: Title of filter
    :type set_name: string
    :param add_pattern: Acceptable file patterns in filter, e.g ["\\*.pdf"]
    :type add_pattern: list
    :param allow_no_file: Allow for no file to be selected
    :type allow_no_file: bool

    :returns: Name of file selected with GUI.
    :rtype: string
    """

    # Make a string for option of not selecting a file
    if set_name:
        no_file = "No %s" % set_name
    else:
        no_file = "No file"

    # Make buttons, allowing for cae in which no cancel button is desired
    if allow_no_file:
        buttons = (no_file, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                   gtk.RESPONSE_OK)
    else:
        buttons = (gtk.STOCK_OPEN, gtk.RESPONSE_OK)

    # Select the file from a dialog box
    dialog = gtk.FileChooserDialog(title=window_title,
                                   action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                   buttons=buttons)
    dialog.set_default_response(gtk.RESPONSE_OK)
    dialog.set_current_folder(os.getcwd())

    # Only show particular files
    file_filter = gtk.FileFilter()
    if set_name:
        file_filter.set_name(set_name)
    if add_pattern:
        for pattern in add_pattern:
            file_filter.add_pattern(pattern)
    dialog.add_filter(file_filter)

    response = dialog.run()

    if response == gtk.RESPONSE_OK:
        # Save the file name/path
        file_name = dialog.get_filename()
    elif response == gtk.RESPONSE_CANCEL:
        warnings.warn("No file selected")
        file_name = None
    else:
        warnings.warn("Unexpected response")
        file_name = None
        exit()

    dialog.destroy()
    print 'File: %s selected' % file_name

    return file_name
コード例 #27
0
		def __init__(self,frame,text):
			self.frm=frame
			self.widget = gtk.FileChooserDialog(text,None,gtk.FILE_CHOOSER_ACTION_OPEN,(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN, gtk.RESPONSE_OK))
			self.widget.set_default_response(gtk.RESPONSE_OK)
コード例 #28
0
 def buttonImportSensors_clicked_cb(self,widget):
     #dialog = gtk.FileChooserDialog(_("Abrir.."), None, gtk.FILE_CHOOSER_ACTION_OPEN,
     dialog = gtk.FileChooserDialog(_("Open.."), None, gtk.FILE_CHOOSER_ACTION_OPEN,
     (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN, gtk.RESPONSE_OK))        
     dialog.set_default_response(gtk.RESPONSE_OK)
     dialog.set_current_folder(dialog.get_current_folder()+"/sensors/")
     response = dialog.run()
     if response == gtk.RESPONSE_OK:
         filename = dialog.get_filename()
         dialog.destroy()
         try:
             FILE = open(filename,"r")
         except Exception as e:
             self.showError(e.__str__())
             return
         
         filetype = filename.split('.')[-1].lower()
         if not (filetype in ['csv','sensor']):
             self.showError(_('Error: unrecognised file type: %s') % filename)
             return
         
         try:
             if filetype == 'sensor':
                 c = ConfigParser()
                 c.readfp(FILE)
                 name = c.get("SENSOR","name")
                 unit = c.get("SENSOR","unit")
                 description = c.get("SENSOR","description")
                 sensor = SensorType(name,unit,description,[])
                 
                 p = 0
                 while True:
                     try:
                         x = c.getint(  'POINT '+str(p), 'x')
                         y = c.getfloat('POINT '+str(p), 'y')
                         sensor.add_point([x,y])
                         p += 1
                     except:
                         break
                     
             else: # CSV
                 # Line 1: name, unit, description
                 name, unit, description = FILE.readline().replace('\r\n','').split(',')
                 sensor = SensorType(name,unit,description,[])
                 # Line 2: skip
                 FILE.readline()
                 # Line 3..<BLANK>: x,y
                 for line in FILE:
                     line = line.replace('\r\n','')
                     if line == '':
                         break
                     x,y = line.split(',')
                     sensor.add_point([int(x), float(y)])
                                              
             self.liststore.append([name,unit,description])
             self.sensorTypes.append(sensor)
             self.writeSensorsConfig()
         
         except Exception as e:
             self.showError(e.__str__())
         
         FILE.close()
コード例 #29
0
ファイル: save.py プロジェクト: uu1477/MyAse
def save_dialog(gui):
    dialog = gtk.FileChooserDialog(_('Save ...'), None,
                                   gtk.FILE_CHOOSER_ACTION_SAVE,
                                   (gtk.STOCK_SAVE, gtk.RESPONSE_OK,
                                    gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
    dialog.set_current_name('')
    dialog.set_current_folder(os.getcwd())
    text = _('Append name with "@n" in order to write image number "n" '
             'instead of the current image.\n'
             'Append "@start:stop" or "@start:stop:step" if you want to write '
             'a range of images.\n'
             'You can leave out "start" and "stop" so that "name@:" will '
             'give you all images.\n'
             'Negative numbers count from the last image '
             '("name@-1": last image, "name@-2:": last two).')
    dialog.set_extra_widget(gtk.Label(text))
    response = dialog.run()
    if response == gtk.RESPONSE_OK:
        filename = dialog.get_filename()
        dialog.destroy()
    else:
        dialog.destroy()
        return

    filename, index = parse_filename(filename)
    if index is None:
        index = slice(gui.frame, gui.frame + 1)
    if isinstance(index, str):
        index = string2index(index)
    format = filetype(filename, read=False)
    io = get_ioformat(format)

    extra = {}
    remove_hidden = False
    if format in ['png', 'eps', 'pov']:
        bbox = np.empty(4)
        size = np.array([gui.width, gui.height]) / gui.scale
        bbox[0:2] = np.dot(gui.center, gui.axes[:, :2]) - size / 2
        bbox[2:] = bbox[:2] + size
        extra['rotation'] = gui.axes
        extra['show_unit_cell'] = gui.ui.get_widget(
            '/MenuBar/ViewMenu/ShowUnitCell').get_active()
        extra['bbox'] = bbox
        extra['colors'] = gui.get_colors(rgb=True)[gui.images.visible]
        remove_hidden = True

    images = [
        gui.images.get_atoms(i, remove_hidden=remove_hidden)
        for i in range(*index.indices(gui.images.nimages))
    ]

    if len(images) > 1 and io.single:
        # We want to write multiple images, but the file format does not
        # support it.  The solution is to write multiple files, inserting
        # a number in the file name before the suffix.
        j = filename.rfind('.')
        filename = filename[:j] + '{0:05d}' + filename[j:]
        for i, atoms in enumerate(images):
            write(filename.format(i), atoms, **extra)
    else:
        write(filename, images, **extra)
コード例 #30
0
ファイル: gui.py プロジェクト: morristech/spelt
    def __create_dialogs(self):
        self.open_chooser = gtk.FileChooserDialog(
            title=_('Select language database to open'),
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))

        self.save_chooser = gtk.FileChooserDialog(
            title=_('Save as...'),
            action=gtk.FILE_CHOOSER_ACTION_SAVE,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))

        all_filter = gtk.FileFilter()
        all_filter.set_name(_('All files'))
        all_filter.add_pattern('*')

        langdb_filter = gtk.FileFilter()
        langdb_filter.set_name(_('Language Database'))
        langdb_filter.add_mime_type('text/xml')
        langdb_filter.add_pattern('*.' + LanguageDB.FILE_EXTENSION)

        self.open_chooser.add_filter(all_filter)
        self.open_chooser.add_filter(langdb_filter)
        self.save_chooser.add_filter(langdb_filter)
        self.save_chooser.add_filter(all_filter)

        # Message dialog
        self.dlg_error = gtk.MessageDialog(parent=self.main_window,
                                           flags=gtk.DIALOG_MODAL,
                                           type=gtk.MESSAGE_ERROR,
                                           buttons=gtk.BUTTONS_OK,
                                           message_format='')

        self.dlg_info = gtk.MessageDialog(parent=self.main_window,
                                          flags=gtk.DIALOG_MODAL,
                                          type=gtk.MESSAGE_INFO,
                                          buttons=gtk.BUTTONS_OK,
                                          message_format='')

        self.dlg_prompt = gtk.MessageDialog(parent=self.main_window,
                                            flags=gtk.DIALOG_MODAL,
                                            type=gtk.MESSAGE_QUESTION,
                                            buttons=gtk.BUTTONS_YES_NO,
                                            message_format='')

        # Source dialog wrapper
        self.dlg_source = DlgSource(self.glade, self.icon_filename)
        # LanguageDB loading dialog
        self.dlg_dbload = DlgDBLoad(self.glade, self)

        # About dialog
        def on_about_url(dialog, uri, data):
            if data == "mail":
                openmailto.mailto(uri)
            elif data == "url":
                openmailto.open(uri)

        self.dlg_about = gtk.AboutDialog()
        gtk.about_dialog_set_url_hook(on_about_url, "url")
        gtk.about_dialog_set_email_hook(on_about_url, "mail")
        self.dlg_about.set_name("Spelt")
        self.dlg_about.set_version(__version__)
        self.dlg_about.set_copyright(
            _("© Copyright 2007-2008 Zuza Software Foundation"))
        self.dlg_about.set_comments(
            _("A tool to categorize words from a language database according to its root."
              ))
        self.dlg_about.set_license(LICENSE)
        self.dlg_about.set_website(
            "http://translate.sourceforge.net/wiki/spelt/index")
        self.dlg_about.set_website_label(_("Spelt website"))
        self.dlg_about.set_authors(
            ["Walter Leibbrandt <*****@*****.**>"])
        self.dlg_about.set_translator_credits(_("translator-credits"))
        self.dlg_about.set_icon(self.main_window.get_icon())
        # XXX entries that we may want to add (commented out):
        #self.dlg_about.set_logo()
        self.dlg_about.set_documenters([
            "Friedel Wolff <*****@*****.**>",
            "Wynand Winterbach <*****@*****.**>",
            "Walter Leibbrandt <*****@*****.**>"
        ])
        #self.dlg_about.set_artists()

        # Set icon on all dialogs
        for dlg in (self.open_chooser, self.save_chooser, self.dlg_error,
                    self.dlg_info, self.dlg_prompt, self.dlg_about):
            dlg.set_icon_from_file(self.icon_filename)