├── volctl ├── __init__.py ├── meta.py ├── __main__.py ├── xwrappers.py ├── prefs.py ├── app.py ├── osd.py ├── status_icon.py ├── pulsemgr.py └── slider_win.py ├── .vscode └── settings.json ├── .gitignore ├── .flake8 ├── Makefile ├── data ├── volctl.desktop └── apps.volctl.gschema.xml ├── .editorconfig ├── pyproject.toml ├── README.md ├── .pylintrc └── LICENSE.txt /volctl/__init__.py: -------------------------------------------------------------------------------- 1 | """volctl module.""" 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.pylintEnabled": true 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.svn 2 | *~ 3 | .DS_Store 4 | ThumbsDB 5 | \#*# 6 | .#* 7 | *.pyc 8 | build 9 | volctl.egg-info 10 | /venv 11 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-complexity = 10 3 | exclude = volctl/lib/pulseaudio.py 4 | # black compatibility 5 | max-line-length = 88 6 | extend-ignore = E203 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | sources = volctl setup.py 2 | 3 | all: lint 4 | 5 | lint: pylint flake8 6 | 7 | pylint: 8 | pylint $(sources) 9 | 10 | flake8: 11 | flake8 $(sources) 12 | 13 | black: 14 | black $(sources) 15 | 16 | .PHONY: all lint pylint flake8 black 17 | -------------------------------------------------------------------------------- /data/volctl.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Type=Application 3 | Name=Volctl 4 | Comment=Per-application volume control for GNU/Linux desktops 5 | Exec=volctl 6 | Icon=multimedia-volume-control 7 | Terminal=false 8 | StartupNotify=false 9 | Categories=AudioVideo;Audio;Mixer;GTK; 10 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | end_of_line = lf 9 | charset = utf-8 10 | 11 | [Makefile] 12 | indent_style = tab 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /volctl/meta.py: -------------------------------------------------------------------------------- 1 | """Version string used by program and setup.py (using regex parsing).""" 2 | 3 | from gi.repository import Gtk 4 | 5 | VERSION = "0.9.5" 6 | PROGRAM_NAME = "Volume Control" 7 | COPYRIGHT = "(c) buzz" 8 | LICENSE = Gtk.License.GPL_2_0 9 | COMMENTS = "Per-application volume control for GNU/Linux desktops" 10 | WEBSITE = "https://buzz.github.io/volctl/" 11 | -------------------------------------------------------------------------------- /volctl/__main__.py: -------------------------------------------------------------------------------- 1 | """volctl main entry point.""" 2 | import gi 3 | 4 | gi.require_version("Gdk", "3.0") 5 | gi.require_version("GdkX11", "3.0") 6 | gi.require_version("Gio", "2.0") 7 | gi.require_version("GLib", "2.0") 8 | gi.require_version("GObject", "2.0") 9 | gi.require_version("Gtk", "3.0") 10 | # pylint: disable=wrong-import-position 11 | from gi.repository import Gtk 12 | from volctl.app import VolctlApp 13 | 14 | 15 | def main(): 16 | """Start volctl.""" 17 | app = None 18 | Gtk.init() 19 | try: 20 | app = VolctlApp() 21 | Gtk.main() 22 | except KeyboardInterrupt: 23 | app.quit() 24 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "volctl" 7 | description = "Per-application volume control for GNU/Linux desktops" 8 | authors = [ 9 | {name = "buzz", email = "buzz@users.noreply.github.com"} 10 | ] 11 | readme = "README.md" 12 | license = "GPL-3.0-or-later" 13 | dynamic = ["version"] 14 | dependencies = [ 15 | "pulsectl", 16 | "pycairo", 17 | "PyGObject", 18 | ] 19 | urls = { Homepage = "https://buzz.github.io/volctl/" } 20 | 21 | [project.gui-scripts] 22 | volctl = "volctl.__main__:main" 23 | 24 | [tool.setuptools.packages.find] 25 | include = ["volctl*"] 26 | 27 | [tool.setuptools.data-files] 28 | "share/applications" = ["data/volctl.desktop"] 29 | "share/glib-2.0/schemas" = ["data/apps.volctl.gschema.xml"] 30 | 31 | [tool.setuptools.dynamic] 32 | version = { attr = "volctl.meta.VERSION" } 33 | -------------------------------------------------------------------------------- /volctl/xwrappers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python wrapper for some X-related stuff. 3 | 4 | Copyright (C) 2017 Kozec 5 | 6 | Adapted from: 7 | https://github.com/kozec/sc-controller/blob/master/scc/lib/xwrappers.py 8 | """ 9 | 10 | # pylint: disable=invalid-name 11 | 12 | from ctypes import c_int, c_short, c_ulong, c_ushort, c_void_p, CDLL, POINTER, Structure 13 | 14 | 15 | def _load_lib(*names): 16 | """Try multiple alternative names to load .so library.""" 17 | for name in names: 18 | try: 19 | return CDLL(name) 20 | except OSError: 21 | pass 22 | raise OSError(f"Failed to load {names[0]}, library not found") 23 | 24 | 25 | libXFixes = _load_lib("libXfixes.so", "libXfixes.so.3") 26 | 27 | # Types 28 | XID = c_ulong 29 | Display = c_void_p 30 | XserverRegion = c_ulong 31 | 32 | 33 | # Structures 34 | class XRectangle(Structure): 35 | """X11 XRectangle structure""" 36 | 37 | # pylint: disable=too-few-public-methods 38 | 39 | _fields_ = [ 40 | ("x", c_short), 41 | ("y", c_short), 42 | ("width", c_ushort), 43 | ("height", c_ushort), 44 | ] 45 | 46 | 47 | # Constants 48 | SHAPE_BOUNDING = 0 49 | SHAPE_INPUT = 2 50 | 51 | create_region = libXFixes.XFixesCreateRegion 52 | create_region.__doc__ = ( 53 | "Creates rectanglular region for use with set_window_shape_region" 54 | ) 55 | create_region.argtypes = [c_void_p, POINTER(XRectangle), c_int] 56 | create_region.restype = XserverRegion 57 | 58 | set_window_shape_region = libXFixes.XFixesSetWindowShapeRegion 59 | set_window_shape_region.__doc__ = "Sets region in which window accepts inputs" 60 | set_window_shape_region.argtypes = [c_void_p, XID, c_int, c_int, c_int, XserverRegion] 61 | 62 | destroy_region = libXFixes.XFixesDestroyRegion 63 | destroy_region.__doc__ = "Frees region created by create_region" 64 | destroy_region.argtypes = [c_void_p, XserverRegion] 65 | -------------------------------------------------------------------------------- /data/apps.volctl.gschema.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 15 18 | Mouse wheel step 19 | The sensitivity of mouse wheel volume changes. 20 | 21 | 22 | "" 23 | Custom mixer command 24 | Command that is executed to launch the system audio mixer application. (Default: pavucontrol) 25 | 26 | 27 | false 28 | Prefer XEmbed 29 | Prefer XEmbed/Gtk.StatusIcon over SNI. Each one supports different functionality. Choose based on your preference and Desktop Environment support. (Restart required!) 30 | 31 | 32 | 33 | false 34 | Show percentage 35 | Display percentage under volume sliders. 36 | 37 | 38 | true 39 | Show volume meters 40 | Display real time volume meters in sliders. 41 | 42 | 43 | true 44 | Enable auto-close 45 | Auto-close volume sliders pop-up after timeout. 46 | 47 | 48 | 49 | 3000 50 | Auto-close timeout 51 | Time after the pop-up closes automatically. 52 | 53 | 54 | false 55 | Allow extra volume 56 | Enable increasing volume beyond 100%. 57 | 58 | 59 | 60 | true 61 | Enable OSD 62 | Display on-screen display on volume change. 63 | 64 | 65 | 66 | 1000 67 | OSD timeout 68 | Time the OSD is being shown. 69 | 70 | 71 | 72 | 100 73 | OSD size 74 | OSD scale in percent. 75 | 76 | 77 | "bottom-right" 78 | OSD position 79 | OSD position: center, bottom-right, middle-right, top-right, top-center, top-left, middle-left, bottom-left, bottom-center 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # volctl 2 | 3 | Per-application volume control and OSD for Linux desktops. 4 | 5 | ![Screenshot](https://buzz.github.io/volctl/screenshot.png) 6 | 7 | I couldn't find a simple tray icon that allows to control multiple 8 | applications easily from the task bar. So I wrote my own. 9 | 10 | **Bug reports and patches welcome!** 11 | 12 | It's not meant to be an replacement for a full-featured mixer 13 | application. If you're looking for that check out the excellent 14 | [pavucontrol](http://freedesktop.org/software/pulseaudio/pavucontrol/). 15 | 16 | ## Features 17 | 18 | * Runs on virtually every desktop environment (Needs to support the freedesktop system tray specs) 19 | * Control main volumes as well as individual applications 20 | * Mute individual applications 21 | * Shows application icons and names 22 | * Per-application VU meter 23 | * Double-click opens *pavucontrol* (or custom mixer application) 24 | * Mouse-wheel support 25 | * On-screen volume display (OSD) 26 | 27 | ## Installation 28 | 29 | ### Manual installation 30 | 31 | 1. Clone this repository somewhere and cd into it. 32 | 1. To install: `pip install --user .` 33 | Note: You might need to copy `data/apps.volctl.gschema.xml` to `~/.local/share/glib-2.0/schemas/` manually. 34 | 1. For the application icon to show up in the menu: `update-desktop-database ~/.local/share/applications/` 35 | 1. Compile GSettings schemas: `glib-compile-schemas ~/.local/share/glib-2.0/schemas/` 36 | 37 | ### Arch Linux 38 | 39 | Available in AUR: [volctl](https://aur.archlinux.org/packages/volctl/) 40 | 41 | ## Status/tray icon implementation 42 | 43 | volctl strives to achieve a high level of support across different Desktop 44 | Environments. Unfortunately, on the Linux Desktop several tray icon 45 | implemenations with various levels of support and capabilities co-exist. 46 | 47 | volctl supports 48 | 49 | - [*SNI*](https://freedesktop.org/wiki/Specifications/StatusNotifierItem/) 50 | Supported on modern Desktop Environments, like Gnome, KDE, works also on Wayland 51 | - [*XEmbed*](https://www.freedesktop.org/wiki/Specifications/systemtray-spec/) 52 | (through `Gtk.StatusIcon`) 53 | Not supported on Gnome, KDE (only through extensions/plugins). No Wayland 54 | support. 55 | 56 | Your Desktop Environment might support both, one or none of these standards. 57 | Personally I use XEmbed as it allows for all important user interactions (mouse 58 | wheel, double-click, etc.) on my current system. The default is to prefer SNI 59 | which can be changed under the Preferences ➝ Prefer XEmbed. 60 | 61 | *Please try for yourself which type of tray icon works best for you.* 62 | 63 | **Note:** If you need support for SNI you have to compile and install 64 | [statusnotifier](https://jjacky.com/statusnotifier/). Use the configure flags 65 | `--enable-introspection` and `--enable-dbusmenu`. If you're on Arch Linux you 66 | can use the AUR package 67 | [statusnotifier-introspection-dbus-menu](https://aur.archlinux.org/packages/statusnotifier-introspection-dbus-menu/). 68 | 69 | ## No Wayland support ([#39](https://github.com/buzz/volctl/issues/39)) 70 | 71 | Through SNI volctl now supports tray icons under Wayland. Unfortunately it's not 72 | possible to display the volume slider window on Wayland at the mouse pointer 73 | position. The Wayland protocol does not allow this unless non-standard Wayland 74 | extensions are used. The only entity that is capable of doing so is the Wayland 75 | compositor (generally your Desktop Environment). 76 | 77 | ## Development 78 | 79 | ### Deploy dev version in Virtualenv 80 | 81 | You can start volctl from the source tree. 82 | 83 | ```sh 84 | $ python -m venv --system-site-packages venv 85 | $ source venv/bin/activate 86 | $ pip install --editable . 87 | $ venv/bin/volctl 88 | ``` 89 | 90 | ### Linting 91 | 92 | Use pylint and flake8 for linting the sources. 93 | 94 | ```sh 95 | $ make lint 96 | ``` 97 | 98 | Use black to auto-format the code. 99 | 100 | ```sh 101 | $ make black 102 | ``` 103 | 104 | ## License 105 | 106 | GNU General Public License v2.0 107 | -------------------------------------------------------------------------------- /volctl/prefs.py: -------------------------------------------------------------------------------- 1 | """volctl preference dialog""" 2 | from math import floor 3 | from gi.repository import Gtk, Gdk, Gio 4 | 5 | 6 | class PreferencesDialog(Gtk.Dialog): 7 | """Preferences dialog for volctl""" 8 | 9 | MARGIN = 8 10 | COL_SPACING = 24 11 | ROW_SPACING = 12 12 | 13 | OSD_POSITION_NAMES_X = "left", "center", "right" 14 | OSD_POSITION_NAMES_Y = "top", "center", "bottom" 15 | 16 | def __init__(self, settings, default_mixer_cmd): 17 | super().__init__("Preferences") 18 | 19 | self._settings = settings 20 | self._schema = settings.get_property("settings-schema") 21 | self._default_mixer_cmd = default_mixer_cmd 22 | self._row_timeout = None 23 | self._row_osd_timeout = None 24 | self._settings.connect("changed", self._cb_settings_changed) 25 | 26 | self.add_button(Gtk.STOCK_CLOSE, Gtk.ResponseType.OK) 27 | self._grid_top = 0 28 | self._setup_ui() 29 | self.set_icon_name("preferences-desktop") 30 | self.set_resizable(False) 31 | self.set_position(Gtk.WindowPosition.CENTER) 32 | 33 | def _setup_ui(self): 34 | self.set_type_hint(Gdk.WindowTypeHint.NORMAL) 35 | 36 | box = self.get_content_area() 37 | box.set_margin_top(self.MARGIN) 38 | box.set_margin_bottom(self.MARGIN) 39 | box.set_margin_start(self.MARGIN) 40 | box.set_margin_end(self.MARGIN) 41 | 42 | self.grid = Gtk.Grid() 43 | self.grid.set_margin_bottom(self.MARGIN * 2) 44 | self.grid.set_column_spacing(self.COL_SPACING) 45 | self.grid.set_row_spacing(self.ROW_SPACING) 46 | self.grid.set_column_homogeneous(True) 47 | self.grid.set_row_homogeneous(False) 48 | 49 | # Tray icon options 50 | self._create_section_label("Tray icon") 51 | self._add_scale("mouse-wheel-step", self._scale_mouse_wheel_step_format) 52 | self._add_entry("mixer-command", placeholder=self._default_mixer_cmd) 53 | self._add_switch("prefer-gtksi") 54 | 55 | # Volume slider window options 56 | self._create_section_label("Volume sliders") 57 | self._add_switch("allow-extra-volume") 58 | self._add_switch("show-percentage") 59 | self._add_switch("vu-enabled") 60 | self._add_switch("auto-close") 61 | self._row_timeout = self._add_scale("timeout", self._scale_timeout_format) 62 | 63 | # OSD options 64 | self._create_section_label("On-screen display") 65 | self._add_switch("osd-enabled") 66 | self._row_osd_timeout = self._add_scale( 67 | "osd-timeout", self._scale_timeout_format 68 | ) 69 | self._row_osd_size = self._add_scale("osd-scale", self._scale_osd_size_format) 70 | self._row_osd_position_group = self._add_osd_position() 71 | 72 | self._update_rows() 73 | box.pack_start(self.grid, False, True, 0) 74 | self.show_all() 75 | 76 | def _create_section_label(self, caption): 77 | label = Gtk.Label() 78 | label.set_markup(f"{caption}") 79 | self._attach(label, width=2) 80 | 81 | def _add_label(self, label_text, tooltip_text): 82 | label = Gtk.Label(label_text, xalign=0) 83 | label.set_tooltip_text(tooltip_text) 84 | label.set_margin_start(self.MARGIN * 2) 85 | self._attach(label, next_row=False) 86 | 87 | def _add_switch(self, name): 88 | key = self._schema.get_key(name) 89 | tooltip_text = key.get_description() 90 | self._add_label(key.get_summary(), tooltip_text) 91 | 92 | switch = Gtk.Switch() 93 | switch.set_tooltip_text(tooltip_text) 94 | self._settings.bind(name, switch, "active", Gio.SettingsBindFlags.DEFAULT) 95 | self._attach(switch, left=1) 96 | return switch 97 | 98 | def _add_scale(self, name, format_func): 99 | key = self._schema.get_key(name) 100 | tooltip_text = key.get_description() 101 | self._add_label(key.get_summary(), tooltip_text) 102 | 103 | scale = Gtk.Scale().new(Gtk.Orientation.HORIZONTAL) 104 | scale.set_tooltip_text(tooltip_text) 105 | key_range = key.get_range() 106 | scale.set_range(key_range[1][0], key_range[1][1]) 107 | scale.set_digits(False) 108 | scale.set_size_request(128, 24) 109 | scale.connect("format_value", format_func) 110 | self._settings.bind( 111 | name, scale.get_adjustment(), "value", Gio.SettingsBindFlags.DEFAULT 112 | ) 113 | self._attach(scale, left=1) 114 | return scale 115 | 116 | def _add_entry(self, name, placeholder=None): 117 | key = self._schema.get_key(name) 118 | tooltip_text = key.get_description() 119 | self._add_label(key.get_summary(), tooltip_text) 120 | 121 | entry = Gtk.Entry() 122 | entry.set_tooltip_text(tooltip_text) 123 | if placeholder: 124 | entry.set_placeholder_text(placeholder) 125 | self._settings.bind(name, entry, "text", Gio.SettingsBindFlags.DEFAULT) 126 | self._attach(entry, left=1) 127 | return entry 128 | 129 | def _add_osd_position(self): 130 | val = self._settings.get_string("osd-position") 131 | key = self._schema.get_key("osd-position") 132 | tooltip_text = key.get_description() 133 | self._add_label(key.get_summary(), tooltip_text) 134 | 135 | grid = Gtk.Grid() 136 | grid.set_column_spacing(8) 137 | grid.set_row_spacing(8) 138 | first_radio_btn = None 139 | for top, yname in enumerate(self.OSD_POSITION_NAMES_Y): 140 | for left, xname in enumerate(self.OSD_POSITION_NAMES_X): 141 | name = f"{yname}-{xname}" 142 | radio_btn = Gtk.RadioButton.new_from_widget(first_radio_btn) 143 | if top == 0 and left == 0: 144 | first_radio_btn = radio_btn 145 | if name == val: 146 | radio_btn.set_active(True) 147 | radio_btn.set_tooltip_text(name) 148 | grid.attach(radio_btn, left, top, 1, 1) 149 | 150 | # Connect after because it would fire on creation 151 | radio_btn_group = first_radio_btn.get_group() 152 | for radio_btn in radio_btn_group: 153 | radio_btn.connect("toggled", self._cb_osd_pos_toggled) 154 | 155 | self._attach(grid, left=1) 156 | return radio_btn_group 157 | 158 | def _attach(self, widget, left=0, width=1, next_row=True): 159 | halign = Gtk.Align.FILL 160 | if left == 0: 161 | halign = Gtk.Align.START 162 | if isinstance(widget, Gtk.Switch) or isinstance(widget, Gtk.Grid): 163 | halign = Gtk.Align.END 164 | widget.set_halign(halign) 165 | widget.set_valign(Gtk.Align.FILL) 166 | widget.set_hexpand(True) 167 | widget.set_vexpand(False) 168 | self.grid.attach(widget, left, self._grid_top, width, 1) 169 | if next_row: 170 | self._grid_top += 1 171 | 172 | @staticmethod 173 | def _scale_timeout_format(_, value): 174 | return f"{value/1000:.1f} sec" 175 | 176 | @staticmethod 177 | def _scale_osd_size_format(_, value): 178 | return f"{round(value)} %" 179 | 180 | @staticmethod 181 | def _scale_mouse_wheel_step_format(_, value): 182 | return f"{value:.1f} %" 183 | 184 | def _update_rows(self): 185 | self._row_timeout.set_sensitive(self._settings.get_boolean("auto-close")) 186 | 187 | osd_enabled = self._settings.get_boolean("osd-enabled") 188 | self._row_osd_timeout.set_sensitive(osd_enabled) 189 | self._row_osd_size.set_sensitive(osd_enabled) 190 | for radio_button in self._row_osd_position_group: 191 | radio_button.set_sensitive(osd_enabled) 192 | 193 | def _cb_osd_pos_toggled(self, radio_btn): 194 | if radio_btn.get_active(): 195 | idx = -self._row_osd_position_group.index(radio_btn) + 8 196 | xname = self.OSD_POSITION_NAMES_X[idx % 3] 197 | yname = self.OSD_POSITION_NAMES_Y[floor(idx / 3)] 198 | self._settings.set_string("osd-position", f"{yname}-{xname}") 199 | 200 | # GSettings callback 201 | 202 | def _cb_settings_changed(self, settings, key): 203 | self._update_rows() 204 | -------------------------------------------------------------------------------- /volctl/app.py: -------------------------------------------------------------------------------- 1 | """volctl application""" 2 | 3 | from subprocess import Popen 4 | import sys 5 | from gi.repository import Gdk, Gio, Gtk 6 | import shlex 7 | 8 | from volctl.meta import ( 9 | PROGRAM_NAME, 10 | COPYRIGHT, 11 | LICENSE, 12 | COMMENTS, 13 | WEBSITE, 14 | VERSION, 15 | ) 16 | from volctl.status_icon import StatusIcon 17 | 18 | from volctl.osd import VolumeOverlay 19 | from volctl.prefs import PreferencesDialog 20 | from volctl.pulsemgr import PulseManager 21 | from volctl.slider_win import VolumeSliders 22 | 23 | 24 | DEFAULT_MIXER_CMD = "pavucontrol" 25 | 26 | TOGGLE_BUTTON_CSS = b""" 27 | button.toggle { 28 | padding: 0; 29 | margin-bottom: -5px; 30 | } 31 | button.toggle:hover { 32 | background-color: transparent; 33 | border-color: transparent; 34 | } 35 | button.toggle:checked { 36 | background-color: transparent; 37 | border-color: transparent; 38 | } 39 | button.toggle:checked image { 40 | -gtk-icon-effect: dim; 41 | } 42 | """ 43 | 44 | 45 | class VolctlApp: 46 | """GUI application for volctl.""" 47 | 48 | def __init__(self): 49 | self._set_style(Gtk.CssProvider()) 50 | self.settings = Gio.Settings("apps.volctl", path="/apps/volctl/") 51 | self.settings.connect("changed", self._cb_settings_changed) 52 | self.mouse_wheel_step = self.settings.get_int("mouse-wheel-step") 53 | self._first_volume_update = True 54 | self.pulsemgr = PulseManager(self) 55 | 56 | self.status_icon = None 57 | self.sliders_win = None 58 | self._about_win = None 59 | self._preferences = None 60 | self._osd = None 61 | self._mixer_process = None 62 | 63 | # Remembered main volume, mute 64 | self._volume, self._mute = 0.0, False 65 | 66 | def create_status_icon(self): 67 | """Create status icon.""" 68 | if self.status_icon is None: 69 | prefer_gtksi = self.settings.get_boolean("prefer-gtksi") 70 | self.status_icon = StatusIcon(self, prefer_gtksi) 71 | 72 | def quit(self): 73 | """Gracefully shut down application.""" 74 | try: 75 | self.pulsemgr.close() 76 | except AttributeError: 77 | pass 78 | if Gtk.main_level() > 0: 79 | if self.sliders_win: 80 | self.sliders_win.destroy() 81 | if self._about_win: 82 | self._about_win.destroy() 83 | if self._preferences: 84 | self._preferences.destroy() 85 | if self._osd: 86 | self._osd.destroy() 87 | Gtk.main_quit() 88 | else: 89 | sys.exit(1) 90 | 91 | @staticmethod 92 | def _set_style(provider): 93 | provider.load_from_data(TOGGLE_BUTTON_CSS) 94 | Gtk.StyleContext.add_provider_for_screen( 95 | Gdk.Screen.get_default(), 96 | provider, 97 | Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, 98 | ) 99 | 100 | def _create_osd(self): 101 | self._osd = VolumeOverlay(self) 102 | self._osd.connect("destroy", self.on_osd_destroy) 103 | 104 | def on_osd_destroy(self, _): 105 | """OSD window destroy callback.""" 106 | self._osd.disconnect_by_func(self.on_osd_destroy) 107 | del self._osd 108 | self._osd = None 109 | 110 | def update_main(self, volume, mute): 111 | """Default sink update.""" 112 | 113 | # Ignore events that don't change anything (prevents OSD from showing) 114 | if volume == self._volume and mute == self._mute: 115 | return 116 | self._volume = volume 117 | self._mute = mute 118 | 119 | self.status_icon.update(volume, mute) 120 | # OSD 121 | if self._first_volume_update: 122 | self._first_volume_update = False # Avoid showing on program start 123 | return 124 | if self.settings.get_boolean("osd-enabled"): 125 | if self._osd is None: 126 | self._create_osd() 127 | self._osd.update_values(volume, mute) 128 | elif self._osd is not None: 129 | self._osd.destroy() 130 | 131 | # Updates coming from pulseaudio 132 | 133 | def sink_update(self, idx, volume, mute): 134 | """A sink update is coming from PulseAudio.""" 135 | if idx == self.pulsemgr.default_sink_idx: 136 | self.update_main(volume, mute) 137 | if self.sliders_win: 138 | self.sliders_win.update_sink_scale(idx, volume, mute) 139 | 140 | def sink_input_update(self, idx, volume, mute): 141 | """A sink input update is coming from PulseAudio.""" 142 | if self.sliders_win: 143 | self.sliders_win.update_sink_input_scale(idx, volume, mute) 144 | 145 | def peak_update(self, idx, val): 146 | """Notify scale when update is coming from pulseaudio.""" 147 | if self.sliders_win: 148 | self.sliders_win.update_scale_peak(idx, val) 149 | 150 | def slider_count_changed(self): 151 | """Amount of sliders changed.""" 152 | if self.status_icon and self.sliders_win: 153 | self.sliders_win.recreate_sliders() 154 | if self.settings.get_boolean("vu-enabled"): 155 | self.pulsemgr.start_peak_monitor() 156 | 157 | def on_connected(self): 158 | """PulseAudio connection was established.""" 159 | self.create_status_icon() 160 | 161 | def on_disconnected(self): 162 | """PulseAudio connection was lost.""" 163 | self.close_slider() 164 | 165 | # Gsettings callback 166 | 167 | def _cb_settings_changed(self, settings, key): 168 | if key == "mouse-wheel-step": 169 | self.mouse_wheel_step = settings.get_int("mouse-wheel-step") 170 | if self.sliders_win: 171 | self.sliders_win.set_increments() 172 | 173 | # GUI 174 | 175 | def show_preferences(self): 176 | """Bring preferences to focus or create if it doesn't exist.""" 177 | if self._preferences: 178 | self._preferences.present() 179 | else: 180 | self._preferences = PreferencesDialog(self.settings, DEFAULT_MIXER_CMD) 181 | self._preferences.run() 182 | self._preferences.destroy() 183 | del self._preferences 184 | self._preferences = None 185 | 186 | def show_about(self): 187 | """Bring about window to focus or create if it doesn't exist.""" 188 | if self._about_win is not None: 189 | self._about_win.present() 190 | else: 191 | self._about_win = Gtk.AboutDialog() 192 | self._about_win.set_program_name(PROGRAM_NAME) 193 | self._about_win.set_version(VERSION) 194 | self._about_win.set_copyright(COPYRIGHT) 195 | self._about_win.set_license_type(LICENSE) 196 | self._about_win.set_comments(COMMENTS) 197 | self._about_win.set_website(WEBSITE) 198 | self._about_win.set_logo_icon_name("audio-volume-high") 199 | self._about_win.run() 200 | self._about_win.destroy() 201 | del self._about_win 202 | self._about_win = None 203 | 204 | def launch_mixer(self): 205 | """Launch external mixer.""" 206 | mixer_cmd = self.settings.get_string("mixer-command") 207 | mixer_cmd_str = self.settings.get_string("mixer-command") 208 | if mixer_cmd_str == "": 209 | mixer_cmd = DEFAULT_MIXER_CMD 210 | else: 211 | mixer_cmd = shlex.split(mixer_cmd_str) 212 | if self._mixer_process is None or not self._mixer_process.poll() is None: 213 | self._mixer_process = Popen(mixer_cmd) 214 | # TODO: bring mixer win to front otherwise 215 | 216 | def show_slider(self, xpos, ypos): 217 | """Show mini window with application volume sliders.""" 218 | self.sliders_win = VolumeSliders(self, xpos, ypos) 219 | if self.settings.get_boolean("vu-enabled"): 220 | self.pulsemgr.start_peak_monitor() 221 | 222 | def close_slider(self): 223 | """Close mini window with application volume sliders.""" 224 | if self.sliders_win: 225 | self.sliders_win.destroy() 226 | del self.sliders_win 227 | self.sliders_win = None 228 | self.pulsemgr.stop_peak_monitor() 229 | return True 230 | return False 231 | -------------------------------------------------------------------------------- /volctl/osd.py: -------------------------------------------------------------------------------- 1 | """ 2 | OSD volume overlay 3 | 4 | A transparent OSD volume indicator. 5 | 6 | Various code snippets taken from https://github.com/kozec/sc-controller 7 | """ 8 | 9 | import math 10 | import cairo 11 | from gi.repository import Gdk, Gtk, GdkX11, GLib 12 | 13 | import volctl.xwrappers as X 14 | 15 | 16 | class VolumeOverlay(Gtk.Window): 17 | """Window that displays volume sliders.""" 18 | 19 | BASE_WIDTH = 200 20 | BASE_HEIGHT = 200 21 | BASE_FONT_SIZE = 42 22 | BASE_LINE_WIDTH = 5 23 | SCREEN_MARGIN = 64 24 | BASE_PADDING = 24 25 | BG_OPACITY = 0.85 26 | BG_CORNER_RADIUS = 8 27 | MUTE_OPACITY = 0.2 28 | TEXT_OPACITY = 0.8 29 | NUM_BARS = 16 30 | 31 | def __init__(self, volctl): 32 | super().__init__() 33 | self._volctl = volctl 34 | self.position = -self.SCREEN_MARGIN, -self.SCREEN_MARGIN 35 | self.osd_position = self._volctl.settings.get_string("osd-position") 36 | 37 | scale = self._volctl.settings.get_int("osd-scale") / 100 38 | self._width = int(self.BASE_WIDTH * scale) 39 | self._height = int(self.BASE_HEIGHT * scale) 40 | self._font_size = int(self.BASE_FONT_SIZE * scale) 41 | self._line_width = self.BASE_LINE_WIDTH * scale 42 | self._padding = int(self.BASE_PADDING * scale) 43 | self._corner_radius = int(self.BG_CORNER_RADIUS * scale) 44 | 45 | self.set_default_size(self._width, self._height) 46 | self._volume = 0 47 | self._mute = False 48 | self._hide_timeout = None 49 | self._fadeout_timeout = None 50 | self._opacity = 1.0 51 | 52 | self.set_decorated(False) 53 | self.stick() 54 | self.set_skip_taskbar_hint(True) 55 | self.set_skip_pager_hint(True) 56 | self.set_keep_above(True) 57 | self.set_type_hint(Gdk.WindowTypeHint.NOTIFICATION) 58 | self.set_resizable(False) 59 | 60 | self.screen = self.get_screen() 61 | self.visual = self.screen.get_rgba_visual() 62 | if self.visual is not None and self.screen.is_composited(): 63 | self._compositing = True 64 | self.set_visual(self.visual) 65 | else: 66 | self._compositing = False 67 | self.set_app_paintable(True) 68 | self.connect("draw", self._draw_osd) 69 | 70 | self.realize() 71 | self.get_window().set_override_redirect(True) 72 | self._move_to_position(self.osd_position) 73 | Gtk.Window.show(self) 74 | self._make_window_clickthrough() 75 | 76 | def update_values(self, volume, mute): 77 | """Remember current volume and mute values.""" 78 | self._volume = volume 79 | self._mute = mute 80 | self._unhide() 81 | if self._hide_timeout is not None: 82 | GLib.Source.remove(self._hide_timeout) 83 | self._hide_timeout = GLib.timeout_add( 84 | self._volctl.settings.get_int("osd-timeout"), self._cb_hide_timeout 85 | ) 86 | 87 | def _move_to_position(self, position): 88 | # Adjusts position for currently active screen (display). 89 | xpos, ypos = 0, 0 90 | marginx, marginy = self.position 91 | width, height = self._get_window_size() 92 | swidth = Gdk.Screen.width() 93 | sheight = Gdk.Screen.height() 94 | geometry = self._get_active_screen_geometry() 95 | if geometry: 96 | xpos = geometry.x 97 | ypos = geometry.y 98 | swidth = geometry.width 99 | sheight = geometry.height 100 | 101 | yname, xname = position.split("-") 102 | 103 | # Caluclate x, y coords 104 | 105 | if xname == "left": 106 | xpos = -marginx + xpos 107 | elif xname == "center": 108 | xpos = (swidth - width) / 2 + xpos 109 | elif xname == "right": 110 | xpos = marginx + xpos + swidth - width 111 | else: 112 | raise ValueError("Got unknown x position for OSD.") 113 | 114 | if yname == "top": 115 | ypos = -marginy + ypos 116 | elif yname == "center": 117 | ypos = (sheight - height) / 2 + ypos 118 | elif yname == "bottom": 119 | ypos = marginy + ypos + sheight - height 120 | else: 121 | raise ValueError("Got unknown y position for OSD.") 122 | 123 | self.move(xpos, ypos) 124 | 125 | def _draw_osd(self, _, cairo_r): 126 | """Draw on-screen volume display.""" 127 | mute_opacity = self.MUTE_OPACITY if self._mute else 1.0 128 | xcenter = self._width / 2 129 | 130 | # Background 131 | deg = math.pi / 180.0 132 | cairo_r.new_sub_path() 133 | cairo_r.arc( 134 | self._width - self._corner_radius, 135 | self._corner_radius, 136 | self._corner_radius, 137 | -90 * deg, 138 | 0, 139 | ) 140 | cairo_r.arc( 141 | self._width - self._corner_radius, 142 | self._height - self._corner_radius, 143 | self._corner_radius, 144 | 0, 145 | 90 * deg, 146 | ) 147 | cairo_r.arc( 148 | self._corner_radius, 149 | self._height - self._corner_radius, 150 | self._corner_radius, 151 | 90 * deg, 152 | 180 * deg, 153 | ) 154 | cairo_r.arc( 155 | self._corner_radius, 156 | self._corner_radius, 157 | self._corner_radius, 158 | 180 * deg, 159 | 270 * deg, 160 | ) 161 | cairo_r.close_path() 162 | 163 | cairo_r.set_source_rgba(0.1, 0.1, 0.1, self.BG_OPACITY * self._opacity) 164 | cairo_r.set_operator(cairo.OPERATOR_SOURCE) 165 | cairo_r.fill() 166 | cairo_r.set_operator(cairo.OPERATOR_OVER) 167 | 168 | # Color 169 | cairo_r.set_source_rgba( 170 | 1.0, 1.0, 1.0, self.TEXT_OPACITY * mute_opacity * self._opacity 171 | ) 172 | 173 | # Text 174 | text = f"{round(100 * self._volume)} %" 175 | cairo_r.select_font_face("sans-serif") 176 | cairo_r.set_font_size(self._font_size) 177 | _, _, text_width, text_height, _, _ = cairo_r.text_extents(text) 178 | cairo_r.move_to(xcenter - text_width / 2, self._height - self._padding) 179 | cairo_r.show_text(text) 180 | 181 | # Volume indicator 182 | ind_height = self._height - 3 * self._padding - text_height 183 | outer_radius = ind_height / 2 184 | inner_radius = outer_radius / 1.618 185 | bars = min(round(self.NUM_BARS * self._volume), self.NUM_BARS) 186 | cairo_r.set_line_width(self._line_width) 187 | cairo_r.set_line_cap(cairo.LINE_CAP_ROUND) 188 | for i in range(bars): 189 | cairo_r.identity_matrix() 190 | cairo_r.translate(xcenter, self._padding + ind_height / 2) 191 | cairo_r.rotate(math.pi + 2 * math.pi / self.NUM_BARS * i) 192 | cairo_r.move_to(0.0, -inner_radius) 193 | cairo_r.line_to(0.0, -outer_radius) 194 | cairo_r.stroke() 195 | 196 | def _make_window_clickthrough(self): 197 | """Make events pass through window.""" 198 | dpy = X.Display(hash(GdkX11.x11_get_default_xdisplay())) 199 | try: 200 | xid = self.get_window().get_xid() 201 | except AttributeError: 202 | # Probably on Wayland 203 | return 204 | win = X.XID(xid) 205 | reg = X.create_region(dpy, None, 0) 206 | X.set_window_shape_region(dpy, win, X.SHAPE_BOUNDING, 0, 0, 0) 207 | X.set_window_shape_region(dpy, win, X.SHAPE_INPUT, 0, 0, reg) 208 | X.destroy_region(dpy, reg) 209 | 210 | def _get_active_screen_geometry(self): 211 | """ 212 | Returns geometry of active screen or None if active screen 213 | cannot be determined. 214 | """ 215 | screen = self.get_window().get_screen() 216 | active_window = screen.get_active_window() 217 | if active_window: 218 | monitor = screen.get_monitor_at_window(active_window) 219 | if monitor is not None: 220 | return screen.get_monitor_geometry(monitor) 221 | return None 222 | 223 | def _get_window_size(self): 224 | return self.get_window().get_width(), self.get_window().get_height() 225 | 226 | def _hide(self): 227 | if self._compositing: 228 | self._fadeout_timeout = GLib.timeout_add(30, self._cb_fadeout_timeout) 229 | else: 230 | self.destroy() 231 | 232 | def _unhide(self): 233 | if self._fadeout_timeout is not None: 234 | GLib.Source.remove(self._fadeout_timeout) 235 | self._fadeout_timeout = None 236 | self._move_to_position(self.osd_position) 237 | self._opacity = 1.0 238 | self.queue_draw() 239 | 240 | def _cb_fadeout_timeout(self): 241 | self._opacity -= 0.05 242 | self.queue_draw() 243 | if self._opacity >= 0: 244 | return True 245 | self._opacity = 0.0 246 | self._fadeout_timeout = None 247 | self.destroy() 248 | return False 249 | 250 | def _cb_hide_timeout(self): 251 | self._hide_timeout = None 252 | self._hide() 253 | -------------------------------------------------------------------------------- /volctl/status_icon.py: -------------------------------------------------------------------------------- 1 | from math import floor 2 | import gi 3 | from gi.repository import Gtk, Gdk, GLib 4 | 5 | try: 6 | gi.require_version("StatusNotifier", "1.0") 7 | from gi.repository import StatusNotifier 8 | except (ImportError, ValueError): 9 | StatusNotifier = None 10 | 11 | from volctl.meta import PROGRAM_NAME 12 | 13 | 14 | class StatusIcon: 15 | """ 16 | Volume control status icon. 17 | 18 | By default StatusNotifier library is used if available. It uses DBUS and 19 | doesn't rely on XEmbed being available (Wayland support). As a fallback 20 | Gtk.StatusIcon will be used. 21 | 22 | Both have slightly different appearance and usability. 23 | """ 24 | 25 | MAX_EMBED_ATTEMPTS = 5 26 | 27 | def __init__(self, volctl, prefer_gtksi): 28 | super().__init__() 29 | self._volctl = volctl 30 | self._menu = None 31 | 32 | self._current_impl = None 33 | 34 | # Prefer statusnotifier as it works under Gnome/KDE and also Wayland 35 | # unless overridden by user 36 | self._available_impl = [] 37 | if StatusNotifier is not None: 38 | self._available_impl.append("sni") 39 | if prefer_gtksi: 40 | self._available_impl.append("gtksi") 41 | else: 42 | self._available_impl.insert(0, "gtksi") 43 | 44 | self._check_embed_timeout = None 45 | self._embed_attempts = 0 46 | self._instance = None 47 | 48 | self._create_menu() 49 | self._create_statusicon() 50 | 51 | def update(self, volume, mute): 52 | """Update status icon according to volume state.""" 53 | icon_name = self._get_icon_name(volume, mute) 54 | if self._instance: 55 | if self._current_impl == "sni": 56 | self._set_sni_tooltip() 57 | self._instance.set_from_icon_name( 58 | StatusNotifier.Icon.STATUS_NOTIFIER_ICON, icon_name 59 | ) 60 | elif self._current_impl == "gtksi": 61 | self._instance.set_from_icon_name(icon_name) 62 | 63 | def get_geometry(self): 64 | """Return status icon position and size.""" 65 | if self._instance and self._current_impl == "gtksi": 66 | return self._instance.get_geometry() 67 | # In case of statusnotifier, we don't have access to the icons geometry 68 | return False, None, None, None 69 | 70 | # GUI setup 71 | 72 | def _create_statusicon(self): 73 | """Attempt to create a status icon using the preferred 74 | implementation.""" 75 | self._embed_attempts = 0 76 | try: 77 | self._current_impl = self._available_impl.pop() 78 | except IndexError: 79 | print( 80 | "Fatal error: Could not create a status icon. " 81 | "Are you sure you have a working notification area?" 82 | ) 83 | self._volctl.quit() 84 | 85 | getattr(self, f"_create_{self._current_impl}")() 86 | 87 | def _create_sni(self): 88 | self._instance = StatusNotifier.Item.new_from_icon_name( 89 | "volctl", 90 | StatusNotifier.Category.HARDWARE, 91 | self._get_icon_name( 92 | self._volctl.pulsemgr.volume, self._volctl.pulsemgr.mute 93 | ), 94 | ) 95 | self._instance.set_title(PROGRAM_NAME) 96 | self._instance.set_status(StatusNotifier.Status.ACTIVE) 97 | self._instance.set_item_is_menu(False) 98 | self._instance.set_context_menu(self._menu) 99 | self._instance.connect("activate", self._cb_sni_on_activate) 100 | self._instance.connect("secondary-activate", self._cb_sni_on_secondary_activate) 101 | self._instance.connect( 102 | "registration-failed", self._cb_sni_on_registration_failed 103 | ) 104 | self._instance.connect("scroll", self._cb_sni_on_scroll) 105 | self._set_sni_tooltip() 106 | self._instance.register() 107 | 108 | def _create_gtksi(self): 109 | self._instance = Gtk.StatusIcon() 110 | self._instance.set_visible(True) 111 | self._instance.set_name("volctl") 112 | self._instance.set_title("Volume") 113 | self._instance.set_has_tooltip(True) 114 | self._instance.connect("popup-menu", self._cb_gtksi_popup) 115 | self._instance.connect("button-press-event", self._cb_gtksi_button_press) 116 | self._instance.connect("scroll-event", self._cb_gtksi_scroll) 117 | self._instance.connect("query-tooltip", self._cb_gtksi_tooltip) 118 | self._instance.connect("notify::embedded", self._cb_gtksi_notify_embedded) 119 | self._check_embed_timeout = GLib.timeout_add(100, self._cb_gtski_check_timeout) 120 | 121 | def _create_menu(self): 122 | self._menu = Gtk.Menu() 123 | mute_menu_item = Gtk.ImageMenuItem("Mute") 124 | img = Gtk.Image.new_from_icon_name( 125 | "audio-volume-muted", Gtk.IconSize.SMALL_TOOLBAR 126 | ) 127 | mute_menu_item.set_image(img) 128 | mute_menu_item.connect("activate", self._cb_menu_mute) 129 | 130 | mixer_menu_item = Gtk.ImageMenuItem("Mixer") 131 | img = Gtk.Image.new_from_icon_name( 132 | "multimedia-volume-control", Gtk.IconSize.SMALL_TOOLBAR 133 | ) 134 | mixer_menu_item.set_image(img) 135 | mixer_menu_item.connect("activate", self._cb_menu_mixer) 136 | 137 | preferences_menu_item = Gtk.ImageMenuItem("Preferences") 138 | img = Gtk.Image.new_from_icon_name( 139 | "preferences-desktop", Gtk.IconSize.SMALL_TOOLBAR 140 | ) 141 | preferences_menu_item.set_image(img) 142 | preferences_menu_item.connect("activate", self._cb_menu_preferences) 143 | 144 | about_menu_item = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_ABOUT) 145 | about_menu_item.connect("activate", self._cb_menu_about) 146 | 147 | exit_menu_item = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_QUIT) 148 | exit_menu_item.connect("activate", self._cb_menu_quit) 149 | 150 | self._menu.append(mute_menu_item) 151 | self._menu.append(mixer_menu_item) 152 | self._menu.append(preferences_menu_item) 153 | self._menu.append(Gtk.SeparatorMenuItem()) 154 | self._menu.append(about_menu_item) 155 | self._menu.append(exit_menu_item) 156 | self._menu.show_all() 157 | 158 | @staticmethod 159 | def _get_icon_name(volume, mute): 160 | if mute: 161 | state = "muted" 162 | else: 163 | idx = min(int(floor(volume * 3)), 2) 164 | state = ["low", "medium", "high"][idx] 165 | return f"audio-volume-{state}" 166 | 167 | def _set_sni_tooltip(self): 168 | self._instance.freeze_tooltip() 169 | self._instance.set_tooltip_title("Volume") 170 | self._instance.set_tooltip_body(self._get_tooltip_markup()) 171 | self._instance.thaw_tooltip() 172 | 173 | def _get_tooltip_markup(self): 174 | """Create tooltip markup.""" 175 | perc = self._volctl.pulsemgr.volume * 100 176 | text = f"Volume: {perc:.0f}%" 177 | if self._volctl.pulsemgr.mute: 178 | text += ' (muted)' 179 | return text 180 | 181 | # Callback actions 182 | 183 | def _cb_activate(self, xpos, ypos): 184 | if not self._volctl.close_slider(): 185 | self._volctl.show_slider(xpos, ypos) 186 | 187 | def _cb_scroll(self, direction): 188 | amount = direction * self._volctl.mouse_wheel_step / 100.0 189 | new_value = self._volctl.pulsemgr.volume + amount 190 | new_value = min(1.0, new_value) 191 | new_value = max(0.0, new_value) 192 | 193 | # User action prolongs auto-close timer 194 | if self._volctl.sliders_win is not None: 195 | self._volctl.sliders_win.reset_timeout() 196 | 197 | self._volctl.pulsemgr.set_main_volume(new_value) 198 | 199 | # Menu callbacks 200 | 201 | def _cb_menu_mute(self, widget): 202 | self._volctl.pulsemgr.toggle_main_mute() 203 | 204 | def _cb_menu_mixer(self, widget): 205 | self._volctl.launch_mixer() 206 | 207 | def _cb_menu_preferences(self, widget): 208 | self._volctl.show_preferences() 209 | 210 | def _cb_menu_about(self, widget): 211 | self._volctl.show_about() 212 | 213 | def _cb_menu_quit(self, widget): 214 | self._volctl.quit() 215 | 216 | # statusnotifier callbacks 217 | 218 | def _cb_sni_on_activate(self, statusnotifer, posx, posy): 219 | self._cb_activate(posx, posy) 220 | 221 | def _cb_sni_on_secondary_activate(self, statusnotifer, posx, posy): 222 | self._volctl.pulsemgr.toggle_main_mute() 223 | 224 | def _cb_sni_on_scroll(self, statusnotifier, delta, orient): 225 | if orient == StatusNotifier.ScrollOrientation.VERTICAL: 226 | self._cb_scroll(-delta) 227 | 228 | def _cb_sni_on_registration_failed(self, statusnotifier, error): 229 | state = self._instance.get_state() 230 | if state == StatusNotifier.State.FAILED: 231 | print("Warning: Could not register StatusNotifierItem.") 232 | GLib.idle_add(self._create_statusicon) 233 | elif state == StatusNotifier.State.REGISTERING: 234 | self._check_embed_timeout = GLib.timeout_add( 235 | 100, self._cb_sni_check_timeout 236 | ) 237 | 238 | def _cb_sni_check_timeout(self): 239 | state = self._instance.get_state() 240 | if state == StatusNotifier.State.REGISTERED: 241 | return GLib.SOURCE_REMOVE 242 | if ( 243 | self._embed_attempts > self.MAX_EMBED_ATTEMPTS 244 | or state == StatusNotifier.State.FAILED 245 | ): 246 | print("Warning: Could not register StatusNotifierItem.") 247 | self._instance = None 248 | GLib.idle_add(self._create_statusicon) 249 | return GLib.SOURCE_REMOVE 250 | self._embed_attempts += 1 251 | return GLib.SOURCE_CONTINUE 252 | 253 | # GTK.StatusIcon callbacks 254 | 255 | def _cb_gtksi_notify_embedded(self, status_icon, embedded): 256 | if embedded: 257 | if self._check_embed_timeout: 258 | GLib.Source.remove(self._check_embed_timeout) 259 | try: 260 | vol, mute = self._volctl.pulsemgr.volume, self._volctl.pulsemgr.mute 261 | except AttributeError: 262 | return 263 | self.update(vol, mute) 264 | 265 | def _cb_gtksi_tooltip(self, item, xcoord, ycoord, keyboard_mode, tooltip): 266 | # pylint: disable=too-many-arguments 267 | tooltip.set_markup(self._get_tooltip_markup()) 268 | return True 269 | 270 | def _cb_gtksi_scroll(self, widget, event): 271 | if event.direction == Gdk.ScrollDirection.DOWN: 272 | self._cb_scroll(-1) 273 | elif event.direction == Gdk.ScrollDirection.UP: 274 | self._cb_scroll(1) 275 | 276 | def _cb_gtksi_button_press(self, widget, event): 277 | if event.button == 1: 278 | if event.type == Gdk.EventType.BUTTON_PRESS: 279 | self._cb_activate(event.x_root, event.y_root) 280 | if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS: 281 | self._volctl.launch_mixer() 282 | 283 | def _cb_gtksi_popup(self, icon, button, time): 284 | self._menu.popup(None, None, None, None, button, time) 285 | 286 | def _cb_gtski_check_timeout(self): 287 | if self._embed_attempts > self.MAX_EMBED_ATTEMPTS: 288 | print("Warning: Could not embed Gtk.StatusIcon.") 289 | self._instance = None 290 | GLib.idle_add(self._create_statusicon) 291 | return GLib.SOURCE_REMOVE 292 | if self._instance.is_embedded(): 293 | return GLib.SOURCE_REMOVE 294 | self._embed_attempts += 1 295 | return GLib.SOURCE_CONTINUE 296 | -------------------------------------------------------------------------------- /volctl/pulsemgr.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | from collections import deque, OrderedDict 3 | import signal 4 | import threading 5 | 6 | from gi.repository import GLib 7 | from pulsectl import ( 8 | Pulse, 9 | PulseDisconnected, 10 | PulseEventMaskEnum, 11 | PulseEventTypeEnum, 12 | ) 13 | from pulsectl.pulsectl import c 14 | 15 | from volctl.meta import PROGRAM_NAME 16 | 17 | 18 | def get_by_attr(list_, attr_name, val): 19 | """Find by attribute in list of objects.""" 20 | return next((s for s in list_ if getattr(s, attr_name) == val), None) 21 | 22 | 23 | class PulsePoller(threading.Thread): 24 | """PulseAudio event loop thread.""" 25 | 26 | def __init__(self, pulse, pulse_lock, pulse_hold, handle_event): 27 | super().__init__(name="volctl-pulsepoller", daemon=True) 28 | self.quit = False 29 | self._pulse_lock, self._pulse_hold = pulse_lock, pulse_hold 30 | self._pulse = pulse 31 | self._handle_event = handle_event 32 | self.events = deque() 33 | self.event_timer_set = False 34 | # Sinks/sink inputs available shorter than this will be ignored 35 | self._transient_detection = 0.05 # sec 36 | 37 | def run(self): 38 | self._pulse.event_mask_set( 39 | PulseEventMaskEnum.sink, PulseEventMaskEnum.sink_input 40 | ) 41 | self._pulse.event_callback_set(self._callback) 42 | while True: 43 | with self._pulse_hold: 44 | self._pulse_lock.acquire() 45 | try: 46 | self._pulse.event_listen(0) 47 | if self.quit: 48 | break 49 | except PulseDisconnected: 50 | self._set_timer() 51 | print("pulseaudio disconnected") 52 | break 53 | finally: 54 | self._pulse_lock.release() 55 | 56 | def _callback(self, event): 57 | if event: 58 | self.events.append(event) 59 | self._set_timer() 60 | 61 | def _set_timer(self): 62 | if not self.event_timer_set: 63 | signal.setitimer(signal.ITIMER_REAL, self._transient_detection) 64 | self.event_timer_set = True 65 | 66 | 67 | class PulseManager: 68 | """Manage connection to PulseAudio and receive updates.""" 69 | 70 | def __init__(self, volctl): 71 | self._volctl = volctl 72 | self._pulse_loop_paused = False 73 | self._pulse = Pulse(client_name=PROGRAM_NAME, connect=False) 74 | 75 | self._poller_thread = None 76 | self._pulse_lock, self._pulse_hold = threading.Lock(), threading.Lock() 77 | signal.signal(signal.SIGALRM, self._handle_pulse_events) 78 | 79 | # Stream monitoring 80 | self._monitor_streams = {} 81 | self._read_cb_ctypes = c.PA_STREAM_REQUEST_CB_T(self._read_cb) 82 | self._samplespec = c.PA_SAMPLE_SPEC( 83 | format=c.PA_SAMPLE_FLOAT32NE, rate=25, channels=1 84 | ) 85 | 86 | self._connect() 87 | 88 | def close(self): 89 | """Close the PulseAudio connection and event polling thread.""" 90 | self.stop_peak_monitor() 91 | self._stop_polling() 92 | if self._pulse: 93 | self._pulse.close() 94 | 95 | @contextmanager 96 | def pulse(self): 97 | """ 98 | Yield the pulse object, pausing the pulse event loop. 99 | See https://github.com/mk-fg/python-pulse-control#event-handling-code-threads 100 | """ 101 | if self._pulse_loop_paused: 102 | yield self._pulse 103 | else: 104 | # Pause PulseAudio event loop 105 | with self._pulse_hold: 106 | for _ in range(int(2.0 / 0.05)): 107 | # Event loop might not be started yet, so wait 108 | self._pulse.event_listen_stop() 109 | if self._pulse_lock.acquire(timeout=0.05): 110 | break 111 | else: 112 | raise RuntimeError("Could not aquire _pulse_lock!") 113 | self._pulse_loop_paused = True 114 | try: 115 | yield self._pulse 116 | finally: 117 | self._pulse_lock.release() 118 | self._pulse_loop_paused = False 119 | 120 | def _connect(self): 121 | self._pulse.connect(wait=True) 122 | print("PulseAudio connected") 123 | self._start_polling() 124 | GLib.idle_add(self._volctl.on_connected) 125 | 126 | def _handle_pulse_events(self, *_): 127 | if self._poller_thread and self._poller_thread.is_alive(): 128 | # Remove transient events and duplicates 129 | events = OrderedDict() 130 | while self._poller_thread.events: 131 | event = self._poller_thread.events.popleft() 132 | 133 | new_tuple = (PulseEventTypeEnum.new, event.facility, event.index) 134 | if event.t == PulseEventTypeEnum.remove and events.pop( 135 | new_tuple, False 136 | ): 137 | change_tuple = ( 138 | PulseEventTypeEnum.change, 139 | event.facility, 140 | event.index, 141 | ) 142 | events.pop(change_tuple, None) 143 | else: 144 | events[event.t, event.facility, event.index] = event 145 | 146 | for event in events.values(): 147 | GLib.idle_add(self._handle_event, event) 148 | self._poller_thread.event_timer_set = False 149 | 150 | # Reconnect on lost connection 151 | if not self._pulse.connected: 152 | GLib.idle_add(self._volctl.on_disconnected) 153 | self._stop_polling() 154 | self._connect() 155 | 156 | def _start_polling(self): 157 | self._poller_thread = PulsePoller( 158 | self._pulse, self._pulse_lock, self._pulse_hold, self._handle_event 159 | ) 160 | self._poller_thread.start() 161 | 162 | def _stop_polling(self): 163 | if self._poller_thread and self._poller_thread.is_alive(): 164 | self._poller_thread.quit = True 165 | self._poller_thread.join(timeout=1.0) 166 | self._poller_thread = None 167 | 168 | def _handle_event(self, event): 169 | """Handle PulseAudio event.""" 170 | fac = "sink" if event.facility == "sink" else "sink_input" 171 | 172 | if event.t == PulseEventTypeEnum.change: 173 | method, obj = None, None 174 | 175 | with self.pulse() as pulse: 176 | obj_list = getattr(pulse, f"{fac}_list")() 177 | obj = get_by_attr(obj_list, "index", event.index) 178 | 179 | if obj: 180 | method = getattr(self._volctl, f"{fac}_update") 181 | method(event.index, obj.volume.value_flat, obj.mute == 1) 182 | 183 | elif event.t in (PulseEventTypeEnum.new, PulseEventTypeEnum.remove): 184 | self._volctl.slider_count_changed() 185 | 186 | else: 187 | print(f"Warning: Unhandled event type for {fac}: {event.t}") 188 | 189 | def _read_cb(self, stream, nbytes, idx): 190 | data = c.c_void_p() 191 | nbytes = c.c_int(nbytes) 192 | idx -= 1 193 | c.pa.stream_peek(stream, data, c.byref(nbytes)) 194 | try: 195 | if not data or nbytes.value < 1: 196 | return 197 | samples = c.cast(data, c.POINTER(c.c_float)) 198 | val = max(samples[i] for i in range(nbytes.value)) 199 | finally: 200 | # stream_drop() flushes buffered data (incl. buff=NULL "hole" data) 201 | # stream.h: "should not be called if the buffer is empty" 202 | if nbytes: 203 | c.pa.stream_drop(stream) 204 | GLib.idle_add(self._volctl.peak_update, idx, min(val, 1.0)) 205 | 206 | def start_peak_monitor(self): 207 | """Start peak monitoring for all sinks and sink inputs.""" 208 | with self.pulse() as pulse: 209 | for sink in pulse.sink_list(): 210 | stream = self._create_peak_stream(sink.index) 211 | self._monitor_streams[sink.index] = stream 212 | for sink_input in pulse.sink_input_list(): 213 | sink_idx = self._pulse.sink_input_info(sink_input.index).sink 214 | stream = self._create_peak_stream(sink_idx, sink_input.index) 215 | self._monitor_streams[sink_input.index] = stream 216 | 217 | def stop_peak_monitor(self): 218 | """Stop peak monitoring for all sinks and sink inputs.""" 219 | with self.pulse(): 220 | for idx, stream in self._monitor_streams.items(): 221 | try: 222 | c.pa.stream_disconnect(stream) 223 | except c.pa.CallError: 224 | pass # Stream was removed 225 | finally: 226 | GLib.idle_add(self._volctl.peak_update, idx, 0.0) 227 | self._monitor_streams = {} 228 | 229 | def _create_peak_stream(self, sink_idx, sink_input_idx=None): 230 | # Cannot use `get_peak_sample` from python-pulse-control as it would block GUI. 231 | proplist = c.pa.proplist_from_string( # Hide this stream in mixer apps 232 | "application.id=org.PulseAudio.pavucontrol" 233 | ) 234 | pa_context = self._pulse._ctx # pylint: disable=protected-access 235 | idx = sink_idx if sink_input_idx is None else sink_input_idx 236 | stream = c.pa.stream_new_with_proplist( 237 | pa_context, f"peak {idx}", c.byref(self._samplespec), None, proplist 238 | ) 239 | c.pa.proplist_free(proplist) 240 | c.pa.stream_set_read_callback(stream, self._read_cb_ctypes, idx + 1) 241 | if sink_input_idx is not None: 242 | # Monitor single sink input 243 | c.pa.stream_set_monitor_stream(stream, sink_input_idx) 244 | c.pa.stream_connect_record( 245 | stream, 246 | str(sink_idx).encode("utf-8"), 247 | c.PA_BUFFER_ATTR(fragsize=4, maxlength=2 ** 32 - 1), 248 | c.PA_STREAM_DONT_MOVE 249 | | c.PA_STREAM_PEAK_DETECT 250 | | c.PA_STREAM_ADJUST_LATENCY 251 | | c.PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND, 252 | ) 253 | return stream 254 | 255 | # Set/get PulseAudio entities 256 | 257 | def set_main_volume(self, val): 258 | """Set default sink volume.""" 259 | with self.pulse() as pulse: 260 | pulse.volume_set_all_chans(self.default_sink, val) 261 | 262 | def toggle_main_mute(self): 263 | """Toggle default sink mute.""" 264 | with self.pulse(): 265 | self.sink_set_mute(self.default_sink_idx, not self.default_sink.mute) 266 | 267 | def sink_set_mute(self, idx, mute): 268 | """Set sink mute.""" 269 | with self.pulse() as pulse: 270 | pulse.sink_mute(idx, mute) 271 | 272 | def sink_input_set_mute(self, idx, mute): 273 | """Set sink input mute.""" 274 | with self.pulse() as pulse: 275 | pulse.sink_input_mute(idx, mute) 276 | 277 | @property 278 | def volume(self): 279 | """Volume of the default sink.""" 280 | try: 281 | return self.default_sink.volume.value_flat 282 | except AttributeError: 283 | return 0.0 284 | 285 | @property 286 | def mute(self): 287 | """Mute state of the default sink.""" 288 | try: 289 | return self.default_sink.mute == 1 290 | except AttributeError: 291 | return False 292 | 293 | @property 294 | def default_sink(self): 295 | """Default sink.""" 296 | with self.pulse() as pulse: 297 | sink_name = pulse.server_info().default_sink_name 298 | return get_by_attr(pulse.sink_list(), "name", sink_name) 299 | 300 | @property 301 | def default_sink_idx(self): 302 | """Default sink index.""" 303 | try: 304 | return self.default_sink.index 305 | except AttributeError: 306 | return None 307 | -------------------------------------------------------------------------------- /volctl/slider_win.py: -------------------------------------------------------------------------------- 1 | """ 2 | VolumeSliders window 3 | 4 | Small window that appears next to tray icon when activated. It show sliders 5 | for main and application volume. 6 | """ 7 | 8 | from gi.repository import Gtk, Gdk, GLib 9 | from pulsectl.pulsectl import c 10 | 11 | 12 | class VolumeSliders(Gtk.Window): 13 | """Window that displays volume sliders.""" 14 | 15 | SPACING = 6 16 | 17 | # Time without receiving an update after which a peak value should be reset to 0 18 | PEAK_TIMEOUT = 100 # ms 19 | 20 | def __init__(self, volctl, xpos, ypos): 21 | super().__init__(type=Gtk.WindowType.POPUP) 22 | self._volctl = volctl 23 | self._xpos, self._ypos = xpos, ypos 24 | self._grid = None 25 | self._show_percentage = self._volctl.settings.get_boolean("show-percentage") 26 | 27 | # GUI objects by index 28 | self._sink_scales = {} 29 | self._sink_input_scales = {} 30 | 31 | self.connect("enter-notify-event", self._cb_enter_notify) 32 | self.connect("leave-notify-event", self._cb_leave_notify) 33 | self.connect("destroy", self._cb_destroy) 34 | 35 | self._frame = Gtk.Frame() 36 | self._frame.set_shadow_type(Gtk.ShadowType.OUT) 37 | self.add(self._frame) 38 | self.create_widgets() 39 | 40 | # Timeout 41 | self._timeout = None 42 | self._enable_timeout() 43 | 44 | # Peak monitoring timeouts 45 | self._peak_timeouts = {} 46 | 47 | def set_increments(self): 48 | """Set sliders increment step.""" 49 | for _, scale in self._sink_scales.items(): 50 | self._set_increments_on_scale(scale) 51 | for _, scale in self._sink_input_scales.items(): 52 | self._set_increments_on_scale(scale) 53 | 54 | def reset_timeout(self): 55 | """Reset auto-close timeout.""" 56 | self._remove_timeout() 57 | self._enable_timeout() 58 | 59 | def _set_increments_on_scale(self, scale): 60 | try: 61 | step = self._volctl.mouse_wheel_step / 100.0 62 | scale.set_increments(step, step) 63 | except AttributeError: 64 | # Pop-up might have closed already. 65 | pass 66 | 67 | def _set_position(self): 68 | if self._xpos == 0 and self._ypos == 0: 69 | # Bogus event positions, happens on Gnome and maybe others, 70 | # use current mouse pointer position instead. 71 | _, self._xpos, self._ypos = ( 72 | Gdk.Display.get_default() 73 | .get_default_seat() 74 | .get_pointer() 75 | .get_position() 76 | ) 77 | 78 | monitor = Gdk.Display.get_default().get_monitor_at_point(self._xpos, self._ypos) 79 | monitor_rect = monitor.get_workarea() 80 | 81 | status_icon = self._volctl.status_icon 82 | info_avail, screen, status_rect, orient = status_icon.get_geometry() 83 | if not info_avail: 84 | # If status icon geometry is not available we need to assume values 85 | status_rect = Gdk.Rectangle() 86 | status_rect.x, status_rect.y = self._xpos, self._ypos 87 | status_rect.width = status_rect.height = 1 88 | win_w, win_h = self.get_size() 89 | 90 | # Initial position (window anchor based on screen quadrant) 91 | win_x = status_rect.x 92 | win_y = status_rect.y 93 | if status_rect.x - monitor_rect.x < monitor_rect.width / 2: 94 | win_x += status_rect.width 95 | else: 96 | if orient == Gtk.Orientation.VERTICAL: 97 | win_x -= win_w 98 | if status_rect.y - monitor_rect.y < monitor_rect.height / 2: 99 | win_y += status_rect.height 100 | else: 101 | win_y -= win_h 102 | 103 | # Keep window inside screen 104 | if win_x + win_w > monitor_rect.x + monitor_rect.width: 105 | win_x = monitor_rect.x + monitor_rect.width - win_w 106 | 107 | if screen: 108 | self.set_screen(screen) 109 | self.move(win_x, win_y) 110 | 111 | def create_widgets(self): 112 | """Create base widgets.""" 113 | self._grid = Gtk.Grid() 114 | self._grid.set_column_spacing(2) 115 | self._grid.set_row_spacing(self.SPACING) 116 | self._frame.add(self._grid) 117 | self.recreate_sliders() 118 | 119 | def clear_sliders(self): 120 | """Remove all children from grid layout.""" 121 | self._sink_scales = {} 122 | self._sink_input_scales = {} 123 | while True: 124 | if self._grid.get_child_at(0, 0) is None: 125 | break 126 | self._grid.remove_column(0) 127 | 128 | def recreate_sliders(self): 129 | """Recreate sliders from PulseAudio sinks.""" 130 | self.clear_sliders() 131 | pos = 0 132 | 133 | with self._volctl.pulsemgr.pulse() as pulse: 134 | try: 135 | sinks = pulse.sink_list() 136 | sink_inputs = pulse.sink_input_list() 137 | except c.pa.CallError: 138 | print("Warning: Could not get sinks/sink inputs") 139 | sinks = [] 140 | sink_inputs = [] 141 | 142 | # Sinks 143 | for sink in sinks: 144 | for prop_name in ["alsa.card_name", "device.description"]: 145 | try: 146 | card_name = sink.proplist[prop_name] 147 | break 148 | except KeyError: 149 | continue 150 | card_name = sink.name 151 | 152 | props = ( 153 | card_name, 154 | "audio-card", 155 | sink.volume.value_flat, 156 | sink.mute, 157 | ) 158 | scale, btn = self._add_scale(pos, props) 159 | self._sink_scales[sink.index] = scale, btn 160 | idx = sink.index 161 | scale.connect("value-changed", self._cb_sink_scale_change, idx) 162 | btn.connect("toggled", self._cb_sink_mute_toggle, idx) 163 | pos += 1 164 | 165 | # Sink inputs 166 | if sink_inputs: 167 | separator = Gtk.Separator().new(Gtk.Orientation.VERTICAL) 168 | separator.set_margin_top(self.SPACING) 169 | separator.set_margin_bottom(self.SPACING) 170 | self._grid.attach(separator, pos, 0, 1, 2) 171 | pos += 1 172 | 173 | for sink_input in sink_inputs: 174 | name = self._name_from_sink_input(sink_input) 175 | icon_name = self._icon_name_from_sink_input(sink_input) 176 | props = name, icon_name, sink_input.volume.value_flat, sink_input.mute 177 | scale, btn = self._add_scale(pos, props) 178 | self._sink_input_scales[sink_input.index] = scale, btn 179 | idx = sink_input.index 180 | scale.connect("value-changed", self._cb_sink_input_scale_change, idx) 181 | btn.connect("toggled", self._cb_sink_input_mute_toggle, idx) 182 | pos += 1 183 | 184 | self.show_all() 185 | self.resize(1, 1) # Smallest possible 186 | GLib.idle_add(self._set_position) 187 | 188 | def _add_scale(self, pos, props): 189 | name, icon_name, val, mute = props 190 | # Scale 191 | scale = Gtk.Scale().new(Gtk.Orientation.VERTICAL) 192 | 193 | scale_size = 128 194 | volume_lim = 1.0 195 | extra_volume_factor = 1.5 # hard-coded for now 196 | if self._volctl.settings.get_boolean("allow-extra-volume"): 197 | scale_size = int(scale_size * extra_volume_factor) 198 | volume_lim = extra_volume_factor 199 | scale.add_mark(1.0, Gtk.PositionType.LEFT, None) 200 | 201 | scale.set_range(0.0, volume_lim) 202 | scale.set_inverted(True) 203 | scale.set_size_request(24, scale_size) 204 | scale.set_margin_top(self.SPACING) 205 | scale.set_tooltip_markup(name) 206 | self._set_increments_on_scale(scale) 207 | if self._show_percentage: 208 | scale.set_draw_value(True) 209 | scale.set_value_pos(Gtk.PositionType.BOTTOM) 210 | scale.connect("format_value", self._cb_format_value) 211 | else: 212 | scale.set_draw_value(False) 213 | 214 | if self._volctl.settings.get_boolean("vu-enabled"): 215 | scale.set_has_origin(False) 216 | scale.set_show_fill_level(False) 217 | scale.set_fill_level(0) 218 | scale.set_restrict_to_fill_level(False) 219 | 220 | # Mute button 221 | icon = Gtk.Image() 222 | icon.set_from_icon_name(icon_name, Gtk.IconSize.SMALL_TOOLBAR) 223 | btn = Gtk.ToggleButton() 224 | btn.set_image(icon) 225 | btn.set_relief(Gtk.ReliefStyle.NONE) 226 | btn.set_margin_bottom(self.SPACING) 227 | btn.set_tooltip_markup(name) 228 | 229 | self._update_scale_values((scale, btn), val, mute) 230 | self._grid.attach(scale, pos, 0, 1, 1) 231 | self._grid.attach(btn, pos, 1, 1, 1) 232 | return scale, btn 233 | 234 | @staticmethod 235 | def _name_from_sink_input(sink_input): 236 | proplist = sink_input.proplist 237 | try: 238 | name = f"{proplist['application.name']}: {proplist['media.name']}" 239 | except KeyError: 240 | try: 241 | name = proplist["application.name"] 242 | except KeyError: 243 | name = sink_input.name 244 | 245 | return name 246 | 247 | @staticmethod 248 | def _icon_name_from_sink_input(sink_input): 249 | proplist = sink_input.proplist 250 | icon_name = proplist.get("application.icon_name") or proplist.get( 251 | "media.icon_name" 252 | ) 253 | 254 | if not icon_name: 255 | binary = proplist.get("application.process.binary", "") 256 | app_name = proplist.get("application.name", "").lower().replace(" ", "-") 257 | icon_name = binary or app_name 258 | 259 | theme = Gtk.IconTheme.get_default() 260 | return icon_name if theme.has_icon(icon_name) else "multimedia-volume-control" 261 | 262 | @staticmethod 263 | def _update_scale_values(scale_btn, volume, mute): 264 | scale, btn = scale_btn 265 | scale.set_value(volume) 266 | if mute is not None: 267 | scale.set_sensitive(not mute) 268 | btn.set_active(mute) 269 | 270 | @staticmethod 271 | def _update_scale_peak(scale, val): 272 | if val > 0: 273 | scale.set_show_fill_level(True) 274 | scale.set_fill_level(val) 275 | else: 276 | scale.set_show_fill_level(False) 277 | scale.set_fill_level(0) 278 | 279 | def _enable_timeout(self): 280 | if self._volctl.settings.get_boolean("auto-close") and self._timeout is None: 281 | self._timeout = GLib.timeout_add( 282 | self._volctl.settings.get_int("timeout"), self._cb_auto_close 283 | ) 284 | 285 | def _remove_timeout(self): 286 | if self._timeout is not None: 287 | GLib.Source.remove(self._timeout) 288 | self._timeout = None 289 | 290 | # Updates coming from outside 291 | 292 | def update_sink_scale(self, idx, volume, mute): 293 | """Update sink scale by index.""" 294 | try: 295 | scale_btn = self._sink_scales[idx] 296 | except KeyError: 297 | return 298 | self._update_scale_values(scale_btn, volume, mute) 299 | 300 | def update_sink_input_scale(self, idx, volume, mute): 301 | """Update sink input scale by index.""" 302 | try: 303 | scale_btn = self._sink_input_scales[idx] 304 | except KeyError: 305 | return 306 | self._update_scale_values(scale_btn, volume, mute) 307 | 308 | def update_scale_peak(self, idx, val): 309 | """Update scale peak value by index on a sink or sink input scale.""" 310 | try: 311 | scale, _ = self._sink_scales[idx] 312 | val = val * scale.get_value() # Need to scale into range for sinks 313 | except KeyError: 314 | try: 315 | scale, _ = self._sink_input_scales[idx] 316 | except KeyError: 317 | return 318 | self._update_scale_peak(scale, val) 319 | 320 | # If a sound source is paused, peak updates stop coming in. To prevent 321 | # to show a stale peak vale, we set peak=0 after a timeout. 322 | try: 323 | GLib.Source.remove(self._peak_timeouts[idx]) 324 | except KeyError: 325 | pass 326 | timeout = GLib.timeout_add(self.PEAK_TIMEOUT, self._cb_peak_reset, idx) 327 | self._peak_timeouts[idx] = timeout 328 | 329 | def _scale_change(self, scale, idx, sink_input=False): 330 | value = scale.get_value() 331 | with self._volctl.pulsemgr.pulse() as pulse: 332 | list_method = pulse.sink_input_list if sink_input else pulse.sink_list 333 | try: 334 | sink = next(s for s in list_method() if s.index == idx) 335 | if sink: 336 | pulse.volume_set_all_chans(sink, value) 337 | except c.pa.CallError as err: 338 | print(f"Warning: Could not set volume on {idx}: {err}") 339 | 340 | # GUI callbacks 341 | 342 | def _cb_destroy(self, win): 343 | self._remove_timeout() 344 | for timeout in self._peak_timeouts.values(): 345 | GLib.Source.remove(timeout) 346 | 347 | @staticmethod 348 | def _cb_format_value(scale, val): 349 | """Format scale label""" 350 | return str(round(100 * val)) 351 | 352 | def _cb_sink_scale_change(self, scale, idx): 353 | self._scale_change(scale, idx) 354 | 355 | def _cb_sink_input_scale_change(self, scale, idx): 356 | self._scale_change(scale, idx, sink_input=True) 357 | 358 | def _cb_sink_mute_toggle(self, button, idx): 359 | mute = button.get_property("active") 360 | self._volctl.pulsemgr.sink_set_mute(idx, mute) 361 | 362 | def _cb_sink_input_mute_toggle(self, button, idx): 363 | mute = button.get_property("active") 364 | self._volctl.pulsemgr.sink_input_set_mute(idx, mute) 365 | 366 | def _cb_enter_notify(self, win, event): 367 | if event.detail in (Gdk.NotifyType.NONLINEAR, Gdk.NotifyType.NONLINEAR_VIRTUAL): 368 | self._remove_timeout() 369 | 370 | def _cb_leave_notify(self, win, event): 371 | if event.detail in (Gdk.NotifyType.NONLINEAR, Gdk.NotifyType.NONLINEAR_VIRTUAL): 372 | self._enable_timeout() 373 | 374 | def _cb_auto_close(self): 375 | self._timeout = None 376 | self._volctl.close_slider() 377 | return GLib.SOURCE_REMOVE 378 | 379 | def _cb_peak_reset(self, idx): 380 | del self._peak_timeouts[idx] 381 | scale = None 382 | try: 383 | scale, _ = self._sink_scales[idx] 384 | except KeyError: 385 | try: 386 | scale, _ = self._sink_input_scales[idx] 387 | except KeyError: 388 | pass 389 | if scale: 390 | self._update_scale_peak(scale, 0.0) 391 | return GLib.SOURCE_REMOVE 392 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # A comma-separated list of package or module names from where C extensions may 4 | # be loaded. Extensions are loading into the active Python interpreter and may 5 | # run arbitrary code. 6 | extension-pkg-whitelist= 7 | 8 | # Add files or directories to the blacklist. They should be base names, not 9 | # paths. 10 | ignore=pulseaudio.py 11 | 12 | # Add files or directories matching the regex patterns to the blacklist. The 13 | # regex matches against base names, not paths. 14 | #ignore-patterns= 15 | 16 | # Python code to execute, usually for sys.path manipulation such as 17 | # pygtk.require(). 18 | #init-hook= 19 | 20 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the 21 | # number of processors available to use. 22 | jobs=0 23 | 24 | # Control the amount of potential inferred values when inferring a single 25 | # object. This can help the performance when dealing with large functions or 26 | # complex, nested conditions. 27 | limit-inference-results=100 28 | 29 | # List of plugins (as comma separated values of python modules names) to load, 30 | # usually to register additional checkers. 31 | load-plugins= 32 | 33 | # Pickle collected data for later comparisons. 34 | persistent=yes 35 | 36 | # Specify a configuration file. 37 | #rcfile= 38 | 39 | # When enabled, pylint would attempt to guess common misconfiguration and emit 40 | # user-friendly hints instead of false-positive error messages. 41 | suggestion-mode=yes 42 | 43 | # Allow loading of arbitrary C extensions. Extensions are imported into the 44 | # active Python interpreter and may run arbitrary code. 45 | unsafe-load-any-extension=no 46 | 47 | 48 | [MESSAGES CONTROL] 49 | 50 | # Only show warnings with the listed confidence levels. Leave empty to show 51 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. 52 | confidence= 53 | 54 | # Disable the message, report, category or checker with the given id(s). You 55 | # can either give multiple identifiers separated by comma (,) or put this 56 | # option multiple times (only on the command line, not in the configuration 57 | # file where it should appear only once). You can also use "--disable=all" to 58 | # disable everything first and then reenable specific checks. For example, if 59 | # you want to run only the similarities checker, you can use "--disable=all 60 | # --enable=similarities". If you want to run only the classes checker, but have 61 | # no Warning level messages displayed, use "--disable=all --enable=classes 62 | # --disable=W". 63 | disable=print-statement, 64 | bad-continuation, 65 | parameter-unpacking, 66 | unpacking-in-except, 67 | old-raise-syntax, 68 | backtick, 69 | long-suffix, 70 | old-ne-operator, 71 | old-octal-literal, 72 | import-star-module-level, 73 | non-ascii-bytes-literal, 74 | raw-checker-failed, 75 | bad-inline-option, 76 | locally-disabled, 77 | locally-enabled, 78 | file-ignored, 79 | suppressed-message, 80 | useless-suppression, 81 | deprecated-pragma, 82 | use-symbolic-message-instead, 83 | apply-builtin, 84 | basestring-builtin, 85 | buffer-builtin, 86 | cmp-builtin, 87 | coerce-builtin, 88 | execfile-builtin, 89 | file-builtin, 90 | long-builtin, 91 | raw_input-builtin, 92 | reduce-builtin, 93 | standarderror-builtin, 94 | unicode-builtin, 95 | xrange-builtin, 96 | coerce-method, 97 | delslice-method, 98 | getslice-method, 99 | setslice-method, 100 | no-absolute-import, 101 | old-division, 102 | dict-iter-method, 103 | dict-view-method, 104 | next-method-called, 105 | metaclass-assignment, 106 | indexing-exception, 107 | raising-string, 108 | reload-builtin, 109 | oct-method, 110 | hex-method, 111 | nonzero-method, 112 | cmp-method, 113 | input-builtin, 114 | round-builtin, 115 | intern-builtin, 116 | unichr-builtin, 117 | map-builtin-not-iterating, 118 | zip-builtin-not-iterating, 119 | range-builtin-not-iterating, 120 | filter-builtin-not-iterating, 121 | using-cmp-argument, 122 | eq-without-hash, 123 | div-method, 124 | idiv-method, 125 | rdiv-method, 126 | exception-message-attribute, 127 | invalid-str-codec, 128 | sys-max-int, 129 | bad-python3-import, 130 | deprecated-string-function, 131 | deprecated-str-translate-call, 132 | deprecated-itertools-function, 133 | deprecated-types-field, 134 | next-method-defined, 135 | dict-items-not-iterating, 136 | dict-keys-not-iterating, 137 | dict-values-not-iterating, 138 | deprecated-operator-function, 139 | deprecated-urllib-function, 140 | xreadlines-attribute, 141 | deprecated-sys-function, 142 | exception-escape, 143 | comprehension-escape, 144 | too-many-instance-attributes, 145 | missing-module-docstring 146 | 147 | # Enable the message, report, category or checker with the given id(s). You can 148 | # either give multiple identifier separated by comma (,) or put this option 149 | # multiple time (only on the command line, not in the configuration file where 150 | # it should appear only once). See also the "--disable" option for examples. 151 | enable=c-extension-no-member 152 | 153 | 154 | [REPORTS] 155 | 156 | # Python expression which should return a note less than 10 (10 is the highest 157 | # note). You have access to the variables errors warning, statement which 158 | # respectively contain the number of errors / warnings messages and the total 159 | # number of statements analyzed. This is used by the global evaluation report 160 | # (RP0004). 161 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 162 | 163 | # Template used to display messages. This is a python new-style format string 164 | # used to format the message information. See doc for all details. 165 | #msg-template= 166 | 167 | # Set the output format. Available formats are text, parseable, colorized, json 168 | # and msvs (visual studio). You can also give a reporter class, e.g. 169 | # mypackage.mymodule.MyReporterClass. 170 | output-format=text 171 | 172 | # Tells whether to display a full report or only the messages. 173 | reports=no 174 | 175 | # Activate the evaluation score. 176 | score=yes 177 | 178 | 179 | [REFACTORING] 180 | 181 | # Maximum number of nested blocks for function / method body 182 | max-nested-blocks=5 183 | 184 | # Complete name of functions that never returns. When checking for 185 | # inconsistent-return-statements if a never returning function is called then 186 | # it will be considered as an explicit return statement and no message will be 187 | # printed. 188 | never-returning-functions=sys.exit 189 | 190 | 191 | [FORMAT] 192 | 193 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 194 | expected-line-ending-format= 195 | 196 | # Regexp for a line that is allowed to be longer than the limit. 197 | ignore-long-lines=^\s*(# )??$ 198 | 199 | # Number of spaces of indent required inside a hanging or continued line. 200 | indent-after-paren=4 201 | 202 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 203 | # tab). 204 | indent-string=' ' 205 | 206 | # Maximum number of characters on a single line. 207 | max-line-length=88 208 | 209 | # Maximum number of lines in a module. 210 | max-module-lines=1000 211 | 212 | # List of optional constructs for which whitespace checking is disabled. `dict- 213 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. 214 | # `trailing-comma` allows a space between comma and closing bracket: (a, ). 215 | # `empty-line` allows space-only lines. 216 | no-space-check=trailing-comma, 217 | dict-separator 218 | 219 | # Allow the body of a class to be on the same line as the declaration if body 220 | # contains single statement. 221 | single-line-class-stmt=no 222 | 223 | # Allow the body of an if to be on the same line as the test if there is no 224 | # else. 225 | single-line-if-stmt=no 226 | 227 | 228 | [SPELLING] 229 | 230 | # Limits count of emitted suggestions for spelling mistakes. 231 | max-spelling-suggestions=4 232 | 233 | # Spelling dictionary name. Available dictionaries: de_AT (aspell), en_US 234 | # (hunspell), he (hspell), en (aspell), en_CA (aspell), en_PH (hunspell), en_GB 235 | # (aspell), de_DE (aspell), de_CH (aspell), en_AU (aspell).. 236 | spelling-dict= 237 | 238 | # List of comma separated words that should not be checked. 239 | spelling-ignore-words= 240 | 241 | # A path to a file that contains private dictionary; one word per line. 242 | spelling-private-dict-file= 243 | 244 | # Tells whether to store unknown words to indicated private dictionary in 245 | # --spelling-private-dict-file option instead of raising a message. 246 | spelling-store-unknown-words=no 247 | 248 | 249 | [VARIABLES] 250 | 251 | # List of additional names supposed to be defined in builtins. Remember that 252 | # you should avoid to define new builtins when possible. 253 | additional-builtins= 254 | 255 | # Tells whether unused global variables should be treated as a violation. 256 | allow-global-unused-variables=yes 257 | 258 | # List of strings which can identify a callback function by name. A callback 259 | # name must start or end with one of those strings. 260 | callbacks=cb_, 261 | _cb 262 | 263 | # A regular expression matching the name of dummy variables (i.e. expected to 264 | # not be used). 265 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 266 | 267 | # Argument names that match this expression will be ignored. Default to name 268 | # with leading underscore. 269 | ignored-argument-names=_.*|^ignored_|^unused_ 270 | 271 | # Tells whether we should check for unused import in __init__ files. 272 | init-import=no 273 | 274 | # List of qualified module names which can have objects that can redefine 275 | # builtins. 276 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io 277 | 278 | 279 | [BASIC] 280 | 281 | # Naming style matching correct argument names. 282 | argument-naming-style=snake_case 283 | 284 | # Regular expression matching correct argument names. Overrides argument- 285 | # naming-style. 286 | #argument-rgx= 287 | 288 | # Naming style matching correct attribute names. 289 | attr-naming-style=snake_case 290 | 291 | # Regular expression matching correct attribute names. Overrides attr-naming- 292 | # style. 293 | #attr-rgx= 294 | 295 | # Bad variable names which should always be refused, separated by a comma. 296 | bad-names=foo, 297 | bar, 298 | baz, 299 | toto, 300 | tutu, 301 | tata 302 | 303 | # Naming style matching correct class attribute names. 304 | class-attribute-naming-style=any 305 | 306 | # Regular expression matching correct class attribute names. Overrides class- 307 | # attribute-naming-style. 308 | #class-attribute-rgx= 309 | 310 | # Naming style matching correct class names. 311 | class-naming-style=PascalCase 312 | 313 | # Regular expression matching correct class names. Overrides class-naming- 314 | # style. 315 | #class-rgx= 316 | 317 | # Naming style matching correct constant names. 318 | const-naming-style=UPPER_CASE 319 | 320 | # Regular expression matching correct constant names. Overrides const-naming- 321 | # style. 322 | #const-rgx= 323 | 324 | # Minimum line length for functions/classes that require docstrings, shorter 325 | # ones are exempt. 326 | docstring-min-length=-1 327 | 328 | # Naming style matching correct function names. 329 | function-naming-style=snake_case 330 | 331 | # Regular expression matching correct function names. Overrides function- 332 | # naming-style. 333 | #function-rgx= 334 | 335 | # Good variable names which should always be accepted, separated by a comma. 336 | good-names=i, 337 | j, 338 | k, 339 | ex, 340 | Run, 341 | _ 342 | 343 | # Include a hint for the correct naming format with invalid-name. 344 | include-naming-hint=no 345 | 346 | # Naming style matching correct inline iteration names. 347 | inlinevar-naming-style=any 348 | 349 | # Regular expression matching correct inline iteration names. Overrides 350 | # inlinevar-naming-style. 351 | #inlinevar-rgx= 352 | 353 | # Naming style matching correct method names. 354 | method-naming-style=snake_case 355 | 356 | # Regular expression matching correct method names. Overrides method-naming- 357 | # style. 358 | #method-rgx= 359 | 360 | # Naming style matching correct module names. 361 | module-naming-style=snake_case 362 | 363 | # Regular expression matching correct module names. Overrides module-naming- 364 | # style. 365 | #module-rgx= 366 | 367 | # Colon-delimited sets of names that determine each other's naming style when 368 | # the name regexes allow several styles. 369 | name-group= 370 | 371 | # Regular expression which should only match function or class names that do 372 | # not require a docstring. 373 | no-docstring-rgx=^_ 374 | 375 | # List of decorators that produce properties, such as abc.abstractproperty. Add 376 | # to this list to register other decorators that produce valid properties. 377 | # These decorators are taken in consideration only for invalid-name. 378 | property-classes=abc.abstractproperty 379 | 380 | # Naming style matching correct variable names. 381 | variable-naming-style=snake_case 382 | 383 | # Regular expression matching correct variable names. Overrides variable- 384 | # naming-style. 385 | #variable-rgx= 386 | 387 | 388 | [TYPECHECK] 389 | 390 | # List of decorators that produce context managers, such as 391 | # contextlib.contextmanager. Add to this list to register other decorators that 392 | # produce valid context managers. 393 | contextmanager-decorators=contextlib.contextmanager 394 | 395 | # List of members which are set dynamically and missed by pylint inference 396 | # system, and so shouldn't trigger E1101 when accessed. Python regular 397 | # expressions are accepted. 398 | generated-members=PulseEventTypeEnum,PulseEventMaskEnum 399 | 400 | # Tells whether missing members accessed in mixin class should be ignored. A 401 | # mixin class is detected if its name ends with "mixin" (case insensitive). 402 | ignore-mixin-members=yes 403 | 404 | # Tells whether to warn about missing members when the owner of the attribute 405 | # is inferred to be None. 406 | ignore-none=yes 407 | 408 | # This flag controls whether pylint should warn about no-member and similar 409 | # checks whenever an opaque object is returned when inferring. The inference 410 | # can return multiple potential results while evaluating a Python object, but 411 | # some branches might not be evaluated, which results in partial inference. In 412 | # that case, it might be useful to still emit no-member and other checks for 413 | # the rest of the inferred objects. 414 | ignore-on-opaque-inference=yes 415 | 416 | # List of class names for which member attributes should not be checked (useful 417 | # for classes with dynamically set attributes). This supports the use of 418 | # qualified names. 419 | ignored-classes=optparse.Values,thread._local,_thread._local 420 | 421 | # List of module names for which member attributes should not be checked 422 | # (useful for modules/projects where namespaces are manipulated during runtime 423 | # and thus existing member attributes cannot be deduced by static analysis. It 424 | # supports qualified module names, as well as Unix pattern matching. 425 | ignored-modules=cairo 426 | 427 | # Show a hint with possible names when a member name was not found. The aspect 428 | # of finding the hint is based on edit distance. 429 | missing-member-hint=yes 430 | 431 | # The minimum edit distance a name should have in order to be considered a 432 | # similar match for a missing member name. 433 | missing-member-hint-distance=1 434 | 435 | # The total number of similar names that should be taken in consideration when 436 | # showing a hint for a missing member. 437 | missing-member-max-choices=1 438 | 439 | 440 | [LOGGING] 441 | 442 | # Logging modules to check that the string format arguments are in logging 443 | # function parameter format. 444 | logging-modules=logging 445 | 446 | 447 | [MISCELLANEOUS] 448 | 449 | # List of note tags to take in consideration, separated by a comma. 450 | notes=FIXME, 451 | XXX, 452 | TODO 453 | 454 | 455 | [SIMILARITIES] 456 | 457 | # Ignore comments when computing similarities. 458 | ignore-comments=yes 459 | 460 | # Ignore docstrings when computing similarities. 461 | ignore-docstrings=yes 462 | 463 | # Ignore imports when computing similarities. 464 | ignore-imports=no 465 | 466 | # Minimum lines number of a similarity. 467 | min-similarity-lines=4 468 | 469 | 470 | [DESIGN] 471 | 472 | # Maximum number of arguments for function / method. 473 | max-args=5 474 | 475 | # Maximum number of attributes for a class (see R0902). 476 | max-attributes=7 477 | 478 | # Maximum number of boolean expressions in an if statement. 479 | max-bool-expr=5 480 | 481 | # Maximum number of branch for function / method body. 482 | max-branches=12 483 | 484 | # Maximum number of locals for function / method body. 485 | max-locals=15 486 | 487 | # Maximum number of parents for a class (see R0901). 488 | max-parents=7 489 | 490 | # Maximum number of public methods for a class (see R0904). 491 | max-public-methods=20 492 | 493 | # Maximum number of return / yield for function / method body. 494 | max-returns=6 495 | 496 | # Maximum number of statements in function / method body. 497 | max-statements=50 498 | 499 | # Minimum number of public methods for a class (see R0903). 500 | min-public-methods=2 501 | 502 | 503 | [IMPORTS] 504 | 505 | # Allow wildcard imports from modules that define __all__. 506 | allow-wildcard-with-all=no 507 | 508 | # Analyse import fallback blocks. This can be used to support both Python 2 and 509 | # 3 compatible code, which means that the block might have code that exists 510 | # only in one or another interpreter, leading to false positives when analysed. 511 | analyse-fallback-blocks=no 512 | 513 | # Deprecated modules which should not be used, separated by a comma. 514 | deprecated-modules=optparse,tkinter.tix 515 | 516 | # Create a graph of external dependencies in the given file (report RP0402 must 517 | # not be disabled). 518 | ext-import-graph= 519 | 520 | # Create a graph of every (i.e. internal and external) dependencies in the 521 | # given file (report RP0402 must not be disabled). 522 | import-graph= 523 | 524 | # Create a graph of internal dependencies in the given file (report RP0402 must 525 | # not be disabled). 526 | int-import-graph= 527 | 528 | # Force import order to recognize a module as part of the standard 529 | # compatibility libraries. 530 | known-standard-library= 531 | 532 | # Force import order to recognize a module as part of a third party library. 533 | known-third-party=enchant 534 | 535 | 536 | [CLASSES] 537 | 538 | # List of method names used to declare (i.e. assign) instance attributes. 539 | defining-attr-methods=__init__, 540 | __new__, 541 | setUp 542 | 543 | # List of member names, which should be excluded from the protected access 544 | # warning. 545 | exclude-protected=_asdict, 546 | _fields, 547 | _replace, 548 | _source, 549 | _make 550 | 551 | # List of valid names for the first argument in a class method. 552 | valid-classmethod-first-arg=cls 553 | 554 | # List of valid names for the first argument in a metaclass class method. 555 | valid-metaclass-classmethod-first-arg=cls 556 | 557 | 558 | [EXCEPTIONS] 559 | 560 | # Exceptions that will emit a warning when being caught. Defaults to 561 | # "Exception". 562 | overgeneral-exceptions=Exception 563 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------