i3-notifier 0.19__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: i3-notifier
3
+ Version: 0.19
4
+ Summary: A notification daemon for i3
5
+ Author: Sencer Selcuk
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.12
8
+ Requires-Dist: dbus-python==1.2.16
9
+ Requires-Dist: i3ipc
10
+ Requires-Dist: python-daemon==2.2.4
11
+ Requires-Dist: pyxdg==0.26
12
+ Description-Content-Type: text/markdown
13
+
14
+ # i3 Notification Manager (Requires a recent version of rofi)
15
+
16
+ This is a notification manager for i3 desktop environment inspired by
17
+ [Rofication](https://github.com/DaveDavenport/Rofication). Like
18
+ Rofication, it implements the [Gnome Desktop Notifications
19
+ Standard](https://developer.gnome.org/notification-spec/) standard.
20
+
21
+ Also see the companion py3status module
22
+ [py3-notifier](https://github.com/sencer/py3-notifier).
23
+
24
+ ## Differences from Rofication
25
+
26
+ - Notifications are stored in a tree structure, where they can be grouped
27
+ by, for example, the application that is sending the notification and
28
+ the subject. This is highly configurable. (No docs at the moment, but
29
+ see the `examples/i3_notifier_config.py`; also see the comments in
30
+ `i3notifier/config.py`)
31
+ - Allows bulk deletion of notifications in a category.
32
+ - Implements "default" action.
33
+ - Shows icons.
34
+ - Does not use sockets, rather adds new dbus methods to show the
35
+ notifications and get the count of notifications.
36
+ - Code is modular, should be straight forward to use another GUI rather
37
+ than Rofi; or another data structure rather than tree structure.
38
+
39
+ ## What does it look like?
40
+
41
+ ![animation](/images/widget.gif)
42
+
43
+ ## Usage
44
+
45
+ To install (also see the requirements.txt)
46
+
47
+ pip install i3-notifier
48
+
49
+ Make sure you are not running any other notification daemon (if you are running `dunst` for example, kill it with `killall dunst`). Then start `i3-notifier`. You might want to make sure `i3-notifier` and its companion script `switch-to-urgent.py` are in the `$PATH`. You can confirm it is running by
50
+
51
+ dbus-send --session --print-reply --dest=org.freedesktop.Notifications /org/freedesktop/Notifications org.freedesktop.Notifications.GetServerInformation
52
+
53
+ Then to launch GUI; bind this to a shortcut
54
+
55
+ dbus-send --session --print-reply --dest=org.freedesktop.Notifications /org/freedesktop/Notifications org.freedesktop.Notifications.ShowNotifications
56
+
57
+ ## Keybindings
58
+ | Key | Action |
59
+ |--------------------------------------------:|-------------------------------------|
60
+ `j`, `Down`, `Tab` or `Ctrl-N` | Choose next
61
+ `k`, `Up` or `Ctrl-P` | Choose previous
62
+ `Enter`, `Space` or `Left Click` | Expand if group; execute action if singleton
63
+ `Shift-Enter` | Execute action
64
+ `Esc`, `Ctrl+[` or `Backspace` | One level up or exit from top level
65
+ `` ` ``, `Ctrl+Backspace` or `Shift-Backspace`| Exit from any level.
66
+ `Delete` | Delete notification or group
67
+ `Ctrl+Delete`, `Shift+Delete` | Delete single notification
68
+
69
+ To get notification count & urgency
70
+
71
+ dbus-send --session --print-reply=literal --dest=org.freedesktop.Notifications /org/freedesktop/Notifications org.freedesktop.Notifications.ShowNotificationCount
72
+
73
+ One can use this with i3blocks to show notifications in the bar
74
+ or even better switch to py3status and install
75
+ [py3-notifier](https://github.com/sencer/py3-notifier).
76
+
77
+ command = "(dbus-send --session --print-reply=literal --dest=org.freedesktop.Notifications /org/freedesktop/Notifications org.freedesktop.Notifications.ShowNotificationCount 2>/dev/null || ($HOME/.local/bin/i3-notifier && echo '? ? ?'))|tr -s ' '|cut -d' ' -f 3"
@@ -0,0 +1,17 @@
1
+ i3notifier/config.py,sha256=f6LaWFxw0kfss2P8rBdfMl-jpVBNgNR-pkUXm70XszM,1942
2
+ i3notifier/data_manager.py,sha256=2olnf5nCkl5fS0OEryGQNzrNBjdIs6Lfgq_NhJx6pzw,4497
3
+ i3notifier/main.py,sha256=5-Ph7aR4Gb3hJYKL2tOrFuPMRxc-zpGyjkHFPqyYpKc,5178
4
+ i3notifier/notification.py,sha256=F5ly4EiikEVMmKRttTiMUsxS8DlB91OySsaSRMtsY0U,4589
5
+ i3notifier/notification_fetcher.py,sha256=ew1nIS5MKMvLmGzLDko1_B5M4MHZVG7pyy0ewy0rwl4,9540
6
+ i3notifier/rofi_gui.py,sha256=UIEYbkC_U5d721PN6BbNct_inEn7Eh6QDVbMFEaGJOI,1814
7
+ i3notifier/switch_to_urgent.py,sha256=yaduAqeRi71nTn05YVDxUEw-MoJAi329LZCJutG40Ps,329
8
+ i3notifier/user_config.py,sha256=-n9EibzE8Zf5q78WlvvLdCITPKCxOQh0iq7bljXxZko,1354
9
+ i3notifier/utils.py,sha256=PRMy_tjpoWcoX7S7cflAma4Li0hzNa3MFXGzmtjpuo0,1135
10
+ i3notifier/rofi-theme/common.rasi,sha256=Wr-F3pMUOikNwrSyCXT1aZR-aHlI5TzHLOLzYKN-KrQ,1643
11
+ i3notifier/rofi-theme/sidebar.rasi,sha256=DZOBBuBH04C49c5vySvd6OEPHGvtkCtdWaVqlpY17Ro,153
12
+ i3notifier/rofi-theme/widget.rasi,sha256=g8B5Agx8m4BLe3H-u-misuEfcvMdKBhGeFFss3Miwmc,112
13
+ i3_notifier-0.19.dist-info/METADATA,sha256=46UmTzLIGeCfBI-LBpqeT9T92J4tekzu903mUtIfXC4,3677
14
+ i3_notifier-0.19.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
15
+ i3_notifier-0.19.dist-info/entry_points.txt,sha256=xDkkzgLegL1HTc8OPLWIjUsLS11bPHZFagRVXCJGVLk,105
16
+ i3_notifier-0.19.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
17
+ i3_notifier-0.19.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ i3-notifier = i3notifier.main:main
3
+ switch-to-urgent = i3notifier.switch_to_urgent:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
i3notifier/config.py ADDED
@@ -0,0 +1,58 @@
1
+ from datetime import datetime
2
+
3
+ from .utils import strip_tags, strip_tags_and_escape
4
+
5
+
6
+ class Config:
7
+ pre_close_hooks = []
8
+ post_close_hooks = []
9
+ pre_action_hooks = []
10
+ post_action_hooks = []
11
+
12
+ # Ignore expiration by default.
13
+ expires = False
14
+
15
+ def should_apply(notification):
16
+ # To group notifications and apply certain formatting inherit this
17
+ # class and make sure should_apply(notification) is the first Config
18
+ # that returns True to those notifications.
19
+ return True
20
+
21
+ def get_keys(notification):
22
+ # Returns a tuple, each element of which corresponds to the group
23
+ # name that the notification should be assigned at the
24
+ # corresponding nesting level.
25
+ return (notification.app_name or "_", notification.body)
26
+
27
+ def update_notification(notification):
28
+ # Edit the notification before saving it. By default no edits are
29
+ # made.
30
+ return notification
31
+
32
+ def format_notification(notification):
33
+ time = datetime.fromtimestamp(notification.created_at // 1e9).strftime("%H:%M")
34
+ # Format the notification
35
+ text = f"<b>{strip_tags_and_escape(notification.summary)}</b> "
36
+ text += f"<small>{time}</small>"
37
+ text += f"<small> {strip_tags_and_escape(notification.app_name)}</small>"
38
+
39
+ if notification.body:
40
+ text += (
41
+ "\n<i>"
42
+ + strip_tags_and_escape(notification.body.replace("\n", "").strip())
43
+ + "</i>"
44
+ )
45
+
46
+ if notification.app_icon:
47
+ return (
48
+ text.encode("utf-8")
49
+ + b"\x00icon\x1f"
50
+ + notification.app_icon.encode("utf-8")
51
+ )
52
+ else:
53
+ return text.encode("utf-8")
54
+
55
+ def single_line(notification):
56
+ return f"{strip_tags(notification.summary)} : {strip_tags(notification.body)}".replace(
57
+ "\n", ""
58
+ ).strip()
@@ -0,0 +1,144 @@
1
+ import pickle
2
+ import threading
3
+
4
+ from .notification import Notification, NotificationCluster
5
+
6
+
7
+ class DataManager(threading.Thread):
8
+
9
+ __slots__ = "tree", "map", "lock", "configs", "dump_path", "last"
10
+
11
+ def __init__(self, configs, dump_path):
12
+ super().__init__()
13
+
14
+ self.tree = NotificationCluster()
15
+ self.map = dict()
16
+ self.last = None
17
+
18
+ self.lock = threading.Lock()
19
+ self.configs = configs
20
+ self.dump_path = dump_path
21
+
22
+ try:
23
+ for notification in pickle.load(open(dump_path, "rb")):
24
+ self.add_notification(notification)
25
+ except:
26
+ pass
27
+
28
+ def _recursive_add_notification(cluster, notification, keys, i=0):
29
+ if i == len(keys):
30
+ return
31
+
32
+ if keys[i] not in cluster.notifications:
33
+ cluster.notifications[keys[i]] = NotificationCluster()
34
+
35
+ DataManager._recursive_add_notification(
36
+ cluster.notifications[keys[i]], notification, keys, i + 1
37
+ )
38
+ cluster.add(keys[i], notification)
39
+
40
+ def add_notification(self, notification):
41
+ for config in self.configs:
42
+ if config.should_apply(notification):
43
+ config.update_notification(notification)
44
+ notification.config = config
45
+ break
46
+
47
+ keys = notification.keys()
48
+
49
+ if notification.id in self.map:
50
+ self.remove_notification(notification.id)
51
+
52
+ with self.lock:
53
+ self.last = notification
54
+ self.map[notification.id] = keys
55
+ DataManager._recursive_add_notification(
56
+ self.tree, notification, [*keys, notification.id]
57
+ )
58
+
59
+ def _recursive_remove_notification(cluster, keys, i=0):
60
+ key = keys[i]
61
+ best_key = i == len(keys) - 1
62
+ has_key = key in cluster.notifications
63
+ if best_key and not has_key:
64
+ # Short-cutted view, descend
65
+ key = list(cluster.notifications.keys())[0]
66
+ i -= 1
67
+
68
+ stop_case = best_key and has_key
69
+ if stop_case:
70
+ cluster_to_delete = cluster.notifications[key]
71
+ best = cluster_to_delete.best
72
+ urgency = cluster.urgency
73
+ nremoved = len(cluster_to_delete)
74
+ else:
75
+ nremoved, best, urgency = DataManager._recursive_remove_notification(
76
+ cluster.notifications[key], keys, i + 1
77
+ )
78
+
79
+ if len(cluster.notifications[key]) == 0 or stop_case:
80
+ del cluster.notifications[key]
81
+
82
+ cluster._len -= nremoved
83
+
84
+ if best is cluster._best:
85
+ cluster._best = None
86
+
87
+ if urgency == cluster._urgency:
88
+ cluster._urgency = None
89
+
90
+ return nremoved, best, urgency
91
+
92
+ def remove_notification(self, id, context=()):
93
+ with self.lock:
94
+ if isinstance(id, int):
95
+ if self.last and id == self.last.id:
96
+ self.last = None
97
+
98
+ context = self.map.pop(id)
99
+ notification = self.get_context(context).notifications[id]
100
+ if notification.timer is not None:
101
+ notification.timer.cancel()
102
+ else:
103
+ for leaf in self.get_context(context).notifications[id].leafs():
104
+ if self.last and leaf.id == self.last.id:
105
+ self.last = None
106
+ if leaf.timer is not None:
107
+ leaf.timer.cancel()
108
+ self.map.pop(leaf.id)
109
+
110
+ DataManager._recursive_remove_notification(self.tree, [*context, id], i=0)
111
+
112
+ def get_context_by_id(self, id):
113
+ return self.get_context(self.map[id])
114
+
115
+ def get_context(self, context=()):
116
+ p = self.tree
117
+
118
+ if context and context[0] not in p.notifications:
119
+ while len(p.notifications) == 1:
120
+ p = next(iter(p.notifications.values()))
121
+
122
+ for key in context:
123
+ p = p.notifications[key]
124
+
125
+ while len(p.notifications) == 1:
126
+ child = next(iter(p.notifications.values()))
127
+
128
+ if isinstance(child, Notification):
129
+ break
130
+
131
+ p = child
132
+
133
+ return p
134
+
135
+ def dump(self):
136
+ pickle.dump(
137
+ [notification.strip() for notification in self.tree.leafs()],
138
+ open(self.dump_path, "wb"),
139
+ )
140
+
141
+ def cancel_timers(self):
142
+ for notification in self.tree.leafs():
143
+ if notification.timer is not None:
144
+ notification.timer.cancel()
i3notifier/main.py ADDED
@@ -0,0 +1,170 @@
1
+ import argparse
2
+ import dbus
3
+ import logging
4
+ import logging.handlers
5
+ import os
6
+ import signal
7
+ import sys
8
+
9
+ import dbus.mainloop.glib
10
+
11
+ import daemon
12
+ import daemon.pidfile
13
+ from gi.repository import GLib
14
+ from i3notifier.data_manager import DataManager
15
+ from i3notifier.notification_fetcher import NotificationFetcher
16
+ from i3notifier.rofi_gui import RofiGUI
17
+ from i3notifier.user_config import get_user_config
18
+
19
+ logger = logging.getLogger("i3notifier")
20
+ files_preserve = []
21
+
22
+
23
+ def run_daemon(config_path=None, nodaemon=False):
24
+ try:
25
+ userconfig = get_user_config(config_path)
26
+ except FileNotFoundError as e:
27
+ print(f"Error: {e}", file=sys.stderr)
28
+ sys.exit(1)
29
+
30
+ logger.info(f"Found {len(userconfig.config_list)} configurations.")
31
+
32
+ dump_path = "/tmp/i3-notifier.dump"
33
+ logger.info(
34
+ f"Notifications will be dumped to {dump_path} on graceful exit or when asked."
35
+ )
36
+ data_manager = DataManager(userconfig.config_list, dump_path)
37
+
38
+ gui = RofiGUI(theme=userconfig.theme)
39
+
40
+ def dump_and_exit(n, f):
41
+ data_manager.dump()
42
+ data_manager.cancel_timers()
43
+ sys.exit(0)
44
+
45
+ pid_file = "/tmp/i3-notifier.pid"
46
+
47
+ if os.path.exists(pid_file):
48
+ try:
49
+ pid = int(open(pid_file).read().strip())
50
+ os.kill(pid, 0)
51
+ logger.info(f"i3-notifier is already running with pid {pid}.")
52
+ except:
53
+ os.remove(pid_file)
54
+ logger.info(
55
+ "i3-notifier is not running, but a lock file exists. Cleaning up."
56
+ )
57
+
58
+ def run():
59
+ logger.info(f"Creating lock file {pid_file}")
60
+ with open(pid_file, "w") as f:
61
+ f.write(str(os.getpid()))
62
+
63
+ dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
64
+ fetcher = NotificationFetcher(data_manager, gui)
65
+
66
+ logger.info(f"Starting i3-notifier.")
67
+ try:
68
+ GLib.MainLoop().run()
69
+ except:
70
+ logger.info("Exiting Glib.MainLoop")
71
+ data_manager.dump()
72
+ finally:
73
+ if os.path.exists(pid_file):
74
+ os.remove(pid_file)
75
+
76
+ if nodaemon:
77
+ run()
78
+ else:
79
+ with daemon.DaemonContext(
80
+ pidfile=daemon.pidfile.PIDLockFile(pid_file),
81
+ signal_map={signal.SIGTERM: dump_and_exit},
82
+ files_preserve=files_preserve,
83
+ ):
84
+ run()
85
+
86
+
87
+ def main():
88
+ parser = argparse.ArgumentParser(description="i3-notifier daemon")
89
+ parser.add_argument(
90
+ "--debug",
91
+ action="store_true",
92
+ help="Enable debug logging. Logs will be written to /tmp/i3-notifier.log.",
93
+ )
94
+ parser.add_argument(
95
+ "--config",
96
+ "-c",
97
+ help="Path to custom user configuration file. Defaults to $XDG_CONFIG_HOME/i3/i3_notifier_config.py or ~/.config/i3/i3_notifier_config.py if not specified.",
98
+ )
99
+ parser.add_argument(
100
+ "--nodaemon",
101
+ action="store_true",
102
+ help="Run in the foreground instead of as a daemon.",
103
+ )
104
+ parser.add_argument(
105
+ "--dump",
106
+ action="store_true",
107
+ help="Command the running daemon to dump notifications to file and exit.",
108
+ )
109
+ parser.add_argument(
110
+ "--kill",
111
+ action="store_true",
112
+ help="Kill the running daemon instance and exit.",
113
+ )
114
+ args = parser.parse_args()
115
+
116
+ if args.dump:
117
+ bus = dbus.SessionBus()
118
+ try:
119
+ obj = bus.get_object(
120
+ "org.freedesktop.Notifications", "/org/freedesktop/Notifications"
121
+ )
122
+ obj.DumpNotifications(dbus_interface="org.freedesktop.Notifications")
123
+ print("Notifications dumped to /tmp/i3-notifier.dump")
124
+ sys.exit(0)
125
+ except dbus.exceptions.DBusException as e:
126
+ print(f"Error communicating with daemon: {e}", file=sys.stderr)
127
+ sys.exit(1)
128
+
129
+ if args.kill:
130
+ pid_file = "/tmp/i3-notifier.pid"
131
+ if os.path.exists(pid_file):
132
+ try:
133
+ with open(pid_file) as f:
134
+ pid = int(f.read().strip())
135
+ os.kill(pid, signal.SIGTERM)
136
+ print(f"Sent SIGTERM to process {pid}")
137
+ sys.exit(0)
138
+ except ProcessLookupError:
139
+ print(f"Process {pid} not found. Cleaning up pid file.")
140
+ os.remove(pid_file)
141
+ sys.exit(0)
142
+ except Exception as e:
143
+ print(f"Error killing process: {e}", file=sys.stderr)
144
+ sys.exit(1)
145
+ else:
146
+ print("i3-notifier is not running (pid file not found).")
147
+ sys.exit(0)
148
+
149
+ global files_preserve
150
+
151
+ if args.debug:
152
+ if args.nodaemon:
153
+ handler = logging.StreamHandler(sys.stderr)
154
+ else:
155
+ handler = logging.FileHandler("/tmp/i3-notifier.log", "w")
156
+ files_preserve.append(handler.stream.fileno())
157
+
158
+ handler.setFormatter(
159
+ logging.Formatter(
160
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
161
+ )
162
+ )
163
+ logger.addHandler(handler)
164
+ logger.setLevel(logging.INFO)
165
+
166
+ run_daemon(config_path=args.config, nodaemon=args.nodaemon)
167
+
168
+
169
+ if __name__ == "__main__":
170
+ main()