We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Missing file for backlight should not crash whole setup
# Issue description

After upgrade qtile 1.5.1 -> 1.6.1, the configuration crashed. The problem is I have same setup for two PC. Both have different GPU: intel and Nvidia. The older version just printed an error message inside the plugin. Not cool, but at least the environment worked. 

I am not sure if it is a bug or a feature, but I prefer to have a more resilient config. I do not see a point of crashing for such situations. 

# Qtile version

1.6.1

# Stack traces
```
Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/libqtile/confreader.py", line 92, in load
    config = __import__(name)  # noqa: F811
  File "/home/neworld/.config/qtile/config.py", line 363, in <module>
    widget.Backlight(
  File "/usr/lib/python3.8/site-packages/libqtile/utils.py", line 213, in class_proxy
    return cls(*args, **kwargs)
  File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 96, in __init__
    self.max_value = self._load_file(self.max_brightness_file)
  File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 105, in _load_file
    raise RuntimeError(
RuntimeError: Unable to read status for max_brightness
```

# Configuration

```
                widget.Backlight(
                    background=color_red,
                    backlight_name = 'intel_backlight',
                ),
```

Missing file for backlight should not crash whole setup
# Issue description

After upgrade qtile 1.5.1 -> 1.6.1, the configuration crashed. The problem is I have same setup for two PC. Both have different GPU: intel and Nvidia. The older version just printed an error message inside the plugin. Not cool, but at least the environment worked. 

I am not sure if it is a bug or a feature, but I prefer to have a more resilient config. I do not see a point of crashing for such situations. 

# Qtile version

1.6.1

# Stack traces
```
Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/libqtile/confreader.py", line 92, in load
    config = __import__(name)  # noqa: F811
  File "/home/neworld/.config/qtile/config.py", line 363, in <module>
    widget.Backlight(
  File "/usr/lib/python3.8/site-packages/libqtile/utils.py", line 213, in class_proxy
    return cls(*args, **kwargs)
  File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 96, in __init__
    self.max_value = self._load_file(self.max_brightness_file)
  File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 105, in _load_file
    raise RuntimeError(
RuntimeError: Unable to read status for max_brightness
```

# Configuration

