示例#1
0
    def __init__(self, bus):
        self.bus = bus
        self.action_group = Gio.SimpleActionGroup()
        self.menu = Gio.Menu()
        self.sub_menu = Gio.Menu()

        self.current_switch_icon = 'phone-smartphone-symbolic'

        self.settings = Gio.Settings.new(self.BASE_KEY)
示例#2
0
  def __init__(self):
    super().__init__()
    self.set_size_request(300, -1)

    actions = Gio.SimpleActionGroup()
    action = Gio.SimpleAction.new('section', GLib.VariantType('s'))
    action.connect('activate', self._section_activate_cb)
    actions.add_action(action)
    self.insert_action_group('toc_popover', actions)
    def _build_actions(self):
        # nterm action group
        self._nterm_action_group = Gio.SimpleActionGroup()
        self._ui_terminal.insert_action_group("nterm", self._nterm_action_group)

        copy_action = Gio.SimpleAction(name="copy")
        copy_action.connect("activate", self._on_nterm_copy_action_activated)
        self._nterm_action_group.add_action(copy_action)

        paste_action = Gio.SimpleAction(name="paste")
        paste_action.connect("activate", self._on_nterm_paste_action_activated)
        self._nterm_action_group.add_action(paste_action)

        # ntermwin action group
        self._ntermwin_action_group = Gio.SimpleActionGroup()

        terminal_visible_action = Gio.SimpleAction(name="terminal-visible")
        terminal_visible_action.connect("activate", self._on_ntermwin_terminal_visible_action_activated)
        self._ntermwin_action_group.add_action(terminal_visible_action)
示例#4
0
    def _create_actions(self):
        self.action_group = Gio.SimpleActionGroup()
        self.insert_action_group("markers", self.action_group)
        self.app.shortcuts.register_group("markers", _("Markers"), position=70)

        self.add_marker_action = Gio.SimpleAction.new("marker-add", GLib.VariantType("mx"))
        self.add_marker_action.connect("activate", self._add_marker_cb)
        self.action_group.add_action(self.add_marker_action)
        self.app.shortcuts.add("markers.marker-add(@mx nothing)", ["<Primary><Shift>m"],
                               self.add_marker_action, _("Add a marker"))
示例#5
0
def create_pitivi(**settings):
    app = Pitivi()
    app._setup()

    app.gui = mock.Mock()
    app.gui.editor.viewer.action_group = Gio.SimpleActionGroup()

    app.settings = __create_settings(**settings)
    app.gui.editor.editor_state = EditorState(app.project_manager)

    return app
    def __init__(self, bus):
        self.get_config()

        self.bus = bus
        self.action_group = Gio.SimpleActionGroup()
        self.menu = Gio.Menu()
        self.sub_menu = Gio.Menu()

        self.current_condition_icon = self.CLEAR
        self.current_condition_text = 'Clear'
        self.current_temperature = 75
        self.error = 'No weather data yet'
示例#7
0
def create_pitivi_mock(**settings):
    app = mock.MagicMock()
    app.write_action = mock.MagicMock(spec=Pitivi.write_action)
    app.settings = __create_settings(**settings)
    app.gui.editor.editor_state = EditorState(app.project_manager)
    app.proxy_manager = ProxyManager(app)

    app.gui.editor.viewer.action_group = Gio.SimpleActionGroup()

    # TODO: Get rid of Zoomable.app.
    Zoomable.app = app

    return app
示例#8
0
    def __init__(self, search_entry):
        super().__init__()
        self.set_relative_to(search_entry)
        self.set_size_request(360, -1)
        self.set_modal(False)

        self._results_menu = Gio.Menu()
        self.bind_model(self._results_menu, None)

        actions = Gio.SimpleActionGroup()
        action = Gio.SimpleAction.new('suggestion', GLib.VariantType('s'))
        action.connect('activate', self._suggestion_activate_cb)
        actions.add_action(action)
        self.insert_action_group('suggestions_popover', actions)
示例#9
0
    def do_load(self, workbench):
        self.workbench = workbench

        group = Gio.SimpleActionGroup()

        self.install_action = Gio.SimpleAction(name='install-docutils', enabled=True)
        self.install_action.connect('activate', lambda *_: self.install_docutils())
        group.insert(self.install_action)

        self.install_action = Gio.SimpleAction(name='install-sphinx', enabled=True)
        self.install_action.connect('activate', lambda *_: self.install_sphinx())
        group.insert(self.install_action)

        self.workbench.insert_action_group('html-preview', group)
示例#10
0
文件: sendEmail.py 项目: jaesivsm/gtg
    def onTaskOpened(self, plugin_api):
        """
        Adds the button when a task is opened.
        """
        group = Gio.SimpleActionGroup()
        send_action = Gio.SimpleAction.new("send_as_email", None)
        send_action.connect("activate", self._on_send_activate, plugin_api)
        group.add_action(send_action)
        plugin_api.get_ui().window.insert_action_group(self.ACTION_GROUP_PREF,
                                                       group)

        self.menu_item = Gio.MenuItem.new(
            _("Send via email"),
            ".".join([self.ACTION_GROUP_PREF, "send_as_email"]))
        plugin_api.add_menu_item(self.menu_item)
