-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
352 lines (347 loc) · 11.6 KB
/
run.py
File metadata and controls
352 lines (347 loc) · 11.6 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import tkinter as tk
from tkinter import ttk
import screeninfo
import subprocess
import threading
from datetime import datetime
import atexit
import traceback
import re,time,sys
from src.functions import *
#--
#
kosdwm = None
VERSION = "0.1b"
#--
#
#
def cleanup():
print("cleanup() START")
kos.wmctrltray.on_close()
return True
#
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
# Let KeyboardInterrupt propagate
print("Exception: Keyboard Interrupt: {}".format(exc_type),{'verbose':True})
return
# Extract traceback info
tb = traceback.extract_tb(exc_traceback)
# Get the last frame (most recent error)
frame = tb[-1]
filename, line, func, text = frame
print(f"Exception: {exc_type.__name__}: {exc_value} (line {line} in {filename})",{'verbose':True,})
# Optionally print full traceback
traceback.print_exception(exc_type, exc_value, exc_traceback)
#
atexit.register(cleanup)
sys.excepthook = handle_exception
#--
#
class WMCtrlTray:
def __init__(self, root):
self.windows = {} # w0={id=0,name='',host='',class='',hash='crc32b'}
self.lines = [] # wmctrl output
self.windows_hash = None # concat all lines of wmctrl -l into one and create crc32b
self.stop_thread = False
self.root = root
# Get the primary monitor's dimensions
self.screen = screeninfo.get_monitors()[0]
screen_width = self.screen.width
screen_height = self.screen.height
# Set the window to span the full width of the screen at the top
self.root.geometry(f"{screen_width}x25+0+0")
# Remove the title bar and window decorations
self.root.overrideredirect(True)
# Make the window stay on top of other windows
self.root.attributes("-topmost", True)
#
#
def test_new_file():
print("test new file!")
#menu_bar = tk.Menu(self.root,tearoff=0)
#file_menu = tk.Menu(menu_bar, tearoff=0)
#file_menu.add_command(label="New", command=test_new_file)
#menu_bar.add_cascade(label="Test",menu=file_menu)
#self.root.config(menu=menu_bar)
self.title_bar = tk.Frame(self.root, bg='gray', height=30,relief='raised',bd=1)
#self.title_bar.pack(fill=tk.X, padx=(20,self.screen.width/2), pady=(0,0), ipady=5, side=tk.TOP)
self.title_bar.pack(fill=tk.X)
# Make the window draggable by the title bar
self.title_bar.bind("<ButtonPress-1>", self.start_move)
self.title_bar.bind("<B1-Motion>", self.on_motion)
# Store the position where the mouse was clicked
self._drag_data = {"x": 0, "y": 0, "drag": False}
# test another window
def test():
r1 = tk.Toplevel(self.root)
r1.title("World")
r1.geometry("300x200")
#menu_bar = tk.Menu(r1)
#file_menu = tk.Menu(r1, tearoff=0)
#file_menu.add_command(label="New", command=test_new_file)
#menu_bar.add_cascade(label="Test",menu=file_menu)
#r1.config(menu=menu_bar)
#self.root.after_idle(test)
#
self.create_widgets()
#
def start_observer_thread(self):
"""Start a thread to observe changes in window list"""
observer_thread = threading.Thread(target=self.observer_loop)
observer_thread.daemon = True
observer_thread.start()
#
def observer_loop(self):
"""Main loop for observing changes in window list"""
#last_windows = set()
#
while not self.stop_thread:
try:
self.lines = []
#
# xprop -root _NET_ACTIVE_WINDOW | awk '{print $5}'
result = subprocess.run(
["xprop", "-root", "_NET_ACTIVE_WINDOW"],
capture_output=True,
text=True,
check=True
)
print("active window by xprop: ",result.stdout.split(" ")[4])
# 0 - 9
# ID X PROC TOP LEFT WIDTH HEIGHT CLASS HOST PROG_INFO
# 0x0080000e 0 4026 468 341 898 446 xterm.UXTerm kosgen0 t3ch@kosgen2: ~/sdb1/t3ch
# 0x0140000a 0 11288 280 93 1086 692 geany.Geany kosgen0 *run.py - /home/t3ch/Working/Hobies/OpenBox/WindowsMenu - Geany
result = subprocess.run(
["wmctrl", "-lpGuFxS"],
capture_output=True,
text=True,
check=True
)
#
for line in result.stdout.splitlines():
line = re.sub(r'\s+',' ',line)
#print("debug line: ",line)
self.lines.append(line)
#
windows_hash = crc32b( "".join(self.lines) )
#
if self.windows_hash!=None and self.windows_hash==windows_hash:
print("Skipping update windows, windows_hash: {} vs {}".format( self.windows_hash, windows_hash ))
else:
print("Updating windows list, windows_hash {} vs {}".format( self.windows_hash, windows_hash ))
self.root.after(0, self.update_window_list)
self.windows_hash = windows_hash
time.sleep(10) # Check every second/s
except subprocess.CalledProcessError as e:
print(f"Error running wmctrl: {e}")
time.sleep(5) # Wait longer if there's an error
except Exception as e:
print(f"Unexpected error: {e}")
time.sleep(5) # Wait longer if there's an unexpected error
#
def update_window_list(self):
"""Update the dropdown menu with the current window list"""
print("update_window_list() START lines.len: {}, hash: {}".format( len(self.lines), self.windows_hash ))
#
def shorten_hex(hex_value):
"""Convert a hexadecimal value to its shortest representation."""
print(f"shorten_hex called with: {hex_value!r} (type: {type(hex_value)})") # Debug line
# Handle string inputs
if isinstance(hex_value, str):
# Remove '0x' prefix if present
if hex_value.startswith('0x'):
hex_value = hex_value[2:]
# Convert to integer
try:
hex_value = int(hex_value, 16)
except ValueError:
raise ValueError(f"Input string '{hex_value}' must be a valid hexadecimal number")
# Convert to hex string and remove leading zeros
hex_str = hex(hex_value)
return '0x' + hex_str[2:].lstrip('0') or '0x0'
#
try:
#
# self.windows = {} # w0={id=0,name='',host='',hash='crc32b'}
windows = []
lines = []
windows_hash = None
self.windows = {}
cnt=0
# 0 - 9
# ID X PID LEFT TOP WIDTH HEIGHT CLASS HOST PROG_INFO
# 0x0080000e 0 4026 468 341 898 446 xterm.UXTerm kosgen0 t3ch@kosgen2: ~/sdb1/t3ch
# 0x0140000a 0 11288 280 93 1086 692 geany.Geany kosgen0 *run.py - /home/t3ch/Working/Hobies/OpenBox/WindowsMenu - Geany
#
for line in reversed(self.lines):
a = line.split(" ",9)
print("a: ",a)
side_number = 1
if int(a[3])>=self.screen.width:
side_number = 2
windows.append("{} ) {}".format(side_number, a[9])) # prepare graphics dropdown with names only
print("{} debug line: {}".format( self.screen.width, line ))
fid = shorten_hex(a[0])
# save object so later is possible to access by selected item id
crc = crc32b( line )
wid = "w{}".format(cnt)
if wid in self.windows:
#
self.windows[wid]["id"] = a[0]
self.windows[wid]["fid"] = fid
self.windows[wid]["pid"] = a[2]
self.windows[wid]["class"] = a[7]
self.windows[wid]["host"] = a[8]
self.windows[wid]["name"] = a[9]
self.windows[wid]["hash"] = crc
else:
#
self.windows[wid] = {"id":a[0],"pid":a[2],"fid":fid,"class":a[7],"host":a[8],"name":a[9],}
cnt+=1
print("wid: {}".format( self.windows[wid] ))
#
self.window_combobox['values'] = windows
if windows:
self.window_combobox.current(0)
except subprocess.CalledProcessError as e:
print(f"Error running wmctrl: {e}")
self.window_combobox['values'] = ["Error getting window list"]
except FileNotFoundError:
self.window_combobox['values'] = ["wmctrl not found"]
return True
#
def start_time_thread(self):
"""Start a thread to update the time display"""
time_thread = threading.Thread(target=self.time_update_loop)
time_thread.daemon = True
time_thread.start()
#
def time_update_loop(self):
"""Main loop for updating the time display"""
while not self.stop_thread:
try:
# Update the time display on the main thread
self.root.after(0, self.update_time_display)
time.sleep(1) # Update every second
except Exception as e:
print(f"Error in time update loop: {e}")
time.sleep(5) # Wait longer if there's an error
#
def update_time_display(self):
"""Update the time and date display"""
now = datetime.now()
time_str = now.strftime("%H:%M:%S")
date_str = "{} |".format(now.strftime("%Y-%m-%d"))
# Update the time label if it exists
if hasattr(self, 'time_label'):
self.time_label.config(text=time_str)
else:
# Create the time label if it doesn't exist
self.time_label = tk.Label(
#self.title_bar,
self.time_frame,
text=time_str,
bg='gray',
fg='white',
font=('Arial', 10)
)
self.time_label.pack(side=tk.RIGHT, padx=0,pady=0,ipady=0)
# Update the date label if it exists
if hasattr(self, 'date_label'):
self.date_label.config(text=date_str)
else:
# Create the date label if it doesn't exist
self.date_label = tk.Label(
#self.title_bar,
self.time_frame,
text=date_str,
bg='gray',
fg='white',
font=('Arial', 10)
)
self.date_label.pack(side=tk.RIGHT, padx=0,pady=0,ipady=0)
#
def create_widgets(self):
"""Create the widgets for the window list"""
#
#self.window_frame = tk.Frame(self.title_bar,width=100)
self.window_frame = tk.Frame(self.title_bar)
self.window_frame.pack(fill=tk.BOTH, side=tk.LEFT, padx=(30))
# Create a Combobox for window selection
self.window_combobox = tk.ttk.Combobox(self.window_frame, state="readonly",width=60)
self.window_combobox.pack(fill=tk.X, padx=(0), pady=(0), ipady=5)
self.window_combobox.bind("<<ComboboxSelected>>", self.on_window_selected)
# Create a frame for the time/date display on the right side of the title bar
self.time_frame = tk.Frame(self.title_bar)
self.time_frame.pack(side=tk.RIGHT, padx=1, pady=0)
#
self.update_window_list()
#
self.start_observer_thread()
self.start_time_thread()
#
def on_window_selected(self, event):
"""Handle window selection and activate the selected window"""
selected_index = self.window_combobox.current() # Get the index of the selected item
selected_value = self.window_combobox.get() # Get the value of the selected item
wid="w{}".format(selected_index)
print("Debug windows wid: ",self.windows[wid])
# You can use either the index or the value to find and activate the window
self.activate_window(self.windows[wid]["id"])
#
def activate_window(self, wmctrlId):
"""Activate the selected window using its index"""
try:
print("activate_window() ",wmctrlId)
result = subprocess.run(
["wmctrl", "-i", "-a", wmctrlId],
capture_output=True,
text=True,
check=True
)
except subprocess.CalledProcessError as e:
print(f"Error activating window: {e}")
#-- MOVE TO TOP OF Window and stick
#
def start_move(self, event):
"""Begin the window movement"""
self._drag_data["x"] = event.x
self._drag_data["y"] = event.y
self._drag_data["drag"] = True
# Raise the window to the top
self.root.attributes("-topmost", True)
#
def on_motion(self, event):
"""Handle the window movement"""
if self._drag_data["drag"]:
# Calculate the new position
x = self.root.winfo_x() + (event.x - self._drag_data["x"])
y = self.root.winfo_y() + (event.y - self._drag_data["y"])
# Update the window position
self.root.geometry(f"+{x}+{y}")
#
def on_release(self, event):
"""End the window movement"""
self._drag_data["drag"] = False
#
def on_close(self):
"""Clean up when the application is closing"""
self.stop_thread = True
self.root.destroy()
#--
#
class KosDWM:
def __init__(self):
print("KosDWM().init() STARTED!")
self.root = tk.Tk()
self.wmctrltray = None
def Start(self):
print("KosDWM.Start() STARTED!")
self.wmctrltray = WMCtrlTray(self.root)
self.root.mainloop()
#--
#
if __name__ == "__main__":
kosdwm = KosDWM()
kosdwm.Start()