コード例 #1
0
ファイル: carrusel.py プロジェクト: adrianvilchez/Carrusel
    def __init__(self):
        super(Carrusel, self).__init__()
        self.builder = Gtk.Builder()

        # Cargamos el XML glade que hemos creado.
        self.builder.add_from_file(
            "/home/mrpatxi/Github/Carrusel/LaSeniaCarrusel/Glade/carrusel.glade"
        )

        # Creamos una variable para cargar los menejadores de los eventos.
        self.handlers = {
            "on_carrusel_window_destroy":
            self.on_carrusel_window_destroy,
            "on_save_button_clicked":
            self.on_save_button_clicked,
            "on_add_button_docs_clicked":
            self.on_add_button_docs_clicked,
            "on_del_button_docs_clicked":
            self.on_del_button_docs_clicked,
            "on_icon_view_docs_item_activated":
            self.on_icon_view_docs_item_activated,
            "on_add_button_pdfs_clicked":
            self.on_add_button_pdfs_clicked,
            "on_del_button_pdfs_clicked":
            self.on_del_button_pdfs_clicked,
            "on_icon_view_pdfs_item_activated":
            self.on_icon_view_pdfs_item_activated,
            "on_add_button_photos_clicked":
            self.on_add_button_photos_clicked,
            "on_del_button_photos_clicked":
            self.on_del_button_photos_clicked,
            "on_icon_view_photos_item_activated":
            self.on_icon_view_photos_item_activated,
            "on_generate_button_clicked":
            self.on_generate_button_clicked,
            "on_label_dnd_docs_drag_data_received":
            self.on_label_dnd_docs_drag_data_received,
            "on_label_dnd_pdfs_drag_data_received":
            self.on_label_dnd_pdfs_drag_data_received,
            "on_label_dnd_photos_drag_data_received":
            self.on_label_dnd_photos_drag_data_received
        }

        # Conectamos los manejadores del archivo glade con las funciones que hemos declarado.
        self.builder.connect_signals(self.handlers)

        # Accedemos al objeto "Window" mediante el identifivador declarado en el XML de "Glade".
        self.window = self.builder.get_object("carrusel_window")

        # Accedemos al objeto "paginas_carrusel mediante el identifivador declarado en el XML de "Glade".
        self.paginas_carrusel = self.builder.get_object("paginas_carrusel")

        # Enlaces
        # Accedemos al objeto "TextView" mediante el identifivador declarado en el XML de "Glade".
        self.text_view_links = self.builder.get_object("text_view_links")

        # Creamos una variable para obtener el buffer del "TextView".
        self.buf = self.text_view_links.get_buffer()

        sw_links = self.builder.get_object("desplazamiento_links")
        sw_links.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        sw_links.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)

        sw_links.add(self.text_view_links)

        with open("/home/mrpatxi/senia-carrusel-workspace/enlaces.txt",
                  'r') as f:
            data = f.read()
            self.buf.set_text(data)

        self.fileIcon = self.get_icon(Gtk.STOCK_FILE)
        self.dirIcon = self.get_icon(Gtk.STOCK_DIRECTORY)

        # Documentos
        ################################### icon_view_docs #########################
        self.icon_view_docs = self.builder.get_object("icon_view_docs")

        self.label_dnd_docs = self.builder.get_object("label_dnd_docs")

        self.label_dnd_docs.drag_dest_set(Gtk.DestDefaults.ALL, [],
                                          Gdk.DragAction.COPY)

        self.add_text_targets_docs()

        self.docs_dir = os.path.expanduser(
            '/home/mrpatxi/senia-carrusel-workspace/docs')
        self.cur_dir_docs = self.docs_dir

        sw_docs = self.builder.get_object("desplazamiento_docs")
        sw_docs.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        sw_docs.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)

        self.store_docs = self.create_store_docs()
        self.fill_store_docs()

        self.icon_view_docs.set_model(self.store_docs)
        #icon_view_docs.set_selection_mode(Gtk.SelectionMode.MULTIPLE)
        self.icon_view_docs.set_selection_mode(Gtk.SelectionMode.SINGLE)

        self.icon_view_docs.set_text_column(COL_PATH)
        self.icon_view_docs.set_pixbuf_column(COL_PIXBUF)

        sw_docs.add(self.icon_view_docs)
        self.icon_view_docs.grab_focus()
        self.model_docs = self.icon_view_docs.get_model()

        # PDF's
        self.icon_view_pdfs = self.builder.get_object("icon_view_pdfs")

        self.label_dnd_pdfs = self.builder.get_object("label_dnd_pdfs")

        self.label_dnd_pdfs.drag_dest_set(Gtk.DestDefaults.ALL, [],
                                          Gdk.DragAction.COPY)

        self.add_text_targets_pdfs()

        self.pdfs_dir = os.path.expanduser(
            '/home/mrpatxi/senia-carrusel-workspace/pdfs')
        self.cur_dir_pdfs = self.pdfs_dir

        sw_pdfs = self.builder.get_object("desplazamiento_pdfs")
        sw_pdfs.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        sw_pdfs.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)

        self.store_pdfs = self.create_store_pdfs()
        self.fill_store_pdfs()

        self.icon_view_pdfs.set_model(self.store_pdfs)
        self.icon_view_pdfs.set_selection_mode(Gtk.SelectionMode.SINGLE)

        self.icon_view_pdfs.set_text_column(COL_PATH)
        self.icon_view_pdfs.set_pixbuf_column(COL_PIXBUF)

        sw_pdfs.add(self.icon_view_pdfs)
        self.icon_view_pdfs.grab_focus()
        self.model_pdfs = self.icon_view_pdfs.get_model()

        # Images
        self.icon_view_photos = self.builder.get_object("icon_view_photos")

        self.label_dnd_photos = self.builder.get_object("label_dnd_photos")

        self.label_dnd_photos.drag_dest_set(Gtk.DestDefaults.ALL, [],
                                            Gdk.DragAction.COPY)

        self.add_text_targets_photos()

        self.photos_dir = os.path.expanduser(
            '/home/mrpatxi/senia-carrusel-workspace/photos')
        self.cur_dir_photos = self.photos_dir

        sw_photos = self.builder.get_object("desplazamiento_photos")
        sw_photos.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        sw_photos.set_policy(Gtk.PolicyType.AUTOMATIC,
                             Gtk.PolicyType.AUTOMATIC)

        self.store_photos = self.create_store_photos()
        self.fill_store_photos()

        self.icon_view_photos.set_model(self.store_photos)
        self.icon_view_photos.set_selection_mode(Gtk.SelectionMode.SINGLE)

        self.icon_view_photos.set_text_column(COL_PATH)
        self.icon_view_photos.set_pixbuf_column(COL_PIXBUF)

        sw_photos.add(self.icon_view_photos)
        self.icon_view_photos.grab_focus()
        self.model_photos = self.icon_view_photos.get_model()

        # Creamos la visiluacización de los eventos de la ventana.

        self.sw_viewport = self.builder.get_object("desplazamiento_viewport")
        self.viewport = self.builder.get_object("viewport")

        # Creamos la terminal
        self.terminal = Vte.Terminal()
        self.terminal.spawn_sync(
            Vte.PtyFlags.DEFAULT,
            os.environ['HOME'],
            ["/bin/sh"],
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
        )

        self.command = "bash /usr/bin/senia-carrusel\n"
        self.viewport.add(self.terminal)

        self.sw_viewport.add(self.viewport)
        self.window.show_all()
コード例 #2
0
ファイル: GDebiGtk.py プロジェクト: frontjang/gdebi
    def __init__(self, datadir, options, file=""):
        GDebiCommon.__init__(self, datadir, options, file)

        SimpleGtkbuilderApp.__init__(self,
                                     path=os.path.join(datadir, "gdebi.ui"),
                                     domain="gdebi")

        # use a nicer default icon
        icons = Gtk.IconTheme.get_default()
        try:
            logo = icons.load_icon("gnome-mime-application-x-deb", 48, 0)
            if logo != "":
                Gtk.Window.set_default_icon_list([logo])
        except Exception as e:
            logging.warning("Error loading logo %s" % e)

        # create terminal
        self.vte_terminal = Vte.Terminal()
        # FIXME: this sucks but without it the terminal window is only
        #        1 line height
        self.vte_terminal.set_size_request(80 * 10, 25 * 10)
        menu = Gtk.Menu()
        menu_items = Gtk.MenuItem(label=_("Copy selected text"))
        menu.append(menu_items)
        menu_items.connect("activate", self.menu_action, self.vte_terminal)
        menu_items.show()
        self.vte_terminal.connect_object("event", self.vte_event, menu)
        self.hbox_install_terminal.pack_start(self.vte_terminal, True, True, 0)
        scrollbar = Gtk.VScrollbar(
            adjustment=self.vte_terminal.get_vadjustment())
        self.hbox_install_terminal.pack_start(scrollbar, False, False, 0)

        # setup status
        self.context = self.statusbar_main.get_context_id(
            "context_main_window")
        self.statusbar_main.push(self.context, _("Loading..."))

        # show what we have
        self.window_main.realize()
        self.window_main.show()

        # setup drag'n'drop
        # FIXME: this seems to have no effect, droping in nautilus does nothing
        target_entry = Gtk.TargetEntry().new('text/uri-list', 0, 0)
        self.window_main.drag_dest_set(Gtk.DestDefaults.ALL, [target_entry],
                                       Gdk.DragAction.COPY)
        self.window_main.connect("drag_data_received",
                                 self.on_window_main_drag_data_received)

        # Check file with gio
        file = self.gio_copy_in_place(file)

        #self.vte_terminal.set_font_from_string("monospace 10")
        self.cprogress = self.CacheProgressAdapter(self.progressbar_cache)
        if not self.openCache():
            self.show_alert(Gtk.MessageType.ERROR, self.error_header,
                            self.error_body)
            sys.exit(1)
        self.statusbar_main.push(self.context, "")

        # setup the details treeview
        self.details_list = Gtk.ListStore(GObject.TYPE_STRING)
        column = Gtk.TreeViewColumn("")
        render = Gtk.CellRendererText()
        column.pack_start(render, True)
        column.add_attribute(render, "markup", 0)
        self.treeview_details.append_column(column)
        self.treeview_details.set_model(self.details_list)

        # setup the files treeview
        column = Gtk.TreeViewColumn("")
        render = Gtk.CellRendererText()
        column.pack_start(render, True)
        column.add_attribute(render, "text", 0)
        self.treeview_files.append_column(column)

        # empty config
        self.synaptic_config = apt_pkg.Configuration()

        if file != "" and os.path.exists(file):
            self.open(file)

        self.window_main.set_sensitive(True)
コード例 #3
0
    def __init__(self):
        Gtk.Window.__init__(self, title=NAME)

        # Attempt to use tux as the icon. If it fails, that's okay
        try:
            self.set_icon_name("{{ tux_icon_name }}")
        except GLib.GError as err:
            logging.warning("Unable to set Tux icon", exc_info=err)

        # Create a box to contain all elements that will be added to the window
        self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        self.add(self.vbox)

        self.create_toolbar()

        contents = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        contents.set_border_width(10)

        instruction_text = (
            "Select the course configurations to add/update"
            " (at this time courses cannot be removed)."
        )
        label = Gtk.Label(label=instruction_text)
        label.set_xalign(0.0)
        label.set_yalign(0.0)

        contents.pack_start(label, False, False, 0)

        courses_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        # This button doesn't do anything. Common is always run
        refresh = Gtk.CheckButton(label="Base configuration")
        refresh.set_tooltip_text("This option is required")
        refresh.set_active(True)
        refresh.set_sensitive(False)
        courses_box.pack_start(refresh, False, False, 0)

        # Add a checkbox for every course; sorting is necessary because
        # dictionaries do not guarantee that order is preserved
        for (course, tag) in sorted(COURSES.items()):
            checkbox = Gtk.CheckButton(label=course)
            checkbox.set_tooltip_text("Configure for %s" % course)
            courses_box.pack_start(checkbox, False, False, 0)
            if tag in USER_CONFIG['roles_this_run']:
                checkbox.set_active(True)
            checkbox.connect("toggled", self.on_course_toggled, tag)
            self.checkboxes.append(checkbox)
        contents.pack_start(courses_box, False, False, 0)

        # Add run and cancel buttons
        button_box = Gtk.Box(spacing=6)
        self.run_button = Gtk.Button.new_with_label("Run")
        self.run_button.set_tooltip_text("Configure the VM")
        self.run_button.connect("clicked", self.on_run_clicked)
        button_box.pack_start(self.run_button, True, True, 0)
        self.cancel_button = Gtk.Button.new_with_mnemonic("_Quit")
        self.cancel_button.connect("clicked", Gtk.main_quit)
        button_box.pack_end(self.cancel_button, True, True, 0)
        contents.pack_end(button_box, False, True, 0)

        # Add the terminal to the window
        self.terminal = Vte.Terminal()
        # Prevent the user from entering text or ^C
        self.terminal.set_input_enabled(False)
        # Ensure that if text is written, the user sees it
        self.terminal.set_scroll_on_output(True)
        # Ensure that all lines can be seen (default is only 512)
        self.terminal.set_scrollback_lines(-1)
        self.terminal.connect("child-exited", self.sub_command_exited)
        contents.pack_end(self.terminal, True, True, 0)
        self.vbox.pack_end(contents, True, True, 0)