示例#11
0
    def __set_keyboard_shortcuts(self):
        group = Gio.SimpleActionGroup()
        self.toplevel_widget.insert_action_group("editor", group)
        self.headerbar.insert_action_group("editor", group)

        self.save_action = Gio.SimpleAction.new("save", None)
        self.save_action.connect("activate", self.__save_project_cb)
        group.add_action(self.save_action)
        self.app.shortcuts.add("editor.save", ["<Primary>s"],
                               _("Save the current project"),
                               group="win")
        self.save_button.set_action_name("editor.save")

        self.save_as_action = Gio.SimpleAction.new("save-as", None)
        self.save_as_action.connect("activate", self.__save_project_as_cb)
        group.add_action(self.save_as_action)
        self.app.shortcuts.add("editor.save-as", ["<Primary><Shift>s"],
                               _("Save the current project as"),
                               group="win")

        self.revert_to_saved_action = Gio.SimpleAction.new(
            "revert-to-saved", None)
        self.revert_to_saved_action.connect("activate",
                                            self.__revert_to_saved_cb)
        group.add_action(self.revert_to_saved_action)

        self.export_project_action = Gio.SimpleAction.new(
            "export-project", None)
        self.export_project_action.connect("activate",
                                           self.__export_project_cb)
        group.add_action(self.export_project_action)

        self.save_frame_action = Gio.SimpleAction.new("save-frame", None)
        self.save_frame_action.connect("activate", self.__save_frame_cb)
        group.add_action(self.save_frame_action)

        self.project_settings_action = Gio.SimpleAction.new(
            "project-settings", None)
        self.project_settings_action.connect("activate",
                                             self.__project_settings_cb)
        group.add_action(self.project_settings_action)

        self.import_asset_action = Gio.SimpleAction.new("import-asset", None)
        self.import_asset_action.connect("activate", self.__import_asset_cb)
        group.add_action(self.import_asset_action)
        self.app.shortcuts.add("editor.import-asset", ["<Primary>i"],
                               _("Add media files to your project"),
                               group="win")
示例#12
0
    def do_workspace_added(self, workspace):
        group = Gio.SimpleActionGroup()

        self.install_action = Gio.SimpleAction(name='install-docutils',
                                               enabled=True)
        self.install_action.connect('activate',
                                    lambda *_: self.install_docutils())
        group.insert(self.install_action)

        self.install_action = Gio.SimpleAction(name='install-sphinx',
                                               enabled=True)
        self.install_action.connect('activate',
                                    lambda *_: self.install_sphinx())
        group.insert(self.install_action)

        workspace.insert_action_group('html-preview', group)
示例#13
0
    def __set_keyboard_shortcuts(self):
        group = Gio.SimpleActionGroup()
        self.toplevel_widget.insert_action_group("greeter", group)
        self.headerbar.insert_action_group("greeter", group)

        self.new_project_action = Gio.SimpleAction.new("new-project", None)
        self.new_project_action.connect("activate", self.__new_project_cb)
        group.add_action(self.new_project_action)
        self.app.shortcuts.add("greeter.new-project", ["<Primary>n"],
                               _("Create a new project"), group="win")

        self.open_project_action = Gio.SimpleAction.new("open-project", None)
        self.open_project_action.connect("activate", self.__open_project_cb)
        group.add_action(self.open_project_action)
        self.app.shortcuts.add("greeter.open-project", ["<Primary>o"],
                               _("Open a project"), group="win")
示例#14
0
    def create_actions(self):
        def add_action(name, handler, parameter_type=None, state=None):
            action = Gio.SimpleAction(name=name,
                                      parameter_type=parameter_type,
                                      state=state)
            action.connect("activate", handler)
            self.application.add_action(action)
            return action

        # Missing override for Gtk.Application.add_action_entries():
        # https://gitlab.gnome.org/GNOME/pygobject/-/issues/426
        # main actions
        for name, handler in self.get_main_actions():
            add_action(name, handler)

        # actions with parameters
        for name, handler in self.get_arrow_actions():
            add_action(name, handler, parameter_type=GLib.VariantType("i"))

        # stateful actions
        self.explorer_action, self.fullscreen_action = \
            [add_action(*x, state=GLib.Variant("b", False)) for x in self.get_toggle_actions()]

        # actions which are only available if we're in 4D mode
        self.fourd_actiongroup = Gio.SimpleActionGroup()
        for name, handler in self.get_fourd_actions():
            action = add_action(name, handler)
            self.fourd_actiongroup.add_action(action)

        # keyboard accelerators for actions
        for key in [x[0] for x in self.get_arrow_actions()]:
            self.application.set_accels_for_action(f"app.{key}(0)",
                                                   [f"<Release>{key}"])
            self.application.set_accels_for_action(
                f"app.{key}({int(Gdk.ModifierType.SHIFT_MASK)})",
                [f"<Release><Shift>{key}"])
            self.application.set_accels_for_action(
                f"app.{key}({int(Gdk.ModifierType.CONTROL_MASK)})",
                [f"<Release><Control>{key}"])
            self.application.set_accels_for_action(
                f"app.{key}"
                f"({int(Gdk.ModifierType.SHIFT_MASK | Gdk.ModifierType.CONTROL_MASK)})",
                [f"<Release><Shift><Control>{key}"])

        self.model.seq.register_callbacks(
            self.application.lookup_action("EditRedoAction").set_enabled,
            self.application.lookup_action("EditUndoAction").set_enabled)
示例#15
0
    def __init__(self):
        assert self.group_name
        assert not hasattr(self, '_instance')

        self.model = None
        self._actions = {}
        super(BaseActions, self).__init__()

        self.group = Gio.SimpleActionGroup()
        # register actions that were decorated with @action('ActionName')
        for key in dir(self):
            callback = getattr(self, key)
            if hasattr(callback, '__action_spec__'):
                name, = callback.__action_spec__
                self.add_action(name, callback)

        self._register_action_group()
    def __init__(self, shell, group_name):
        '''
        constructor
        :param shell: `RBShell`
        :param group_name: `str` unique name for the object to create
        '''
        self.group_name = group_name
        self.shell = shell

        self._actions = {}

        if is_rb3(self.shell):
            self.actiongroup = Gio.SimpleActionGroup()
        else:
            self.actiongroup = Gtk.ActionGroup(group_name)
            uim = self.shell.props.ui_manager
            uim.insert_action_group(self.actiongroup)
