-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
279 lines (225 loc) · 9.23 KB
/
main.py
File metadata and controls
279 lines (225 loc) · 9.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/python3 -u
"""
Description: Loads the config and spawns the bar
Author: thnikk
"""
import os
import sys
import argparse
import logging
import version
def parse_args():
""" Parse arguments """
parser = argparse.ArgumentParser(exit_on_error=False)
parser.add_argument('-C', '--config', type=str, default='~/.config/pybar',
help="Configuration path")
parser.add_argument('-n', '--new', action='store_true',
help="Allow multiple instances")
parser.add_argument('-r', '--replace', action='store_true',
help="Replace existing instance")
parser.add_argument('-s', '--settings', action='store_true',
help="Launch settings window")
parser.add_argument('-l', '--log-level', type=str, default='WARNING',
choices=[
'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help="Set the application logging level")
parser.add_argument('-g', '--gtk-log-level', type=str, default='WARNING',
choices=[
'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help="Set the GTK/GLib logging level")
parser.add_argument('-d', '--debug', action='store_true',
help="Enable debug mode "
"(enables inspector and screenshots)")
parser.add_argument('--clear-cache', action='store_true',
help="Clear cache directory contents on startup")
parser.add_argument('-v', '--version', action='version',
version='%(prog)s ' + version.get_version())
args, unknown = parser.parse_known_args()
return args
# Parse early to set environment variables and log level
args = parse_args()
# Reap child processes automatically so they never linger as zombies.
# This covers both children inherited from a previous execv-based reload
# and any that exit later during normal operation (e.g. nvtop, nmcli).
import signal as _signal
def _reap_children(signum, frame):
"""SIGCHLD handler: reap all exited children without blocking."""
try:
while True:
pid, _ = os.waitpid(-1, os.WNOHANG)
if pid == 0:
break
except ChildProcessError:
pass
_signal.signal(_signal.SIGCHLD, _reap_children)
# Do an initial reap pass for any children already waiting.
_reap_children(None, None)
# Set GTK debug env var if GTK debug is requested
if args.gtk_log_level.upper() == 'DEBUG':
os.environ['G_MESSAGES_DEBUG'] = 'all'
# Prefer the NGL (OpenGL) renderer over Vulkan. GTK4 defaults to Vulkan
# on Wayland, but after a prolonged display blank the compositor tears
# down its render pipeline, leaving Vulkan with no valid surface
# (VK_ERROR_SURFACE_LOST_KHR). The NGL renderer uses EGL and survives
# display blank/unblank cycles without errors.
os.environ.setdefault('GSK_RENDERER', 'gl')
from ctypes import CDLL
try:
CDLL('libgtk4-layer-shell.so')
except Exception:
pass
import threading
import traceback
import config as Config
from bar import Display
import common as c
import module
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Gtk4LayerShell', '1.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Gio, Adw, GLib # noqa
class StreamToLogger:
""" Redirect a stream (stdout/stderr) to a logger """
def __init__(self, logger, log_level, stream):
self.logger = logger
self.log_level = log_level
self.stream = stream
def write(self, buf):
if buf.strip():
for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip())
self.stream.write(buf)
def flush(self):
self.stream.flush()
def setup_logging(app_level=logging.WARNING, gtk_level=logging.WARNING):
""" Setup logging to file and stderr """
log_dir = os.path.expanduser('~/.cache/pybar')
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = os.path.join(log_dir, 'pybar.log')
# Root level must be the minimum to catch all requested logs
root_level = min(app_level, gtk_level)
# Configure logging
logging.basicConfig(
level=root_level,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
handlers=[
logging.FileHandler(log_file, mode='w'),
logging.StreamHandler(sys.stderr)
]
)
# Redirect stdout and stderr to logger
stdout_logger = logging.getLogger('STDOUT')
stderr_logger = logging.getLogger('STDERR')
stdout_logger.setLevel(app_level)
stderr_logger.setLevel(app_level)
sys.stdout = StreamToLogger(stdout_logger, logging.INFO, sys.stdout)
sys.stderr = StreamToLogger(stderr_logger, logging.ERROR, sys.stderr)
# Set default level for all app loggers (those not starting with GLib domains)
# This is a bit tricky with basicConfig, but we can set the levels of specific loggers later
# For now, we'll rely on the fact that most modules use their own names.
# Suppress verbose connection pool logging
logging.getLogger("urllib3").setLevel(logging.WARNING)
# Redirect GLib/GTK logs to Python logging
def glib_log_handler(domain, level, message, user_data):
levels = {
GLib.LogLevelFlags.LEVEL_DEBUG: logging.DEBUG,
GLib.LogLevelFlags.LEVEL_INFO: logging.INFO,
GLib.LogLevelFlags.LEVEL_MESSAGE: logging.INFO,
GLib.LogLevelFlags.LEVEL_WARNING: logging.WARNING,
GLib.LogLevelFlags.LEVEL_CRITICAL: logging.ERROR,
GLib.LogLevelFlags.LEVEL_ERROR: logging.CRITICAL,
}
py_level = levels.get(level & GLib.LogLevelFlags.LEVEL_MASK, logging.INFO)
# Only log if it meets the gtk_level requirement
if py_level >= gtk_level:
logging.getLogger(domain or "GLib").log(py_level, message)
# Connect the handler for common GTK/GLib domains
for domain in [None, "Gtk", "Gdk", "GLib", "Gio", "Adw"]:
GLib.log_set_handler(domain, GLib.LogLevelFlags.LEVEL_MASK | GLib.LogLevelFlags.FLAG_FATAL | GLib.LogLevelFlags.FLAG_RECURSION, glib_log_handler, None)
return log_file
def on_activate(app, config):
if hasattr(app, 'started') and app.started:
return
app.started = True
# Hold application to prevent exit when no monitors are connected
app.hold()
# Get a set of all used modules
unique = set(
config['modules-left'] +
config['modules-center'] +
config['modules-right']
)
# Start module threads
for name in unique:
# Load the module config if it exists
module_config = config['modules'].get(name, {})
# Start the worker thread for this module
module.start_worker(name, module_config)
try:
app.display = Display(config, app)
# Draw all bars
app.display.draw_all()
except Exception:
logging.error("Failed to activate application", exc_info=True)
sys.exit(1)
def clear_cache(cache_path):
""" Remove cache directory contents, preserving the log file """
import shutil
cache_path = os.path.expanduser(cache_path)
if not os.path.exists(cache_path):
return
for entry in os.scandir(cache_path):
if entry.name == 'pybar.log':
continue
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.path)
else:
os.remove(entry.path)
def launch_settings(config_path):
"""Launch settings window"""
from settings.window import SettingsApplication
app = SettingsApplication(config_path)
app.run([])
def main():
""" Main function """
# Handle settings mode
if args.settings:
launch_settings(os.path.expanduser(args.config))
return
# log_level was parsed early
app_log_level = getattr(logging, args.log_level.upper(), logging.WARNING)
gtk_log_level = getattr(logging, args.gtk_log_level.upper(), logging.WARNING)
# Clear cache before logging so the log starts fresh this session
if args.clear_cache:
clear_cache('~/.cache/pybar')
log_file = setup_logging(app_log_level, gtk_log_level)
logging.info(f"Starting pybar, logging to {log_file}")
# Register bundled fonts
fonts_dir = c.get_resource_path('fonts')
if os.path.exists(fonts_dir):
c.register_fonts(fonts_dir)
config = Config.load(args.config)
c.state_manager.update('config', config)
c.state_manager.update('config_path', args.config)
c.state_manager.update('debug', args.debug)
# Set the cache directory if it's not specified in the config
if "cache" not in list(config):
config["cache"] = '~/.cache/pybar'
# Create display object
flags = Gio.ApplicationFlags.ALLOW_REPLACEMENT
if args.new:
flags |= Gio.ApplicationFlags.NON_UNIQUE
if args.replace:
flags |= Gio.ApplicationFlags.REPLACE
app = Gtk.Application(
application_id='org.thnikk.pybar',
flags=flags
)
app.config_path = args.config # Store config path for settings window
app.connect('activate', lambda app: on_activate(app, config))
# Use an empty list for argv to prevent GTK from parsing custom args
app.run([])
if __name__ == "__main__":
main()