示例#1
0
 def on_usbcreator_destroy(self, widget):
     # Unmount devices
     for device in self.devices:
         if self.get_device_mount(device) != "":
             self.unmount_device(device)
     # Close the app
     Gtk.main_quit()
示例#2
0
 def start(self, bridge):
     """Start the UI event loop."""
     bridge.attach(80, 24, True)
     drawing_area = Gtk.DrawingArea()
     drawing_area.connect('draw', self._gtk_draw)
     window = Gtk.Window()
     window.add(drawing_area)
     window.set_events(window.get_events() |
                       Gdk.EventMask.BUTTON_PRESS_MASK |
                       Gdk.EventMask.BUTTON_RELEASE_MASK |
                       Gdk.EventMask.POINTER_MOTION_MASK |
                       Gdk.EventMask.SCROLL_MASK)
     window.connect('configure-event', self._gtk_configure)
     window.connect('delete-event', self._gtk_quit)
     window.connect('key-press-event', self._gtk_key)
     window.connect('key-release-event', self._gtk_key_release)
     window.connect('button-press-event', self._gtk_button_press)
     window.connect('button-release-event', self._gtk_button_release)
     window.connect('motion-notify-event', self._gtk_motion_notify)
     window.connect('scroll-event', self._gtk_scroll)
     window.connect('focus-in-event', self._gtk_focus_in)
     window.connect('focus-out-event', self._gtk_focus_out)
     window.show_all()
     im_context = Gtk.IMMulticontext()
     im_context.set_client_window(drawing_area.get_window())
     im_context.set_use_preedit(False)  # TODO: preedit at cursor position
     im_context.connect('commit', self._gtk_input)
     self._pango_context = drawing_area.create_pango_context()
     self._drawing_area = drawing_area
     self._window = window
     self._im_context = im_context
     self._bridge = bridge
     Gtk.main()
        def destroy(self, window):
            try:
                self.conn.destroy()
            except AttributeError:
                pass

            Gtk.main_quit()
示例#4
0
def start_gui(datadir):
    if not options.profile:
        if cfg.get_bool("app/noprofilemanager"):
            options.profile = cfg.get_string("app/last_profile")
        elif do_profiles():
            if solfege.splash_win:
                solfege.splash_win.hide()
            p = ProfileManager(cfg.get_string("app/last_profile"))
            ret = p.run()
            if ret == Gtk.ResponseType.ACCEPT:
                options.profile = p.get_profile()
                cfg.set_string("app/last_profile", "" if not options.profile else options.profile)
            elif ret in (Gtk.ResponseType.CLOSE, Gtk.ResponseType.DELETE_EVENT):
                Gtk.main_quit()
                return
            p.destroy()
            if solfege.splash_win:
                solfege.splash_win.show()

    cfg.set_bool('config/no_random', bool(options.no_random))

    lessonfile.infocache = lessonfile.InfoCache()

    def f(s):
        if solfege.splash_win:
            solfege.splash_win.show_progress(s)
    if solfege.splash_win:
        solfege.splash_win.show_progress(_("Opening statistics database"))
    try:
        solfege.db = statistics.DB(f, profile=options.profile)
    except sqlite3.OperationalError, e:
        solfege.splash_win.hide()
        gu.dialog_ok(_(u"Failed to open the statistics database:\n«%s»") % str(e).decode(sys.getfilesystemencoding(), 'replace'), secondary_text=_("Click OK to exit the program. Then try to quit all other instances of the program, or reboot the computer. You can only run one instance of GNU Solfege at once."))
        sys.exit()
示例#5
0
文件: main.py 项目: oeli/yafra
 def main(self):
     tdbglobal.tdblogdebug("start gtk main loop")
     self.window.connect("delete-event", Gtk.main_quit)
     self.host = self.builder.get_object("e_main_db")
     self.host.set_text(config.SERVERNAME)
     self.window.show()
     Gtk.main()
示例#6
0
 def test_next_nosong_536(self):
     self.pl.go_to(1)
     self.pl.repeat = True
     self.pl.order = ORDERS[1](self.pl)
     self.pl.set([])
     Gtk.main_iteration_do(False)
     self.pl.next()
示例#7
0
 def flush_events(self):
     # docstring inherited
     Gdk.threads_enter()
     while Gtk.events_pending():
         Gtk.main_iteration()
     Gdk.flush()
     Gdk.threads_leave()
示例#8
0
 def update_accelerator_label(self):
     if self.current_node.shortcut:
         key, mods = Gtk.accelerator_parse(self.current_node.shortcut)
         label = Gtk.accelerator_get_label(key, mods)
         self['accelerator'].set_text(label)
     else:
         self['accelerator'].set_text('')
示例#9
0
 def test_go_to_saves_current(self):
     self.pl.go_to(5)
     self.failUnlessEqual(self.pl.current, 5)
     self.pl.set([5, 10, 15, 20])
     Gtk.main_iteration_do(False)
     self.pl.next()
     self.failUnlessEqual(self.pl.current, 10)
示例#10
0
文件: manager.py 项目: GNOME/gedit
    def get_cell_data_cb(self, column, cell, model, piter, user_data=None):
        tool = model.get_value(piter, self.TOOL_COLUMN)

        if tool == None or not isinstance(tool, Tool):
            if tool == None:
                label = _('All Languages')
            elif not isinstance(tool, GtkSource.Language):
                label = _('Plain Text')
            else:
                label = tool.get_name()

            markup = saxutils.escape(label)
            editable = False
        else:
            escaped = saxutils.escape(tool.name)

            if tool.shortcut:
                key, mods = Gtk.accelerator_parse(tool.shortcut)
                label = Gtk.accelerator_get_label(key, mods)
                markup = '%s (<b>%s</b>)' % (escaped, label)
            else:
                markup = escaped

            editable = True

        cell.set_properties(markup=markup, editable=editable)
示例#11
0
 def drag_begin_cb(self, widget, context):
     color = self.get_managed_color()
     preview = GdkPixbuf.Pixbuf.new(
         GdkPixbuf.Colorspace.RGB, False, 8, 32, 32)
     pixel = color.to_fill_pixel()
     preview.fill(pixel)
     Gtk.drag_set_icon_pixbuf(context, preview, 0, 0)
示例#12
0
    def main(self):

        log.LOG("START  main")
        "Run main loop"
        gtk.main()

        log.LOG("END  main")
示例#13
0
 def __expanded(self, iter, path, model):
     window = self.get_window()
     if window:
         window.set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
         Gtk.main_iteration_do(False)
     try:
         try:
             if model is None:
                 return
             while model.iter_has_child(iter):
                 model.remove(model.iter_children(iter))
             folder = model[iter][0]
             for path in listdir(folder):
                 try:
                     if not os.path.isdir(path):
                         continue
                     for filename in listdir(path):
                         if os.path.isdir(filename):
                             niter = model.append(iter, [path])
                             model.append(niter, ["dummy"])
                             break
                     else:
                         model.append(iter, [path])
                 except OSError:
                     pass
             if not model.iter_has_child(iter):
                 return True
         except OSError:
             pass
     finally:
         if window:
             window.set_cursor(None)
示例#14
0
def run(server_list, random, default=False):
    """Run"""
    window = GraphicalUI(server_list, random, default)
    window.connect("delete-event", Gtk.main_quit)
    window.show_all()
    Gtk.main()
    return window
示例#15
0
    def __key_function(self, entry, event):

        log.LOG("START __key_function")
        if event.keyval == Gdk.KEY_Return:

            self.entryCommandLine.emit_stop_by_name('key_press_event')

        elif event.keyval in (Gdk.KEY_KP_Up, Gdk.KEY_Up, Gdk.KEY_Page_Up):

            self.entryCommandLine.emit_stop_by_name('key_press_event')
            self.historyUp()

        elif event.keyval in (Gdk.KEY_KP_Down, Gdk.KEY_Down, Gdk.KEY_Page_Down):

            self.entryCommandLine.emit_stop_by_name('key_press_event')
            self.historyDown()

        elif event.keyval in (Gdk.KEY_D, Gdk.KEY_d) and\
                event.state & Gdk.ModifierType.CONTROL_MASK:

            self.entryCommandLine.emit_stop_by_name('key_press_event')
            self.setHisoryFile()
            gtk.main_quit()
            self.window.destroy()

        log.LOG("END __key_function")
示例#16
0
文件: hotot.py 项目: sarim/Hotot
def main():
    for opt in sys.argv[1:]:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()
        elif opt in ('-d', '--dev'):
            config.ENABLE_INSPECTOR = True
        else:
            print "hotot: unrecognized option '%s'" % opt
            usage()
            sys.exit(1)

    try:
        import i18n
    except:
        from gettext import gettext as _

    try:
        import prctl
        prctl.set_name('hotot')
    except:
        pass

    GObject.threads_init()
    config.loads();

    agent.init_notify()
    app = Hotot()
    agent.app = app

    Gdk.threads_enter()
    Gtk.main()
    Gdk.threads_leave()
示例#17
0
    def done(self, button):
        """Confirm choice"""
        dialog = Gtk.Dialog(txt.I_CONFIRM_SELECTION, None, 0, (
            Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
            Gtk.STOCK_OK, Gtk.ResponseType.OK))
        dialog.set_transient_for(self)
        dialog.set_border_width(10)
        box = dialog.get_content_area()
        box.set_spacing(10)
        box.add(Gtk.Label(txt.I_USE_THESE_MIRRORS))
        dialog.show_all()
        response = dialog.run()

        if response == Gtk.ResponseType.OK:
            # Quit GUI
            dialog.destroy()
            for line in self.custom_list:
                line["last_sync"] = line["last_sync"].replace(" ", ":").replace("h", "").replace("m", "")
            if self.random:
                shuffle(self.custom_list)
            else:
                self.custom_list.sort(key=itemgetter("resp_time"))
            self.is_done = True
            Gtk.main_quit()
        elif response == Gtk.ResponseType.CANCEL:
            dialog.destroy()  # Go back to selection