示例#17
0
    def create_action_group(self):
        self.action_group = Gio.SimpleActionGroup()
        self.actions = {}

        actions = (
            ('change-directory', self.change_to_current_directory),
            ('copy-clipboard', self.copy_clipboard),
            ('paste-clipboard', self.paste_clipboard),
            ('paste-current-file', self.paste_current_file),
        )

        for name, callback in actions:
            action = Gio.SimpleAction.new(name, None)
            action.connect('activate', callback)

            self.actions[name] = action
            self.action_group.add_action(action)
    def _create_actions(self):
        group = Gio.SimpleActionGroup()
        self.toplevel_widget.insert_action_group("editor", group)
        self.headerbar.insert_action_group("editor", group)

        # pylint: disable=attribute-defined-outside-init
        self.save_action = Gio.SimpleAction.new("save", None)
        self.save_action.connect("activate", self.__save_project_cb)
        group.add_action(self.save_action)
        self.app.shortcuts.add("editor.save", ["<Primary>s"], self.save_action,
                               _("Save the current project"), group="win")
        self.save_button.set_action_name("editor.save")

        self.save_as_action = Gio.SimpleAction.new("save-as", None)
        self.save_as_action.connect("activate", self.__save_project_as_cb)
        group.add_action(self.save_as_action)
        self.app.shortcuts.add("editor.save-as", ["<Primary><Shift>s"],
                               self.save_as_action,
                               _("Save the current project as"), group="win")

        self.revert_to_saved_action = Gio.SimpleAction.new("revert-to-saved", None)
        self.revert_to_saved_action.connect("activate", self.__revert_to_saved_cb)
        group.add_action(self.revert_to_saved_action)

        self.export_project_action = Gio.SimpleAction.new("export-project", None)
        self.export_project_action.connect("activate", self.__export_project_cb)
        group.add_action(self.export_project_action)

        self.save_frame_action = Gio.SimpleAction.new("save-frame", None)
        self.save_frame_action.connect("activate", self.__save_frame_cb)
        group.add_action(self.save_frame_action)

        self.project_settings_action = Gio.SimpleAction.new("project-settings", None)
        self.project_settings_action.connect("activate", self.__project_settings_cb)
        group.add_action(self.project_settings_action)

        group.add_action(self.intro.intro_action)
        self.app.shortcuts.add("editor.interactive-intro", [], self.intro.intro_action,
                               _("Quick intros to Pitivi"), group="win")

        self.import_asset_action = Gio.SimpleAction.new("import-asset", None)
        self.import_asset_action.connect("activate", self.__import_asset_cb)
        group.add_action(self.import_asset_action)
        self.app.shortcuts.add("editor.import-asset", ["<Primary>i"],
                               self.import_asset_action,
                               _("Add media files to your project"), group="win")
示例#19
0
    def _createActionGroup(self):
        '''
            Create the action group for the
            files view.

            :return: The files view action group
            :rtype: Gio.SimpleActionGroup
        '''
        group = Gio.SimpleActionGroup()
        open_folder = Gio.SimpleAction.new("open_folder")
        open_folder.connect("activate", self.openFolder)
        tag_file = Gio.SimpleAction.new("tag_file")
        tag_file.connect("activate", self.openTagger)
        remove_file = Gio.SimpleAction.new("remove_file")
        remove_file.connect("activate", self.removeFile)
        group.add_action(open_folder)
        group.add_action(tag_file)
        group.add_action(remove_file)
        return group
示例#20
0
    def __create_menu_model(self):
        action_group = Gio.SimpleActionGroup()
        menu_model = Gio.Menu()

        self.__move_layer_top_action = Gio.SimpleAction.new(
            "move-layer-to-top", None)
        action = self.__move_layer_top_action
        action.connect("activate", self.__move_layer_cb, -2)
        action_group.add_action(action)
        menu_model.append(_("Move layer to top"),
                          "layer.%s" % action.get_name().replace(" ", "."))

        self.__move_layer_up_action = Gio.SimpleAction.new(
            "move-layer-up", None)
        action = self.__move_layer_up_action
        action.connect("activate", self.__move_layer_cb, -1)
        action_group.add_action(action)
        menu_model.append(_("Move layer up"),
                          "layer.%s" % action.get_name().replace(" ", "."))

        self.__move_layer_down_action = Gio.SimpleAction.new(
            "move-layer-down", None)
        action = self.__move_layer_down_action
        action.connect("activate", self.__move_layer_cb, 1)
        action_group.add_action(action)
        menu_model.append(_("Move layer down"),
                          "layer.%s" % action.get_name().replace(" ", "."))

        self.__move_layer_bottom_action = Gio.SimpleAction.new(
            "move-layer-to-bottom", None)
        action = self.__move_layer_bottom_action
        action.connect("activate", self.__move_layer_cb, 2)
        action_group.add_action(action)
        menu_model.append(_("Move layer to bottom"),
                          "layer.%s" % action.get_name().replace(" ", "."))

        self.delete_layer_action = Gio.SimpleAction.new("delete-layer", None)
        action = self.delete_layer_action
        action.connect("activate", self.__delete_layer_cb)
        action_group.add_action(action)
        menu_model.append(_("Delete layer"), "layer.%s" % action.get_name())

        return menu_model, action_group
示例#21
0
    def _create_application_actions(self):
        """Create the actions that activate the applications.

        This actions are prefixed by 'launch', followed by the app name (for
        instance launch.pos)
        """
        def callback(action, parameter, name):
            self.switch_application(name)

        group = Gio.SimpleActionGroup()
        self.toplevel.insert_action_group('launch', group)
        for app in self.get_available_applications():
            action = Gio.SimpleAction.new(app.name, None)
            action.connect('activate', callback, app.name)
            group.add_action(action)

        # Also add the launcher app
        action = Gio.SimpleAction.new('launcher', None)
        action.connect('activate', callback, 'launcher')
        group.add_action(action)
示例#22
0
    def setup_menus(self, vbox):
        self._action_group = Gio.SimpleActionGroup()

        self._about_action = Gio.SimpleAction.new('about', None)
        self._about_action.connect('activate', self.on_about)

        self._help_action = Gio.SimpleAction.new('help', None)
        self._help_action.connect('activate', self.on_help)

        self._quit_action = Gio.SimpleAction.new('quit', None)
        self._quit_action.connect('activate', self.on_quit)

        self._action_group.add_action(self._about_action)
        self._action_group.add_action(self._help_action)
        self._action_group.add_action(self._quit_action)

        self.insert_action_group('keygen', self._action_group)

        builder = Gtk.Builder()
        builder.add_from_string(MENU_XML)
        menubar = builder.get_object('menubar')
        vbox.pack_start(Gtk.MenuBar.new_from_model(menubar), False, True, 0)