```
                widget.Backlight(
                    background=color_red,
                    backlight_name = 'intel_backlight',
                ),
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `libqtile/widget/backlight.py`
Content:
```
1 # Copyright (c) 2012 Tim Neumann
2 # Copyright (c) 2012, 2014 Tycho Andersen
3 # Copyright (c) 2013 Tao Sauvage
4 # Copyright (c) 2014 Sean Vig
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 # SOFTWARE.
23 
24 import enum
25 import os
26 import shlex
27 from typing import Dict
28 
29 from libqtile.log_utils import logger
30 from libqtile.widget import base
31 
32 BACKLIGHT_DIR = '/sys/class/backlight'
33 
34 
35 @enum.unique
36 class ChangeDirection(enum.Enum):
37     UP = 0
38     DOWN = 1
39 
40 
41 class Backlight(base.InLoopPollText):
42     """A simple widget to show the current brightness of a monitor.
43 
44     If the change_command parameter is set to None, the widget will attempt to
45     use the interface at /sys/class to change brightness. Depending on the
46     setup, the user may need to be added to the video group to have permission
47     to write to this interface. This depends on having the correct udev rules
48     the brightness file; these are typically installed alongside brightness
49     tools such as brightnessctl (which changes the group to 'video') so
50     installing that is an easy way to get it working.
51 
52     You can also bind keyboard shortcuts to the backlight widget with:
53 
54     .. code-block: python
55 
56         from libqtile.widget import backlight
57         Key([], "XF86MonBrightnessUp", lazy.widget['backlight'].change_backlight(backlight.ChangeDirection.UP)),
58         Key([], "XF86MonBrightnessDown", lazy.widget['backlight'].change_backlight(backlight.ChangeDirection.DOWN)),
59     """
60 
61     filenames = {}  # type: Dict
62 
63     orientations = base.ORIENTATION_HORIZONTAL
64 
65     defaults = [
66         ('backlight_name', 'acpi_video0', 'ACPI name of a backlight device'),
67         (
68             'brightness_file',
69             'brightness',
70             'Name of file with the '
71             'current brightness in /sys/class/backlight/backlight_name'
72         ),
73         (
74             'max_brightness_file',
75             'max_brightness',
76             'Name of file with the '
77             'maximum brightness in /sys/class/backlight/backlight_name'
78         ),
79         ('update_interval', .2, 'The delay in seconds between updates'),
80         ('step', 10, 'Percent of backlight every scroll changed'),
81         ('format', '{percent: 2.0%}', 'Display format'),
82         ('change_command', 'xbacklight -set {0}', 'Execute command to change value')
83     ]
84 
85     def __init__(self, **config):
86         base.InLoopPollText.__init__(self, **config)
87         self.add_defaults(Backlight.defaults)
88         self.future = None
89 
90         self.brightness_file = os.path.join(
91             BACKLIGHT_DIR, self.backlight_name, self.brightness_file,
92         )
93         self.max_brightness_file = os.path.join(
94             BACKLIGHT_DIR, self.backlight_name, self.max_brightness_file,
95         )
96         self.max_value = self._load_file(self.max_brightness_file)
97         self.step = self.max_value * self.step / 100
98 
99     def _load_file(self, path):
100         try:
101             with open(path, 'r') as f:
102                 return float(f.read().strip())
103         except FileNotFoundError:
104             logger.debug('Failed to get %s' % path)
105             raise RuntimeError(
106                 'Unable to read status for {}'.format(os.path.basename(path))
107             )
108 
109     def _get_info(self):
110         brightness = self._load_file(self.brightness_file)
111 
112         info = {
113             'brightness': brightness,
114             'max': self.max_value,
115         }
116         return info
117 
118     def poll(self):
119         try:
120             info = self._get_info()
121         except RuntimeError as e:
122             return 'Error: {}'.format(e)
123 
124         percent = info['brightness'] / info['max']
125         return self.format.format(percent=percent)
126 
127     def change_backlight(self, value):
128         if self.change_command is None:
129             try:
130                 with open(self.brightness_file, 'w') as f:
131                     f.write(str(round(value)))
132             except PermissionError:
133                 logger.warning("Cannot set brightness: no write permission for {0}"
134                                .format(self.brightness_file))
135         else:
136             self.call_process(shlex.split(self.change_command.format(value)))
137 
138     def cmd_change_backlight(self, direction):
139         if self.future and not self.future.done():
140             return
141         info = self._get_info()
142         if not info:
143             new = now = self.max_value
144         else:
145             new = now = info["brightness"]
146         if direction is ChangeDirection.DOWN:  # down
147             new = max(now - self.step, 0)
148         elif direction is ChangeDirection.UP:  # up
149             new = min(now + self.step, self.max_value)
150         if new != now:
151             self.future = self.qtile.run_in_executor(self.change_backlight,
152                                                      new)
153 
154     def button_press(self, x, y, button):
155         if button == 5:
156             self.cmd_change_backlight(ChangeDirection.DOWN)
157         elif button == 4:
158             self.cmd_change_backlight(ChangeDirection.UP)
159
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/libqtile/widget/backlight.py b/libqtile/widget/backlight.py
--- a/libqtile/widget/backlight.py
+++ b/libqtile/widget/backlight.py
@@ -85,7 +85,7 @@
     def __init__(self, **config):
         base.InLoopPollText.__init__(self, **config)
         self.add_defaults(Backlight.defaults)