コード例 #4
0
ファイル: caja-terminal.py プロジェクト: rbuj/caja-terminal
 def get_widget(self, uri, window):
     """Returns the widgets to display to Caja."""
     #Kill old child process
     try:
         window.nt_lastpid
     except AttributeError:  #First terminal of the window
         window.nt_lastpid = -1
     else:  #Kill old child
         if window.nt_lastpid > 0:
             try:
                 os.kill(window.nt_lastpid, signal.SIGKILL)
             except:
                 pass
             finally:
                 window.nt_lastpid = -1
     #Set some variables for new windows
     try:
         window.nt_termheight
     except AttributeError:
         window.nt_termheight = -1
     try:
         window.nt_termhidden
     except AttributeError:
         window.nt_termhidden = CONF['general_starthidden']
     #If it's not a local folder, directory = $HOME
     if uri[:7] == "file://":
         path = urllib.url2pathname(uri[7:])
     else:
         path = os.environ.get("HOME")
     #Disable for desktop folder
     if uri.startswith("x-caja-desktop://"):
         return
     #White list
     if not CONF['folders_showinall'] and \
     not match_path(path, CONF['folders_list']):
         return
     #GUI
     gui = Gtk.Builder()
     gui.set_translation_domain(__appname__)
     gui.add_from_file(TERMINAL_GUI_FILE)
     vboxMain = gui.get_object("vboxMain")
     #### hboxHidden ####
     hboxHidden = gui.get_object("hboxHidden")
     if window.nt_termhidden:
         hboxHidden.show()
     else:
         hboxHidden.hide()
     btnPref2 = gui.get_object("btnPref2")
     btnHide = gui.get_object("btnHide")
     btnShow = gui.get_object("btnShow")
     #### hboxTerm ####
     hboxTerm = gui.get_object("hboxTerm")
     if window.nt_termhidden:
         hboxTerm.hide()
     else:
         hboxTerm.show()
     btnPref = gui.get_object("btnPref")
     sclwinTerm = gui.get_object("sclwinTerm")
     #terminal
     terminal = Vte.Terminal()
     terminal.last_size = window.nt_termheight
     self.fork_cmd(window, terminal, sclwinTerm, path)
     terminal.show()
     sclwinTerm.add(terminal)
     #scrollbar
     terminal.set_hadjustment(gui.get_object("adjH"))
     terminal.set_vadjustment(gui.get_object("adjV"))
     if CONF['general_showscrollbar']:
         vpolicy = Gtk.PolicyType.ALWAYS
     else:
         vpolicy = Gtk.PolicyType.NEVER
     sclwinTerm.set_policy(
         Gtk.PolicyType.NEVER,  #Horizontal
         vpolicy,  #Vertical
     )
     if window.nt_termheight == -1:
         window.nt_termheight = terminal.get_char_height(
         ) * CONF['general_defheight']
     sclwinTerm.set_size_request(-1, window.nt_termheight)
     #Apply config on the terminal
     self._set_terminal(terminal)
     #### evResize ####
     evResize = gui.get_object("evResize")
     if window.nt_termhidden:
         evResize.hide()
     else:
         evResize.show()
     #### Signals ####
     #evResize
     evResize.connect("enter-notify-event",
                      self.on_evResize_enter_notify_event, sclwinTerm)
     evResize.connect("leave-notify-event",
                      self.on_evResize_leave_notify_event)
     evResize.connect("motion-notify-event",
                      self.on_evResize_motion_notify_event, sclwinTerm,
                      terminal, window)
     #Button preferences
     btnPref.connect("clicked", self.preferences, terminal)
     #Button preferences 2
     btnPref2.connect("clicked", self.preferences, terminal)
     #Button Hide
     btnHide.connect(
         "clicked",
         self.hide,
         window,
         hboxHidden,
         hboxTerm,
         evResize,
     )
     #Button Show
     btnShow.connect(
         "clicked",
         self.show,
         window,
         hboxHidden,
         hboxTerm,
         terminal,
         evResize,
     )
     #Terminal
     terminal.connect("destroy", self.on_terminal_destroy, window)
     terminal.connect("child-exited", self.on_terminal_child_exited)
     terminal.connect(
         "commit",
         self.on_terminal_commit,
         window,
         sclwinTerm,
         path,
     )
     terminal.connect(
         "focus",
         self.on_terminal_need_child,
         window,
         terminal,
         sclwinTerm,
         path,
     )
     if Gtk.check_version(3, 0, 0) is None:
         terminal.connect(
             "draw",
             self.on_terminal_need_child,
             window,
             terminal,
             sclwinTerm,
             path,
         )
     else:
         terminal.connect(
             "expose-event",
             self.on_terminal_need_child,
             window,
             terminal,
             sclwinTerm,
             path,
         )
     terminal.connect(
         "button-press-event",
         self.on_terminal_need_child,
         window,
         terminal,
         sclwinTerm,
         path,
     )
     terminal.connect(
         "key-press-event",
         self.on_terminal_key_press_event,
         window,
         sclwinTerm,
         path,
     )
     terminal.connect("key-release-event",
                      self.on_terminal_key_release_event)
     #DnD
     try:
         # Missing from Gtk-2.0 introspection
         terminal.drag_dest_set(
             Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT
             | Gtk.DestDefaults.DROP,
             [Gtk.TargetEntry.new('text/uri-list', 0, 80)],
             Gdk.DragAction.COPY,
         )
         terminal.connect("drag_motion", self.on_terminal_drag_motion)
         terminal.connect("drag_drop", self.on_terminal_drag_drop)
         terminal.connect("drag_data_received",
                          self.on_terminal_drag_data_received)
     except (AttributeError, TypeError):
         pass
     #### Accel ####
     accel_group = Gtk.AccelGroup()
     window.add_accel_group(accel_group)
     terminal.add_accelerator(
         "paste-clipboard",
         accel_group,
         ord('V'),
         Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
         Gtk.AccelFlags.VISIBLE,
     )
     terminal.add_accelerator(
         "copy-clipboard",
         accel_group,
         ord('C'),
         Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
         Gtk.AccelFlags.VISIBLE,
     )
     btnShow.add_accelerator(
         "clicked",
         accel_group,
         ord('T'),
         Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
         Gtk.AccelFlags.VISIBLE,
     )
     btnHide.add_accelerator(
         "clicked",
         accel_group,
         ord('T'),
         Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
         Gtk.AccelFlags.VISIBLE,
     )
     #### Return the widgets ####
     vboxMain.unparent()
     return vboxMain
コード例 #5
0
    def __init__(self, parent):
        Gtk.Dialog.__init__(self, "Backup Job", parent, 0)
        self.set_default_size(300, 350)
        now = datetime.now().strftime('%Y%m%d_%H%M%S')  # Prepares timestamp

        # Define scrolled window and child terminal widget
        self.terminal = Vte.Terminal()
        scrolledterm = Gtk.ScrolledWindow()
        scrolledterm.set_min_content_height(300)
        scrolledterm.set_min_content_width(500)
        scrolledterm.add(self.terminal)
        scrolledterm.set_policy(hscrollbar_policy=Gtk.PolicyType.AUTOMATIC,
                                vscrollbar_policy=Gtk.PolicyType.AUTOMATIC)
        self.terminal.fork_command_full(Vte.PtyFlags.DEFAULT,
                                        os.environ['HOME'], ["/bin/sh"], [],
                                        GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                                        None, None)
        self.terminal.connect("child-exited",
                              lambda x: self.backupdone(parent.readybackup))

        # Populate box (this dialog window)
        box = self.get_content_area()
        box.add(scrolledterm)
        self.okbutton = self.add_button("_Ok", Gtk.ResponseType.OK)
        self.cancelbutton = self.add_button("_Cancel", Gtk.ResponseType.CANCEL)
        self.cancelbutton.set_sensitive(True)
        self.okbutton.set_sensitive(False)  # Hide until job is complete
        self.confirmlabel = Gtk.Label(
            "The backup job is complete. Hit OK to return.")
        box.add(self.confirmlabel)

        self.show_all()
        self.confirmlabel.hide()  # Hide until job is complete

        # RUN Backup Job: this uses a softlink to be used as a hardlinked location path.
        # Term "hardlink" used below but may refer to a softlink
        self.hardlink = parent.readybackup["dest"] + "LatestBackup"
        self.newbackuppath = parent.readybackup["dest"] + now
        if os.path.exists(
                self.hardlink):  # Check if softlink exists and is valid
            hardlinkarg = '--link-dest="' + self.hardlink + '"'
        else:  # Softlink doesn't exist or is invalid
            a = re.compile("^\d{8}_\d{6}$")  # Pattern to match
            matchlist = []
            for prevbackup in sorted(os.listdir(parent.readybackup["dest"])):
                if a.match(prevbackup):
                    matchlist.append(prevbackup)
            if matchlist:  # At least one prev backup exists
                newlink = parent.readybackup["dest"] + matchlist[-1]
                hardlinkarg = '--link-dest="' + newlink + '"'
            else:  # No previous backup exists
                hardlinkarg = ''  # Initializes first backup without hardlinking
        if parent.readybackup["sudo"]:
            sudoarg = "sudo "
        else:
            sudoarg = ""
        args = [
            sudoarg + "rsync", "-avWh", "--progress", "--stats",
            parent.readybackup["options"], hardlinkarg, '--log-file="' +
            parent.logspath + parent.readybackup["name"] + 'backup.txt"',
            '"' + parent.readybackup["source"] + '"',
            '"' + self.newbackuppath + '"'
        ]
        #~ print(' '.join(args)) #Comment out
        command = ' '.join(
            args) + '; exit\n'  # Added 'exit' to trigger exit signal
        length = len(command)  # Null terminates command
        self.terminal.feed_child(command,
                                 length)  # Inputs command into terminal
コード例 #6
0
    def __init__(self):

        self.builder = Gtk.Builder()
        self.builder.add_from_file(UIFILE)
        self.builder.connect_signals(self)

        window = self.builder.get_object('window')
        #show main window

        window.show_all()

        global Uproject
        Uproject = None
        global ProjectList
        ProjectList = None

        #Init_Install___________________________________________________________________
        #init Editor VTE
        EDITORVTE = self.builder.get_object('VTE_Editor')
        self.Editor_terminal = Vte.Terminal()

        #decide the vte version
        if VTEver == 290:

            self.Editor_terminal.fork_command_full(
                Vte.PtyFlags.DEFAULT,
                os.environ['HOME'],
                ["/bin/sh"],
                [],
                GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                None,
                None,
            )
            print("old VTE used! (v 2.90) *WINDOW_INIT*")
        else:

            self.Editor_terminal.spawn_sync(
                Vte.PtyFlags.DEFAULT,
                os.environ['HOME'],
                ["/bin/sh"],
                [],
                GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                None,
                None,
            )
            print("New VTE Used () v. 2.91 *WINDOW_INIT*")

        EDITORVTE.add(self.Editor_terminal)
        EDITORVTE.show_all()

        #HelpBrowser____________________________________________________________________

        #initialise help browser
        if fct.readconf('stream') == '1':
            helpurl = fct.readconf('defurl')

            helpbrowser = WebKit.WebView()
            # To disallow editing the webpage.
            helpbrowser.set_editable(False)
            #load url and show window
            helpbrowser.load_uri(helpurl)
            sw = self.builder.get_object('Help_Browser')
            sw.add(helpbrowser)
            helpbrowser.show()
            print('Opened help URL')
        else:
            print('Not Loading Internet URL (Learn Tab)')