示例#23
0
    def __init__(self, app, builder):
        super().__init__()
        self.container = builder.get_object('toc_container')
        self.scrolled_window = builder.get_object('toc_scrolledwindow')
        self.view = builder.get_object('toc_treeview')

        self.actions = Gio.SimpleActionGroup()
        self.actions.add_action_entries([
            ('add-row', self._on_action_add_row),
            ('edit-row', self._on_action_edit_row),
            ('create-row', self._on_action_create_row, 's'),
            ('move-row', self._on_action_move_row, 's'),
            ('delete-row', self._on_action_remove_row),
        ])
        self.container.get_toplevel().insert_action_group('toc', self.actions)

        self.sidebar = TOCSidebar(builder, self.actions)

        title_cell = ActivatableCellRendererText()
        column = Gtk.TreeViewColumn('Title', title_cell, text=0)
        column.set_property('expand', True)
        self.view.append_column(column)

        page_cell = ActivatableCellRendererText()
        column = Gtk.TreeViewColumn('Page', page_cell, text=1)
        self.view.append_column(column)

        self.view.connect('row-activated', self._on_row_activated)
        self.view.connect('button-release-event',
                          self._on_button_release_event)
        self.view.connect('popup-menu', self._on_popup_menu)
        self.view.get_selection().connect('changed',
                                          self._on_selection_changed)

        self.edit_form = EditForm(builder)
        self.edit_form.connect('submit', self._on_edit_form_submit)

        self.context_menu = TOCContextMenu()
        self.context_menu.attach_to_widget(self.view)
示例#24
0
    def __init__(self):
        super().__init__()
        executable_path = self._get_executable_path()
        self._config = TrackerConfig()
        csv_dir = os.path.dirname(self._config.get_csv_path())
        self.terminal = Vte.Terminal()
        self.terminal.spawn_sync(
            Vte.PtyFlags.DEFAULT,
            csv_dir,
            [executable_path],
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
            )
        self.terminal.connect("child-exited", self._on_terminal_exit)

        self.hb = Gtk.HeaderBar()
        self.hb.set_title(_("Data Analyzer"))
        self.hb.set_subtitle(_("Learn everything about your data"))
        self.hb.set_show_close_button(True)
        self.set_titlebar(self.hb)

        self.button_menu = Gtk.MenuButton()
        self.button_menu.set_tooltip_text("Open menu")
        self.button_menu.set_image(Gtk.Image.new_from_icon_name("application-vnd.oasis.opendocument.chart", Gtk.IconSize.LARGE_TOOLBAR))
        self.hb.pack_end(self.button_menu)

        popover = Gtk.Popover.new_from_model(self.button_menu, self._build_app_menu())

        self.button_menu.set_popover(popover)

        self.add(self.terminal)

        self.action_group = Gio.SimpleActionGroup()
        self.insert_action_group("analyzer", self.action_group)

        self._set_actions()
        self.show_all()
示例#25
0
    def __init__(self, *args, **kwargs):
        Gtk.Notebook.__init__(self, *args, **kwargs)

        self.action_group = Gio.SimpleActionGroup()

        actions = (
            ("tabmoveleft", self.on_tab_move_left),
            ("tabmoveright", self.on_tab_move_right),
        )
        for (name, callback) in actions:
            action = Gio.SimpleAction.new(name, None)
            action.connect('activate', callback)
            self.action_group.add_action(action)

        self.insert_action_group("popup", self.action_group)

        builder = Gtk.Builder.new_from_string(self.ui, -1)
        self.popup_menu = builder.get_object("tab-menu")

        provider = Gtk.CssProvider()
        provider.load_from_data(self.css)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        # Awful hacks because we can't create GtkBindingArg from Python, or
        # create a BindingSet from Python, or get a set by class from Python.
        bindings = Gtk.BindingSet.find('TabSwitchBindings')
        for i in range(10):
            key = (i + 1) % 10
            Gtk.BindingEntry().add_signal_from_string(
                bindings, 'bind "<Alt>%d" { "tab-switch" (%d) };' % (key, i))
        self.connect('tab-switch', self.do_tab_switch)

        self.connect('button-press-event', self.on_button_press_event)
        self.connect('popup-menu', self.on_popup_menu)
        self.connect('page-added', self.on_page_added)
        self.connect('page-removed', self.on_page_removed)
示例#26
0
    def _create_actions(self):
        self.action_group = Gio.SimpleActionGroup()
        self.insert_action_group("viewer", self.action_group)
        self.app.shortcuts.register_group("viewer", _("Viewer"), position=60)

        self.toggle_guidelines_action = Gio.SimpleAction.new(
            "toggle-composition-guidelines", None)
        self.toggle_guidelines_action.connect("activate",
                                              self.__toggle_guidelines_cb)
        self.action_group.add_action(self.toggle_guidelines_action)
        self.app.shortcuts.add(
            "viewer.toggle-composition-guidelines", ["<Primary><Shift>c"],
            self.toggle_guidelines_action,
            _("Toggle the currently selected composition guidelines"))

        self.toggle_safe_areas_action = Gio.SimpleAction.new(
            "toggle-safe-areas", None)
        self.toggle_safe_areas_action.connect("activate",
                                              self.__toggle_safe_areas_cb)
        self.action_group.add_action(self.toggle_safe_areas_action)
        self.app.shortcuts.add("viewer.toggle-safe-areas", ["apostrophe"],
                               self.toggle_safe_areas_action,
                               _("Toggle safe areas on viewer"))
示例#27
0
    def setup_ui(self, combo, button):
        # pylint: disable=attribute-defined-outside-init
        self.combo = combo
        self.button = button

        combo.set_model(self.ordered)
        combo.set_id_column(0)
        combo.set_entry_text_column(0)
        combo.connect("changed", self._preset_changed_cb)

        entry = combo.get_child()
        alter_style_class("GtkEntry.unsaved", entry, "font-style:italic;")

        action_group = Gio.SimpleActionGroup()
        menu_model = Gio.Menu()

        action = Gio.SimpleAction.new("new", None)
        action.connect("activate", self._add_preset_cb)
        action_group.add_action(action)
        menu_model.append(_("New"), "preset.%s" % action.get_name())
        self.action_new = action

        action = Gio.SimpleAction.new("remove", None)
        action.connect("activate", self._remove_preset_cb)
        action_group.add_action(action)
        menu_model.append(_("Remove"), "preset.%s" % action.get_name())
        self.action_remove = action

        action = Gio.SimpleAction.new("save", None)
        action.connect("activate", self._save_preset_cb)
        action_group.add_action(action)
        menu_model.append(_("Save"), "preset.%s" % action.get_name())
        self.action_save = action

        menu = Gtk.Menu.new_from_model(menu_model)
        menu.insert_action_group("preset", action_group)
        button.set_popup(menu)
