Python gi.repository.Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION Examples

The following are 29 code examples of gi.repository.Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.Gtk , or try the search function .
Example #1
Source File: break_screen.py    From SafeEyes with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, context, on_skip, on_postpone, style_sheet_path):
        self.context = context
        self.count_labels = []
        self.display = Display()
        self.enable_postpone = False
        self.enable_shortcut = False
        self.is_pretified = False
        self.keycode_shortcut_postpone = 65
        self.keycode_shortcut_skip = 9
        self.on_postpone = on_postpone
        self.on_skip = on_skip
        self.shortcut_disable_time = 2
        self.strict_break = False
        self.windows = []

        # Initialize the theme
        css_provider = Gtk.CssProvider()
        css_provider.load_from_path(style_sheet_path)
        Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 
Example #2
Source File: distractionfree.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def on_fullscreen_changed(self, window):
		self.window.toggle_menubar(True) # always do this first to allow recovery

		screen = Gdk.Screen.get_default()
		if window.isfullscreen:
			self._show_panes = bool(window.get_visible_panes())
			window.toggle_panes(False)
			self.save_bar_state()
			self.set_bar_state_fullscreen()
			self.insert_maxwidth()
			for widget in self._pathbar_widgets():
				widget.hide()
			self._css_provider = self._new_css_provider()
			Gtk.StyleContext.add_provider_for_screen(screen, self._css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
		else:
			Gtk.StyleContext.remove_provider_for_screen(screen, self._css_provider)
			self.remove_maxwidth()
			window.toggle_panes(self._show_panes)
			self.restore_bar_state()
			for widget in self._pathbar_widgets():
				widget.show()
			window.pageview.grab_focus() 
Example #3
Source File: gtk.py    From pywebview with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def configure_transparency(c):
    c.set_visual(c.get_screen().get_rgba_visual())
    c.override_background_color(gtk.StateFlags.ACTIVE, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.BACKDROP, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.DIR_LTR, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.DIR_RTL, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.FOCUSED, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.INCONSISTENT, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.INSENSITIVE, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.PRELIGHT, Gdk.RGBA(0, 0, 0, 0))
    c.override_background_color(gtk.StateFlags.SELECTED, Gdk.RGBA(0, 0, 0, 0))
    transparentWindowStyleProvider = gtk.CssProvider()
    transparentWindowStyleProvider.load_from_data(b"""
        GtkWindow {
            background-color:rgba(0,0,0,0);
            background-image:none;
        }""")
    c.get_style_context().add_provider(transparentWindowStyleProvider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 
Example #4
Source File: touchpad.py    From hazzy with GNU General Public License v2.0 6 votes vote down vote up
def main():
    style_provider = Gtk.CssProvider()

    with open(os.path.join(STYLEDIR, "style.css"), 'rb') as css:
        css_data = css.read()

    style_provider.load_from_data(css_data)

    Gtk.StyleContext.add_provider_for_screen(
        Gdk.Screen.get_default(), style_provider,
        Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
    )

    TouchPad(test=True)

    Gtk.main() 
Example #5
Source File: talk_time.py    From pympress with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, label_time):
        self.label_time = label_time

        style_context = self.label_time.get_style_context()
        self.color_override = Gtk.CssProvider()
        style_context.add_provider(self.color_override, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + 1)

        self.label_color_default = self.load_color_from_css(style_context)
        label_color_ett_reached = self.load_color_from_css(style_context, "ett-reached")
        label_color_ett_info = self.load_color_from_css(style_context, "ett-info")
        label_color_ett_warn = self.load_color_from_css(style_context, "ett-warn")

        self.color_map = [
            ( 300, self.label_color_default),
            (   0, label_color_ett_reached),
            (-150, label_color_ett_info),
            (-300, label_color_ett_warn)
        ] 
Example #6
Source File: preview.py    From oomox with GNU General Public License v3.0 6 votes vote down vote up
def reset_gradients(self):
        css_provider_gradient = self.css_providers.gradient.get("reset")
        if not css_provider_gradient:
            css_provider_gradient = \
                    self.css_providers.gradient["reset"] = \
                    Gtk.CssProvider()
            css_provider_gradient.load_from_data((
                """
                * {
                    background-image: none;
                }
                """
            ).encode('ascii'))
        for widget in [
                self.gtk_preview.button,
                self.gtk_preview.headerbar.button,
                self.gtk_preview.entry,
                self.gtk_preview.headerbar,
        ]:
            Gtk.StyleContext.add_provider(
                widget.get_style_context(),
                css_provider_gradient,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
            ) 
Example #7
Source File: preview.py    From oomox with GNU General Public License v3.0 6 votes vote down vote up
def update_preview_carets(self, colorscheme):
        self.css_providers.caret.load_from_data((
            (Gtk.get_minor_version() >= 20 and """
            * {{
                caret-color: #{primary_caret_color};
                -gtk-secondary-caret-color: #{secondary_caret_color};
                -GtkWidget-cursor-aspect-ratio: {caret_aspect_ratio};
            }}
            """ or """
            * {{
                -GtkWidget-cursor-color: #{primary_caret_color};
                -GtkWidget-secondary-cursor-color: #{secondary_caret_color};
                -GtkWidget-cursor-aspect-ratio: {caret_aspect_ratio};
            }}
            """).format(
                primary_caret_color=colorscheme['CARET1_FG'],
                secondary_caret_color=colorscheme['CARET2_FG'],
                caret_aspect_ratio=colorscheme['CARET_SIZE']
            )
        ).encode('ascii'))
        Gtk.StyleContext.add_provider(
            self.gtk_preview.entry.get_style_context(),
            self.css_providers.caret,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        ) 
Example #8
Source File: windows.py    From syncthing-gtk with GNU General Public License v2.0 6 votes vote down vote up
def override_menu_borders():
	""" Loads custom CSS to create borders around popup menus """
	style_provider = Gtk.CssProvider()
	style_provider.load_from_data(b"""
		.menu {
			border-image: linear-gradient(to top,
										  alpha(@borders, 0.80),
										  alpha(@borders, 0.60) 33%,
										  alpha(@borders, 0.50) 66%,
										  alpha(@borders, 0.15)) 2 2 2 2/ 2px 2px 2px 2px;
		}

		.menubar .menu {
			border-image: linear-gradient(to top,
										  alpha(@borders, 0.80),
										  alpha(@borders, 0.60) 33%,
										  alpha(@borders, 0.50) 66%,
										  transparent 99%) 2 2 2 2/ 2px 2px 2px 2px;
		}
		""")
	Gtk.StyleContext.add_provider_for_screen(
		Gdk.Screen.get_default(), 
		style_provider,     
		Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
	) 
Example #9
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def on_app_startup(self, app):
        # initiate custom css
        # css stylesheet
        stylesheet = os.path.join(cli.install_dir, "ui", "gtk.css")
        # ...encode() is needed because CssProvider expects byte type input
        with open(stylesheet, "r") as f:
            css = f.read().encode()

        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(css)

        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        ) 