#BlogBrowser____________________________________________________________________

        if fct.readconf('stream') == '1':
            blogurl = fct.readconf('blogurl')

            #initialise blog browser
            blogbrowser = WebKit.WebView()

            #disable editing
            blogbrowser.set_editable(False)

            #load default URL
            blogbrowser.load_uri(blogurl)
            bsw = self.builder.get_object('Blog_Browser')
            bsw.add(blogbrowser)
            blogbrowser.show()
        else:
            print('Not Loading Internet URL (BLOG)')

#Marketplace
        if fct.readconf('stream') == '1':
            mpurl = fct.readconf('mpurl')
            mpbrowser = WebKit.WebView()

            mpbrowser.set_editable(False)
            mpbrowser.load_uri(mpurl)
            mpwin = self.builder.get_object('SW_Marketplace')
            mpwin.add(mpbrowser)
            mpbrowser.show()
        else:
            print("Not Loading Internet URL (MARKETPLACE)")
#MAININTERFACE__________________________________________________________________

#UpdateSymbol
        Symbol = self.builder.get_object('MAIN_Launcher_Symbol')
        Symbol.set_from_file(PIXMAP)

        #add text to textbuffer
        vTextbuffer = self.builder.get_object('VersionTextBuffer')
        BufferTextList = fct.get_folder_content(str(fct.readconf('defloc')))
        items = len(BufferTextList)
        finaltext = ''
        for itemcount in range(items):
            finaltext = finaltext + str('Unreal Branch: ' +
                                        str(BufferTextList[itemcount]) + '\n')
        vTextbuffer.set_text(finaltext)

        #ShowStartup on first start
        if fct.readconf('firststart') == '1':
            startwin = self.builder.get_object('FirstStartupMessage')
            startwin.show_all()
            fct.newdi('firststart', '0')
        else:
            print('not showing firststart')

#make the library list__________________________________________________________

#make the iconview plus liststore

        ProjectList = fct.get_folder_content(fct.readconf('proloc'))
        projectstore = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        LibraryView = self.builder.get_object('LibraryIconView')
        LibraryView.set_model(projectstore)
        LibraryView.set_pixbuf_column(0)
        LibraryView.set_text_column(1)

        #create the etrys
        for i in range(len(ProjectList)):
            try:
                pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
                    str(
                        str(
                            fct.readconf('proloc') + '/' +
                            str(ProjectList[i]) +
                            '/Saved/AutoScreenshot.png')), 64, 64)
            except:
                pixbuf = Gtk.IconTheme.get_default().load_icon(
                    'dialog-error', 64, 0)
            projectstore.append([pixbuf, ProjectList[i]])
コード例 #7
0
    def _build_and_inject_ui(self):
        # GtkPaned (vpanel) injection:
        #
        # To inject our terminal in Nautilus, we first have to empty the
        # NautilusWindowSlot widget (parent widget) of the current view to make
        # some free space to insert a GtkPaned widget. Then we will insert back
        # the Nautilus' widgets we removed in the bottom part of the GtkPaned.

        self._ui_vpanel = Gtk.VPaned(visible=True)
        self._ui_vpanel._nt_instance = self
        vbox = Gtk.VBox(visible=True)
        self._ui_vpanel.add2(vbox)
        for widget in self._parent_widget:
            self._parent_widget.remove(widget)
            expand = widget.get_name() in ["GtkOverlay", "NautilusCanvasView"]
            vbox.pack_start(widget, expand, expand, 0)
        self._parent_widget.pack_start(self._ui_vpanel, True, True, 0)

        # Terminal creation:
        #
        # We can now create our VteTerminal and insert it in the top part of
        # our GtkPaned.

        self._ui_terminal = Vte.Terminal()
        self._ui_terminal.connect("child-exited",
                                  self._on_terminal_child_existed)
        self._ui_vpanel.pack1(self._ui_terminal, resize=False, shrink=False)

        TERMINAL_CHAR_HEIGHT = self._ui_terminal.get_char_height()
        TERMINAL_BORDER_WIDTH = 1
        TERMINAL_MIN_HEIGHT = self._settings.get_uint("min-terminal-height")

        self._ui_terminal.set_property(
            "height-request", TERMINAL_CHAR_HEIGHT * TERMINAL_MIN_HEIGHT +
            TERMINAL_BORDER_WIDTH * 2)

        # File drag & drop support

        self._ui_terminal.drag_dest_set(
            Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT
            | Gtk.DestDefaults.DROP,
            [Gtk.TargetEntry.new("text/uri-list", 0, 0)], Gdk.DragAction.COPY)
        self._ui_terminal.drag_dest_add_uri_targets()
        self._ui_terminal.connect("drag-data-received",
                                  self._on_terminal_drag_data_received)

        # Disabling Nautilus' accels when the terminal is focused:
        #
        # When the terminal is focused, we MUST remove ALL Nautilus accels to
        # be able to use properly the terminal (else we cannot type some
        # characters like "/", "~",... because the actions of the corresponding
        # accels are called). Of course we have also to restore the accels when
        # the terminal is no more focused.

        self._ui_terminal.connect("focus-in-event",
                                  self._on_terminal_focus_in_event)
        self._ui_terminal.connect("focus-out-event",
                                  self._on_terminal_focus_out_event)

        # Register the window-level action group of the currently displayed
        # terminal
        #
        # When the active tab changes, we have to register on the nautilus
        # window the corresponding action group to allow related accels to work
        # properly. The "map" event of the NautilusWindowSlot (our parent
        # widget) is called when its tab become active.

        self._parent_widget.connect("map",
                                    self._on_nautilus_window_slot_mapped)

        # Kill the shell when the tab is closed:
        #
        # Finally, we have to listen to some events of our parent widget (the
        # NautilusWindowSlot) to guess when the tab is closed in order to
        # kill the shell (else we will have plenty zombie shell running in
        # background).
        #
        # * When the tab (or the window) is closed, the "unrealize" event is
        #   called so we have to kill the shell when the parent widget emit
        #   this event...
        #
        # * BUT when the tab is drag & dropped outside of the window (to open
        #   it in a new window), this event is also emitted... and the
        #   "realize" event is emitted right after. So we have to spawn a new
        #   shell if that happen...

        self._parent_widget.connect("unrealize",
                                    self._on_nautilus_window_slot_unrealized)
        self._parent_widget.connect("realize",
                                    self._on_nautilus_window_slot_realized)
コード例 #8
0
    def init(self):
        self.all_category = {}
        self.switchcategory = {}

        self.sw = Gtk.ScrolledWindow()
        self.maincontainer = Gtk.VBox()
        self.grid = Gtk.Grid()
        self.stack = Gtk.Stack()
        self.stack.set_hexpand(True)
        self.stack.set_vexpand(True)
        self.listbox_ = Gtk.ListBox()

        self.grid.attach(self.listbox_, 0, 0, 1, 1)
        self.grid.attach(self.stack, 1, 0, 1, 1)
        self.maincontainer.add(self.grid)
        self.sw.add(self.maincontainer)
        self.add(self.sw)

        self.loading_all_plugins()

        self.listbox_.connect("row-activated", self.on_activated_row)
        try:
            gi.require_version('Vte', '2.91')
            from gi.repository import Vte
            tscrolledwindow = Gtk.ScrolledWindow()
            self.terminal = Vte.Terminal()

            #self.terminal.set_color_background(Gdk.RGBA(red=0.180392, green=0.203922, blue=0.211765, alpha=1.000000))
            self.terminal.set_color_foreground(
                Gdk.RGBA(red=0.988235,
                         green=0.913725,
                         blue=0.309804,
                         alpha=1.000000))
            vadjustment = self.terminal.get_vadjustment()
            tscrolledwindow.set_vadjustment(vadjustment)
            _pty = Vte.Pty.new_sync(Vte.PtyFlags(0), None)
            _pty.child_setup()
            self.terminal.set_pty(_pty)

            self.terminal.connect("button-release-event", self.on_button_event)

            self.menu = Gtk.Menu()
            self.menu.set_screen(Gdk.Screen().get_default())

            self.copytextmenuitem = Gtk.MenuItem.new_with_label("Copy")
            cursorcolormenuitem = Gtk.MenuItem.new_with_label("Cursor Color")
            backgroundmenuitem = Gtk.MenuItem.new_with_label("Backgound Color")
            foregroundmenuitem = Gtk.MenuItem.new_with_label(
                "Foreground Color")

            self.copytextmenuitem.connect("activate", self.copy_text)
            cursorcolormenuitem.connect("activate",
                                        self.on_cursor_menuitem_activated)
            backgroundmenuitem.connect("activate",
                                       self.on_background_menuitem_activated)
            foregroundmenuitem.connect("activate",
                                       self.on_foreground_menuitem_activated)

            self.menu.append(self.copytextmenuitem)
            self.menu.append(cursorcolormenuitem)
            self.menu.append(backgroundmenuitem)
            self.menu.append(foregroundmenuitem)

            self.vte_format = Vte.Format(1)
            tscrolledwindow.add(self.terminal)
            self.maincontainer.pack_end(tscrolledwindow, True, True, 0)
        except Exception as e:
            print(e)
        self.show_all()
コード例 #9
0
ファイル: vte.py プロジェクト: PyCManager/termi
 def __init__(self):
   self.terminal = Vte.Terminal()
   self.options = {}
コード例 #10
0
    def __init__(self, model, view):
        def show_command():
            """ User clicked Show Command button. """
            lines = textwrap.wrap(self.command,
                                  60,
                                  break_long_words=False,
                                  break_on_hyphens=False)
            text = ' \\\n'.join(lines)
            self.view.show_info("mode2 command string", text)

        def show_log():
            """ User clicked View log button. """
            path = os.path.expanduser("~/.cache/mode2.log")
            if not os.path.exists(path) or os.stat(path)[6] < 10:
                self.view.show_info("No log available")
                return
            with open(path, "r") as f:
                log = '\n'.join(f.readlines())
            self.view.show_info("mode2 logfile", log)

        Gtk.Window.__init__(self, title="Test device and driver setup")
        self.view = view
        self.command = model.get_mode2() + '\n'
        self.set_default_size(600, 300)
        self.terminal = Vte.Terminal()
        self.terminal.spawn_sync(
            Vte.PtyFlags.DEFAULT,
            os.getcwd(),
            ['/bin/sh'],
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
        )
        self.run_btn = Gtk.Button("Run command")
        self.cmd_btn = Gtk.Button("Show command")
        self.log_btn = Gtk.Button("View log")
        self.run_btn.connect("clicked", self.input_to_term)
        self.quit_btn = Gtk.Button("Quit")
        self.quit_btn.connect("clicked", lambda b: self.destroy())
        self.cmd_btn.connect("clicked", lambda b: show_command())
        self.log_btn.connect("clicked", lambda b: show_log())
        self.help_btn = Gtk.Button("Help")
        self.help_btn.connect(
            "clicked", lambda b: view.show_info("mode2 help", MODE2_HELP_MSG))
        self.set_focus(self.run_btn)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        scroller = Gtk.ScrolledWindow()
        scroller.set_hexpand(True)
        scroller.set_vexpand(True)
        scroller.add(self.terminal)
        vbox.pack_start(scroller, False, True, 1)
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox.set_spacing(5)
        hbox.pack_end(self.run_btn, False, True, 5)
        hbox.pack_end(self.cmd_btn, False, True, 5)
        hbox.pack_end(self.log_btn, False, True, 5)
        hbox.pack_end(self.quit_btn, False, True, 5)
        hbox.pack_start(self.help_btn, False, True, 5)
        vbox.pack_start(hbox, False, True, 2)
        self.add(vbox)