示例#28
0
    def __init__(self, event_manager):
        super().__init__(event_manager)
        self._event_handlers = []
        self.gui_is_active = False
        self.gui = Gtk.Builder()
        self._mainloop_is_running = False
        self.mainloop = get_mainloop(use_gtk=True)
        gtk_build_file = get_ui_file_location(GTKBUILD_FILE)
        if gtk_build_file is None:
            raise InitializationError(
                "Failed to load GTK layout specification file: {}".format(
                    gtk_build_file))
        self.gui.add_from_file(gtk_build_file)
        if pycam.Utils.get_platform() == pycam.Utils.OSPlatform.WINDOWS:
            gtkrc_file = get_ui_file_location(GTKRC_FILE_WINDOWS)
            if gtkrc_file:
                Gtk.rc_add_default_file(gtkrc_file)
                Gtk.rc_reparse_all_for_settings(Gtk.settings_get_default(),
                                                True)
        action_group = Gio.SimpleActionGroup()
        self.settings.set("gtk_action_group_prefix", "pycam")
        self.settings.set("gtk_action_group", action_group)
        self.window = self.gui.get_object("ProjectWindow")
        self.window.insert_action_group(
            self.settings.get("gtk_action_group_prefix"),
            self.settings.get("gtk_action_group"))
        self.settings.set("main_window", self.window)
        # show stock items on buttons
        # increase the initial width of the window (due to hidden elements)
        self.window.set_default_size(400, -1)
        # initialize the RecentManager (TODO: check for Windows)
        if False and pycam.Utils.get_platform(
        ) == pycam.Utils.OSPlatform.WINDOWS:
            # The pyinstaller binary for Windows fails mysteriously when trying
            # to display the stock item.
            # Error message: Gtk:ERROR:gtkrecentmanager.c:1942:get_icon_fallback:
            #    assertion failed: (retval != NULL)
            self.recent_manager = None
        else:
            try:
                self.recent_manager = Gtk.recent_manager_get_default()
            except AttributeError:
                # GTK 2.12.1 seems to have problems with "RecentManager" on
                # Windows. Sadly this is the version, that is shipped with the
                # "appunti" GTK packages for Windows (April 2010).
                # see http://www.daa.com.au/pipermail/pygtk/2009-May/017052.html
                self.recent_manager = None
        # file loading
        self.last_dirname = None
        self.last_model_uri = None
        # define callbacks and accelerator keys for the menu actions
        for objname, callback, data, accel_key in (
            ("OpenModel", self.load_model_file, None,
             "<Control>o"), ("Quit", self.destroy, None, "<Control>q"),
            ("GeneralSettings", self.toggle_preferences_window, None,
             "<Control>p"), ("UndoButton", self.restore_undo_state, None,
                             "<Control>z"),
            ("HelpIntroduction", self.show_help, "introduction", "F1"),
            ("HelpSupportedFormats", self.show_help, "supported-formats",
             None), ("HelpModelTransformations", self.show_help,
                     "model-transformations", None),
            ("HelpProcessSettings", self.show_help, "process-settings",
             None), ("HelpBoundsSettings", self.show_help, "bounding-box",
                     None), ("HelpTouchOff", self.show_help, "touch-off",
                             None), ("Help3DView", self.show_help, "3d-view",
                                     None), ("HelpServerMode", self.show_help,
                                             "server-mode", None),
            ("HelpCommandLine", self.show_help, "cli-examples",
             None), ("HelpHotkeys", self.show_help, "keyboard-shortcuts",
                     None), ("ProjectWebsite", self.show_help,
                             "http://pycam.sourceforge.net",
                             None), ("DevelopmentBlog", self.show_help,
                                     "http://fab.senselab.org/pycam", None),
            ("Forum", self.show_help,
             "http://sourceforge.net/projects/pycam/forums",
             None), ("BugTracker", self.show_help,
                     "https://github.com/SebKuzminsky/pycam/issues/",
                     None), ("FeatureRequest", self.show_help,
                             "https://github.com/SebKuzminsky/pycam/issues/",
                             None)):
            item = self.gui.get_object(objname)
            action = "activate"
            if data is None:
                item.connect(action, callback)
            else:
                item.connect(action, callback, data)
            if accel_key:
                key, mod = Gtk.accelerator_parse(accel_key)
                accel_path = "<pycam>/%s" % objname
                item.set_accel_path(accel_path)
                # Gtk.accel_map_change_entry(accel_path, key, mod, True) FIXME
        # LinkButton does not work on Windows: https://bugzilla.gnome.org/show_bug.cgi?id=617874
        if pycam.Utils.get_platform() == pycam.Utils.OSPlatform.WINDOWS:

            def open_url(widget, data=None):
                webbrowser.open(widget.get_uri())

            Gtk.link_button_set_uri_hook(open_url)
        # configure drag-n-drop for config files and models
        self.settings.set("configure-drag-drop-func",
                          self.configure_drag_and_drop)
        self.settings.get("configure-drag-drop-func")(self.window)
        # other events
        self.window.connect("destroy", self.destroy)
        self.window.connect("delete-event", self.destroy)
        # the settings window
        self.gui.get_object("CloseSettingsWindow").connect(
            "clicked", self.toggle_preferences_window, False)
        self.gui.get_object("ResetPreferencesButton").connect(
            "clicked", self.reset_preferences)
        self.preferences_window = self.gui.get_object("GeneralSettingsWindow")
        self.preferences_window.connect("delete-event",
                                        self.toggle_preferences_window, False)
        self.preferences_window.insert_action_group(
            self.settings.get("gtk_action_group_prefix"),
            self.settings.get("gtk_action_group"))
        self._preferences_window_position = None
        self._preferences_window_visible = False
        # "about" window
        self.about_window = self.gui.get_object("AboutWindow")
        self.about_window.set_version(VERSION)
        self.about_window.insert_action_group(
            self.settings.get("gtk_action_group_prefix"),
            self.settings.get("gtk_action_group"))
        self.gui.get_object("About").connect("activate",
                                             self.toggle_about_window, True)
        # we assume, that the last child of the window is the "close" button
        # TODO: fix this ugly hack!
        about_window_children = self.gui.get_object(
            "AboutWindowButtons").get_children()
        if about_window_children:
            # it seems to be possible that there are no children - weird :(
            # see https://github.com/SebKuzminsky/pycam/issues/59
            about_window_children[-1].connect("clicked",
                                              self.toggle_about_window, False)
        self.about_window.connect("delete-event", self.toggle_about_window,
                                  False)
        # menu bar
        uimanager = Gtk.UIManager()
        self.settings.set("gtk-uimanager", uimanager)
        self._accel_group = uimanager.get_accel_group()
        # send a "delete" event on "CTRL-w" for every window
        self._accel_group.connect(
            ord('w'), Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.LOCKED,
            lambda accel_group, window, *args: window.emit(
                "delete-event", Gdk.Event()))
        self._accel_group.connect(ord('q'), Gdk.ModifierType.CONTROL_MASK,
                                  Gtk.AccelFlags.LOCKED,
                                  lambda *args: self.destroy())
        self.settings.add_item("gtk-accel-group", lambda: self._accel_group)
        for obj in self.gui.get_objects():
            if isinstance(obj, Gtk.Window):
                obj.add_accel_group(self._accel_group)
        # preferences tab
        preferences_book = self.gui.get_object("PreferencesNotebook")

        def clear_preferences():
            for child in preferences_book.get_children():
                preferences_book.remove(child)

        def add_preferences_item(item, name):
            preferences_book.append_page(item, Gtk.Label(name))

        self.settings.register_ui_section("preferences", add_preferences_item,
                                          clear_preferences)
        for obj_name, label, priority in (("GeneralSettingsPrefTab", "General",
                                           -50), ("ProgramsPrefTab",
                                                  "Programs", 50)):
            obj = self.gui.get_object(obj_name)
            obj.unparent()
            self.settings.register_ui("preferences", label, obj, priority)
        # general preferences
        general_prefs = self.gui.get_object("GeneralPreferencesBox")

        def clear_general_prefs():
            for item in general_prefs.get_children():
                general_prefs.remove(item)

        def add_general_prefs_item(item, name):
            general_prefs.pack_start(item, expand=False, fill=False, padding=3)

        self.settings.register_ui_section("preferences_general",
                                          add_general_prefs_item,
                                          clear_general_prefs)
        # set defaults
        main_tab = self.gui.get_object("MainTabs")

        def clear_main_tab():
            while main_tab.get_n_pages() > 0:
                main_tab.remove_page(0)

        def add_main_tab_item(item, name):
            main_tab.append_page(item, Gtk.Label(name))

        # TODO: move these to plugins, as well
        self.settings.register_ui_section("main", add_main_tab_item,
                                          clear_main_tab)
        main_window = self.gui.get_object("WindowBox")

        def clear_main_window():
            main_window.foreach(main_window.remove)

        def add_main_window_item(item, name, **extra_args):
            # some widgets may want to override the defaults
            args = {"expand": False, "fill": False, "padding": 3}
            args.update(extra_args)
            main_window.pack_start(item, **args)

        main_tab.unparent()
        self.settings.register_ui_section("main_window", add_main_window_item,
                                          clear_main_window)
        self.settings.register_ui("main_window",
                                  "Tabs",
                                  main_tab,
                                  -20,
                                  args_dict={
                                      "expand": True,
                                      "fill": True
                                  })

        def disable_gui():
            self.menubar.set_sensitive(False)
            main_tab.set_sensitive(False)

        def enable_gui():
            self.menubar.set_sensitive(True)
            main_tab.set_sensitive(True)

        # configure locations of external programs
        for auto_control_name, location_control_name, browse_button, key in (
            ("ExternalProgramInkscapeAuto", "ExternalProgramInkscapeControl",
             "ExternalProgramInkscapeBrowse", "inkscape"),
            ("ExternalProgramPstoeditAuto", "ExternalProgramPstoeditControl",
             "ExternalProgramPstoeditBrowse", "pstoedit")):
            self.gui.get_object(auto_control_name).connect(
                "clicked", self._locate_external_program, key)
            location_control = self.gui.get_object(location_control_name)
            self.settings.add_item("external_program_%s" % key,
                                   location_control.get_text,
                                   location_control.set_text)
            self.gui.get_object(browse_button).connect(
                "clicked", self._browse_external_program_location, key)
        for objname, callback in (
            ("ResetWorkspace", lambda widget: self.reset_workspace()),
            ("LoadWorkspace", lambda widget: self.load_workspace_dialog()),
            ("SaveWorkspace",
             lambda widget: self.save_workspace_dialog(self.last_workspace_uri)
             ), ("SaveAsWorkspace",
                 lambda widget: self.save_workspace_dialog())):
            self.gui.get_object(objname).connect("activate", callback)
        # set the icons (in different sizes) for all windows
        # Gtk.window_set_default_icon_list(*get_icons_pixbuffers()) FIXME
        # load menu data
        gtk_menu_file = get_ui_file_location(GTKMENU_FILE)
        if gtk_menu_file is None:
            raise InitializationError(
                "Failed to load GTK menu specification file: {}".format(
                    gtk_menu_file))
        uimanager.add_ui_from_file(gtk_menu_file)
        # make the actions defined in the GTKBUILD file available in the menu
        actiongroup = Gtk.ActionGroup("menubar")
        for action in [
                aobj for aobj in self.gui.get_objects()
                if isinstance(aobj, Gtk.Action)
        ]:
            actiongroup.add_action(action)
        # the "pos" parameter is optional since 2.12 - we can remove it later
        uimanager.insert_action_group(actiongroup)
        # the "recent files" sub-menu
        if self.recent_manager is not None:
            recent_files_menu = Gtk.RecentChooserMenu(self.recent_manager)
            recent_files_menu.set_name("RecentFilesMenu")
            recent_menu_filter = Gtk.RecentFilter()
            case_converter = pycam.Utils.get_case_insensitive_file_pattern
            for filter_name, patterns in FILTER_MODEL:
                if not isinstance(patterns, (list, set, tuple)):
                    patterns = [patterns]
                # convert it into a mutable list (instead of set/tuple)
                patterns = list(patterns)
                for index in range(len(patterns)):
                    patterns[index] = case_converter(patterns[index])
                for pattern in patterns:
                    recent_menu_filter.add_pattern(pattern)
            recent_files_menu.add_filter(recent_menu_filter)
            recent_files_menu.set_show_numbers(True)
            # non-local files (without "file://") are not supported. yet
            recent_files_menu.set_local_only(False)
            # most recent files to the top
            recent_files_menu.set_sort_type(Gtk.RECENT_SORT_MRU)
            # show only ten files
            recent_files_menu.set_limit(10)
            uimanager.get_widget("/MenuBar/FileMenu/OpenRecentModelMenu"
                                 ).set_submenu(recent_files_menu)
            recent_files_menu.connect("item-activated",
                                      self.load_recent_model_file)
        else:
            self.gui.get_object("OpenRecentModel").set_visible(False)
        # load the menubar and connect functions to its items
        self.menubar = uimanager.get_widget("/MenuBar")
        # dict of all merge-ids
        menu_merges = {}

        def clear_menu(menu_key):
            for merge in menu_merges.get(menu_key, []):
                uimanager.remove_ui(merge)

        def append_menu_item(menu_key, base_path, widget, name):
            merge_id = uimanager.new_merge_id()
            if widget:
                action_group = widget.props.action_group
                if action_group not in uimanager.get_action_groups():
                    uimanager.insert_action_group(action_group, -1)
                widget_name = widget.get_name()
                item_type = Gtk.UIManagerItemType.MENU
            else:
                widget_name = name
                item_type = Gtk.UIManagerItemType.SEPARATOR
            uimanager.add_ui(merge_id, base_path, name, widget_name, item_type,
                             False)
            if menu_key not in menu_merges:
                menu_merges[menu_key] = []
            menu_merges[menu_key].append(merge_id)

        def get_menu_funcs(menu_key, base_path):
            return (lambda widget, name: append_menu_item(
                menu_key, base_path, widget, name),
                    lambda: clear_menu(menu_key))

        for ui_name, base_path in (("view_menu", "/MenuBar/ViewMenu"),
                                   ("file_menu", "/MenuBar/FileMenu"),
                                   ("edit_menu", "/MenuBar/EditMenu"),
                                   ("export_menu",
                                    "/MenuBar/FileMenu/ExportMenu")):
            append_func, clear_func = get_menu_funcs(ui_name, base_path)
            self.settings.register_ui_section(ui_name, append_func, clear_func)
        self.settings.register_ui("file_menu", "Quit",
                                  self.gui.get_object("Quit"), 100)
        self.settings.register_ui("file_menu", "QuitSeparator", None, 95)
        self.settings.register_ui("main_window", "Main", self.menubar, -100)
        self.settings.set("set_last_filename", self.add_to_recent_file_list)
        self._event_handlers.extend((
            ("history-changed", self._update_undo_button),
            ("model-change-after", "visual-item-updated"),
            ("gui-disable", disable_gui),
            ("gui-enable", enable_gui),
            ("notify-file-saved", self.add_to_recent_file_list),
            ("notify-file-opened", self.add_to_recent_file_list),
        ))
        for name, target in self._event_handlers:
            self.settings.register_event(name, target)
        # allow the task settings control to be updated
        self.mainloop.update()
        # register a logging handler for displaying error messages
        pycam.Utils.log.add_gtk_gui(self.window, logging.ERROR)
        self.window.show()
        self.mainloop.update()