Example #10
Source File: application.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_style_css(self, css_file):
		self.logger.debug('loading style from css file: ' + css_file)
		css_file = Gio.File.new_for_path(css_file)
		style_provider = Gtk.CssProvider()
		style_provider.connect('parsing-error', self.signal_css_provider_parsing_error)
		try:
			style_provider.load_from_file(css_file)
		except GLib.Error:  # pylint: disable=catching-non-exception
			self.logger.error('there was an error parsing the css file, it will not be applied as a style provider')
			return None
		Gtk.StyleContext.add_provider_for_screen(
			Gdk.Screen.get_default(),
			style_provider,
			Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
		)
		return style_provider 
Example #11
Source File: application.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def init_style(self):
        """Load the application's CSS file."""

        screen = Gdk.Screen.get_default()
        provider = Gtk.CssProvider()
        add_provider = Gtk.StyleContext.add_provider_for_screen
        css_path = os.path.join(CSS_DIR, 'style.css')

        provider.load_from_path(css_path)
        add_provider(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 
Example #12
Source File: widgets.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
def widget_set_css(widget, name, css):
	text = '#%s {%s}' % (name, css)
	css_provider = Gtk.CssProvider()
	css_provider.load_from_data(text.encode('UTF-8'))
	widget_style = widget.get_style_context()
	widget_style.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
	widget.set_name(name) 
Example #13
Source File: styled_window.py    From Apostrophe with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Set theme css
        css_provider_file = Gio.File.new_for_uri(
            "resource:///org/gnome/gitlab/somas/Apostrophe/media/css/gtk/base.css")
        style_provider = Gtk.CssProvider()
        style_provider.load_from_file(css_provider_file)
        Gtk.StyleContext.add_provider_for_screen(
            self.get_screen(), style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 
Example #14
Source File: gtk_ui.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, gui):
        self.gui = gui

        style_provider = Gtk.CssProvider()
        style_provider.load_from_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'main.css'))
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

        self._set_builder_objects()

        self._set_markers()

        cell_renderer = Gtk.CellRendererText()
        self.device_combobox.pack_start(cell_renderer, True)
        self.device_combobox.add_attribute(cell_renderer, 'text', 1)
        self.device_combobox.set_id_column(0)

        cell_renderer = Gtk.CellRendererText()
        self.profile_combobox.pack_start(cell_renderer, True)
        self.profile_combobox.add_attribute(cell_renderer, 'text', 1)
        self.profile_combobox.set_id_column(0)

        cell_renderer = Gtk.CellRendererText()
        self.emulation_mode_combobox.pack_start(cell_renderer, True)
        self.emulation_mode_combobox.add_attribute(cell_renderer, 'text', 1)
        self.emulation_mode_combobox.set_id_column(0)

        self.set_wheel_range_overlay('never')

        self.builder.connect_signals(self)

        self.window.show_all() 