示例#18
0
def main():
    win = ScrolledInfoBarDemoWindow()
    win.set_size_request(600, 300)
    win.set_position(Gtk.WindowPosition.MOUSE)
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()
示例#19
0
	def recordLine(self):
		'''Listen to temperature data from the serial port, save to a 
		log file (csv) and return as a list:
		return log = [datetime_stamp, temperature]
		'''
		try:
			n = 0
			while n < 5:
				# Record temp from the defined log number
				row = self.ser.readline()
				logger = row.split(' ')[0]
				temp = row.split(' ')[1]
				if int(logger) == self.log_no:
					print('row ', str(self.log_no), row)
					date_num = date2num(datetime.now())
					self.log = [str(datetime.now()), float(temp)]
					#self.temp_read = self.log
					self.liststore.append(self.log)
					self.plotpoints()
					# Send email alert
					if temp > 5:
						sendEmailAlert(self.log_no, temp)
				row = None
				temp = None
				n += 1
				while Gtk.events_pending():
					Gtk.main_iteration()  # runs the GTK main loop as needed
				
		except:
			print('Could not read serial device')
			self.temp_read = None
		return True
示例#20
0
    def _runSpoke(self, action):
        from gi.repository import Gtk

        # This duplicates code in widgets/src/BaseWindow.c, but we want to make sure
        # maximize gets called every time a spoke is displayed to prevent the 25%
        # UI from showing up.
        action.window.maximize()
        action.window.set_property("expand", True)

        action.refresh()

        action.window.set_beta(self.window.get_beta())
        action.window.set_property("distribution", distributionText().upper())

        action.window.set_transient_for(self.window)
        action.window.show_all()

        # Start a recursive main loop for this spoke, which will prevent
        # signals from going to the underlying (but still displayed) Hub and
        # prevent the user from switching away.  It's up to the spoke's back
        # button handler to kill its own layer of main loop.
        Gtk.main()
        action.window.set_transient_for(None)

        action._visitedSinceApplied = True

        # Don't take _visitedSinceApplied into account here.  It will always be
        # True from the line above.
        if action.changed and (not action.skipTo or (action.skipTo and action.applyOnSkip)):
            action.apply()
            action.execute()
            action._visitedSinceApplied = False
 def on_botonVer_clicked(self, widget):
     ''' Evento del boton Ver para mostrar los datos del evento. Llama a la clase Evento que crea una ventana
     con las tablas de la BD '''
     ventanaEvento = vEvento.Evento()
     ventanaEvento.connect("delete-event", Gtk.main_quit)
     ventanaEvento.show_all()
     Gtk.main()
示例#22
0
    def install(self):
        if self._win is not None:
            self._win.blur()
            self._win.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH))

        if not self._download_app():
            return self._end(False)

        if self._check_if_installed:
            if not self._installed_check():
                return self._end(False)

        if not self._get_sudo_pw():
            return self._end(False)

        # Make sure the dialogs are gone before installing
        while Gtk.events_pending():
            Gtk.main_iteration()

        rv = self._install()

        if rv and self._report_install:
            self._report()

        return self._end(rv)
示例#23
0
 def _gtk_main():
     gui = GtkRll()
     gui.connect("delete-event", Gtk.main_quit)
     signal(SIGINT, SIG_DFL)
     gui.show_all()
     # FIXME: KeyboardInterrupt here hangs it.
     Gtk.main()
示例#24
0
def on_ChooseButton_clicked(*args):
    ChooseDialog.hide()
    while Gtk.events_pending():
        Gtk.main_iteration()
    for row in choose_list:
        if row[0] is True:
            to_add.add(row[1].split(":")[0])  # split done in case of optdep choice
示例#25
0
文件: gtk.py 项目: apodda/NotebookPy
def main(db, debug=False):
    builder = Gtk.Builder()
    builder.add_from_file("view/notebook.glade")

    liststore = builder.get_object("liststore")
    view = builder.get_object("treeview_notelist")
    textbuffer = builder.get_object("current_note_buffer")
    selection = builder.get_object("treeview_notelist_selection")

    # Populate the liststore. Set the text buffer to the first note text if
    # the note db is non-empty
    query = db.query('')
    if query != []:
        for title, uid in query:
            liststore.append([title, uid])

            textbuffer.set_text(db.get_text(query[0][1])) # 0,1 means first note, uid
    else:
        liststore.append(db.add_note('')) # Handle empty db

    # Make sure the first note is selected
    selection.select_iter(liststore.get_iter("0")) # 0 means first note, no search in-tree

    handler = Handler(liststore, selection, textbuffer, view, db)
    builder.connect_signals(handler)

    if debug is False:
        window = builder.get_object("main_window")
        window.show_all()
        Gtk.main()
    else:
        return handler
示例#26
0
def log_error(msg):
    ErrorDialog.format_secondary_text(msg)
    response = ErrorDialog.run()
    while Gtk.events_pending():
        Gtk.main_iteration()
    if response:
        ErrorDialog.hide()
示例#27
0
def log_warning(msg):
    WarningDialog.format_secondary_text(msg)
    response = WarningDialog.run()
    while Gtk.events_pending():
        Gtk.main_iteration()
    if response:
        WarningDialog.hide()
示例#28
0
 def update_label(self):
     if not self.accel_string:
         text = _("unassigned")
     else:
         key, codes, mods = Gtk.accelerator_parse_with_keycode(self.accel_string)
         text = Gtk.accelerator_get_label_with_keycode(None, key, codes[0], mods)
     self.set_property("text", text)
示例#29
0
    def test_dance_grid ():
        from . import gsudoku
        window = Gtk.Window()
        game = '''9 1 6 3 2 8 4 5 7
                  5 7 4 6 1 9 2 8 3
                  8 3 2 5 7 4 9 6 1
                  6 8 7 2 4 1 3 9 5
                  2 9 5 7 3 6 1 4 8
                  3 4 1 8 9 5 7 2 6
                  4 6 9 1 8 7 5 3 2
                  1 2 8 9 5 3 6 7 4
                  7 5 3 4 6 2 8 1 9'''
        gsd = gsudoku.SudokuGameDisplay(game)
        dancer = GridDancer(gsd)

        button = Gtk.Button('toggle')
        button.connect('clicked',
                lambda *args: dancer.stop_dancing() if dancer.dancing
                    else dancer.start_dancing())

        vbox = Gtk.VBox()
        vbox.pack_start(gsd, True, True, 0)
        vbox.pack_end(button, True, True, 0)
        vbox.set_focus_child(button)

        window.add(vbox)
        window.show_all()
        window.connect('delete-event', Gtk.main_quit)
        Gtk.main()
示例#30
0
def run(screen_name):
    window = Gtk.Window()
    window.connect('destroy', Gtk.main_quit)
    window.set_size_request(800, 500)
    window.set_border_width(12)
    window.set_title("Cnchi - Test of %s screen" % screen_name)

    import config
    settings = config.Settings()
    settings.set('data', '/usr/share/cnchi/data')
    from desktop_environments import DESKTOPS
    settings.set('desktops', DESKTOPS)
    settings.set('language_code', 'ca')
    
    params = {}
    params['title'] = "Cnchi"
    params['ui_dir'] = "/usr/share/cnchi/ui"
    params['disable_tryit'] = False
    params['settings'] = settings
    params['forward_button'] = Gtk.Button.new()
    params['backwards_button'] = Gtk.Button.new()
    params['main_progressbar'] = Gtk.ProgressBar.new()
    params['header'] = Gtk.HeaderBar.new()
    params['testing'] = True
    params['callback_queue'] = None
    params['alternate_package_list'] = ""
    screen = get_screen(screen_name, params)
    if screen != None:
        screen.prepare('forward')
        window.add(screen)
        window.show_all()
        Gtk.main()
    else:
        print("Unknown screen")
示例#31
0
 def run(self):
     GObject.threads_init()
     Gtk.main()
示例#32
0
.right-semi-circle {
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
}

.circular {
  margin-top: 10px;
}