コード例 #11
0
    def __init__(self):
        Gtk.Window.__init__(self)

        self.channel = implementations.insecure_channel('localhost', 60000)
        self.stub = gui_pb2.beta_create_ControllerView_stub(self.channel)

        self.connect("delete-event", Gtk.main_quit)
        self.set_title("Measurement")
        self.resize(800, 400)
        self.daQubits = [self.registerSize]
        self.hQubits = [self.registerSize]
        self.eZeros = [self.registerSize]
        self.eOnes = [self.registerSize]
        self.cVquBitInfo = [self.registerSize]
        self.ePolarizations = [self.registerSize]
        self.eMeasurementAngles = [self.registerSize]
        self.bFindAngle = [self.registerSize]
        self.bMeasure = [self.registerSize]

        self.polarizations = [0.0, 0.0, 0.0, 0.0]
        self.measurementAngles = [0.0, 0.0, 0.0, 0.0]

        cGMain = Gtk.Grid(column_spacing=10)

        cGQubits = Gtk.Grid()
        cGUserInput = Gtk.Grid()

        cVRegister = Gtk.VBox()
        cVRegister.set_size_request(150, 400)

        lGQubits = Gtk.Label()
        lGQubits.set_text("Qubit State")
        lGRegister = Gtk.Label()
        lGRegister.set_text("Register State")
        lGUserInput = Gtk.Label()
        lGUserInput.set_text("Outcome Probability")

        cGMain.attach(lGUserInput, 0, 0, 1, 1)
        cGMain.attach(lGQubits, 1, 0, 2, 1)
        cGMain.attach(lGRegister, 3, 0, 1, 1)

        cGMain.attach(cGQubits, 0, 1, 3, 8)
        cGMain.attach(cVRegister, 3, 1, 1, 8)

        for i in range(self.registerSize):
            cGProbabilities = Gtk.Grid()
            lProbabilities = Gtk.Label()
            lProbabilities.set_text("Qubit " + str(i))
            lProbabilities.set_size_request(80, 20)

            lZero = Gtk.Label()
            lZero.set_text("|0>")
            lZero.set_size_request(40, 20)
            self.eZeros.insert(i, Gtk.Entry())
            self.eZeros[i].set_text("1.0")
            self.eZeros[i].set_width_chars(5)
            lOne = Gtk.Label()
            lOne.set_text("|1>")
            lOne.set_size_request(40, 20)
            self.eOnes.insert(i, Gtk.Entry())
            self.eOnes[i].set_text("0.0")
            self.eOnes[i].set_width_chars(5)

            userInputOffset = 5 * i

            cGQubits.attach(lProbabilities, 0, userInputOffset + 0, 2, 1)
            cGQubits.attach(lZero, 0, userInputOffset + 1, 1, 1)
            cGQubits.attach(self.eZeros[i], 1, userInputOffset + 1, 1, 1)
            cGQubits.attach(lOne, 0, userInputOffset + 2, 1, 1)
            cGQubits.attach(self.eOnes[i], 1, userInputOffset + 2, 1, 1)

            self.daQubits.insert(i, Gtk.DrawingArea())
            self.daQubits[i].set_size_request(150, 100)
            self.daQubits[i].connect("draw", self.expose, i)
            cGQubits.attach(self.daQubits[i], 2, userInputOffset, 1, 3)

            self.bFindAngle.insert(i, Gtk.Button())
            self.bFindAngle[i].set_label("Find Angle")
            self.bFindAngle[i].connect("clicked", self.bFindAngle_exec, i)
            cGQubits.attach(self.bFindAngle[i], 3, userInputOffset, 1, 1)

            self.bMeasure.insert(i, Gtk.Button())
            self.bMeasure[i].set_label("Measure")
            self.bMeasure[i].connect("clicked", self.bMeasure_exec, i)
            cGQubits.attach(self.bMeasure[i], 4, userInputOffset, 1, 1)

            lPolarization = Gtk.Label()
            lPolarization.set_justify(Gtk.Justification.LEFT)
            lPolarization.set_text("Polarization:")
            lPolarization.set_size_request(200, 20)
            self.ePolarizations.insert(i, Gtk.Entry())
            self.ePolarizations[i].set_text(str(self.polarizations[i]))
            self.ePolarizations[i].set_width_chars(5)
            self.ePolarizations[i].set_editable(False)
            self.ePolarizations[i].set_has_frame(False)
            self.ePolarizations[i].set_can_focus(False)
            cGQubits.attach(lPolarization, 3, userInputOffset + 1, 1, 1)
            cGQubits.attach(self.ePolarizations[i], 4, userInputOffset + 1, 1,
                            1)

            lMeasurementAngle = Gtk.Label()
            lMeasurementAngle.set_justify(Gtk.Justification.LEFT)
            lMeasurementAngle.set_text("Detector Angle:")
            lMeasurementAngle.set_size_request(200, 20)
            self.eMeasurementAngles.insert(i, Gtk.Entry())
            self.eMeasurementAngles[i].set_text(str(self.measurementAngles[i]))
            self.eMeasurementAngles[i].set_width_chars(5)
            cGQubits.attach(lMeasurementAngle, 3, userInputOffset + 2, 1, 1)
            cGQubits.attach(self.eMeasurementAngles[i], 4, userInputOffset + 2,
                            1, 1)

        self.daRegister = Gtk.DrawingArea()
        self.daRegister.set_size_request(150, 400)
        self.daRegister.connect("draw", self.exposeRegister)
        cVRegister.pack_start(self.daRegister, True, False, 0)

        self.vt = Vte.Terminal()
        self.vt.set_size_request(400, 400)
        self.vt.fork_command_full(
            Vte.PtyFlags.DEFAULT,
            os.environ['PWD'],
            ["/bin/bash"],
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
        )

        command = "./superpositionController\r\n"
        self.vt.feed_child(command, len(command))
        self.vt.hide()
        cGMain.attach(self.vt, 4, 1, 1, 8)

        self.add(cGMain)
        self.show_all()
        self.vt.hide()
        time.sleep(1)
        self.initDone = 1
コード例 #12
0
    def __init__(self, model, view):
        def show_command():
            """ User clicked Show Command button. """
            lines = textwrap.wrap(self.command,
                                  60,
                                  break_long_words=False,
                                  break_on_hyphens=False)
            text = ' \\\n'.join(lines)
            self.view.show_info("lircd + irw command string", text)

        def do_quit():
            """ User clicked "Quit" button. """
            cmd = self.kill + '\n'
            self.terminal.feed_child(cmd, len(cmd))
            self.destroy()

        Gtk.Window.__init__(self, title="Test decoding")
        self.view = view
        ok, self.command, self.kill = model.get_irwcheck()
        if not ok:
            view.show_error("Test setup error", self.command)
            return
        self.command += '\n'
        self.set_default_size(600, 300)
        self.terminal = Vte.Terminal()
        self.terminal.spawn_sync(
            Vte.PtyFlags.DEFAULT,
            os.getcwd(),
            ['/bin/sh'],
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
        )
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        scroller = Gtk.ScrolledWindow()
        scroller.set_hexpand(True)
        scroller.set_vexpand(True)
        scroller.add(self.terminal)
        vbox.pack_start(scroller, False, True, 1)

        self.run_btn = Gtk.Button("Run command")
        self.quit_btn = Gtk.Button("Quit")
        self.cmd_btn = Gtk.Button("Show command")
        help_btn = Gtk.Button("Help")
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox.set_spacing(10)
        hbox.pack_end(self.run_btn, False, True, 10)
        hbox.pack_end(self.quit_btn, False, True, 10)
        hbox.pack_end(self.cmd_btn, False, True, 10)
        hbox.pack_start(help_btn, False, True, 10)
        vbox.pack_start(hbox, False, True, 2)

        self.add(vbox)
        self.set_focus(self.run_btn)
        self.run_btn.connect("clicked", self.input_to_term)
        self.quit_btn.connect("clicked", lambda b: do_quit())
        self.cmd_btn.connect("clicked", lambda b: show_command())
        help_btn.connect("clicked",
                         lambda b: view.show_info("mode2 help", IRW_HELP_MSG))
        self.connect("delete-event", lambda e, v: do_quit())
コード例 #13
0
    def create_ui(self):
        self.set_border_width(5)
        app_vbox = Gtk.VBox(spacing=5)

        self.module_hbox = Gtk.HBox(spacing=5)
        app_vbox.pack_start(self.module_hbox, False, False, 9)

        label = Gtk.Label()
        label.set_markup('<b>%s</b>' % _('Choose Module:'))
        self.module_hbox.pack_start(label, False, False, 0)

        self.module_combo = Gtk.ComboBox.new_with_model(
            self.modules_list_model)
        cell = Gtk.CellRendererText()
        self.module_combo.pack_start(cell, True)
        self.module_combo.add_attribute(cell, 'text', 0)
        self.module_combo.changed_signal_id = self.module_combo.connect(
            'changed', self.on_module_selection_changed_cb)

        self.module_combo.set_row_separator_func(lambda x, y: x.get(y, 1)[0])
        self.module_hbox.pack_start(self.module_combo, False, True, 0)

        separator = Gtk.VSeparator()
        self.module_hbox.pack_start(separator, False, True, 0)
        preferences = Gtk.Button(stock=Gtk.STOCK_PREFERENCES)
        preferences.connect('clicked', self.on_preferences_cb)
        self.module_hbox.pack_start(preferences, False, True, 0)

        self.progressbar = Gtk.ProgressBar()
        self.progressbar.set_text(_('Build Progress'))
        app_vbox.pack_start(self.progressbar, False, True, 0)

        expander = Gtk.Expander.new(_('Terminal'))
        expander.set_expanded(False)
        app_vbox.pack_start(expander, False, False, 0)
        sclwin = Gtk.ScrolledWindow()
        sclwin.set_size_request(-1, 300)
        sclwin.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.ALWAYS)
        expander.add(sclwin)
        if Vte:
            self.terminal = Vte.Terminal()
            self.terminal.connect('child-exited', self.on_vte_child_exit_cb)
        else:
            os.environ['TERM'] = 'dumb'  # avoid commands printing vt sequences
            self.terminal = Gtk.TextView()
            self.terminal.set_size_request(800, -1)
            textbuffer = self.terminal.get_buffer()
            terminal_bold_tag = textbuffer.create_tag('bold')
            terminal_bold_tag.set_property('weight', Pango.Weight.BOLD)
            terminal_mono_tag = textbuffer.create_tag('mono')
            terminal_mono_tag.set_property('family', 'Monospace')
            terminal_stdout_tag = textbuffer.create_tag('stdout')
            terminal_stdout_tag.set_property('family', 'Monospace')
            terminal_stderr_tag = textbuffer.create_tag('stderr')
            terminal_stderr_tag.set_property('family', 'Monospace')
            terminal_stderr_tag.set_property('foreground', 'red')
            terminal_stdin_tag = textbuffer.create_tag('stdin')
            terminal_stdin_tag.set_property('family', 'Monospace')
            terminal_stdin_tag.set_property('style', Pango.Style.ITALIC)
            self.terminal.set_editable(False)
            self.terminal.set_wrap_mode(Gtk.WrapMode.CHAR)
        sclwin.add(self.terminal)
        self.terminal_sclwin = sclwin

        self.error_hbox = self.create_error_hbox()
        app_vbox.pack_start(self.error_hbox, False, False, 0)

        buttonbox = Gtk.HButtonBox()
        buttonbox.set_layout(Gtk.ButtonBoxStyle.END)
        app_vbox.pack_start(buttonbox, False, False, 0)

        # Translators: This is a button label (to start build)
        self.build_button = Gtk.Button(_('Start'))
        self.build_button.connect('clicked', self.on_build_cb)
        buttonbox.add(self.build_button)

        button = Gtk.Button(stock=Gtk.STOCK_HELP)
        button.connect('clicked', self.on_help_cb)
        buttonbox.add(button)
        buttonbox.set_child_secondary(button, True)

        app_vbox.show_all()
        self.error_hbox.hide()
        self.add(app_vbox)
コード例 #14
0
 def details_enable(self):
     from gi.repository import Vte
     self._details_widget = Vte.Terminal()
     self.widget("details-box").add(self._details_widget)
     self._details_widget.set_visible(True)
     self.widget("details").set_visible(True)