-        self.future = None
+        self._future = None
 
         self.brightness_file = os.path.join(
             BACKLIGHT_DIR, self.backlight_name, self.brightness_file,
@@ -93,8 +93,13 @@
         self.max_brightness_file = os.path.join(
             BACKLIGHT_DIR, self.backlight_name, self.max_brightness_file,
         )
-        self.max_value = self._load_file(self.max_brightness_file)
-        self.step = self.max_value * self.step / 100
+
+        mouse_callbacks = {
+            'Button4': lambda q: self.cmd_change_backlight(ChangeDirection.UP),
+            'Button5': lambda q: self.cmd_change_backlight(ChangeDirection.DOWN),
+        }
+        mouse_callbacks.update(self.mouse_callbacks)
+        self.mouse_callbacks = mouse_callbacks
 
     def _load_file(self, path):
         try:
@@ -108,24 +113,20 @@
 
     def _get_info(self):
         brightness = self._load_file(self.brightness_file)
-
-        info = {
-            'brightness': brightness,
-            'max': self.max_value,
-        }
-        return info
+        max_value = self._load_file(self.max_brightness_file)
+        return brightness / max_value
 
     def poll(self):
         try:
-            info = self._get_info()
+            percent = self._get_info()
         except RuntimeError as e:
             return 'Error: {}'.format(e)
 
-        percent = info['brightness'] / info['max']
         return self.format.format(percent=percent)
 
-    def change_backlight(self, value):
+    def _change_backlight(self, value):
         if self.change_command is None:
+            value = self._load_file(self.max_brightness_file) * value / 100
             try:
                 with open(self.brightness_file, 'w') as f:
                     f.write(str(round(value)))
@@ -136,23 +137,12 @@
             self.call_process(shlex.split(self.change_command.format(value)))
 
     def cmd_change_backlight(self, direction):
-        if self.future and not self.future.done():
+        if self._future and not self._future.done():
             return
-        info = self._get_info()
-        if not info:
-            new = now = self.max_value
-        else:
-            new = now = info["brightness"]
-        if direction is ChangeDirection.DOWN:  # down
+        new = now = self._get_info() * 100
+        if direction is ChangeDirection.DOWN:
             new = max(now - self.step, 0)
-        elif direction is ChangeDirection.UP:  # up
-            new = min(now + self.step, self.max_value)
+        elif direction is ChangeDirection.UP:
+            new = min(now + self.step, 100)
         if new != now:
-            self.future = self.qtile.run_in_executor(self.change_backlight,
-                                                     new)
-
-    def button_press(self, x, y, button):
-        if button == 5:
-            self.cmd_change_backlight(ChangeDirection.DOWN)
-        elif button == 4:
-            self.cmd_change_backlight(ChangeDirection.UP)
+            self._future = self.qtile.run_in_executor(self._change_backlight, new)

{"golden_diff": "diff --git a/libqtile/widget/backlight.py b/libqtile/widget/backlight.py\n--- a/libqtile/widget/backlight.py\n+++ b/libqtile/widget/backlight.py\n@@ -85,7 +85,7 @@\n     def __init__(self, **config):\n         base.InLoopPollText.__init__(self, **config)\n         self.add_defaults(Backlight.defaults)\n-        self.future = None\n+        self._future = None\n \n         self.brightness_file = os.path.join(\n             BACKLIGHT_DIR, self.backlight_name, self.brightness_file,\n@@ -93,8 +93,13 @@\n         self.max_brightness_file = os.path.join(\n             BACKLIGHT_DIR, self.backlight_name, self.max_brightness_file,\n         )\n-        self.max_value = self._load_file(self.max_brightness_file)\n-        self.step = self.max_value * self.step / 100\n+\n+        mouse_callbacks = {\n+            'Button4': lambda q: self.cmd_change_backlight(ChangeDirection.UP),\n+            'Button5': lambda q: self.cmd_change_backlight(ChangeDirection.DOWN),\n+        }\n+        mouse_callbacks.update(self.mouse_callbacks)\n+        self.mouse_callbacks = mouse_callbacks\n \n     def _load_file(self, path):\n         try:\n@@ -108,24 +113,20 @@\n \n     def _get_info(self):\n         brightness = self._load_file(self.brightness_file)\n-\n-        info = {\n-            'brightness': brightness,\n-            'max': self.max_value,\n-        }\n-        return info\n+        max_value = self._load_file(self.max_brightness_file)\n+        return brightness / max_value\n \n     def poll(self):\n         try:\n-            info = self._get_info()\n+            percent = self._get_info()\n         except RuntimeError as e:\n             return 'Error: {}'.format(e)\n \n-        percent = info['brightness'] / info['max']\n         return self.format.format(percent=percent)\n \n-    def change_backlight(self, value):\n+    def _change_backlight(self, value):\n         if self.change_command is None:\n+            value = self._load_file(self.max_brightness_file) * value / 100\n             try:\n                 with open(self.brightness_file, 'w') as f:\n                     f.write(str(round(value)))\n@@ -136,23 +137,12 @@\n             self.call_process(shlex.split(self.change_command.format(value)))\n \n     def cmd_change_backlight(self, direction):\n-        if self.future and not self.future.done():\n+        if self._future and not self._future.done():\n             return\n-        info = self._get_info()\n-        if not info:\n-            new = now = self.max_value\n-        else:\n-            new = now = info[\"brightness\"]\n-        if direction is ChangeDirection.DOWN:  # down\n+        new = now = self._get_info() * 100\n+        if direction is ChangeDirection.DOWN:\n             new = max(now - self.step, 0)\n-        elif direction is ChangeDirection.UP:  # up\n-            new = min(now + self.step, self.max_value)\n+        elif direction is ChangeDirection.UP:\n+            new = min(now + self.step, 100)\n         if new != now:\n-            self.future = self.qtile.run_in_executor(self.change_backlight,\n-                                                     new)\n-\n-    def button_press(self, x, y, button):\n-        if button == 5:\n-            self.cmd_change_backlight(ChangeDirection.DOWN)\n-        elif button == 4:\n-            self.cmd_change_backlight(ChangeDirection.UP)\n+            self._future = self.qtile.run_in_executor(self._change_backlight, new)\n", "issue": "Missing file for backlight should not crash whole setup\n# Issue description\r\n\r\nAfter upgrade qtile 1.5.1 -> 1.6.1, the configuration crashed. The problem is I have same setup for two PC. Both have different GPU: intel and Nvidia. The older version just printed an error message inside the plugin. Not cool, but at least the environment worked. \r\n\r\nI am not sure if it is a bug or a feature, but I prefer to have a more resilient config. I do not see a point of crashing for such situations. \r\n\r\n# Qtile version\r\n\r\n1.6.1\r\n\r\n# Stack traces\r\n```\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/confreader.py\", line 92, in load\r\n    config = __import__(name)  # noqa: F811\r\n  File \"/home/neworld/.config/qtile/config.py\", line 363, in <module>\r\n    widget.Backlight(\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/utils.py\", line 213, in class_proxy\r\n    return cls(*args, **kwargs)\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py\", line 96, in __init__\r\n    self.max_value = self._load_file(self.max_brightness_file)\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py\", line 105, in _load_file\r\n    raise RuntimeError(\r\nRuntimeError: Unable to read status for max_brightness\r\n```\r\n\r\n# Configuration\r\n\r\n```\r\n                widget.Backlight(\r\n                    background=color_red,\r\n                    backlight_name = 'intel_backlight',\r\n                ),\r\n```\r\n\nMissing file for backlight should not crash whole setup\n# Issue description\r\n\r\nAfter upgrade qtile 1.5.1 -> 1.6.1, the configuration crashed. The problem is I have same setup for two PC. Both have different GPU: intel and Nvidia. The older version just printed an error message inside the plugin. Not cool, but at least the environment worked. \r\n\r\nI am not sure if it is a bug or a feature, but I prefer to have a more resilient config. I do not see a point of crashing for such situations. \r\n\r\n# Qtile version\r\n\r\n1.6.1\r\n\r\n# Stack traces\r\n```\r\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/confreader.py\", line 92, in load\r\n    config = __import__(name)  # noqa: F811\r\n  File \"/home/neworld/.config/qtile/config.py\", line 363, in <module>\r\n    widget.Backlight(\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/utils.py\", line 213, in class_proxy\r\n    return cls(*args, **kwargs)\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py\", line 96, in __init__\r\n    self.max_value = self._load_file(self.max_brightness_file)\r\n  File \"/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py\", line 105, in _load_file\r\n    raise RuntimeError(\r\nRuntimeError: Unable to read status for max_brightness\r\n```\r\n\r\n# Configuration\r\n\r\n```\r\n                widget.Backlight(\r\n                    background=color_red,\r\n                    backlight_name = 'intel_backlight',\r\n                ),\r\n```\r\n\n", "before_files": [{"content": "# Copyright (c) 2012 Tim Neumann\n# Copyright (c) 2012, 2014 Tycho Andersen\n# Copyright (c) 2013 Tao Sauvage\n# Copyright (c) 2014 Sean Vig\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport enum\nimport os\nimport shlex\nfrom typing import Dict\n\nfrom libqtile.log_utils import logger\nfrom libqtile.widget import base\n\nBACKLIGHT_DIR = '/sys/class/backlight'\n\n\n@enum.unique\nclass ChangeDirection(enum.Enum):\n    UP = 0\n    DOWN = 1\n\n\nclass Backlight(base.InLoopPollText):\n    \"\"\"A simple widget to show the current brightness of a monitor.\n\n    If the change_command parameter is set to None, the widget will attempt to\n    use the interface at /sys/class to change brightness. Depending on the\n    setup, the user may need to be added to the video group to have permission\n    to write to this interface. This depends on having the correct udev rules\n    the brightness file; these are typically installed alongside brightness\n    tools such as brightnessctl (which changes the group to 'video') so\n    installing that is an easy way to get it working.\n\n    You can also bind keyboard shortcuts to the backlight widget with:\n\n    .. code-block: python\n\n        from libqtile.widget import backlight\n        Key([], \"XF86MonBrightnessUp\", lazy.widget['backlight'].change_backlight(backlight.ChangeDirection.UP)),\n        Key([], \"XF86MonBrightnessDown\", lazy.widget['backlight'].change_backlight(backlight.ChangeDirection.DOWN)),\n    \"\"\"\n\n    filenames = {}  # type: Dict\n\n    orientations = base.ORIENTATION_HORIZONTAL\n\n    defaults = [\n        ('backlight_name', 'acpi_video0', 'ACPI name of a backlight device'),\n        (\n            'brightness_file',\n            'brightness',\n            'Name of file with the '\n            'current brightness in /sys/class/backlight/backlight_name'\n        ),\n        (\n            'max_brightness_file',\n            'max_brightness',\n            'Name of file with the '\n            'maximum brightness in /sys/class/backlight/backlight_name'\n        ),\n        ('update_interval', .2, 'The delay in seconds between updates'),\n        ('step', 10, 'Percent of backlight every scroll changed'),\n        ('format', '{percent: 2.0%}', 'Display format'),\n        ('change_command', 'xbacklight -set {0}', 'Execute command to change value')\n    ]\n\n    def __init__(self, **config):\n        base.InLoopPollText.__init__(self, **config)\n        self.add_defaults(Backlight.defaults)\n        self.future = None\n\n        self.brightness_file = os.path.join(\n            BACKLIGHT_DIR, self.backlight_name, self.brightness_file,\n        )\n        self.max_brightness_file = os.path.join(\n            BACKLIGHT_DIR, self.backlight_name, self.max_brightness_file,\n        )\n        self.max_value = self._load_file(self.max_brightness_file)\n        self.step = self.max_value * self.step / 100\n\n    def _load_file(self, path):\n        try:\n            with open(path, 'r') as f:\n                return float(f.read().strip())\n        except FileNotFoundError:\n            logger.debug('Failed to get %s' % path)\n            raise RuntimeError(\n                'Unable to read status for {}'.format(os.path.basename(path))\n            )\n\n    def _get_info(self):\n        brightness = self._load_file(self.brightness_file)\n\n        info = {\n            'brightness': brightness,\n            'max': self.max_value,\n        }\n        return info\n\n    def poll(self):\n        try:\n            info = self._get_info()\n        except RuntimeError as e:\n            return 'Error: {}'.format(e)\n\n        percent = info['brightness'] / info['max']\n        return self.format.format(percent=percent)\n\n    def change_backlight(self, value):\n        if self.change_command is None:\n            try:\n                with open(self.brightness_file, 'w') as f:\n                    f.write(str(round(value)))\n            except PermissionError:\n                logger.warning(\"Cannot set brightness: no write permission for {0}\"\n                               .format(self.brightness_file))\n        else:\n            self.call_process(shlex.split(self.change_command.format(value)))\n\n    def cmd_change_backlight(self, direction):\n        if self.future and not self.future.done():\n            return\n        info = self._get_info()\n        if not info:\n            new = now = self.max_value\n        else:\n            new = now = info[\"brightness\"]\n        if direction is ChangeDirection.DOWN:  # down\n            new = max(now - self.step, 0)\n        elif direction is ChangeDirection.UP:  # up\n            new = min(now + self.step, self.max_value)\n        if new != now:\n            self.future = self.qtile.run_in_executor(self.change_backlight,\n                                                     new)\n\n    def button_press(self, x, y, button):\n        if button == 5:\n            self.cmd_change_backlight(ChangeDirection.DOWN)\n        elif button == 4:\n            self.cmd_change_backlight(ChangeDirection.UP)\n", "path": "libqtile/widget/backlight.py"}], "after_files": [{"content": "# Copyright (c) 2012 Tim Neumann\n# Copyright (c) 2012, 2014 Tycho Andersen\n# Copyright (c) 2013 Tao Sauvage\n# Copyright (c) 2014 Sean Vig\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport enum\nimport os\nimport shlex\nfrom typing import Dict\n\nfrom libqtile.log_utils import logger\nfrom libqtile.widget import base\n\nBACKLIGHT_DIR = '/sys/class/backlight'\n\n\n@enum.unique\nclass ChangeDirection(enum.Enum):\n    UP = 0\n    DOWN = 1\n\n\nclass Backlight(base.InLoopPollText):\n    \"\"\"A simple widget to show the current brightness of a monitor.\n\n    If the change_command parameter is set to None, the widget will attempt to\n    use the interface at /sys/class to change brightness. Depending on the\n    setup, the user may need to be added to the video group to have permission\n    to write to this interface. This depends on having the correct udev rules\n    the brightness file; these are typically installed alongside brightness\n    tools such as brightnessctl (which changes the group to 'video') so\n    installing that is an easy way to get it working.\n\n    You can also bind keyboard shortcuts to the backlight widget with:\n\n    .. code-block: python\n\n        from libqtile.widget import backlight\n        Key([], \"XF86MonBrightnessUp\", lazy.widget['backlight'].change_backlight(backlight.ChangeDirection.UP)),\n        Key([], \"XF86MonBrightnessDown\", lazy.widget['backlight'].change_backlight(backlight.ChangeDirection.DOWN)),\n    \"\"\"\n\n    filenames = {}  # type: Dict\n\n    orientations = base.ORIENTATION_HORIZONTAL\n\n    defaults = [\n        ('backlight_name', 'acpi_video0', 'ACPI name of a backlight device'),\n        (\n            'brightness_file',\n            'brightness',\n            'Name of file with the '\n            'current brightness in /sys/class/backlight/backlight_name'\n        ),\n        (\n            'max_brightness_file',\n            'max_brightness',\n            'Name of file with the '\n            'maximum brightness in /sys/class/backlight/backlight_name'\n        ),\n        ('update_interval', .2, 'The delay in seconds between updates'),\n        ('step', 10, 'Percent of backlight every scroll changed'),\n        ('format', '{percent: 2.0%}', 'Display format'),\n        ('change_command', 'xbacklight -set {0}', 'Execute command to change value')\n    ]\n\n    def __init__(self, **config):\n        base.InLoopPollText.__init__(self, **config)\n        self.add_defaults(Backlight.defaults)\n        self._future = None\n\n        self.brightness_file = os.path.join(\n            BACKLIGHT_DIR, self.backlight_name, self.brightness_file,\n        )\n        self.max_brightness_file = os.path.join(\n            BACKLIGHT_DIR, self.backlight_name, self.max_brightness_file,\n        )\n\n        mouse_callbacks = {\n            'Button4': lambda q: self.cmd_change_backlight(ChangeDirection.UP),\n            'Button5': lambda q: self.cmd_change_backlight(ChangeDirection.DOWN),\n        }\n        mouse_callbacks.update(self.mouse_callbacks)\n        self.mouse_callbacks = mouse_callbacks\n\n    def _load_file(self, path):\n        try:\n            with open(path, 'r') as f:\n                return float(f.read().strip())\n        except FileNotFoundError:\n            logger.debug('Failed to get %s' % path)\n            raise RuntimeError(\n                'Unable to read status for {}'.format(os.path.basename(path))\n            )\n\n    def _get_info(self):\n        brightness = self._load_file(self.brightness_file)\n        max_value = self._load_file(self.max_brightness_file)\n        return brightness / max_value\n\n    def poll(self):\n        try:\n            percent = self._get_info()\n        except RuntimeError as e:\n            return 'Error: {}'.format(e)\n\n        return self.format.format(percent=percent)\n\n    def _change_backlight(self, value):\n        if self.change_command is None:\n            value = self._load_file(self.max_brightness_file) * value / 100\n            try:\n                with open(self.brightness_file, 'w') as f:\n                    f.write(str(round(value)))\n            except PermissionError:\n                logger.warning(\"Cannot set brightness: no write permission for {0}\"\n                               .format(self.brightness_file))\n        else:\n            self.call_process(shlex.split(self.change_command.format(value)))\n\n    def cmd_change_backlight(self, direction):\n        if self._future and not self._future.done():\n            return\n        new = now = self._get_info() * 100\n        if direction is ChangeDirection.DOWN:\n            new = max(now - self.step, 0)\n        elif direction is ChangeDirection.UP:\n            new = min(now + self.step, 100)\n        if new != now:\n            self._future = self.qtile.run_in_executor(self._change_backlight, new)\n", "path": "libqtile/widget/backlight.py"}]}