.margin-fix {
  margin-top: 15px;
}
"""

style_provider = Gtk.CssProvider()
style_provider.load_from_data(str.encode(css))
Gtk.StyleContext.add_provider_for_screen(
  Gdk.Screen.get_default(),
  style_provider,
  Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)

def get_window_position_by_args(display):
  """
    If the script was given arguments, it will use those as the position,
    if not it will find the primary monitor and the middle of that
    as the position
  """
  if POSITION_X is not None and POSITION_Y is not None:
    return POSITION_X, POSITION_Y
示例#33
0
    def switchClipWin2(self):
        # self.newVideo.stopPlay()
        self.revealer2.set_reveal_child(False)
        self.revealer3.set_reveal_child(True)
        print("switchClipWin2")

    def on_key_press_event(self, widget, event):
        # print("Key press on widget: ", widget)
        # print("          Modifiers: ", event.state)
        # print("      Key val, name: ", event.keyval, Gdk.keyval_name(event.keyval))

        # check the event modifiers (can also use SHIFTMASK, etc)
        ctrl = event.state & Gdk.ModifierType.CONTROL_MASK

        # see if we recognise a keypress
        if ctrl and event.keyval == Gdk.KEY_q:
            print("Quit App")
            Gtk.main_quit()


GObject.threads_init()
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
# print(dir(win.button.props))
# win.set_size_request(800, 600)
win.set_position(Gtk.WindowPosition.CENTER)
# win.set_resizable(False)

Gtk.main()
示例#34
0
        ing = self.get_value(itr, self.ING_OBJECT_COLUMN)
        if isinstance(editable, Gtk.ComboBoxEntry):
            while len(self.usda_model) > 0:
                del self.usda_model[0]  # empty our liststore...
            usda_list = self.nd.get_usda_list_for_string(ing.ingkey)
            self.usdaDict = {}
            for l in usda_list:
                self.usdaDict[l[0]] = l[1]
                self.usda_model.append(l)

    def usda_edited_cb(self, renderer, path_string, text):
        indices = path_string.split(':')
        path = tuple(map(int, indices))
        itr = self.get_iter(path)
        ing = self.get_value(itr, self.ING_OBJECT_COLUMN)
        self.nd.set_key_from_ndbno(ing.ingkey, self.usdaDict[text])
        self.set_value(itr, self.ts_col_dic['USDA'], text)


if __name__ == '__main__':
    w = Gtk.Window()
    f = Gtk.Entry()
    b = Gtk.Button(stock=Gtk.STOCK_ADD)
    hb = Gtk.HBox()
    hb.add(f)
    hb.add(b)
    vb = Gtk.VBox()
    vb.add(hb)
    t = Gtk.Table()
    nt = Gtk.NutritionTable(t, {}, True)
示例#35
0
    def run(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.VIDEORESIZE:
                pygame.display.set_mode(
                    (event.size[0], event.size[1] - GRID_CELL_SIZE),
                    pygame.RESIZABLE)
                break
        pygame.display.init()
        pygame.font.init()
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        if self.screen:
            w = self.screen.get_width()
            h = self.screen.get_height()
            global GAME_SIZE
            GAME_SIZE = [w, h]
        else:
            self.screen = pygame.display.set_mode(GAME_SIZE)
            pygame.display.set_caption('Flappy')
        self.sound_enable = True
        try:
            pygame.mixer.init()
            self._snd_pipe = pygame.mixer.Sound('data/sounds/pipe.ogg')
            self._snd_pipe.set_volume(0.5)
            self._snd_bird = pygame.mixer.Sound('data/sounds/bird.ogg')
            self._snd_bird.set_volume(0.5)
        except BaseException:
            self.sound_enable = False
        self.load_all()
        self.state = INIT
        self.running = True
        while self.running:
            while Gtk.events_pending():
                Gtk.main_iteration()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.MOUSEBUTTONDOWN or (
                        event.type == pygame.KEYDOWN
                        and event.key == pygame.K_SPACE):
                    if self.state == INIT:
                        self.state = PLAY
                        self.load_game()
                    elif self.state == PLAY:
                        self.bird.setVel(8)
                        if self.sound_enable and self.sound:
                            self._snd_bird.play()
                    elif self.state == END:
                        self.state = INIT
                        self.load_all()
                    elif self.state == PAUSE:
                        self.state = PLAY
                elif event.type == pygame.KEYDOWN:
                    if event.key in [pygame.K_p, pygame.K_ESCAPE]:
                        if self.state == PAUSE:
                            self.state = PLAY
                        elif self.state == PLAY:
                            self.state = PAUSE

            if self.state == PAUSE:
                continue

            self.sprites.clear(self.screen, self.background)
            self.sprites.update()
            self.sprites.draw(self.screen)

            col = pygame.sprite.spritecollide(self.bird, self.tubes, False)
            if not (col == []):
                self.state = END
                self.bird.mAcc = 0
                self.bird.count = -99
                self.floor.mVel = 0
                for spr in self.tubes:
                    spr.mVel = 0
                if self.score > self.best:
                    self.best = self.score
                self.end_scores.update_scores(self.score, self.best)
                self.sprites.add(self.end_scores, layer=3)
                self.sprites.draw(self.screen)

            pygame.display.flip()
            self.clock.tick(30)
示例#36
0
 def createTheme( d ):
     theme = Gtk.IconTheme()
     theme.set_custom_theme( d )
     return theme
示例#37
0
def app_config():
    from config_panel import ConfigPanel
    from gi.repository import Gtk
    ConfigPanel()
    Gtk.main()
	def setup_widgets(self):
		# Load glade file
		self.builder = Gtk.Builder()
		self.builder.add_from_file(os.path.join(self.app.gladepath, "daemon-output.glade"))
		self.builder.connect_signals(self)
		self["tvOutput"].connect('size-allocate', self.scroll)
示例#39
0
文件: main.py 项目: bertob/Avvie
    def setup_window(self):

        draw = Gtk.DrawingArea()
        self.add(draw)

        draw.set_events(
            draw.get_events()
            | Gdk.EventMask.LEAVE_NOTIFY_MASK
            | Gdk.EventMask.BUTTON_PRESS_MASK
            | Gdk.EventMask.BUTTON_RELEASE_MASK
            | Gdk.EventMask.POINTER_MOTION_MASK
            | Gdk.EventMask.POINTER_MOTION_HINT_MASK
        )

        self.set_events(self.get_events() | Gdk.EventMask.KEY_PRESS_MASK | Gdk.EventMask.KEY_RELEASE_MASK)

        draw.connect("button-press-event", self.click)
        draw.connect("button-release-event", self.click_up)
        draw.connect("motion-notify-event", self.mouse_motion)
        draw.connect("leave-notify-event", self.mouse_leave)
        self.connect("key-press-event", self.on_key_press_event)
        self.connect("key-release-event", self.on_key_release_event)

        draw.connect("draw", self.draw)
        self.connect("drag_data_received", self.drag_drop_file)
        self.drag_dest_set(
            Gtk.DestDefaults.MOTION
            | Gtk.DestDefaults.HIGHLIGHT
            | Gtk.DestDefaults.DROP,
            [Gtk.TargetEntry.new("text/uri-list", 0, 80)],
            Gdk.DragAction.COPY,
        )

        hb = Gtk.HeaderBar()
        hb.set_show_close_button(True)
        hb.props.title = app_title
        self.set_titlebar(hb)

        button = Gtk.Button()
        button.set_tooltip_text("Open image file")
        icon = Gio.ThemedIcon(name="document-open-symbolic")
        image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
        button.add(image)
        hb.pack_start(button)
        button.connect("clicked", self.open_file)

        button = Gtk.Button()
        button.set_tooltip_text("Export to Downloads folder")
        icon = Gio.ThemedIcon(name="document-save-symbolic")
        image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
        button.add(image)
        button.connect("clicked", self.save)
        button.set_sensitive(False)
        self.open_button = button

        hb.pack_end(button)
        hb.pack_end(Gtk.Separator())

        popover = Gtk.Popover()

        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        vbox.set_border_width(15)

        opt = Gtk.RadioButton.new_with_label_from_widget(None, "No Downscale")
        opt.connect("toggled", self.toggle_menu_setting, "1:1")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)

        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "184")
        opt.connect("toggled", self.toggle_menu_setting, "184")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)
        
        # opt = Gtk.RadioButton.new_with_label_from_widget(opt, "500")
        # opt.connect("toggled", self.toggle_menu_setting, "500")
        # vbox.pack_start(child=opt, expand=True, fill=False, padding=4)

        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "1000")
        opt.connect("toggled", self.toggle_menu_setting, "1000")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)

        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "1920")
        opt.connect("toggled", self.toggle_menu_setting, "1920")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)

        inline_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        self.custom_resize_radio = Gtk.RadioButton.new_with_label_from_widget(opt, "Custom")
        self.custom_resize_radio.connect("toggled", self.toggle_menu_setting, "custom")
        inline_box.pack_start(child=self.custom_resize_radio, expand=True, fill=False, padding=0)

        self.custom_resize_adjustment = Gtk.Adjustment(value=500, lower=2, upper=10000, step_increment=50)
        self.custom_resize_adjustment.connect("value-changed", self.set_custom_resize)

        spinbutton = Gtk.SpinButton()
        spinbutton.set_numeric(True)
        spinbutton.set_update_policy(Gtk.SpinButtonUpdatePolicy.ALWAYS)
        spinbutton.set_adjustment(self.custom_resize_adjustment)
        inline_box.pack_start(child=spinbutton, expand=True, fill=False, padding=4)

        vbox.pack_start(child=inline_box, expand=True, fill=False, padding=0)

        vbox.pack_start(child=Gtk.Separator(), expand=True, fill=False, padding=4)

        pn = Gtk.CheckButton()
        pn.set_label("Export as PNG")
        pn.connect("toggled", self.toggle_menu_setting, "png")
        vbox.pack_start(child=pn, expand=True, fill=False, padding=4)

        sh = Gtk.CheckButton()
        sh.set_label("Sharpen")
        sh.connect("toggled", self.toggle_menu_setting, "sharpen")
        vbox.pack_start(child=sh, expand=True, fill=False, padding=4)

        sh = Gtk.CheckButton()
        sh.set_label("Grayscale")
        sh.connect("toggled", self.toggle_menu_setting, "grayscale")
        vbox.pack_start(child=sh, expand=True, fill=False, padding=4)

        self.preview_circle_check.set_label("Circle (Preview Only)")
        self.preview_circle_check.connect("toggled", self.toggle_menu_setting, "circle")
        vbox.pack_start(child=self.preview_circle_check, expand=True, fill=False, padding=4)

        vbox.pack_start(child=Gtk.Separator(), expand=True, fill=False, padding=4)

        vbox2 = vbox

        m1 = Gtk.ModelButton(label="Export As")
        m1.connect("clicked", self.export_as)
        vbox.pack_start(child=m1, expand=True, fill=False, padding=4)

        m1 = Gtk.ModelButton(label="About")
        m1.connect("clicked", self.show_about)
        vbox.pack_start(child=m1, expand=True, fill=False, padding=4)

        menu = Gtk.MenuButton()
        icon = Gio.ThemedIcon(name="open-menu-symbolic")
        menu.set_tooltip_text("Options Menu")
        image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
        menu.add(image)
        menu.set_popover(popover)

        hb.pack_end(menu)

        # CROP MENU ----------------------------------------------------------
        popover = Gtk.PopoverMenu()

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        vbox.set_border_width(13)

        opt = Gtk.RadioButton.new_with_label_from_widget(None, "No Crop")
        opt.connect("toggled", self.toggle_menu_setting2, "none")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)
        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "Square")
        opt.connect("toggled", self.toggle_menu_setting2, "square")
        opt.set_active(True)
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)

        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "Rectangle")
        opt.connect("toggled", self.toggle_menu_setting2, "rect")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)

        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "16:10")
        opt.connect("toggled", self.toggle_menu_setting2, "16:10")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)
        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "16:9")
        opt.connect("toggled", self.toggle_menu_setting2, "16:9")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)
        opt = Gtk.RadioButton.new_with_label_from_widget(opt, "21:9")
        opt.connect("toggled", self.toggle_menu_setting2, "21:9")
        vbox.pack_start(child=opt, expand=True, fill=False, padding=4)

        self.rotate_reset_button.connect("clicked", self.rotate_reset)
        self.rotate_reset_button.set_sensitive(False)

        self.rot.set_value(0)
        self.rot.set_size_request(180, -1)
        self.rot.set_draw_value(False)
        self.rot.set_has_origin(False)
        self.rot.connect("value-changed", self.rotate)
        vbox.pack_start(child=self.rot, expand=True, fill=False, padding=7)
        vbox.pack_start(child=self.rotate_reset_button, expand=True, fill=False, padding=7)

        flip_vert_button = Gtk.Button(label="Flip Vertical")
        flip_vert_button.connect("clicked", self.toggle_flip_vert)
        vbox.pack_start(child=flip_vert_button, expand=True, fill=False, padding=2)
        flip_hoz_button = Gtk.Button(label="Flip Horizontal")
        flip_hoz_button.connect("clicked", self.toggle_flip_hoz)
        vbox.pack_start(child=flip_hoz_button, expand=True, fill=False, padding=2)

        hbox.pack_start(child=vbox, expand=True, fill=False, padding=4)
        hbox.pack_start(child=Gtk.Separator(), expand=True, fill=False, padding=4)
        hbox.pack_start(child=vbox2, expand=True, fill=False, padding=4)

        popover.add(hbox)
        vbox.show_all()
        vbox2.show_all()
        hbox.show_all()

        menu.set_popover(popover)
        vbox.show_all()

        self.about.set_authors(["Taiko2k"])
        # self.about.set_artists(["Test"])
        self.about.set_copyright("Copyright 2019 Taiko2k [email protected]")
        self.about.set_license_type(Gtk.License(3))
        self.about.set_website("https://github.com/taiko2k/" + app_title.lower())
        self.about.set_website_label("Github")
        self.about.set_destroy_with_parent(True)
        self.about.set_version(version)
        self.about.set_logo_icon_name(app_id)

        for item in sys.argv:
            if not item.endswith(".py") and os.path.isfile(item):
                self.open_button.set_sensitive(True)
                picture.load(item, self.get_size())
                break
示例#40
0
def new_user_dialog():
    dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO,
                                   Gtk.ButtonsType.OK_CANCEL)

    dialog.set_title(_('New user'))
    dialog.set_position(Gtk.WindowPosition.CENTER)
    dialog.set_default_response(Gtk.ResponseType.OK)
    dialog.set_icon_name('dialog-password')
    dialog.set_markup(_('Type the new user information:'))

    hboxname = Gtk.HBox()
    lblname = Gtk.Label(_('name'))
    lblname.set_visible(True)
    hboxname.pack_start(lblname, False, False, False)
    name = Gtk.Entry()
    name.set_activates_default(True)
    name.show()
    hboxname.pack_end(name, False, False, False)
    hboxname.show()

    hboxlogin = Gtk.HBox()
    lbluser = Gtk.Label(_('login'))
    lbluser.set_visible(True)
    hboxlogin.pack_start(lbluser, False, False, False)
    user = Gtk.Entry()
    user.set_activates_default(True)
    user.show()
    hboxlogin.pack_end(user, False, False, False)
    hboxlogin.show()

    hboxpwd = Gtk.HBox()
    lblpwd = Gtk.Label(_('password'))
    lblpwd.set_visible(True)
    hboxpwd.pack_start(lblpwd, False, False, False)
    pwd = Gtk.Entry()
    pwd.set_activates_default(True)
    pwd.set_visibility(False)
    pwd.show()
    hboxpwd.pack_end(pwd, False, False, False)
    hboxpwd.show()

    hboxconfirm = Gtk.HBox()
    lblconfirm = Gtk.Label(_('confirm'))
    lblconfirm.set_visible(True)
    hboxconfirm.pack_start(lblconfirm, False, False, False)
    confirm = Gtk.Entry()
    confirm.set_activates_default(True)
    confirm.set_visibility(False)
    confirm.show()
    hboxconfirm.pack_end(confirm, False, False, False)
    hboxconfirm.show()

    dialog.get_message_area().pack_start(hboxname, False, False, False)
    dialog.get_message_area().pack_start(hboxlogin, False, False, False)
    dialog.get_message_area().pack_start(hboxpwd, False, False, False)
    dialog.get_message_area().pack_start(hboxconfirm, False, False, False)
    result = dialog.run()

    retval = False
    if result == Gtk.ResponseType.OK:
        retval = {
            'name': name.get_text(),
            'login': user.get_text(),
            'password': pwd.get_text(),
            'confirm': confirm.get_text(),
            'groups': ''
        }

    dialog.destroy()
    return retval
示例#41
0
文件: main.py 项目: sahwar/quodlibet
    def __init__(self, library):
        Browser.__init__(self, spacing=6)
        self.set_orientation(Gtk.Orientation.VERTICAL)
        self.songcontainer = qltk.paned.ConfigRVPaned(
            "browsers", "covergrid_pos", 0.4)
        if config.getboolean("browsers", "covergrid_wide", False):
            self.songcontainer.set_orientation(Gtk.Orientation.HORIZONTAL)

        self._register_instance()
        if self.__model is None:
            self._init_model(library)

        self._cover_cancel = Gio.Cancellable()

        self.scrollwin = sw = ScrolledWindow()
        sw.set_shadow_type(Gtk.ShadowType.IN)
        model_sort = AlbumSortModel(model=self.__model)
        model_filter = AlbumFilterModel(child_model=model_sort)
        self.view = view = IconView(model_filter)
        #view.set_item_width(get_cover_size() + 12)
        self.view.set_row_spacing(config.getint("browsers", "row_spacing", 6))
        self.view.set_column_spacing(config.getint("browsers",
            "column_spacing", 6))
        self.view.set_item_padding(config.getint("browsers",
            "item_padding", 6))
        self.view.set_has_tooltip(True)
        self.view.connect("query-tooltip", self._show_tooltip)

        self.__bg_filter = background_filter()
        self.__filter = None
        model_filter.set_visible_func(self.__parse_query)

        mag = config.getfloat("browsers", "covergrid_magnification", 3.)

        self.view.set_item_width(get_cover_size() * mag + 8)

        self.__cover = render = Gtk.CellRendererPixbuf()
        render.set_property('width', get_cover_size() * mag + 8)
        render.set_property('height', get_cover_size() * mag + 8)
        view.pack_start(render, False)

        def cell_data_pb(view, cell, model, iter_, no_cover):
            item = model.get_value(iter_)

            if item.album is None:
                surface = None
            elif item.cover:
                pixbuf = item.cover
                pixbuf = add_border_widget(pixbuf, self.view)
                surface = get_surface_for_pixbuf(self, pixbuf)
                # don't cache, too much state has an effect on the result
                self.__last_render_surface = None
            else:
                surface = no_cover

            if self.__last_render_surface == surface:
                return
            self.__last_render_surface = surface
            cell.set_property("surface", surface)

        view.set_cell_data_func(render, cell_data_pb, self._no_cover)

        self.__text_cells = render = Gtk.CellRendererText()
        render.set_visible(config.getboolean("browsers", "album_text", True))
        render.set_property('alignment', Pango.Alignment.CENTER)
        render.set_property('xalign', 0.5)
        render.set_property('ellipsize', Pango.EllipsizeMode.END)
        view.pack_start(render, False)

        def cell_data(view, cell, model, iter_, data):
            album = model.get_album(iter_)

            if album is None:
                text = "<b>%s</b>" % _("All Albums")
                text += "\n" + ngettext("%d album", "%d albums",
                        len(model) - 1) % (len(model) - 1)
                markup = text
            else:
                markup = self.display_pattern % album

            if self.__last_render == markup:
                return
            self.__last_render = markup
            cell.markup = markup
            cell.set_property('markup', markup)

        view.set_cell_data_func(render, cell_data, None)

        view.set_selection_mode(Gtk.SelectionMode.MULTIPLE)
        sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        sw.add(view)

        view.connect('item-activated', self.__play_selection, None)

        self.__sig = connect_destroy(
            view, 'selection-changed',
            util.DeferredSignal(self.__update_songs, owner=self))

        targets = [("text/x-quodlibet-songs", Gtk.TargetFlags.SAME_APP, 1),
                   ("text/uri-list", 0, 2)]
        targets = [Gtk.TargetEntry.new(*t) for t in targets]

        view.drag_source_set(
            Gdk.ModifierType.BUTTON1_MASK, targets, Gdk.DragAction.COPY)
        view.connect("drag-data-get", self.__drag_data_get) # NOT WORKING
        connect_obj(view, 'button-press-event',
            self.__rightclick, view, library)
        connect_obj(view, 'popup-menu', self.__popup, view, library)

        self.accelerators = Gtk.AccelGroup()
        search = SearchBarBox(completion=AlbumTagCompletion(),
                              accel_group=self.accelerators)
        search.connect('query-changed', self.__update_filter)
        connect_obj(search, 'focus-out', lambda w: w.grab_focus(), view)
        self.__search = search

        prefs = PreferencesButton(self, model_sort)
        search.pack_start(prefs, False, True, 0)
        self.pack_start(Align(search, left=6, top=6), False, True, 0)
        self.pack_start(sw, True, True, 0)

        self.connect("destroy", self.__destroy)

        self.enable_row_update(view, sw, self.view)

        self.__update_filter()

        self.connect('key-press-event', self.__key_pressed, library.librarian)

        if app.cover_manager:
            connect_destroy(
                app.cover_manager, "cover-changed", self._cover_changed)

        self.show_all()
示例#42
0
文件: actiongutter.py 项目: xyui/meld
    def do_draw(self, context):
        view = self.source_view
        if not view or not view.get_realized():
            return

        self.buttons = []

        width = self.get_allocated_width()
        height = self.get_allocated_height()

        style_context = self.get_style_context()
        Gtk.render_background(style_context, context, 0, 0, width, height)

        buf = view.get_buffer()

        context.save()
        context.set_line_width(1.0)

        # Get our linked view's visible offset, get our vertical offset
        # against our view (e.g., for info bars at the top of the view)
        # and translate our context to match.
        view_y_start = view.get_visible_rect().y
        view_y_offset = view.translate_coordinates(self, 0, 0)[1]
        gutter_y_translate = view_y_offset - view_y_start
        context.translate(0, gutter_y_translate)

        button_x = 1
        button_width = width - 2

        for chunk in self.get_chunk_range(view_y_start, view_y_start + height):

            change_type, start_line, end_line, *_unused = chunk

            rect_y = view.get_y_for_line_num(start_line)
            rect_height = max(
                0, view.get_y_for_line_num(end_line) - rect_y - 1)

            # Draw our rectangle outside x bounds, so we don't get
            # vertical lines. Fill first, over-fill with a highlight
            # if in the focused chunk, and then stroke the border.
            context.rectangle(-0.5, rect_y + 0.5, width + 1, rect_height)
            if start_line != end_line:
                context.set_source_rgba(*self.fill_colors[change_type])
                context.fill_preserve()
                if view.current_chunk_check(chunk):
                    highlight = self.fill_colors['current-chunk-highlight']
                    context.set_source_rgba(*highlight)
                    context.fill_preserve()
            context.set_source_rgba(*self.line_colors[change_type])
            context.stroke()

            # Button rendering and tracking
            action = self._classify_change_actions(chunk)
            if action is None:
                continue

            it = buf.get_iter_at_line(start_line)
            button_y, button_height = view.get_line_yrange(it)
            button_y += 1
            button_height -= 2

            button_style_context = get_style(None, 'button.flat.image-button')
            if chunk == self.pointer_chunk:
                button_style_context.set_state(Gtk.StateFlags.PRELIGHT)

            Gtk.render_background(
                button_style_context, context, button_x, button_y,
                button_width, button_height)
            Gtk.render_frame(
                button_style_context, context, button_x, button_y,
                button_width, button_height)

            # TODO: Ideally we'd do this in a pre-render step of some
            # kind, but I'm having trouble figuring out what that would
            # look like.
            self.buttons.append(
                (
                    button_x,
                    button_y + gutter_y_translate,
                    button_x + button_width,
                    button_y + gutter_y_translate + button_height,
                    chunk,
                )
            )

            pixbuf = self.action_map.get(action)
            icon_x = button_x + (button_width - pixbuf.props.width) // 2
            icon_y = button_y + (button_height - pixbuf.props.height) // 2
            Gtk.render_icon(
                button_style_context, context, pixbuf, icon_x, icon_y)

        context.restore()
示例#43
0
文件: gui.py 项目: alghafli/tilfaz
from gi.repository import GdkPixbuf
import sqlalchemy
import utils
import db
import pathlib
import datetime
import display
import gettext
import locale
import re
import urllib.parse

search_filter = None
edited_program = db.Program()
edited_subprogram = None
label_css = Gtk.CssProvider()
vid_win_css = Gtk.CssProvider()


class Handler:
    next_page_callback_id = None
    next_page_thumb_path = None
    next_page_thumb_mtime = datetime.datetime.utcfromtimestamp(0)

    def on_main_win_destroy(*args):
        Gtk.main_quit()

    def on_search_entry_activate(entry):
        ui.get_object('search_popover').popdown()

    def on_search_radio_toggled(button):
示例#44
0
 def run(self):
     Gtk.main()
示例#45
0
    def _handle_action(self, action, *args):
        log.debug("_handle_action({0}, {1})".format(action, args))
        main = self.main_window
        page = main.current_page
        flow_graph = page.flow_graph if page else None

        def flow_graph_update(fg=flow_graph):
            main.vars.update_gui(fg.blocks)
            fg.update()

        ##################################################
        # Initialize/Quit
        ##################################################
        if action == Actions.APPLICATION_INITIALIZE:
            log.debug("APPLICATION_INITIALIZE")
            file_path_to_show = self.config.file_open()
            for file_path in (self.init_file_paths
                              or self.config.get_open_files()):
                if os.path.exists(file_path):
                    main.new_page(file_path,
                                  show=file_path_to_show == file_path)
            if not main.current_page:
                main.new_page()  # ensure that at least a blank page exists

            main.btwin.search_entry.hide()
            """
            Only disable certain actions on startup. Each of these actions are
            conditionally enabled in _handle_action, so disable them first.
             - FLOW_GRAPH_UNDO/REDO are set in gui/StateCache.py
             - XML_PARSER_ERRORS_DISPLAY is set in RELOAD_BLOCKS

            TODO: These 4 should probably be included, but they are not currently
            enabled anywhere else:
             - PORT_CONTROLLER_DEC, PORT_CONTROLLER_INC
             - BLOCK_INC_TYPE, BLOCK_DEC_TYPE

            TODO: These should be handled better. They are set in
            update_exec_stop(), but not anywhere else
             - FLOW_GRAPH_GEN, FLOW_GRAPH_EXEC, FLOW_GRAPH_KILL
            """
            for action in (Actions.ERRORS_WINDOW_DISPLAY,
                           Actions.ELEMENT_DELETE, Actions.BLOCK_PARAM_MODIFY,
                           Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW,
                           Actions.BLOCK_VALIGN_TOP,
                           Actions.BLOCK_VALIGN_MIDDLE,
                           Actions.BLOCK_VALIGN_BOTTOM,
                           Actions.BLOCK_HALIGN_LEFT,
                           Actions.BLOCK_HALIGN_CENTER,
                           Actions.BLOCK_HALIGN_RIGHT, Actions.BLOCK_CUT,
                           Actions.BLOCK_COPY, Actions.BLOCK_PASTE,
                           Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE,
                           Actions.BLOCK_BYPASS, Actions.BLOCK_CREATE_HIER,
                           Actions.OPEN_HIER, Actions.BUSSIFY_SOURCES,
                           Actions.BUSSIFY_SINKS, Actions.FLOW_GRAPH_SAVE,
                           Actions.FLOW_GRAPH_UNDO, Actions.FLOW_GRAPH_REDO,
                           Actions.XML_PARSER_ERRORS_DISPLAY):
                action.disable()

            # Load preferences
            for action in (
                    Actions.TOGGLE_BLOCKS_WINDOW,
                    Actions.TOGGLE_CONSOLE_WINDOW,
                    Actions.TOGGLE_HIDE_DISABLED_BLOCKS,
                    Actions.TOGGLE_SCROLL_LOCK,
                    Actions.TOGGLE_AUTO_HIDE_PORT_LABELS,
                    Actions.TOGGLE_SNAP_TO_GRID,
                    Actions.TOGGLE_SHOW_BLOCK_COMMENTS,
                    Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB,
                    Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY,
                    Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR,
                    Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR_SIDEBAR,
                    Actions.TOGGLE_HIDE_VARIABLES,
                    Actions.TOGGLE_SHOW_BLOCK_IDS,
            ):
                action.set_enabled(True)
                if hasattr(action, 'load_from_preferences'):
                    action.load_from_preferences()

            # Hide the panels *IF* it's saved in preferences
            main.update_panel_visibility(
                main.BLOCKS, Actions.TOGGLE_BLOCKS_WINDOW.get_active())
            main.update_panel_visibility(
                main.CONSOLE, Actions.TOGGLE_CONSOLE_WINDOW.get_active())
            main.update_panel_visibility(
                main.VARIABLES,
                Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR.get_active())

            # Force an update on the current page to match loaded preferences.
            # In the future, change the __init__ order to load preferences first
            page = main.current_page
            if page:
                page.flow_graph.update()

            self.init = True
        elif action == Actions.APPLICATION_QUIT:
            if main.close_pages():
                while Gtk.main_level():
                    Gtk.main_quit()
                exit(0)
        ##################################################
        # Selections
        ##################################################
        elif action == Actions.ELEMENT_SELECT:
            pass  #do nothing, update routines below
        elif action == Actions.NOTHING_SELECT:
            flow_graph.unselect()
        elif action == Actions.SELECT_ALL:
            if main.btwin.search_entry.has_focus():
                main.btwin.search_entry.select_region(0, -1)
            else:
                flow_graph.select_all()
        ##################################################
        # Enable/Disable
        ##################################################
        elif action in (Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE,
                        Actions.BLOCK_BYPASS):
            changed = flow_graph.change_state_selected(
                new_state={
                    Actions.BLOCK_ENABLE: 'enabled',
                    Actions.BLOCK_DISABLE: 'disabled',
                    Actions.BLOCK_BYPASS: '******',
                }[action])
            if changed:
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        ##################################################
        # Cut/Copy/Paste
        ##################################################
        elif action == Actions.BLOCK_CUT:
            Actions.BLOCK_COPY()
            Actions.ELEMENT_DELETE()
        elif action == Actions.BLOCK_COPY:
            self.clipboard = flow_graph.copy_to_clipboard()
        elif action == Actions.BLOCK_PASTE:
            if self.clipboard:
                flow_graph.paste_from_clipboard(self.clipboard)
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        ##################################################
        # Create hier block
        ##################################################
        elif action == Actions.BLOCK_CREATE_HIER:

            selected_blocks = []

            pads = []
            params = set()

            for block in flow_graph.selected_blocks():
                selected_blocks.append(block)
                # Check for string variables within the blocks
                for param in block.params.values():
                    for variable in flow_graph.get_variables():
                        # If a block parameter exists that is a variable, create a parameter for it
                        if param.get_value() == variable.name:
                            params.add(param.get_value())
                    for flow_param in flow_graph.get_parameters():
                        # If a block parameter exists that is a parameter, create a parameter for it
                        if param.get_value() == flow_param.name:
                            params.add(param.get_value())

            x_min = min(block.coordinate[0] for block in selected_blocks)
            y_min = min(block.coordinate[1] for block in selected_blocks)

            for connection in flow_graph.connections:

                # Get id of connected blocks
                source = connection.source_block
                sink = connection.sink_block

                if source not in selected_blocks and sink in selected_blocks:
                    # Create Pad Source
                    pads.append({
                        'key': connection.sink_port.key,
                        'coord': source.coordinate,
                        'block_index': selected_blocks.index(sink) +
                        1,  # Ignore the options block
                        'direction': 'source'
                    })

                elif sink not in selected_blocks and source in selected_blocks:
                    # Create Pad Sink
                    pads.append({
                        'key': connection.source_port.key,
                        'coord': sink.coordinate,
                        'block_index': selected_blocks.index(source) +
                        1,  # Ignore the options block
                        'direction': 'sink'
                    })

            # Copy the selected blocks and paste them into a new page
            #   then move the flowgraph to a reasonable position
            Actions.BLOCK_COPY()
            main.new_page()
            flow_graph = main.current_page.flow_graph
            Actions.BLOCK_PASTE()
            coords = (x_min, y_min)
            flow_graph.move_selected(coords)

            # Set flow graph to heir block type
            top_block = flow_graph.get_block("top_block")
            top_block.params['generate_options'].set_value('hb')

            # this needs to be a unique name
            top_block.params['id'].set_value('new_hier')

            # Remove the default samp_rate variable block that is created
            remove_me = flow_graph.get_block("samp_rate")
            flow_graph.remove_element(remove_me)

            # Add the param blocks along the top of the window
            x_pos = 150
            for param in params:
                param_id = flow_graph.add_new_block('parameter', (x_pos, 10))
                param_block = flow_graph.get_block(param_id)
                param_block.params['id'].set_value(param)
                x_pos = x_pos + 100

            for pad in pads:
                # add the pad sources and sinks within the new hier block
                if pad['direction'] == 'sink':

                    # add new pad_sink block to the canvas
                    pad_id = flow_graph.add_new_block('pad_sink', pad['coord'])

                    # setup the references to the sink and source
                    pad_block = flow_graph.get_block(pad_id)
                    pad_sink = pad_block.sinks[0]

                    source_block = flow_graph.get_block(
                        flow_graph.blocks[pad['block_index']].name)
                    source = source_block.get_source(pad['key'])

                    # ensure the port types match
                    if pad_sink.dtype != source.dtype:
                        if pad_sink.dtype == 'complex' and source.dtype == 'fc32':
                            pass
                        else:
                            pad_block.params['type'].value = source.dtype
                            pad_sink.dtype = source.dtype

                    # connect the pad to the proper sinks
                    new_connection = flow_graph.connect(source, pad_sink)

                elif pad['direction'] == 'source':
                    pad_id = flow_graph.add_new_block('pad_source',
                                                      pad['coord'])

                    # setup the references to the sink and source
                    pad_block = flow_graph.get_block(pad_id)
                    pad_source = pad_block.sources[0]

                    sink_block = flow_graph.get_block(
                        flow_graph.blocks[pad['block_index']].name)
                    sink = sink_block.get_sink(pad['key'])

                    # ensure the port types match
                    if pad_source.dtype != sink.dtype:
                        if pad_source.dtype == 'complex' and sink.dtype == 'fc32':
                            pass
                        else:
                            pad_block.params['type'].value = sink.dtype
                            pad_source.dtype = sink.dtype

                    # connect the pad to the proper sinks
                    new_connection = flow_graph.connect(pad_source, sink)

            flow_graph_update(flow_graph)
        ##################################################
        # Move/Rotate/Delete/Create
        ##################################################
        elif action == Actions.BLOCK_MOVE:
            page.state_cache.save_new_state(flow_graph.export_data())
            page.saved = False
        elif action in Actions.BLOCK_ALIGNMENTS:
            if flow_graph.align_selected(action):
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        elif action == Actions.BLOCK_ROTATE_CCW:
            if flow_graph.rotate_selected(90):
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        elif action == Actions.BLOCK_ROTATE_CW:
            if flow_graph.rotate_selected(-90):
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        elif action == Actions.ELEMENT_DELETE:
            if flow_graph.remove_selected():
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                Actions.NOTHING_SELECT()
                page.saved = False
        elif action == Actions.ELEMENT_CREATE:
            flow_graph_update()
            page.state_cache.save_new_state(flow_graph.export_data())
            Actions.NOTHING_SELECT()
            page.saved = False
        elif action == Actions.BLOCK_INC_TYPE:
            if flow_graph.type_controller_modify_selected(1):
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        elif action == Actions.BLOCK_DEC_TYPE:
            if flow_graph.type_controller_modify_selected(-1):
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        elif action == Actions.PORT_CONTROLLER_INC:
            if flow_graph.port_controller_modify_selected(1):
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        elif action == Actions.PORT_CONTROLLER_DEC:
            if flow_graph.port_controller_modify_selected(-1):
                flow_graph_update()
                page.state_cache.save_new_state(flow_graph.export_data())
                page.saved = False
        ##################################################
        # Window stuff
        ##################################################
        elif action == Actions.ABOUT_WINDOW_DISPLAY:
            Dialogs.show_about(main, self.platform.config)
        elif action == Actions.HELP_WINDOW_DISPLAY:
            Dialogs.show_help(main)
        elif action == Actions.GET_INVOLVED_WINDOW_DISPLAY:
            Dialogs.show_get_involved(main)
        elif action == Actions.TYPES_WINDOW_DISPLAY:
            Dialogs.show_types(main)
        elif action == Actions.KEYBOARD_SHORTCUTS_WINDOW_DISPLAY:
            Dialogs.show_keyboard_shortcuts(main)
        elif action == Actions.ERRORS_WINDOW_DISPLAY:
            Dialogs.ErrorsDialog(main, flow_graph).run_and_destroy()
        elif action == Actions.TOGGLE_CONSOLE_WINDOW:
            action.set_active(not action.get_active())
            main.update_panel_visibility(main.CONSOLE, action.get_active())
            action.save_to_preferences()
        elif action == Actions.TOGGLE_BLOCKS_WINDOW:
            # This would be better matched to a Gio.PropertyAction, but to do
            # this, actions would have to be defined in the window not globally
            action.set_active(not action.get_active())
            main.update_panel_visibility(main.BLOCKS, action.get_active())
            action.save_to_preferences()
        elif action == Actions.TOGGLE_SCROLL_LOCK:
            action.set_active(not action.get_active())
            active = action.get_active()
            main.console.text_display.scroll_lock = active
            if active:
                main.console.text_display.scroll_to_end()
            action.save_to_preferences()
        elif action == Actions.CLEAR_CONSOLE:
            main.console.text_display.clear()
        elif action == Actions.SAVE_CONSOLE:
            file_path = FileDialogs.SaveConsole(main, page.file_path).run()
            if file_path is not None:
                main.console.text_display.save(file_path)
        elif action == Actions.TOGGLE_HIDE_DISABLED_BLOCKS:
            action.set_active(not action.get_active())
            flow_graph_update()
            action.save_to_preferences()
            page.state_cache.save_new_state(flow_graph.export_data())
            Actions.NOTHING_SELECT()
        elif action == Actions.TOGGLE_AUTO_HIDE_PORT_LABELS:
            action.set_active(not action.get_active())
            action.save_to_preferences()
            for page in main.get_pages():
                page.flow_graph.create_shapes()
        elif action in (Actions.TOGGLE_SNAP_TO_GRID,
                        Actions.TOGGLE_SHOW_BLOCK_COMMENTS,
                        Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB):
            action.set_active(not action.get_active())
            action.save_to_preferences()
        elif action == Actions.TOGGLE_SHOW_FLOWGRAPH_COMPLEXITY:
            action.set_active(not action.get_active())
            action.save_to_preferences()
            for page in main.get_pages():
                flow_graph_update(page.flow_graph)
        elif action == Actions.TOGGLE_HIDE_VARIABLES:
            action.set_active(not action.get_active())
            active = action.get_active()
            # Either way, triggering this should simply trigger the variable editor
            # to be visible.
            varedit = Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR
            if active:
                log.debug(
                    "Variables are hidden. Forcing the variable panel to be visible."
                )
                varedit.disable()
            else:
                varedit.enable()
            # Just force it to show.
            varedit.set_active(True)
            main.update_panel_visibility(main.VARIABLES)
            Actions.NOTHING_SELECT()
            action.save_to_preferences()
            varedit.save_to_preferences()
            flow_graph_update()
        elif action == Actions.TOGGLE_SHOW_BLOCK_IDS:
            action.set_active(not action.get_active())
            active = action.get_active()
            Actions.NOTHING_SELECT()
            action.save_to_preferences()
            flow_graph_update()
        elif action == Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR:
            # TODO: There may be issues at startup since these aren't triggered
            # the same was as Gtk.Actions when loading preferences.
            action.set_active(not action.get_active())
            # Just assume this was triggered because it was enabled.
            main.update_panel_visibility(main.VARIABLES, action.get_active())
            action.save_to_preferences()

            # Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR_SIDEBAR.set_enabled(action.get_active())
            action.save_to_preferences()
        elif action == Actions.TOGGLE_FLOW_GRAPH_VAR_EDITOR_SIDEBAR:
            action.set_active(not action.get_active())
            if self.init:
                Dialogs.MessageDialogWrapper(
                    main,
                    Gtk.MessageType.INFO,
                    Gtk.ButtonsType.CLOSE,
                    markup=
                    "Moving the variable editor requires a restart of GRC."
                ).run_and_destroy()
                action.save_to_preferences()
        ##################################################
        # Param Modifications
        ##################################################
        elif action == Actions.BLOCK_PARAM_MODIFY:
            selected_block = args[0] if args[0] else flow_graph.selected_block
            if selected_block:
                self.dialog = PropsDialog(self.main_window, selected_block)
                response = Gtk.ResponseType.APPLY
                while response == Gtk.ResponseType.APPLY:  # rerun the dialog if Apply was hit
                    response = self.dialog.run()
                    if response in (Gtk.ResponseType.APPLY,
                                    Gtk.ResponseType.ACCEPT):
                        page.state_cache.save_new_state(
                            flow_graph.export_data())
                        ### Following  lines force an complete update of io ports
                        n = page.state_cache.get_current_state()
                        flow_graph.import_data(n)
                        flow_graph_update()

                        page.saved = False
                    else:  # restore the current state
                        n = page.state_cache.get_current_state()
                        flow_graph.import_data(n)
                        flow_graph_update()
                    if response == Gtk.ResponseType.APPLY:
                        # null action, that updates the main window
                        Actions.ELEMENT_SELECT()
                self.dialog.destroy()
                self.dialog = None
        elif action == Actions.EXTERNAL_UPDATE:
            page.state_cache.save_new_state(flow_graph.export_data())
            flow_graph_update()
            if self.dialog is not None:
                self.dialog.update_gui(force=True)
            page.saved = False
        elif action == Actions.VARIABLE_EDITOR_UPDATE:
            page.state_cache.save_new_state(flow_graph.export_data())
            flow_graph_update()
            page.saved = False
        ##################################################
        # View Parser Errors
        ##################################################
        elif action == Actions.XML_PARSER_ERRORS_DISPLAY:
            pass
        ##################################################
        # Undo/Redo
        ##################################################
        elif action == Actions.FLOW_GRAPH_UNDO:
            n = page.state_cache.get_prev_state()
            if n:
                flow_graph.unselect()
                flow_graph.import_data(n)
                flow_graph_update()
                page.saved = False
        elif action == Actions.FLOW_GRAPH_REDO:
            n = page.state_cache.get_next_state()
            if n:
                flow_graph.unselect()
                flow_graph.import_data(n)
                flow_graph_update()
                page.saved = False
        ##################################################
        # New/Open/Save/Close
        ##################################################
        elif action == Actions.FLOW_GRAPH_NEW:
            main.new_page()
            args = (GLib.Variant('s', 'qt_gui'), )
            flow_graph = main.current_page.flow_graph
            flow_graph.options_block.params['generate_options'].set_value(
                str(args[0])[1:-1])
            flow_graph.options_block.params['author'].set_value(getuser())
            flow_graph_update(flow_graph)
        elif action == Actions.FLOW_GRAPH_NEW_TYPE:
            main.new_page()
            if args:
                flow_graph = main.current_page.flow_graph
                flow_graph.options_block.params['generate_options'].set_value(
                    str(args[0])[1:-1])
                flow_graph_update(flow_graph)
        elif action == Actions.FLOW_GRAPH_OPEN:
            file_paths = args[0] if args[0] else FileDialogs.OpenFlowGraph(
                main, page.file_path).run()
            if file_paths:  # Open a new page for each file, show only the first
                for i, file_path in enumerate(file_paths):
                    main.new_page(file_path, show=(i == 0))
                    self.config.add_recent_file(file_path)
                    main.tool_bar.refresh_submenus()
                    #main.menu_bar.refresh_submenus()
        elif action == Actions.FLOW_GRAPH_OPEN_QSS_THEME:
            file_paths = FileDialogs.OpenQSS(
                main, self.platform.config.install_prefix +
                '/share/gnuradio/themes/').run()
            if file_paths:
                self.platform.config.default_qss_theme = file_paths[0]
        elif action == Actions.FLOW_GRAPH_CLOSE:
            main.close_page()
        elif action == Actions.FLOW_GRAPH_OPEN_RECENT:
            file_path = str(args[0])[1:-1]
            main.new_page(file_path, show=True)
            main.tool_bar.refresh_submenus()
        elif action == Actions.FLOW_GRAPH_SAVE:
            #read-only or undefined file path, do save-as
            if page.get_read_only() or not page.file_path:
                Actions.FLOW_GRAPH_SAVE_AS()
            #otherwise try to save
            else:
                try:
                    self.platform.save_flow_graph(page.file_path, flow_graph)
                    flow_graph.grc_file_path = page.file_path
                    page.saved = True
                except IOError:
                    Messages.send_fail_save(page.file_path)
                    page.saved = False
        elif action == Actions.FLOW_GRAPH_SAVE_AS:
            file_path = FileDialogs.SaveFlowGraph(main, page.file_path).run()

            if file_path is not None:
                if flow_graph.options_block.params['id'].get_value(
                ) == 'default':
                    file_name = os.path.basename(file_path).replace(".grc", "")
                    flow_graph.options_block.params['id'].set_value(file_name)
                    flow_graph_update(flow_graph)

                page.file_path = os.path.abspath(file_path)
                try:
                    self.platform.save_flow_graph(page.file_path, flow_graph)
                    flow_graph.grc_file_path = page.file_path
                    page.saved = True
                except IOError:
                    Messages.send_fail_save(page.file_path)
                    page.saved = False
                self.config.add_recent_file(file_path)
                main.tool_bar.refresh_submenus()
                #TODO
                #main.menu_bar.refresh_submenus()
        elif action == Actions.FLOW_GRAPH_SAVE_COPY:
            try:
                if not page.file_path:
                    # Make sure the current flowgraph has been saved
                    Actions.FLOW_GRAPH_SAVE_AS()
                else:
                    dup_file_path = page.file_path
                    dup_file_name = '.'.join(
                        dup_file_path.split('.')[:-1]
                    ) + "_copy"  # Assuming .grc extension at the end of file_path
                    dup_file_path_temp = dup_file_name + Constants.FILE_EXTENSION
                    count = 1
                    while os.path.exists(dup_file_path_temp):
                        dup_file_path_temp = '{}({}){}'.format(
                            dup_file_name, count, Constants.FILE_EXTENSION)
                        count += 1
                    dup_file_path_user = FileDialogs.SaveFlowGraph(
                        main, dup_file_path_temp).run()
                    if dup_file_path_user is not None:
                        self.platform.save_flow_graph(dup_file_path_user,
                                                      flow_graph)
                        Messages.send('Saved Copy to: "' + dup_file_path_user +
                                      '"\n')
            except IOError:
                Messages.send_fail_save(
                    "Can not create a copy of the flowgraph\n")
        elif action == Actions.FLOW_GRAPH_DUPLICATE:
            previous = flow_graph
            # Create a new page
            main.new_page()
            page = main.current_page
            new_flow_graph = page.flow_graph
            # Import the old data and mark the current as not saved
            new_flow_graph.import_data(previous.export_data())
            flow_graph_update(new_flow_graph)
            page.state_cache.save_new_state(new_flow_graph.export_data())
            page.saved = False
        elif action == Actions.FLOW_GRAPH_SCREEN_CAPTURE:
            file_path, background_transparent = FileDialogs.SaveScreenShot(
                main, page.file_path).run()
            if file_path is not None:
                try:
                    Utils.make_screenshot(flow_graph, file_path,
                                          background_transparent)
                except ValueError:
                    Messages.send('Failed to generate screen shot\n')
        ##################################################
        # Gen/Exec/Stop
        ##################################################
        elif action == Actions.FLOW_GRAPH_GEN:
            if not page.process:
                if not page.saved or not page.file_path:
                    Actions.FLOW_GRAPH_SAVE(
                    )  # only save if file path missing or not saved
                if page.saved and page.file_path:
                    generator = page.get_generator()
                    try:
                        Messages.send_start_gen(generator.file_path)
                        generator.write()
                    except Exception as e:
                        Messages.send_fail_gen(e)
                else:
                    self.generator = None
        elif action == Actions.FLOW_GRAPH_EXEC:
            if not page.process:
                Actions.FLOW_GRAPH_GEN()
                xterm = self.platform.config.xterm_executable
                if self.config.xterm_missing() != xterm:
                    if not os.path.exists(xterm):
                        Dialogs.show_missing_xterm(main, xterm)
                    self.config.xterm_missing(xterm)
                if page.saved and page.file_path:
                    Executor.ExecFlowGraphThread(
                        flow_graph_page=page,
                        xterm_executable=xterm,
                        callback=self.update_exec_stop)
        elif action == Actions.FLOW_GRAPH_KILL:
            if page.process:
                try:
                    page.process.terminate()
                except OSError:
                    print("could not terminate process: %d" % page.process.pid)

        elif action == Actions.PAGE_CHANGE:  # pass and run the global actions
            flow_graph_update()
        elif action == Actions.RELOAD_BLOCKS:
            self.platform.build_library()
            main.btwin.repopulate()

            #todo: implement parser error dialog for YAML

            # Force a redraw of the graph, by getting the current state and re-importing it
            main.update_pages()

        elif action == Actions.FIND_BLOCKS:
            flow_graph.unselect()
            main.update_panel_visibility(main.BLOCKS, True)
            main.btwin.search_entry.show()
            main.btwin.search_entry.grab_focus()
        elif action == Actions.OPEN_HIER:
            for b in flow_graph.selected_blocks():
                grc_source = b.extra_data.get('grc_source', '')
                if grc_source:
                    main.new_page(grc_source, show=True)
        elif action == Actions.BUSSIFY_SOURCES:
            for b in flow_graph.selected_blocks():
                b.bussify('source')
            flow_graph._old_selected_port = None
            flow_graph._new_selected_port = None
            Actions.ELEMENT_CREATE()

        elif action == Actions.BUSSIFY_SINKS:
            for b in flow_graph.selected_blocks():
                b.bussify('sink')
            flow_graph._old_selected_port = None
            flow_graph._new_selected_port = None
            Actions.ELEMENT_CREATE()

        elif action == Actions.TOOLS_RUN_FDESIGN:
            subprocess.Popen('gr_filter_design',
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

        else:
            log.warning('!!! Action "%s" not handled !!!' % action)
        ##################################################
        # Global Actions for all States
        ##################################################
        page = main.current_page  # page and flow graph might have changed
        flow_graph = page.flow_graph if page else None

        selected_blocks = list(flow_graph.selected_blocks())
        selected_block = selected_blocks[0] if selected_blocks else None

        #update general buttons
        Actions.ERRORS_WINDOW_DISPLAY.set_enabled(not flow_graph.is_valid())
        Actions.ELEMENT_DELETE.set_enabled(bool(flow_graph.selected_elements))
        Actions.BLOCK_PARAM_MODIFY.set_enabled(bool(selected_block))
        Actions.BLOCK_ROTATE_CCW.set_enabled(bool(selected_blocks))
        Actions.BLOCK_ROTATE_CW.set_enabled(bool(selected_blocks))
        #update alignment options
        for act in Actions.BLOCK_ALIGNMENTS:
            if act:
                act.set_enabled(len(selected_blocks) > 1)
        #update cut/copy/paste
        Actions.BLOCK_CUT.set_enabled(bool(selected_blocks))
        Actions.BLOCK_COPY.set_enabled(bool(selected_blocks))
        Actions.BLOCK_PASTE.set_enabled(bool(self.clipboard))
        #update enable/disable/bypass
        can_enable = any(block.state != 'enabled' for block in selected_blocks)
        can_disable = any(block.state != 'disabled'
                          for block in selected_blocks)
        can_bypass_all = (all(block.can_bypass() for block in selected_blocks)
                          and any(not block.get_bypassed()
                                  for block in selected_blocks))
        Actions.BLOCK_ENABLE.set_enabled(can_enable)
        Actions.BLOCK_DISABLE.set_enabled(can_disable)
        Actions.BLOCK_BYPASS.set_enabled(can_bypass_all)

        Actions.BLOCK_CREATE_HIER.set_enabled(bool(selected_blocks))
        Actions.OPEN_HIER.set_enabled(bool(selected_blocks))
        Actions.BUSSIFY_SOURCES.set_enabled(bool(selected_blocks))
        Actions.BUSSIFY_SINKS.set_enabled(bool(selected_blocks))
        Actions.RELOAD_BLOCKS.enable()
        Actions.FIND_BLOCKS.enable()

        self.update_exec_stop()

        Actions.FLOW_GRAPH_SAVE.set_enabled(not page.saved)
        main.update()

        flow_graph.update_selected()
        page.drawing_area.queue_draw()

        return True  # Action was handled
示例#46
0
文件: gui.py 项目: alghafli/tilfaz
 def on_main_win_destroy(*args):
     Gtk.main_quit()
示例#47
0
 def onDestroyWindow(self, sender):
     Gtk.main_quit()
示例#48
0
 def on_destroy(self, widget):
     subprocess.check_output(
         ['/usr/bin/systemctl', 'restart', METRICS_SYSTEMD_SERVICE])
     Gtk.main_quit()
示例#49
0
#!/usr/bin/env python3

from gi.repository import Gtk

def cell_toggled(cellrenderertoggle, path):
    liststore[path][1] = not liststore[path][1]

window = Gtk.Window()
window.connect("destroy", lambda q: Gtk.main_quit())

liststore = Gtk.ListStore(str, bool)
liststore.append(["Ethernet", True])
liststore.append(["Wireless", True])
liststore.append(["Bluetooth", False])
liststore.append(["3g Mobile", True])

treeview = Gtk.TreeView(model=liststore)
treeviewcolumn = Gtk.TreeViewColumn("Connection Type")
treeview.append_column(treeviewcolumn)
cellrenderertext = Gtk.CellRendererText()
treeviewcolumn.pack_start(cellrenderertext, False)
treeviewcolumn.add_attribute(cellrenderertext, "text", 0)
treeviewcolumn = Gtk.TreeViewColumn("Status")
treeview.append_column(treeviewcolumn)
cellrenderertoggle = Gtk.CellRendererToggle()
cellrenderertoggle.connect("toggled", cell_toggled)
treeviewcolumn.pack_start(cellrenderertoggle, False)
treeviewcolumn.add_attribute(cellrenderertoggle, "active", 1)
window.add(treeview)

window.show_all()
示例#50
0
 def onDeleteWindow(self, sender, data=None):
     Gtk.main_quit()
示例#51
0
文件: sliders.py 项目: yazici/mypaint
 def __init__(self):
     CombinedAdjusterPage.__init__(self)
     grid = Gtk.Grid()
     grid.set_size_request(150, -1)
     grid.set_row_spacing(6)
     grid.set_column_spacing(0)
     grid.set_border_width(6)
     self._sliders = []   #: List of slider widgets.
     grid.set_valign(0.5)
     grid.set_halign(0.5)
     grid.set_hexpand(True)
     grid.set_vexpand(False)
     row_defs = [
         (
             C_("color sliders panel: red/green/blue: slider label", "R"),
             RGBRedSlider,
             0,
         ), (
             C_("color sliders panel: red/green/blue: slider label", "G"),
             RGBGreenSlider,
             0,
         ), (
             C_("color sliders panel: red/green/blue: slider label", "B"),
             RGBBlueSlider,
             0,
         ), (
             C_("color sliders panel: hue/chroma/luma: slider label", "H"),
             HCYHueSlider,
             12,
         ), (
             C_("color sliders panel: hue/chroma/luma: slider label", "C"),
             HCYChromaSlider,
             0,
         ), (
             C_("color sliders panel: hue/chroma/luma: slider label", "Y"),
             HCYLumaSlider,
             0,
         ),
     ]
     row = 0
     for row_def in row_defs:
         label_text, adj_class, margin_top = row_def
         label = Gtk.Label()
         label.set_text(label_text)
         label.set_tooltip_text(adj_class.STATIC_TOOLTIP_TEXT)
         label.set_vexpand(True)
         label.set_hexpand(False)
         label.set_valign(0.0)
         label.set_margin_top(margin_top)
         label.set_margin_left(3)
         label.set_margin_right(3)
         adj = adj_class()
         adj.set_size_request(100, 22)
         adj.set_vexpand(False)
         adj.set_hexpand(True)
         adj.set_margin_top(margin_top)
         adj.set_margin_left(3)
         adj.set_margin_right(3)
         adj.set_valign(0.0)
         self._sliders.append(adj)
         grid.attach(label, 0, row, 1, 1)
         grid.attach(adj, 1, row, 1, 1)
         row += 1
     align = Gtk.Alignment(
         xalign=0.5, yalign=0.5,
         xscale=1.0, yscale=0.0,
     )
     align.add(grid)
     self._page_widget = align  #: Page's layout widget
示例#52
0
 def onQuitApp(self, sender, data=None):
     Gtk.main_quit()
示例#53
0
    def __init__(self, **kwargs):
        Palette.__init__(self, **kwargs)

        self.button_box = Gtk.HBox()
        self.button_box.show()
        self.set_content(self.button_box)
示例#54
0
def _gtk_main_loop():
    from gi.repository import Gtk
    while True:
        while Gtk.events_pending():
            Gtk.main_iteration()
        gevent.sleep(0.1)
示例#55
0
 def ik_exit(self, evt):
     Gtk.main_quit()
     sys.exit(1)
示例#56
0
文件: sliders.py 项目: yazici/mypaint
    def get_bar_amount_for_color(self, col):
        col = HCYColor(color=col)
        return col.y

    def get_background_validity(self):
        col = HCYColor(color=self.get_managed_color())
        return int(col.h * 1000), int(col.c * 1000)


if __name__ == '__main__':
    import os
    import sys
    from adjbases import ColorManager
    mgr = ColorManager(prefs={}, datapath=".")
    cs_adj = ComponentSlidersAdjusterPage()
    cs_adj.set_color_manager(mgr)
    cs_adj.set_managed_color(RGBColor(0.3, 0.6, 0.7))
    if len(sys.argv) > 1:
        icon_name = cs_adj.get_page_icon_name()
        for dir_name in sys.argv[1:]:
            cs_adj.save_icon_tree(dir_name, icon_name)
    else:
        # Interactive test
        window = Gtk.Window()
        window.add(cs_adj.get_page_widget())
        window.set_title(os.path.basename(sys.argv[0]))
        window.connect("destroy", lambda *a: Gtk.main_quit())
        window.show_all()
        Gtk.main()
def load_symbolic_icon(icon_name, size, fg=None, success=None,
                       warning=None, error=None, outline=None):
    """More Pythonic wrapper for gtk_icon_info_load_symbolic() etc.

    :param str icon_name: Name of the symbolic icon to render
    :param int size: Pixel size to render at
    :param tuple fg: foreground color (rgba tuple, values in [0..1])
    :param tuple success: success color (rgba tuple, values in [0..1])
    :param tuple warning: warning color (rgba tuple, values in [0..1])
    :param tuple error: error color (rgba tuple, values in [0..1])
    :param tuple outline: outline color (rgba tuple, values in [0..1])
    :returns: The rendered symbolic icon
    :rtype: GdkPixbuf.Pixbuf

    If the outline color is specified, a single-pixel outline is faked
    for the icon. Outlined renderings require a size 2 pixels larger
    than non-outlined if the central icon is to be of the same size.

    The returned value should be cached somewhere.

    """
    theme = Gtk.IconTheme.get_default()
    if outline is not None:
        size -= 2
    info = theme.lookup_icon(icon_name, size, Gtk.IconLookupFlags(0))

    def rgba_or_none(tup):
        return (tup is not None) and Gdk.RGBA(*tup) or None

    icon_pixbuf, was_symbolic = info.load_symbolic(
        fg=rgba_or_none(fg),
        success_color=rgba_or_none(success),
        warning_color=rgba_or_none(warning),
        error_color=rgba_or_none(error),
    )
    assert was_symbolic
    if outline is None:
        return icon_pixbuf

    result = GdkPixbuf.Pixbuf.new(
        GdkPixbuf.Colorspace.RGB, True, 8,
        size+2, size+2,
    )
    result.fill(0x00000000)
    outline_rgba = list(outline)
    outline_rgba[3] /= 3.0
    outline_rgba = Gdk.RGBA(*outline_rgba)
    outline_stamp, was_symbolic = info.load_symbolic(
        fg=outline_rgba,
        success_color=outline_rgba,
        warning_color=outline_rgba,
        error_color=outline_rgba,
    )
    w = outline_stamp.get_width()
    h = outline_stamp.get_height()
    assert was_symbolic
    offsets = [
        (-1, -1), (0, -1), (1, -1),
        (-1, 0),          (1, 0),   # noqa: E241 (it's clearer)
        (-1, 1), (0, 1), (1, 1),
    ]
    for dx, dy in offsets:
        outline_stamp.composite(
            result,
            dx+1, dy+1, w, h,
            dx+1, dy+1, 1, 1,
            GdkPixbuf.InterpType.NEAREST, 255,
        )
    icon_pixbuf.composite(
        result,
        1, 1, w, h,
        1, 1, 1, 1,
        GdkPixbuf.InterpType.NEAREST, 255,
    )
    return result
示例#58
0
 def main(self):
     Gtk.main()
示例#59
0
 def update(self, count):
     from gi.repository import Gtk
     self.pm.step()
     while Gtk.events_pending():
         Gtk.main_iteration()
示例#60
0
 def make_menu(self):
     self.menu = Gtk.Menu()
     self.make_menu_item("Config")
     self.make_menu_item("Exit")
     self.menu.show()
     self.ik.set_menu(self.menu)