コード例 #15
0
ファイル: activity.py プロジェクト: vipulgupta2048/Pippy
    def __init__(self, handle):
        super(VteActivity, self).__init__(handle)

        self.max_participants = 1  # no sharing

        toolbox = ToolbarBox()
        activity_button_toolbar = ActivityToolbarButton(self)
        toolbox.toolbar.insert(activity_button_toolbar, 0)
        activity_button_toolbar.show()
        self.set_toolbar_box(toolbox)
        toolbox.show()
        self.toolbar = toolbox.toolbar

        '''
        # add 'copy' icon from standard toolbar.
        edittoolbar = activity.EditToolbar()
        edittoolbar.copy.set_tooltip(_('Copy selected text to clipboard'))
        edittoolbar.copy.connect('clicked', self._on_copy_clicked_cb)
        edittoolbar.paste.connect('clicked', self._on_paste_clicked_cb)
        # as long as nothing is selected, copy needs to be insensitive.
        edittoolbar.copy.set_sensitive(False)
        toolbox.add_toolbar(_('Edit'), edittoolbar)
        edittoolbar.show()
        self._copy_button = edittoolbar.copy
        '''

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbox.toolbar.insert(separator, -1)
        separator.show()

        stop_button = StopButton(self)
        stop_button.props.accelerator = '<Ctrl>q'
        toolbox.toolbar.insert(stop_button, -1)
        stop_button.show()

        toolbox.toolbar.show_all()

        # creates vte widget
        self._vte = Vte.Terminal()
        self._vte.set_size(30, 5)
        self._vte.set_size_request(200, 300)
        font = 'Monospace 10'
        self._vte.set_font(Pango.FontDescription(font))
        self._vte.set_colors(Gdk.color_parse('#000000'),
                             Gdk.color_parse('#E7E7E7'),
                             [])
        '''
        self._vte.connect('selection-changed', self._on_selection_changed_cb)
        # FIXME It does not work because it expects and receives
        # StructMeta Gtk.TargetEntry
        #
        #self._vte.drag_dest_set(Gtk.DestDefaults.ALL,
        #                        [("text/plain", 0, TARGET_TYPE_TEXT)],
        #                        Gdk.DragAction.COPY)

        self._vte.connect('drag_data_received', self._on_drop_cb)
        '''
        # ...and its scrollbar
        vtebox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        vtebox.pack_start(self._vte, True, True, 0)
        vtesb = Gtk.Scrollbar(orientation=Gtk.Orientation.VERTICAL)
        # vtesb.set_adjustment(self._vte.get_adjustment())
        vtesb.show()
        vtebox.pack_start(vtesb, False, False, 0)
        self.set_canvas(vtebox)
        self.show_all()
        '''
        # hide the buttons we don't use.
        toolbar.share.hide()  # this should share bundle.
        edittoolbar.undo.hide()
        edittoolbar.redo.hide()
        edittoolbar.separator.hide()
        '''

        # now start subprocess.
        self._vte.connect('child-exited', self.on_child_exit)
        self._vte.grab_focus()
        bundle_path = activity.get_bundle_path()
        # the 'sleep 1' works around a bug with the command dying before
        # the vte widget manages to snarf the last bits of its output
        logging.error(bundle_path)

        self._pid = self._vte.fork_command_full(
            Vte.PtyFlags.DEFAULT,
            bundle_path,
            ['/bin/sh', '-c', 'python %s/pippy_app.py; sleep 1' % bundle_path],
            ["PYTHONPATH=%s/library" % bundle_path],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,)
コード例 #16
0
ファイル: main.py プロジェクト: omgold/mantid-term
    def __init__(self, keep_open):

        self.keep_open = keep_open
        self.command_mode = False
        self.select_mode = None
        self.selection_start = None
        self.normal_cursor_position = None

        self.vte = Vte.Terminal()
        vte_style = self.vte.get_style_context()
        Gtk.StyleContext.add_class(vte_style, "mantid")
        vte_style.add_provider(app.style, Gtk.STYLE_PROVIDER_PRIORITY_USER)

        self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox_style = self.hbox.get_style_context()
        Gtk.StyleContext.add_class(hbox_style, "mantid")
        hbox_style.add_provider(app.style, Gtk.STYLE_PROVIDER_PRIORITY_USER)

        self.hint_overlay = Gtk.Overlay()
        self.hint_overlay.override_background_color(Gtk.StateFlags.NORMAL,
                                                    transparent)

        self.scrollbar = Gtk.Scrollbar.new(Gtk.Orientation.VERTICAL,
                                           self.vte.get_vadjustment())
        scrollbar_style = self.scrollbar.get_style_context()
        Gtk.StyleContext.add_class(scrollbar_style, "mantid")
        scrollbar_style.add_provider(app.style,
                                     Gtk.STYLE_PROVIDER_PRIORITY_USER)

        self.da = Gtk.DrawingArea()
        self.da.override_background_color(Gtk.StateFlags.NORMAL, transparent)
        self.da.set_halign(Gtk.Align.FILL)
        self.da.set_valign(Gtk.Align.FILL)

        self.panel_overlay = Gtk.Overlay()

        self.panel_entry = Gtk.Entry()
        self.panel_entry.set_margin_start(5)
        self.panel_entry.set_margin_end(5)
        self.panel_entry.set_margin_top(5)
        self.panel_entry.set_margin_bottom(5)
        self.panel_entry.set_halign(Gtk.Align.START)
        self.panel_entry.set_valign(Gtk.Align.END)
        self.panel_entry.connect("key-press-event", entry_key_press_cb, self)
        self.panel_overlay.connect("get-child-position",
                                   get_entry_position_overlay_cb)

        self.vte.connect("child-exited", child_exited_cb, self)
        self.vte.connect("key-press-event", key_press_cb, self)
        #self.vte.connect("button-press-event", button_press_cb, self)
        self.vte.connect("window-title-changed", window_title_cb, self)

        self.hint_overlay.add_overlay(self.da)
        self.hint_overlay.add(self.vte)
        self.hbox.pack_start(self.hint_overlay, True, True, 0)
        self.hbox.pack_start(self.scrollbar, False, False, 0)
        self.panel_overlay.add(self.hbox)
        # self.panel_overlay.add_overlay(self.panel_entry)

        self.panel_overlay.show_all()

        self.apply_config()

        self.panel_entry.hide()
        self.da.hide()
コード例 #17
0
    def on_B_Install_clicked(self, button):
        instwin = self.builder.get_object('Install_Dialog')
        #init VTE
        termwin = self.builder.get_object('VTE')

        self.term = Vte.Terminal()

        #decide the vte version

        if VTEver == 290:

            self.term.fork_command_full(
                Vte.PtyFlags.DEFAULT,
                os.environ['HOME'],
                ["/bin/sh"],
                [],
                GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                None,
                None,
            )
            print("old VTE used! (v 2.90) *WINDOW_INSTALLDIALOG*")
        else:

            self.term.spawn_sync(
                Vte.PtyFlags.DEFAULT,
                os.environ['HOME'],
                ["/bin/sh"],
                [],
                GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                None,
                None,
            )
            print("New VTE Used (v. 2.91) *WINDOW_INSTALLDIALOG*")

        termwin.add(self.term)
        instwin.show_all()
        #set texts______________________________________________________________________

        #default location
        defaultlocation = self.builder.get_object('E_Install_DefLoc')
        defaultlocation.set_text(fct.readconf('defloc'))

        #Dependecies
        deps = self.builder.get_object('E_Install_Dependencies')
        distroversion = fct.readconf('distribution')
        print("distro = " + str(distroversion))
        if distroversion == '0':
            deps.set_text(str(fct.readconf('deparch')))
        elif distroversion == '1':
            deps.set_text(str(fct.readconf('depubuntu')))
        elif distroversion == '2':
            deps.set_text(str(fct.readconf('depmint')))
        else:
            deps.set_text('Unknown distribution,please check settings!')

#set text in "Download
        EditGit = self.builder.get_object('E_Install_GitHub')
        EditConfig = self.builder.get_object('E_Install_Config')
        EditSlate = self.builder.get_object('E_Install_SlateViewer')
        SlateCheck = self.builder.get_object('CB_SlateCheck')
        #set texts
        EditGit.set_text(str(fct.readconf('giturl')))
        EditConfig.set_text(str(fct.readconf('s1')))
        EditSlate.set_text(str(fct.readconf('s2')))

        #set text in "Build"
        ES3 = self.builder.get_object('E_Install_S3')
        ES4 = self.builder.get_object('E_Install_S4')
        infolabel = self.builder.get_object('L_Install_Info')
        if fct.readconf('distribution') == '0':
            infolabel.set_text(
                '  Please add "export PATH=$HOME/bin:$PATH" to your \n  .bashrc or .zshrc in your home folder before \n  continuing.\n'
            )
        else:
            print("leaving arch info out")

        ES3.set_text(fct.readconf('s3'))
        ES4.set_text(fct.readconf('s4'))
コード例 #18
0
ファイル: d-term.py プロジェクト: Caticer/debian-subsystem
#!/usr/bin/python3
import gi, sys, os
gi.require_version('Gtk', '3.0')
gi.require_version('Vte', '2.91')
from gi.repository import Gtk, Vte, GLib
terminal = Vte.Terminal()
scrolled_window = Gtk.ScrolledWindow()
terminal.connect("child_exited", Gtk.main_quit)
cmd = ""
if len(sys.argv) > 1:
    if "--" not in sys.argv[1]:
        cmd += sys.argv[1]
    for i in sys.argv[2:]:
        cmd += "\"" + i + "\" "
if cmd == "":
    cmd = os.environ["SHELL"]
print(cmd)
win = Gtk.Window()
if os.path.isfile("/usr/lib/sulin/dsl/debian.svg"):
    win.set_icon_from_file("/usr/lib/sulin/dsl/debian.svg")
win.connect('delete-event', Gtk.main_quit)
win.add(scrolled_window)
scrolled_window.add(terminal)
if len(sys.argv) > 1 and sys.argv[1] == "--fullscreen":
    win.fullscreen()
else:
    win.set_size_request(547, 352)