示例#29
0
    def _export(self, window, gtk_group):
        actions = [
            ["Preferences", "Plugins"],
            ["RefreshLibrary"],
            ["OnlineHelp", "About", "Quit"],
        ]

        # build the new menu
        menu = Gio.Menu()
        action_names = []
        for group in actions:
            section = Gio.Menu()
            for name in group:
                action = gtk_group.get_action(name)
                assert action
                label = action.get_label()
                section.append(label, "app." + name)
                action_names.append(name)
            menu.append_section(None, section)
        menu.freeze()

        # proxy activate to the old group
        def callback(action, data):
            name = action.get_name()
            gtk_action = gtk_group.get_action(name)
            gtk_action.activate()

        action_group = Gio.SimpleActionGroup()
        for name in action_names:
            action = Gio.SimpleAction.new(name, None)
            action_group.insert(action)
            action.connect("activate", callback)

        # export on the bus
        ag_object_path = "/net/sacredchao/QuodLibet"
        am_object_path = "/net/sacredchao/QuodLibet/menus/appmenu"
        app_id = "net.sacredchao.QuodLibet"

        win = window.get_window()
        if not hasattr(win, "set_utf8_property"):
            # not a GdkX11.X11Window
            print_d("Registering appmenu failed: X11 only")
            return

        # FIXME: this doesn't fail on Windows but takes for ages.
        # Maybe remove some deps to make it fail fast?
        # We don't need dbus anyway there.
        try:
            bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
            self._ag_id = bus.export_action_group(ag_object_path, action_group)
            self._am_id = bus.export_menu_model(am_object_path, menu)
        except GLib.GError as e:
            print_d("Registering appmenu failed: %r" % e)
            return

        self._bus = bus

        win.set_utf8_property("_GTK_UNIQUE_BUS_NAME", bus.get_unique_name())
        win.set_utf8_property("_GTK_APPLICATION_ID", app_id)
        win.set_utf8_property("_GTK_APPLICATION_OBJECT_PATH", ag_object_path)
        win.set_utf8_property("_GTK_APP_MENU_OBJECT_PATH", am_object_path)