Example #15
Source File: preview.py    From oomox with GNU General Public License v3.0 5 votes vote down vote up
def override_css_style(self, colorscheme, theme_plugin):
        new_theme_plugin_name = colorscheme["THEME_STYLE"]
        if new_theme_plugin_name == self.theme_plugin_name:
            return
        if self.theme_plugin_name:
            for child in self.get_children():
                self.remove(child)
                child.destroy()
            self.init_widgets()
        self.theme_plugin_name = new_theme_plugin_name
        base_theme_css_provider = self.get_theme_css_provider(theme_plugin)

        def apply_css(widget):
            widget_style_context = widget.get_style_context()
            Gtk.StyleContext.add_provider(
                widget_style_context,
                self.css_providers.reset_style,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
            )
            Gtk.StyleContext.add_provider(
                widget_style_context,
                base_theme_css_provider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
            )
            if isinstance(widget, Gtk.Container):
                widget.forall(apply_css)
        apply_css(self)

        Gtk.StyleContext.add_provider(
            self.gtk_preview.headerbar.get_style_context(),
            self.css_providers.headerbar_border,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

        self.show_all() 
Example #16
Source File: gtk.py    From kickoff-player with GNU General Public License v3.0 5 votes vote down vote up
def add_widget_custom_css(widget, style):
  priority = Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
  provider = Gtk.CssProvider()
  context  = widget.get_style_context()
  filename = relative_path(style)

  if os.path.exists(filename):
    provider.load_from_path(filename)
  else:
    provider.load_from_data(style.encode())

  context.add_provider(provider, priority) 
Example #17
Source File: apply_styles.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def apply_styling_to_screen(css_file, priority="USER"):
    css = Gtk.CssProvider()

    if not os.path.exists(css_file):
        sys.exit(css_file + ' CSS file missing!')

    css.load_from_path(css_file)

    screen = Gdk.Screen.get_default()
    styleContext = Gtk.StyleContext()

    if priority == "FALLBACK":
        gtk_priority = Gtk.STYLE_PROVIDER_PRIORITY_FALLBACK
    elif priority == "THEME":
        gtk_priority = Gtk.STYLE_PROVIDER_PRIORITY_THEME
    elif priority == "SETTINGS":
        gtk_priority = Gtk.STYLE_PROVIDER_PRIORITY_SETTINGS
    elif priority == "APPLICATION":
        gtk_priority = Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
    elif priority == "USER":
        gtk_priority = Gtk.STYLE_PROVIDER_PRIORITY_USER

    styleContext.add_provider_for_screen(screen, css, gtk_priority)


# Apply the styling from a CSS file to a specific widget 
Example #18
Source File: gtk.py    From kickoff-player with GNU General Public License v3.0 5 votes vote down vote up
def add_custom_css(style):
  screen   = Gdk.Screen.get_default()
  priority = Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
  provider = Gtk.CssProvider()
  filename = relative_path(style)

  if os.path.exists(filename):
    provider.load_from_path(filename)
  else:
    provider.load_from_data(style.encode())

  Gtk.StyleContext.add_provider_for_screen(screen, provider, priority) 
Example #19
Source File: statusbar.py    From vimiv with MIT License 5 votes vote down vote up
def _error_false(self):
        """Strip one error and update the statusbar if no more errors remain."""
        # Remove any timers that remove the error message
        if self._timer_id:
            GLib.source_remove(self._timer_id)
            self._timer_id = 0
        # Strip one error
        self._errors = False
        # Reset css from error_message
        css_provider = Gtk.CssProvider()
        css_str = "#OverLay { border-top: solid 0px; }"
        css_provider.load_from_data(css_str.encode())
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 
Example #20
Source File: statusbar.py    From vimiv with MIT License 5 votes vote down vote up
def message(self, message, style="error", timeout=5):
        """Push a message to the statusbar.

        Args:
            message: Message to push.
            style: One of error, warning and info.
            timeout: Time until the message shall be removed by update info.
        """
        if self._app.debug:
            self._app["log"].write_message(style, message)
        self._errors = True
        styles = {"error": "#CC0000", "warning": "#FA9E21", "info": "#6699FF"}
        message = "<b><span foreground='" + styles[style] + "'>" + \
            style.upper() + ": </span></b>" + message
        self._timer_id = GLib.timeout_add(timeout * 1000, self.update_info)
        # Show if is was hidden
        if not settings["display_bar"].get_value():
            settings.override("display_bar", "true")
            self._was_hidden = True
        self._left_label.set_markup(message)
        # CSS to style bar according to message
        css_provider = Gtk.CssProvider()
        css_str = "#OverLay { border-top: solid 2px " + styles[style] + ";}"
        css_provider.load_from_data(css_str.encode())
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 
Example #21
Source File: app.py    From vimiv with MIT License 5 votes vote down vote up
def _create_window_structure(self):
        """Generate the structure of all the widgets and add it to the window.

        There is a large Gtk.Grid() to organize the widgets packed into a
        Gtk.Overlay(). The commandline is added as overlay.
        """
        main_grid = Gtk.Grid()
        main_grid.attach(self["library"].grid, 0, 0, 1, 1)
        main_grid.attach(self["main_window"], 1, 0, 1, 1)
        main_grid.attach(self["manipulate"], 0, 1, 2, 1)
        main_grid.attach(self["statusbar"].separator, 0, 2, 2, 1)

        overlay_grid = Gtk.Grid()
        overlay_grid.attach(self["statusbar"], 0, 0, 1, 1)
        overlay_grid.attach(self["completions"].info, 0, 1, 1, 1)
        overlay_grid.attach(self["commandline"], 0, 2, 1, 1)
        overlay_grid.set_valign(Gtk.Align.END)

        # Make it nice using CSS
        overlay_grid.set_name("OverLay")
        style = Gtk.Window().get_style_context()
        bg = style.get_background_color(Gtk.StateType.NORMAL)
        color_str = "#OverLay { background: " + bg.to_string() + "; }"
        command_provider = Gtk.CssProvider()
        command_css = color_str.encode()
        command_provider.load_from_data(command_css)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), command_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        # Overlay contains grid mainly and adds commandline as floating
        overlay = Gtk.Overlay()
        overlay.add(main_grid)
        overlay.add_overlay(overlay_grid)
        self["window"].add(overlay) 