terminal.set_font_scale(0.9)
win.set_title("d-term")
win.show_all()
terminal.spawn_sync(Vte.PtyFlags.DEFAULT, None, ["/bin/bash", "-c", cmd], [],
コード例 #19
0
`notification_received` signal to catch the OSC escape sequence in the prompt

Code is adapted from https://github.com/x4lldux/terminator-long-cmd-notify
Thanks to @xll4dux on Github for the code and his permission to use it

"""
import terminatorlib.plugin as plugin
from terminatorlib.terminator import Terminator
import gi
gi.require_version('Notify', '0.7')
from gi.repository import GObject, GLib, Notify, Vte
VERSION = '0.1.0'

### Test for proper signal
try:
    Vte.Terminal().connect('notification-received', lambda *args: None, None)
    AVAILABLE = ['CommandNotify']
except TypeError as e:
    AVAILABLE = []
    pass


class CommandNotify(plugin.Plugin):
    capabilities = ['command_watch']
    watched = set()

    def __init__(self):
        self.update_watched()
        Notify.init('Terminator')
        return None
コード例 #20
0
ファイル: terminal.py プロジェクト: postman721/Quick-Terminal
    def __init__(self):
        # Create THE WINDOW
        self.window1 = Gtk.Window()
        self.window1.set_position(Gtk.WindowPosition.CENTER)
        self.window1.set_title("Quick Terminal-GTK3")
        self.window1.connect("button_press_event", self.right_click)
        #Menu
        self.menu = Gtk.Menu()
        #Menu buttons
        #Copy&Paste
        self.copy_it = Gtk.MenuItem("Copy")
        self.copy_it.connect("activate", self.copy)

        self.paste_it = Gtk.MenuItem("Paste")
        self.paste_it.connect("activate", self.paste)

        self.menu.append(self.copy_it)
        self.menu.append(self.paste_it)

        #Clear history & Clear Terminal
        self.clear_his = Gtk.MenuItem("Clear history")
        self.clear_his.connect("activate", self.clear_history)

        self.clear_ter = Gtk.MenuItem("Clear terminal")
        self.clear_ter.connect("activate", self.clear_terminal)

        self.menu.append(self.clear_his)
        self.menu.append(self.clear_ter)

        #Memory status
        self.memorys = Gtk.MenuItem("Memory status")
        self.memorys.connect("activate", self.memory)

        self.menu.append(self.memorys)

        #About Quick Terminal
        self.about_ter = Gtk.MenuItem("About Quick Terminal")
        self.about_ter.connect("activate", self.about1)
        self.menu.append(self.about_ter)
        #Toolbars
        self.toolbar2 = Gtk.Toolbar()

        #Toolbar2 buttons

        self.SOUND_button = Gtk.ToolButton(Gtk.STOCK_EXECUTE)
        self.SOUND_button.set_label("Alsa Sound Selector")
        self.SOUND_button.connect("clicked", self.sound)
        self.SOUND_button.set_tooltip_text("Alsa Sound Selector")
        self.toolbar2.insert(self.SOUND_button, -1)

        self.WLAN_button = Gtk.ToolButton(Gtk.STOCK_PROPERTIES)
        self.WLAN_button.set_label("Wlan setup")
        self.WLAN_button.connect("clicked", self.wlan)
        self.WLAN_button.set_tooltip_text("Wlan Setup")
        self.toolbar2.insert(self.WLAN_button, -1)

        self.NET_button = Gtk.ToolButton(Gtk.STOCK_CONNECT)
        self.NET_button.set_label("Network setup")
        self.NET_button.connect("clicked", self.net)
        self.NET_button.set_tooltip_text("Network Setup")
        self.toolbar2.insert(self.NET_button, -1)

        self.MOUNT_button = Gtk.ToolButton(Gtk.STOCK_HARDDISK)
        self.MOUNT_button.set_label("Simple Mount")
        self.MOUNT_button.connect("clicked", self.mount)
        self.MOUNT_button.set_tooltip_text("Simple Mount")
        self.toolbar2.insert(self.MOUNT_button, -1)

        self.APT_button = Gtk.ToolButton(Gtk.STOCK_GO_DOWN)
        self.APT_button.set_label("Apt Fetcher")
        self.APT_button.connect("clicked", self.apt)
        self.APT_button.set_tooltip_text("Apt Fetcher")
        self.toolbar2.insert(self.APT_button, -1)

        self.UPDATES_button = Gtk.ToolButton(Gtk.STOCK_REFRESH)
        self.UPDATES_button.set_label("Updates")
        self.UPDATES_button.connect("clicked", self.updates)
        self.UPDATES_button.set_tooltip_text("Fetch Updates")
        self.toolbar2.insert(self.UPDATES_button, -1)

        self.INI_button = Gtk.ToolButton(Gtk.STOCK_APPLY)
        self.INI_button.set_label("Bluetooth Initialization")
        self.INI_button.connect("clicked", self.blue_initial)
        self.INI_button.set_tooltip_text("Bluetooth Initialization")
        self.toolbar2.insert(self.INI_button, -1)

        self.BLUE_button = Gtk.ToolButton(Gtk.STOCK_PREFERENCES)
        self.BLUE_button.set_label("Bluetooth Setup")
        self.BLUE_button.connect("clicked", self.blue_connect)
        self.BLUE_button.set_tooltip_text("Bluetooth Setup")
        self.toolbar2.insert(self.BLUE_button, -1)

        self.MIIMO_button = Gtk.ToolButton(Gtk.STOCK_OPEN)
        self.MIIMO_button.set_label("Miimo Tool")
        self.MIIMO_button.connect("clicked", self.miimo)
        self.MIIMO_button.set_tooltip_text("Miimo Decompress/Compress")
        self.toolbar2.insert(self.MIIMO_button, -1)
        #Terminal
        self.vte = Vte.Terminal()
        self.vte.connect("child-exited", lambda term: Gtk.main_quit())

        #Fork
        self.vte.spawn_sync(
            Vte.PtyFlags.DEFAULT,
            os.environ['HOME'],
            ["/bin/bash"],
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
        )
        #Make a clipboard for copy and paste
        self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

        #Scrolled window
        self.scroll = Gtk.ScrolledWindow()
        self.scroll.set_min_content_height(350)
        self.scroll.set_min_content_width(640)
        self.scroll.add(self.vte)

        #Vertical box/buttons container
        self.vbox = Gtk.VBox(False)
        self.vbox.pack_start(self.scroll, True, True, True)
        self.vbox.pack_start(self.toolbar2, False, False, False)

        #Show everything
        self.window1.add(self.vbox)
        self.window1.show_all()

        #Making window resizable and enabling the close window connector
        self.window1.set_resizable(True)
        self.window1.connect("destroy", Gtk.main_quit)
コード例 #21
0
ファイル: caja-terminal.py プロジェクト: rbuj/caja-terminal
 def __init__(self, callback, terminal):
     """The constructor."""
     self._callback = callback
     self._terminal = terminal
     self._conf = Conf(CONF_FILE)
     #Change current path to home dir
     os.chdir(os.environ.get("HOME"))
     #GUI
     self.gui = Gtk.Builder()
     self.gui.set_translation_domain(__appname__)
     self.gui.add_from_file(PREF_GUI_FILE)
     self.gui.connect_signals(self)
     #### winMain ####
     self.winMain = self.gui.get_object("winMain")
     #demoTerm
     self.demoTerm = Vte.Terminal()
     self.demoTerm.set_size(20, 3)
     #Display something in the terminal
     self.demoTerm.feed("       _\|/_   zZ    ❭       ")
     self.demoTerm.feed("        ❭         _\|/_\n\033[1G")
     self.demoTerm.feed("       (- -) zZ      ❭  \_°< ")
     self.demoTerm.feed("Coin !  ❭         (O O)\n\033[1G")
     self.demoTerm.feed("---oOO--(_)--OOo---  ❭               ❭  ")
     self.demoTerm.feed("---oOO--(_)--OOo---\n\033[2J\033[1;1f")
     self.demoTerm.feed("[\033[40m \033[41m \033[42m \033[43m \033[44m ")
     self.demoTerm.feed("\033[45m \033[46m \033[47m \033[0m] ")
     self.demoTerm.feed("[\033[30m#\033[31m#\033[32m#\033[33m#\033[34m#")
     self.demoTerm.feed("\033[35m#\033[36m#\033[37m#\033[0m] ")
     self.demoTerm.feed("[\033[1;30m#\033[1;31m#\033[1;32m#\033[1;33m#")
     self.demoTerm.feed("\033[1;34m#\033[1;35m#\033[1;36m#\033[1;37m#")
     self.demoTerm.feed("\033[0m] [\033[0m#\033[0m\033[1m#\033[0m\033[4m#")
     self.demoTerm.feed("\033[0m\033[5m#\033[0m\033[7m#\033[0m]\n\033[1G")
     self.demoTerm.feed("CajaTerminal@Preferences:~# ")
     self.demoTerm.show()
     #General
     self.cbShowScrollbar = self.gui.get_object("cbShowScrollbar")
     self.cbStartHidden = self.gui.get_object("cbStartHidden")
     self.spbtnDefHeight = self.gui.get_object("spbtnDefHeight")
     self.entryCmd = self.gui.get_object("entryCmd")
     self.comboboxCursor = self.gui.get_object("comboboxCursor")
     self.lsstCursor = Gtk.ListStore(str)
     self.comboboxCursor.set_model(self.lsstCursor)
     self.cellCursor = Gtk.CellRendererText()
     self.comboboxCursor.pack_start(self.cellCursor, True)
     self.comboboxCursor.add_attribute(self.cellCursor, "text", 0)
     for shape in CURSOR_SHAPE:
         self.lsstCursor.append([shape])
     #Color
     self.comboboxPalette = self.gui.get_object("comboboxPalette")
     self.lsstPalette = Gtk.ListStore(str)
     self.comboboxPalette.set_model(self.lsstPalette)
     self.cellPallette = Gtk.CellRendererText()
     self.comboboxPalette.pack_start(self.cellPallette, True)
     self.comboboxPalette.add_attribute(self.cellPallette, "text", 0)
     self._palette_list = []
     for palette in PREDEF_PALETTE:
         self._palette_list.append(palette)
         self.lsstPalette.append([palette])
     self._palette_list.append("Custom")
     gettext.install(__appname__)  #Why it does not works whereas it was
     #already defined at the beginning :/ ?
     self.lsstPalette.append([_("Custom")])
     self.clbtnFg = self.gui.get_object("clbtnFg")
     self.clbtnBg = self.gui.get_object("clbtnBg")
     self.clbtnPalette = []
     for i in xrange(16):
         self.clbtnPalette.append(self.gui.get_object("clbtnPalette%i" % i))
         self.clbtnPalette[i].connect("color-set",
                                      self.on_clbtnPalette_color_set, i)
     #Font
     self.fontbtn = self.gui.get_object("fontbtn")
     self.cbAllowBold = self.gui.get_object("cbAllowBold")
     #Folders
     self.rbAllFolders = self.gui.get_object("rbAllFolders")
     self.rbFolderList = self.gui.get_object("rbFolderList")
     self.btnFolderRemove = self.gui.get_object("btnRemoveFolder")
     self.trvFolderList = self.gui.get_object("trvFolderList")
     self.lsstFolderList = Gtk.ListStore(str)
     self.trvFolderList.set_model(self.lsstFolderList)
     self.columnFolderList = Gtk.TreeViewColumn(
         "Path",
         Gtk.CellRendererText(),
         text=0,
     )
     self.trvFolderList.append_column(self.columnFolderList)
     #vboxTerm
     self.alTerm = self.gui.get_object("alTerm")
     self.alTerm.add(self.demoTerm)
     #### winAbout ####
     self.winAbout = self.gui.get_object("winAbout")
     self.winAbout.connect("response", self.on_winAbout_response)
     self.winAbout.set_version(__version__)
     #### filechooser ####
     self.filechooser = self.gui.get_object("filechooser")
     ##
     self._put_opt()
コード例 #22
0
    def __init__(self, root_dir, filter_out_extensions=[]):
        self.tmpfiles = []  # files to be deleted upon quit
        self.root_dir = root_dir
        self.filter_out_ext = filter_out_extensions

        ## The store will contain:
        ## 0. filename (str)
        ## 1. whether it's a directory (bool)
        ## 2. file size (int)
        ## 3. last modified (str)
        column_mapping = [0, 2, 3]  # From user columns to model columns
        self.file_structure = Gtk.TreeStore(str, bool)
        self.populate_tree(root_dir, self.file_structure.get_iter_first())
        uifile = abs_path_gui("gui.ui")
        wTree = Gtk.Builder()
        wTree.add_from_file(uifile)
        ## Create the treeview and link it to the model
        # self.w_treeview = wTree.get_widget("treeview")
        self.w_treeview = wTree.get_object("treeview")
        self.w_treeview.set_model(self.file_structure)

        self.srcView = GtkSource.View()
        self.srcBfr = self.srcView.get_buffer()
        srcLanguage = get_language_for_mime_type("text/x-python")

        #self.helpBfr = Gtk.TextBuffer()
        self.srcScrolledWindow = wTree.get_object("srcScrolledWindow")
        self.srcScrolledWindow.add(self.srcView)
        self.srcBfr.set_language(srcLanguage)
        self.srcBfr.set_highlight_syntax(True)
        self.srcView.set_buffer(self.srcBfr)
        self.srcView.set_show_line_numbers(True)
        context = self.srcView.get_pango_context()
        font = context.get_font_description()
        font.set_size(int(font.get_size() * 1.5))
        self.srcView.modify_font(font)
        #self.srcView.set_editable(False)
        self.srcView.show()
        self.terminalScrolledWindow = wTree.get_object(
            "terminalScrolledWindow")
        self.terminal_expander = wTree.get_object("terminalexpander")
        self.terminal = Vte.Terminal()
        self.terminalScrolledWindow.add(self.terminal)
        self.terminal.show()
        #self.helpView = wTree.get_widget("helpView")
        #self.helpView.set_buffer(self.helpBfr)
        self.srcBfr.set_text(
            "#Python Code Browser: Select a python program from the left panel"
        )
        self.btnExecute = wTree.get_object("btnExecute")
        self.btnSaveas = wTree.get_object("btnSaveas")
        self.tbtnExecute = wTree.get_object("tbtnExecute")
        self.tbtnSaveas = wTree.get_object("tbtnSaveas")
        dic = {
            "on_frm_treeview_delete_event": self.quit,
            "quit_clicked": self.quit,
            "execute_clicked": self.open_file,
            "on_treeview_cursor_changed": self.disp_details,
            "saveas_clicked": self.save_as,
            "about_clicked": self.about
        }
        wTree.connect_signals(dic)
        ## Create the columns to view the contents
        self.columns = [Gtk.TreeViewColumn(title) for title in ['Filename']]
        self.w_cell = Gtk.CellRendererText()
        self.w_cell.set_property("xalign", 0)
        for i, column in enumerate(self.columns):
            self.w_treeview.append_column(column)
            column.set_property("resizable", True)
            column.pack_end(self.w_cell, True)
            column.add_attribute(self.w_cell, 'text', column_mapping[i])

        ## Create a cell-renderer that displays a little directory or
        ## document icon depending on the file type
        self.w_cellpix = Gtk.CellRendererPixbuf()
        self.w_cellpix.set_property("xpad", 8)
        self.w_cellpix.set_property("xalign", 0)

        def pix_format_func(treeviewcolumn, cell, model, iter, dummyParam):
            if model.get(iter, 1)[0]:
                cell.set_property("stock-id", Gtk.STOCK_DIRECTORY)
            else:
                cell.set_property("stock-id", Gtk.STOCK_ABOUT)

        self.columns[0].pack_start(self.w_cellpix, expand=True)
        self.columns[0].set_cell_data_func(self.w_cellpix, pix_format_func)
コード例 #23
0
    def __init__(self, application):
        """
		:param application: The application instance to which this window belongs.
		:type application: :py:class:`.KingPhisherClientApplication`
		"""
        utilities.assert_arg_type(application, Gtk.Application, arg_pos=1)
        self.application = application
        self.logger = logging.getLogger('KingPhisher.Client.' +
                                        self.__class__.__name__)
        if not has_vte:
            gui_utilities.show_dialog_error(
                'RPC Terminal Is Unavailable',
                self.application.get_active_window(), 'VTE is not installed')
            return
        config = application.config

        self.terminal = Vte.Terminal()
        self.rpc_window = RPCTerminalAppWindow(self.terminal, self.application)

        rpc = self.application.rpc
        config = {
            'campaign_id': config['campaign_id'],
            'campaign_name': config['campaign_name'],
            'rpc_data': {
                'address': (rpc.host, rpc.port),
                'use_ssl': rpc.use_ssl,
                'username': rpc.username,
                'uri_base': rpc.uri_base,
                'headers': rpc.headers
            },
            'user_data_path': self.application.user_data_path,
            'user_library_path': self.application.user_library_path
        }

        module_path = os.path.dirname(client_rpc.__file__) + (
            (os.path.sep + '..') * client_rpc.__name__.count('.'))
        module_path = os.path.normpath(module_path)

        python_command = [
            "import {0}".format(client_rpc.__name__),
            "{0}.vte_child_routine('{1}')".format(
                client_rpc.__name__,
                serializers.JSON.dumps(config, pretty=False))
        ]
        python_command = '; '.join(python_command)

        if hasattr(self.terminal, 'pty_new_sync'):
            # Vte._version >= 2.91
            vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT)
            self.terminal.set_pty(vte_pty)
            self.terminal.connect(
                'child-exited',
                lambda vt, status: self.rpc_window.window.destroy())
        else:
            # Vte._version <= 2.90
            vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT)
            self.terminal.set_pty_object(vte_pty)
            self.terminal.connect('child-exited',
                                  lambda vt: self.rpc_window.window.destroy())

        child_pid, _, _, _ = GLib.spawn_async(
            working_directory=os.getcwd(),
            argv=[sys.executable, '-c', python_command],
            envp=[
                find.ENV_VAR + '=' + os.environ[find.ENV_VAR],
                'DISPLAY=' + os.environ['DISPLAY'],
                'PATH=' + os.environ['PATH'], 'PYTHONDONTWRITEBYTECODE=x',
                'PYTHONPATH=' + module_path,
                'TERM=' + os.environ.get('TERM', 'xterm')
            ],
            flags=(GLib.SpawnFlags.SEARCH_PATH
                   | GLib.SpawnFlags.DO_NOT_REAP_CHILD),
            child_setup=self._child_setup,
            user_data=vte_pty)

        self.logger.info(
            "vte spawned child process with pid: {0}".format(child_pid))
        self.child_pid = child_pid
        self.terminal.watch_child(child_pid)
        GLib.spawn_close_pid(child_pid)
        self.rpc_window.window.show_all()
        self.rpc_window.child_pid = child_pid
        return
コード例 #24
0
    def __init__(self, uri, window):
        """The constructor."""
        self._window = window
        self._path = self._uri_to_path(uri)
        #Term
        self.shell_pid = -1
        self.term = Vte.Terminal()

        settings.bind("audible-bell", self.term, "audible-bell", Gio.SettingsBindFlags.GET)

        self.shell_pid = self.term.spawn_sync(Vte.PtyFlags.DEFAULT, self._path, [terminal_or_default()], None, GLib.SpawnFlags.SEARCH_PATH, None, None, None)[1]

        # Make vte.sh active
        #vte_current_dir_script = ". /etc/profile.d/vte.sh ; clear"
        #self.term.feed_child(vte_current_dir_script, len(vte_current_dir_script))

        self.term.connect_after("child-exited", self._on_term_child_exited)
        self.term.connect_after("popup-menu", self._on_term_popup_menu)
        self.term.connect("button-press-event", self._on_term_popup_menu)

        #Accelerators
        accel_group = Gtk.AccelGroup()
        self._window.add_accel_group(accel_group)
        self.term.add_accelerator(
            "paste-clipboard",
            accel_group,
            ord("V"),
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
            Gtk.AccelFlags.VISIBLE)
        self.term.add_accelerator(
            "copy-clipboard",
            accel_group,
            ord("C"),
            Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
            Gtk.AccelFlags.VISIBLE)
        #Drag & Drop
        self.term.drag_dest_set(
            Gtk.DestDefaults.MOTION |
            Gtk.DestDefaults.HIGHLIGHT |
            Gtk.DestDefaults.DROP,
            [Gtk.TargetEntry.new("text/uri-list", 0, 80)],
            Gdk.DragAction.COPY,
        )
        self.term.drag_dest_add_uri_targets()
        self.term.connect("drag_data_received", self._on_drag_data_received)

        # Container
        self.vscrollbar = Gtk.VScrollbar.new(self.term.get_vadjustment())

        self.hbox = Gtk.HBox()
        self.hbox.pack_start(self.term, True, True, 0)
        self.hbox.pack_end(self.vscrollbar, False, False, 0)

        self.hbox.nt = self # store a reference to this obj

        #Popup Menu
        self.menu = Gtk.Menu()
        #MenuItem => copy
        menu_item = Gtk.ImageMenuItem.new_from_stock("gtk-copy", None)
        menu_item.connect_after("activate",
                                lambda w: self.term.copy_clipboard())
        self.menu.add(menu_item)
        #MenuItem => paste
        menu_item = Gtk.ImageMenuItem.new_from_stock("gtk-paste", None)
        menu_item.connect_after("activate",
                                lambda w: self.term.paste_clipboard())
        self.menu.add(menu_item)
        #MenuItem => paste filenames (only added if URI types on clipboard)
        menu_item_pastefilenames = \
            Gtk.ImageMenuItem.new_from_stock("gtk-paste", None)
        menu_item_pastefilenames.connect_after("activate",
                                               lambda w: self._paste_filenames_clipboard())
        menu_item_pastefilenames.set_label(_("Paste Filenames"))
        self.menu_item_pastefilenames = menu_item_pastefilenames
        self.menu.add(menu_item_pastefilenames)
        #MenuItem => separator #TODO: Implement the preferences window
        #menu_item = Gtk.SeparatorMenuItem()
        #self.menu.add(menu_item)
        #MenuItem => preferences
        #menu_item = Gtk.ImageMenuItem.new_from_stock("gtk-preferences", None)
        #self.menu.add(menu_item)
        #MenuItem => separator
        #menu_item = Gtk.SeparatorMenuItem()
        #self.menu.add(menu_item)
        #MenuItem => Goto current terminal directory
        #menu_item = Gtk.MenuItem.new_with_label(_("Goto current terminal directory"))
        #menu_item.connect_after("activate",
        #        lambda w: self._goto_current_terminal_directory())
        #self.menu.add(menu_item)
        #MenuItem => separator
        menu_item = Gtk.SeparatorMenuItem()
        self.menu.add(menu_item)
        #MenuItem => About
        menu_item = Gtk.ImageMenuItem.new_from_stock("gtk-about", None)
        menu_item.connect_after("activate",
                                lambda w: self.show_about_dialog())
        self.menu.add(menu_item)
        self.menu.show_all()

        self._set_term_height(settings.get_int("default-terminal-height"))
        self._visible = True

        #Lock
        self._respawn_lock = False
        #Register the callback for show/hide
        if hasattr(window, "toggle_hide_cb"):
            window.toggle_hide_cb.append(self.set_visible)
コード例 #25
0
ファイル: asyncjob.py プロジェクト: yen3/virt-manager
 def details_enable(self):
     self._details_widget = Vte.Terminal()
     self.widget("details-box").add(self._details_widget)
     self._details_widget.set_visible(True)
     self.widget("details").set_visible(True)
コード例 #26
0
    def _create_tab(self, tab_state):
        vt = Vte.Terminal()
        vt.connect("child-exited", self.__tab_child_exited_cb)
        vt.connect("window-title-changed", self.__tab_title_changed_cb)

        vt.drag_dest_set(Gtk.DestDefaults.MOTION | Gtk.DestDefaults.DROP, [
            Gtk.TargetEntry.new('text/plain', 0, 0),
            Gtk.TargetEntry.new('STRING', 0, 1)
        ], Gdk.DragAction.DEFAULT | Gdk.DragAction.COPY)
        vt.drag_dest_add_text_targets()
        vt.connect('drag_data_received', self.__drag_data_received_cb)

        self._configure_vt(vt)

        vt.show()

        scrollbar = Gtk.VScrollbar.new(vt.get_vadjustment())

        box = Gtk.HBox()
        box.pack_start(vt, True, True, 0)
        box.pack_start(scrollbar, False, True, 0)

        box.vt = vt
        box.show()

        tablabel = TabLabel(box)
        tablabel.connect('tab-close', self.__close_tab_cb)
        tablabel.update_size(200)
        box.label = tablabel

        index = self._notebook.append_page(box, tablabel)
        tablabel.show_all()

        # Uncomment this to only show the tab bar when there is at least
        # one tab. I think it's useful to always see it, since it displays
        # the 'window title'.
        # self._notebook.props.show_tabs = self._notebook.get_n_pages() > 1
        if self._notebook.get_n_pages() == 1:
            tablabel.hide_close_button()
        if self._notebook.get_n_pages() == 2:
            self._notebook.get_tab_label(
                self._notebook.get_nth_page(0)).show_close_button()
        self._notebook.show_all()

        # Launch the default shell in the HOME directory.
        os.chdir(os.environ["HOME"])

        if tab_state:
            # Restore the environment.
            # This is currently not enabled.
            environment = tab_state['env']

            filtered_env = []
            for e in environment:
                var, sep, value = e.partition('=')
                if var not in MASKED_ENVIRONMENT:
                    filtered_env.append(var + sep + value)

            # TODO: Make the shell restore these environment variables,
            # then clear out TERMINAL_ENV.
            # os.environ['TERMINAL_ENV'] = '\n'.join(filtered_env)

            # Restore the working directory.
            if 'cwd' in tab_state and os.path.exists(tab_state['cwd']):
                try:
                    os.chdir(tab_state['cwd'])
                except:
                    # ACLs may deny access
                    sys.stdout.write("Could not chdir to " + tab_state['cwd'])

            if 'font_size' in tab_state:
                font_desc = vt.get_font()
                font_desc.set_size(tab_state['font_size'])
                vt.set_font(font_desc)

            # Restore the scrollback buffer.
            for l in tab_state['scrollback']:
                vt.feed(str(l) + '\r\n')

        shell_cmd = os.environ.get('SHELL') or '/bin/bash'
        if hasattr(vt, 'fork_command_full'):
            sucess_, box.pid = vt.fork_command_full(
                Vte.PtyFlags.DEFAULT, os.environ["HOME"], [shell_cmd], [],
                GLib.SpawnFlags.DO_NOT_REAP_CHILD, None, None)
        else:
            sucess_, box.pid = vt.spawn_sync(Vte.PtyFlags.DEFAULT,
                                             os.environ["HOME"], [shell_cmd],
                                             [],
                                             GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                                             None, None)

        self._notebook.props.page = index
        vt.grab_focus()

        return index
コード例 #27
0
ファイル: tools.py プロジェクト: dshimola/king-phisher
	def __init__(self, config, parent, application):
		"""
		:param dict config: The King Phisher client configuration.
		:param parent: The parent window for this object.
		:type parent: :py:class:`Gtk.Window`
		:param application: The application instance to which this window belongs.
		:type application: :py:class:`.KingPhisherClientApplication`
		"""
		assert isinstance(application, Gtk.Application)
		self.config = config
		self.parent = parent
		self.application = application
		self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__)
		if not has_vte:
			gui_utilities.show_dialog_error('RPC Terminal Is Unavailable', parent, 'VTE is not installed')
			return

		self.window = Gtk.ApplicationWindow(application=application)
		self.window.set_property('title', 'King Phisher RPC')
		self.window.set_transient_for(parent)
		self.window.set_destroy_with_parent(True)
		self.window.connect('destroy', self.signal_window_destroy)
		self.terminal = Vte.Terminal()
		self.terminal.set_property('rewrap-on-resize', True)
		self.terminal.set_scroll_on_keystroke(True)
		vbox = Gtk.VBox()
		self.window.add(vbox)
		vbox.pack_end(self.terminal, True, True, 0)

		action_group = Gtk.ActionGroup("rpc_terminal_window_actions")
		self._add_menu_actions(action_group)
		uimanager = self._create_ui_manager()
		uimanager.insert_action_group(action_group)
		menubar = uimanager.get_widget("/MenuBar")
		vbox.pack_start(menubar, False, False, 0)

		rpc = self.parent.rpc
		config = {}
		config['campaign_id'] = self.config['campaign_id']
		config['campaign_name'] = self.config['campaign_name']
		config['rpc_data'] = {
			'address': (rpc.host, rpc.port),
			'use_ssl': rpc.use_ssl,
			'username': rpc.username,
			'uri_base': rpc.uri_base,
			'hmac_key': rpc.hmac_key,
		}

		module_path = os.path.dirname(client_rpc.__file__) + ((os.path.sep + '..') * client_rpc.__name__.count('.'))
		module_path = os.path.normpath(module_path)

		python_command = [
			"import {0}".format(client_rpc.__name__),
			"{0}.vte_child_routine('{1}')".format(client_rpc.__name__, json.dumps(config))
		]
		python_command = '; '.join(python_command)

		if hasattr(self.terminal, 'pty_new_sync'):
			# Vte._version >= 2.91
			vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT)
			self.terminal.set_pty(vte_pty)
			self.terminal.connect('child-exited', lambda vt, status: self.window.destroy())
		else:
			# Vte._version <= 2.90
			vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT)
			self.terminal.set_pty_object(vte_pty)
			self.terminal.connect('child-exited', lambda vt: self.window.destroy())

		child_pid, _, _, _ = GLib.spawn_async(
			working_directory=os.getcwd(),
			argv=[utilities.which('python'), '-c', python_command],
			envp=['PYTHONPATH=' + module_path],
			flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD),
			child_setup=self._child_setup,
			user_data=vte_pty
		)

		self.logger.info("vte spawned child process with pid: {0}".format(child_pid))
		self.child_pid = child_pid
		self.terminal.watch_child(child_pid)
		GLib.spawn_close_pid(child_pid)
		self.window.show_all()

		# automatically enter the password
		vte_pty_fd = vte_pty.get_fd()
		if len(select.select([vte_pty_fd], [], [], 1)[0]):
			os.write(vte_pty_fd, rpc.password + '\n')
		return
コード例 #28
0
    def __init__(self):
        Gtk.Window.__init__(self)

        self.channel = implementations.insecure_channel('localhost', 60000)
        self.stub = gui_pb2.beta_create_ControllerView_stub(self.channel)

        self.connect("delete-event", Gtk.main_quit)
        self.set_title("Superposition 1")
        self.resize(800, 600)
        self.daQubits = [self.registerSize]
        self.ePolarizations = [self.registerSize]
        self.bPolarize = [self.registerSize]
        self.bMeasure = [self.registerSize]
        self.polarizations = [0.0, 0.0, 0.0, 0.0]
        self.measurementAngles = [0.0, 0.0, 0.0, 0.0]

        cVLauncher = Gtk.VBox()
        cHLauncher = Gtk.HBox()
        cHLauncher.set_size_request(700, 30)
        cHdaQubits = Gtk.HBox()
        cHdaQubits.set_size_request(800, 100)

        cVLauncher.pack_start(cHLauncher, True, False, 0)
        cVLauncher.pack_start(cHdaQubits, True, False, 0)

        for i in range(self.registerSize):
            self.daQubits.insert(i, Gtk.DrawingArea())
            self.daQubits[i].set_size_request(200, 150)
            self.daQubits[i].connect("draw", self.expose, i)
            cHdaQubits.pack_start(self.daQubits[i], True, False, 0)

        for i in range(self.registerSize):
            self.ePolarizations.insert(i, Gtk.Entry())
            self.ePolarizations[i].set_text(str(self.polarizations[i]))
            self.ePolarizations[i].set_width_chars(5)
            #			self.ePolarizations[i].connect("draw", self.updateDaQubits, i)
            self.bPolarize.insert(i, Gtk.Button())
            self.bPolarize[i].set_label("Polarize")
            self.bPolarize[i].connect("clicked", self.bPolarize_exec, i)
            self.bMeasure.insert(i, Gtk.Button())
            self.bMeasure[i].set_label("Measure")
            self.bMeasure[i].connect("clicked", self.bMeasure_exec, i)
            cHLauncher.pack_start(self.ePolarizations[i], True, False, 0)
            cHLauncher.pack_start(self.bPolarize[i], True, False, 0)
            cHLauncher.pack_start(self.bMeasure[i], True, False, 0)

        self.daRegister = Gtk.DrawingArea()
        self.daRegister.set_size_request(800, 100)
        self.daRegister.connect("draw", self.exposeRegister)
        cVLauncher.pack_start(self.daRegister, True, False, 0)

        self.vt = Vte.Terminal()
        self.vt.set_size_request(800, 400)
        self.vt.fork_command_full(
            Vte.PtyFlags.DEFAULT,
            os.environ['PWD'],
            ["/bin/bash"],
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
        )

        command = "./superpositionController\r\n"
        self.vt.feed_child(command, len(command))
        cVLauncher.pack_start(self.vt, True, True, 0)

        self.add(cVLauncher)
        self.show_all()
        time.sleep(1)
        self.initDone = 1
コード例 #29
0
    def reconfigure(self):
        """Update configuration for the whole application"""

        if self.style_providers != []:
            for style_provider in self.style_providers:
                Gtk.StyleContext.remove_provider_for_screen(
                    Gdk.Screen.get_default(),
                    style_provider)
        self.style_providers = []

        # Force the window background to be transparent for newer versions of
        # GTK3. We then have to fix all the widget backgrounds because the
        # widgets theming may not render it's own background.
        css = """
            .terminator-terminal-window {
                background-color: alpha(@theme_bg_color,0); }

            .terminator-terminal-window .notebook.header,
            .terminator-terminal-window notebook header {
                background-color: @theme_bg_color; }

            .terminator-terminal-window .pane-separator {
                background-color: @theme_bg_color; }

            .terminator-terminal-window .terminator-terminal-searchbar {
                background-color: @theme_bg_color; }
            """

        # Fix several themes that put a borders, corners, or backgrounds around
        # viewports, making the titlebar look bad.
        css += """
            .terminator-terminal-window GtkViewport,
            .terminator-terminal-window viewport {
                border-width: 0px;
                border-radius: 0px;
                background-color: transparent; }
            """

        # Add per profile snippets for setting the background of the HBox
        template = """
            .terminator-profile-%s {
                background-color: alpha(%s, %s); }
            """
        profiles = self.config.base.profiles
        for profile in list(profiles.keys()):
            if profiles[profile]['use_theme_colors']:
                # Create a dummy window/vte and realise it so it has correct
                # values to read from
                tmp_win = Gtk.Window()
                tmp_vte = Vte.Terminal()
                tmp_win.add(tmp_vte)
                tmp_win.realize()
                bgcolor = tmp_vte.get_style_context().get_background_color(Gtk.StateType.NORMAL)
                bgcolor = "#{0:02x}{1:02x}{2:02x}".format(int(bgcolor.red  * 255),
                                                          int(bgcolor.green * 255),
                                                          int(bgcolor.blue * 255))
                tmp_win.remove(tmp_vte)
                del(tmp_vte)
                del(tmp_win)
            else:
                bgcolor = Gdk.RGBA()
                bgcolor = profiles[profile]['background_color']
            if profiles[profile]['background_type'] == 'transparent':
                bgalpha = profiles[profile]['background_darkness']
            else:
                bgalpha = "1"

            munged_profile = "".join([c if c.isalnum() else "-" for c in profile])
            css += template % (munged_profile, bgcolor, bgalpha)

        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(css.encode('utf-8'))
        self.style_providers.append(style_provider)

        # Attempt to load some theme specific stylistic tweaks for appearances
        usr_theme_dir = os.path.expanduser('~/.local/share/themes')
        (head, _tail) = os.path.split(borg.__file__)
        app_theme_dir = os.path.join(head, 'themes')

        theme_name = self.gtk_settings.get_property('gtk-theme-name')

        theme_part_list = ['terminator.css']
        if self.config['extra_styling']:    # checkbox_style - needs adding to prefs
            theme_part_list.append('terminator_styling.css')
        for theme_part_file in theme_part_list:
            for theme_dir in [usr_theme_dir, app_theme_dir]:
                path_to_theme_specific_css = os.path.join(theme_dir,
                                                          theme_name,
                                                          'gtk-3.0/apps',
                                                          theme_part_file)
                if os.path.isfile(path_to_theme_specific_css):
                    style_provider = Gtk.CssProvider()
                    style_provider.connect('parsing-error', self.on_css_parsing_error)
                    try:
                        style_provider.load_from_path(path_to_theme_specific_css)
                    except GError:
                        # Hmmm. Should we try to provide GTK version specific files here on failure?
                        gtk_version_string = '.'.join([str(Gtk.get_major_version()),
                                                       str(Gtk.get_minor_version()),
                                                       str(Gtk.get_micro_version())])
                        err('Error(s) loading css from %s into Gtk %s' % (path_to_theme_specific_css,
                                                                          gtk_version_string))
                    self.style_providers.append(style_provider)
                    break

        # Size the GtkPaned splitter handle size.
        css = ""
        if self.config['handle_size'] in range(0, 21):
            css += """
                .terminator-terminal-window GtkPaned,
                .terminator-terminal-window paned {
                    -GtkPaned-handle-size: %s; }
                """ % self.config['handle_size']
        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(css.encode('utf-8'))
        self.style_providers.append(style_provider)

        # Apply the providers, incrementing priority so they don't cancel out
        # each other
        for idx in range(0, len(self.style_providers)):
            Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(),
                self.style_providers[idx],
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION+idx)

        # Cause all the terminals to reconfigure
        for terminal in self.terminals:
            terminal.reconfigure()

        # Reparse our keybindings
        self.keybindings.configure(self.config['keybindings'])

        # Update tab position if appropriate
        maker = Factory()
        for window in self.windows:
            child = window.get_child()
            if maker.isinstance(child, 'Notebook'):
                child.configure()
コード例 #30
0
	def addPage(self,textBuffer,pageTitle):
		print "INSIDE_ADD_PAGE"
		caption=_("Untitled"+str(self.counter))
		#add hbox
		self.hbox=Gtk.HBox();
		self.hbox.show();

		#create text_buffer
		
		self.sourceBuffer= GtkSource.Buffer()
		#add textview
		self.textview=GtkSource.View()
		self.textview.set_buffer(self.sourceBuffer)
		self.textview.set_show_line_numbers(True)
		self.textview.set_show_line_marks(True)
		self.textview.set_size_request(250,400)
		self.setLanguage(self.textview)
	
		#check for textBuffer passed as param
		if textBuffer!=None:			
			#set the textbuffer data to editor	
			start, end = textBuffer.get_bounds()		
			self.sourceBuffer.set_text(textBuffer.get_text(start, end, True))

		#add vpane
		self.vpane=Gtk.VPaned();
		#add scroll to text view
		self.scroll=Gtk.ScrolledWindow();
		self.scroll.set_policy(Gtk.PolicyType.NEVER,Gtk.PolicyType.AUTOMATIC);
		self.scroll.add_with_viewport(self.textview)
		self.scroll.set_size_request(250,400)
		self.scroll.show()
		self.vpane.add(self.scroll)

		
		#add scroll to text view
		self.opScroll= Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
		

		#create Vte Terminal
		self.vteObject=Vte.Terminal()
		self.opScroll.pack_start(self.vteObject, True, True, 0)
		self.outsb = Gtk.Scrollbar(orientation=Gtk.Orientation.VERTICAL)
		self.outsb.set_adjustment(self.vteObject.get_vadjustment())
		self.outsb.show()
		self.opScroll.pack_start(self.outsb, False, False, 0)		

		self.vteObject.set_colors(Gdk.color_parse('#000000'),Gdk.color_parse('#E7E7E7'),[])
		self.vteObject.set_size_request(200,200)
		self.vteObject.show()
		#self.opScroll.set_size_request(250,200)
		self.opScroll.show()	
		print "VTE_KARTIK:",self.vteObject.get_vadjustment()
		self.vpane.add(self.opScroll)
		self.vpane.show()

		self.hbox.pack_start(self.vpane,True,True,0)
		self.textview.show()

		#attach text-change listener for buffer
		self.attachTextChangedListener(self.hbox)		

		self.hbox.set_size_request(250, 300)

		#if pageTitle is none then give a Untitled caption
		if pageTitle==None:
			self.newlabel=Label(caption)
		else:
			self.newlabel=Label(pageTitle)

		#self.newlabel.set_size_request(75,30)
		self.resizeLabel(self.newlabel)
		self.newlabel.show()		
		self.notebook.append_page(self.hbox,self.newlabel)

		#assigning notebook page for the filename
		#self.pageMap[self.newlabel.get_text()]=self.hbox
		self.addPageToPageMap(self.newlabel.get_text(),self.hbox)

		self.counter=self.counter+1
	
		print "Curr :",self.pageMap
		self.selectFileNamePage(self.newlabel.get_text())