示例#30
0
    def __init__(self, app, clip_properties):
        Gtk.Expander.__init__(self)
        self.set_expanded(True)
        self.set_label(_("Effects"))
        Loggable.__init__(self)

        # Global variables related to effects
        self.app = app

        self._project = None
        self._selection = None
        self.selected_effects = []
        self.clips = []
        self._effect_config_ui = None
        self.effects_properties_manager = EffectsPropertiesManager(app)
        self.clip_properties = clip_properties

        # The toolbar that will go between the list of effects and properties
        buttons_box = Gtk.ButtonBox()
        buttons_box.set_halign(Gtk.Align.END)
        buttons_box.set_margin_end(SPACING)
        buttons_box.props.margin_top = SPACING / 2

        remove_effect_button = Gtk.Button()
        remove_icon = Gtk.Image.new_from_icon_name("list-remove-symbolic",
                                                   Gtk.IconSize.BUTTON)
        remove_effect_button.set_image(remove_icon)
        remove_effect_button.set_always_show_image(True)
        remove_effect_button.set_label(_("Remove effect"))
        buttons_box.pack_start(remove_effect_button,
                               expand=False,
                               fill=False,
                               padding=0)

        # We need to specify Gtk.TreeDragSource because otherwise we are hitting
        # bug https://bugzilla.gnome.org/show_bug.cgi?id=730740.
        class EffectsListStore(Gtk.ListStore, Gtk.TreeDragSource):
            """Just a work around!"""

            # pylint: disable=non-parent-init-called
            def __init__(self, *args):
                Gtk.ListStore.__init__(self, *args)
                # Set the source index on the storemodel directly,
                # to avoid issues with the selection_data API.
                # FIXME: Work around
                # https://bugzilla.gnome.org/show_bug.cgi?id=737587
                self.source_index = None

            def do_drag_data_get(self, path, unused_selection_data):
                self.source_index = path.get_indices()[0]

        self.storemodel = EffectsListStore(bool, str, str, str, str, object)
        self.treeview = Gtk.TreeView(model=self.storemodel)
        self.treeview.set_property("has_tooltip", True)
        self.treeview.set_headers_visible(False)
        self.treeview.props.margin_top = SPACING
        self.treeview.props.margin_left = SPACING
        # Without this, the treeview hides the border of its parent.
        # I should file a bug about this.
        self.treeview.props.margin_right = 1

        activated_cell = Gtk.CellRendererToggle()
        activated_cell.props.xalign = 0
        activated_cell.props.xpad = 0
        activated_cell.connect("toggled", self._effectActiveToggleCb)
        self.treeview.insert_column_with_attributes(-1,
                                                    _("Active"),
                                                    activated_cell,
                                                    active=COL_ACTIVATED)

        type_col = Gtk.TreeViewColumn(_("Type"))
        type_col.set_spacing(SPACING)
        type_col.set_sizing(Gtk.TreeViewColumnSizing.AUTOSIZE)
        type_cell = Gtk.CellRendererText()
        type_cell.props.xpad = PADDING
        type_col.pack_start(type_cell, expand=True)
        type_col.add_attribute(type_cell, "text", COL_TYPE)
        self.treeview.append_column(type_col)

        name_col = Gtk.TreeViewColumn(_("Effect name"))
        name_col.set_spacing(SPACING)
        name_cell = Gtk.CellRendererText()
        name_cell.props.xpad = PADDING
        name_cell.set_property("ellipsize", Pango.EllipsizeMode.END)
        name_col.pack_start(name_cell, expand=True)
        name_col.add_attribute(name_cell, "text", COL_NAME_TEXT)
        self.treeview.append_column(name_col)

        # Allow the treeview to accept EFFECT_TARGET_ENTRY when drag&dropping.
        self.treeview.enable_model_drag_dest([EFFECT_TARGET_ENTRY],
                                             Gdk.DragAction.COPY)

        # Enable reordering by drag&drop.
        self.treeview.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK,
                                               [EFFECT_TARGET_ENTRY],
                                               Gdk.DragAction.MOVE)

        self.treeview_selection = self.treeview.get_selection()
        self.treeview_selection.set_mode(Gtk.SelectionMode.SINGLE)

        self._infobar = clip_properties.createInfoBar(
            _("Select a clip on the timeline to configure its associated effects"
              ))
        self._infobar.show_all()

        # Prepare the main container widgets and lay out everything
        self._vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self._vbox.pack_start(self.treeview,
                              expand=False,
                              fill=False,
                              padding=0)
        self._vbox.pack_start(buttons_box, expand=False, fill=False, padding=0)
        separator = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
        separator.set_margin_top(SPACING)
        separator.set_margin_left(SPACING)
        separator.set_margin_right(SPACING)
        self._vbox.pack_start(separator, expand=False, fill=False, padding=0)
        self._vbox.show_all()
        self.add(self._vbox)
        self.hide()

        effects_actions_group = Gio.SimpleActionGroup()
        self.treeview.insert_action_group("clipproperties-effects",
                                          effects_actions_group)
        buttons_box.insert_action_group("clipproperties-effects",
                                        effects_actions_group)
        self.app.shortcuts.register_group("clipproperties-effects",
                                          _("Clip Effects"),
                                          position=60)

        self.remove_effect_action = Gio.SimpleAction.new("remove-effect", None)
        self.remove_effect_action.connect("activate", self._removeEffectCb)
        effects_actions_group.add_action(self.remove_effect_action)
        self.app.shortcuts.add("clipproperties-effects.remove-effect",
                               ["Delete"], _("Remove the selected effect"))
        self.remove_effect_action.set_enabled(False)
        remove_effect_button.set_action_name(
            "clipproperties-effects.remove-effect")

        # Connect all the widget signals
        self.treeview_selection.connect("changed",
                                        self._treeviewSelectionChangedCb)
        self.treeview.connect("drag-motion", self._dragMotionCb)
        self.treeview.connect("drag-leave", self._dragLeaveCb)
        self.treeview.connect("drag-data-received", self._dragDataReceivedCb)
        self.treeview.connect("query-tooltip", self._treeViewQueryTooltipCb)
        self.app.project_manager.connect_after("new-project-loaded",
                                               self._newProjectLoadedCb)
        self.connect('notify::expanded', self._expandedCb)