Example #22
Source File: themes.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def scroll_changed(self, obj):
        ''' Scrollbar changed '''
        value = obj.get_active()
        config.set('interface.fixed-scrollbar', str(value))
        self.gtksettings.set_property('gtk-primary-button-warps-slider',
                                      not value)
        if hasattr(MyPrefs, 'provider'):
            Gtk.StyleContext.remove_provider_for_screen(
                Screen.get_default(), MyPrefs.provider)
        if value:
            MyPrefs.provider = Gtk.CssProvider()
            css = ('* { -GtkScrollbar-has-backward-stepper: 1; '
                   '-GtkScrollbar-has-forward-stepper: 1; }')
            MyPrefs.provider.load_from_data(css.encode('utf8'))
            Gtk.StyleContext.add_provider_for_screen(
                Screen.get_default(), MyPrefs.provider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        try:
            if value:
                txt = subprocess.check_output('setx GTK_OVERLAY_SCROLLING 0',
                                              shell=True)
            else:
                txt = subprocess.check_output(
                    'reg delete HKCU\Environment /v GTK_OVERLAY_SCROLLING /f',
                    shell=True)
        except subprocess.CalledProcessError:
            print("Cannot set environment variable GTK_OVERLAY_SCROLLING") 
Example #23
Source File: preview.py    From oomox with GNU General Public License v3.0 4 votes vote down vote up
def update_preview_gradients(self, colorscheme):
        gradient = colorscheme['GRADIENT']
        if gradient == 0:
            self.reset_gradients()
            return
        for widget, color_key in zip(
                [
                    self.gtk_preview.button,
                    self.gtk_preview.headerbar.button,
                    self.gtk_preview.entry,
                    self.gtk_preview.headerbar,
                ],
                [
                    "BTN_BG",
                    "HDR_BTN_BG",
                    "TXT_BG",
                    "HDR_BG"
                ]
        ):
            color = colorscheme[color_key]
            css_provider_gradient = self.css_providers.gradient.get(color_key)
            if not css_provider_gradient:
                css_provider_gradient = \
                        self.css_providers.gradient[color_key] = \
                        Gtk.CssProvider()
            css_provider_gradient.load_from_data((
                """
                * {{
                    background-image: linear-gradient(to bottom,
                        shade(#{color}, {amount1}),
                        shade(#{color}, {amount2})
                    );
                }}
                """.format(
                    color=color,
                    amount1=1 + gradient / 2,
                    amount2=1 - gradient / 2,
                )
            ).encode('ascii'))
            Gtk.StyleContext.add_provider(
                widget.get_style_context(),
                css_provider_gradient,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
            ) 
Example #24
Source File: GPUgui.py    From gpu-utils with GNU General Public License v3.0 4 votes vote down vote up
def set_style(cls, css_str=None) -> None:
        """
        Set the specified css style, or set default styles if no css string is specified.

        :param css_str: A valid css format string.
        """
        css_list = []
        if css_str is None:
            # Initialize formatting colors.
            css_list.append("grid { background-image: image(%s); }" % cls._colors['gray80'])
            css_list.append("#light_grid { background-image: image(%s); }" % cls._colors['gray20'])
            css_list.append("#dark_grid { background-image: image(%s); }" % cls._colors['gray70'])
            css_list.append("#dark_box { background-image: image(%s); }" % cls._colors['slate_dk'])
            css_list.append("#med_box { background-image: image(%s); }" % cls._colors['slate_md'])
            css_list.append("#light_box { background-image: image(%s); }" % cls._colors['slate_lt'])
            css_list.append("#head_box { background-image: image(%s); }" % cls._colors['blue'])
            css_list.append("#warn_box { background-image: image(%s); }" % cls._colors['red'])
            css_list.append("#button_box { background-image: image(%s); }" % cls._colors['slate_dk'])
            css_list.append("#message_box { background-image: image(%s); }" % cls._colors['gray50'])
            css_list.append("#message_label { color: %s; }" % cls._colors['white_off'])
            css_list.append("#warn_label { color: %s; }" % cls._colors['white_pp'])
            css_list.append("#white_label { color: %s; }" % cls._colors['white_off'])
            css_list.append("#black_label { color: %s; }" % cls._colors['gray95'])
            css_list.append("#ppm_combo { background-image: image(%s); color: %s; }" %
                            (cls._colors['green'], cls._colors['black']))
            css_list.append("button { background-image: image(%s); color: %s; }" %
                            (cls._colors['slate_lt'], cls._colors['black']))
            css_list.append("entry { background-image: image(%s); color: %s; }" %
                            (cls._colors['green'], cls._colors['gray95']))
            # Below format does not work.
            css_list.append("entry:selected { background-image: image(%s); color: %s; }" %
                            (cls._colors['yellow'], cls._colors['white']))
        else:
            css_list.append(css_str)
        LOGGER.info('css %s', css_list)

        screen = Gdk.Screen.get_default()

        for css_item in css_list:
            provider = Gtk.CssProvider()
            css = css_item.encode('utf-8')
            provider.load_from_data(css)
            style_context = Gtk.StyleContext()
            style_context.add_provider_for_screen(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) 
Example #25
Source File: preview.py    From oomox with GNU General Public License v3.0 4 votes vote down vote up
def update_preview_borders(self, colorscheme):
        for widget_name, widget, fg, bg, ratio in (  # pylint: disable=invalid-name
                (
                    'button',
                    self.gtk_preview.button,
                    colorscheme['BTN_FG'],
                    colorscheme['BTN_BG'],
                    0.22
                ), (
                    'headerbar_button',
                    self.gtk_preview.headerbar.button,
                    colorscheme['HDR_BTN_FG'],
                    colorscheme['HDR_BTN_BG'],
                    0.22
                ), (
                    'entry',
                    self.gtk_preview.entry,
                    colorscheme['TXT_BG'],
                    colorscheme['TXT_FG'],
                    0.8 * (0.7 + (
                        0 if hex_lightness(colorscheme['TXT_BG']) > 0.66 else (
                            0.1 if hex_lightness(colorscheme['TXT_BG']) > 0.33 else 0.3
                        )
                    ))
                ),
        ):
            border_color = mix_theme_colors(fg, bg, ratio)
            css_provider_border_color = self.css_providers.border.get(widget_name)
            if not css_provider_border_color:
                css_provider_border_color = \
                    self.css_providers.border[widget_name] = \
                    Gtk.CssProvider()
            css_provider_border_color.load_from_data(
                """
                * {{
                    border-color: #{border_color};
                    border-radius: {roundness}px;
                }}
                """.format(
                    border_color=border_color,
                    roundness=colorscheme["ROUNDNESS"],
                ).encode('ascii')
            )
            Gtk.StyleContext.add_provider(
                widget.get_style_context(),
                css_provider_border_color,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
            ) 
Example #26
Source File: lock_screen.py    From epoptes with GNU General Public License v3.0 4 votes vote down vote up
def lock(self, msg, unlock_secs=None):
        """Lock the screen. Unlock after unlock_secs if it's not None."""
        screen = Gdk.Screen.get_default()
        swidth = screen.get_width()
        sheight = screen.get_height()
        smin = min(swidth, sheight)

        gtk_provider = Gtk.CssProvider()
        gtk_context = Gtk.StyleContext()
        gtk_context.add_provider_for_screen(
            screen, gtk_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        gtk_provider.load_from_data(bytes("""
* {{ transition-property: color;  transition-duration: 4s; }}
window, GtkWindow {{ background-color: black; }}
label, GtkLabel {{ font-size: {0:.0f}px; }}
label#black, GtkLabel#black {{ color: black; }}
label#white, GtkLabel#white {{ color: #e0e0e0; }}
""".format(swidth / 70).encode()))

        backlock = Gtk.Window(type=Gtk.WindowType.POPUP)
        self.backlock = backlock
        backlock.resize(1, 1)
        frontview = Gtk.Window()
        self.frontview = frontview
        frontview.resize(swidth, sheight)

        box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL, spacing=smin/12,
            halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER)
        image = Gtk.Image(pixbuf=GdkPixbuf.Pixbuf.new_from_file_at_size(
            'lock.svg', smin/3, smin/3))
        box.pack_start(image, False, False, 0)
        self.label = Gtk.Label(label=msg, name="black")
        box.pack_start(self.label, False, False, 0)
        frontview.add(box)

        backlock.show_all()
        frontview.show_all()

        frontview.set_keep_above(True)
        frontview.fullscreen()
        Gdk.beep()
        Gdk.keyboard_grab(backlock.get_window(), False, 0)

        # Transitions need an event to start
        GLib.timeout_add(100, self.do_transition)

        # While developing, to only lock the screen for e.g. 5 seconds, run:
        # ./lock-screen "" 5
        if unlock_secs is not None:
            GLib.timeout_add(unlock_secs*1000, self.unlock) 
Example #27
Source File: clearine.py    From clearine with MIT License 4 votes vote down vote up
def draw_button(self, name, widget, index):
        # setup a buttons inside card
        status = logging.getLogger(self.__class__.__name__)
        button_name = name.strip()

        dir_ic_home = "%s/.themes/%s/clearine" % (os.environ['HOME'], config["button-theme"])
        dir_ic_share = "%s/%s/clearine" % ("%s/share/themes" % sys.prefix, config["button-theme"])
        dir_ic_share_fb = "%s/%s/clearine" % ("%s/share/themes" % sys.prefix, 'Clearine-Fallback')
        dir_ic_default = "%s/data" % root_module
        print(dir_ic_share)

        ic_png_home = "%s/%s.png" % (dir_ic_home, button_name)
        ic_png_share = "%s/%s.png" % (dir_ic_share, button_name)
        ic_svg_home = "%s/%s.svg" % (dir_ic_home, button_name)
        ic_svg_share = "%s/%s.svg" % (dir_ic_share, button_name)
        ic_svg_share_fb = "%s/%s.svg" % (dir_ic_share_fb, button_name)
        ic_svg_default = "%s/%s.svg" % (dir_ic_default, button_name)

        if os.path.exists(ic_png_home):
            iconfile = ic_png_home
        elif os.path.exists(ic_svg_home):
            iconfile = ic_svg_home
        elif os.path.exists(ic_png_share):
            iconfile = ic_png_share
        elif os.path.exists(ic_svg_share):
            iconfile = ic_svg_share
        elif os.path.exists(ic_svg_share_fb):
            iconfile = ic_svg_share_fb
        elif os.path.exists(ic_svg_default):
            iconfile = ic_svg_default
        else:
            status.info("No Clearine theme available, exiting")
            sys.exit()

        icon_buffer = Pixbuf.new_from_file_at_size(iconfile, config["button-icon-width"], config["button-icon-height"])

        icon = Gtk.Image()
        icon.set_from_pixbuf(icon_buffer)
        icon.set_margin_bottom(10)
        icon.set_margin_top(10)

        button = Gtk.Button()
        button.set_always_show_image(True)
        button.set_image_position(2)
        button.set_label(button_name.capitalize())
        button.set_image(icon)
        button.connect("clicked", self.do, button_name)
        button.set_size_request(config["button-width"], config["button-height"])
        button.set_can_focus(True)

        Gtk.StyleContext.add_class(button.get_style_context(), "clearine-button")
        Gtk.StyleContext.add_provider(button.get_style_context(), self.card_style, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        widget.pack_start(button, False, False, False) 
Example #28
Source File: main.py    From hazzy with GNU General Public License v2.0 4 votes vote down vote up
def do_startup(self):
        Gtk.Application.do_startup(self)

        self.start_time = datetime.now()
        log.info("green<Starting>")

        style_provider = Gtk.CssProvider()
        style_provider.load_from_path(os.path.join(Paths.STYLEDIR, "style.css"))

        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

        self.builder = Gtk.Builder()
        self.builder.add_from_file(os.path.join(Paths.UIDIR, 'menu.ui'))

        self.app_menu = self.builder.get_object('appmenu')
        self.set_app_menu(self.app_menu)

        actions = ['open','new_window', 'about', 'quit', 'launch_hal_meter', 
                'launch_hal_scope', 'launch_hal_configuration', 'launch_classicladder', 
                'launch_status']

        for action in actions:
            self.add_simple_action(action)

        toggle_actions = ['estop', 'power','edit_layout', 'dark_theme']
        for action in toggle_actions:
            self.add_toggle_action(action)

        status.on_changed('stat.task_state', self.on_task_state_changed)
        status.on_changed('stat.interp_state', self.on_interp_state_changed)

        # Show any Startup Notifications given in INI
        startup_notification = ini_info.get_startup_notification()
        if startup_notification:
            notifications.show_info(startup_notification, timeout=0)

        startup_warning = ini_info.get_startup_warning()
        if startup_warning:
            notifications.show_warning(startup_warning, timeout=0)

        log_time('app startup done') 
Example #29
Source File: message_bar.py    From hazzy with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self):
        Gtk.Window.__init__(self, title='MessageBar Demo')

        self.set_default_size(400, 200)
        self.connect('destroy', Gtk.main_quit)

        style_provider = Gtk.CssProvider()
        style_provider.load_from_path(os.path.join('..', "themes/style.css"))

        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(), style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

        self.overlay = Gtk.Overlay()
        self.add(self.overlay)

        button_box = Gtk.ButtonBox()
        button_box.set_halign(Gtk.Align.FILL)
        button_box.set_valign(Gtk.Align.END)
        button_box.set_layout(Gtk.ButtonBoxStyle.EXPAND)
        button_box.set_margin_bottom(5)

        # Show info message button
        btn = Gtk.Button('Info')
        btn.connect('clicked', self.show_info)
        button_box.add(btn)

        # Show warning message button
        btn = Gtk.Button('Warning')
        btn.connect('clicked', self.show_warning)
        button_box.add(btn)

        # Show error message button
        btn = Gtk.Button('Error')
        btn.connect('clicked', self.show_error)
        button_box.add(btn)

        # Show question message button
        btn = Gtk.Button('Question')
        btn.connect('clicked', self.show_question)
        button_box.add(btn)

        self.overlay.add(button_box)

        self.message_bar = MessageBar()
        self.overlay.add_overlay(self.message_bar)

        self.show_all()
        Gtk.main()