-
Notifications
You must be signed in to change notification settings - Fork 0
/
progress.py
executable file
·325 lines (262 loc) · 10.5 KB
/
progress.py
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
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QLabel,
QProgressBar,
QWidget,
QVBoxLayout,
)
from PySide6.QtCore import QTimer, Qt
from PySide6.QtGui import QColor, QIcon
from PySide6 import QtSvg # without this import, the icons won't show up
import random
import colorsys
import time
import os
import sys
import signal
import darkdetect
import argparse
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.dirname(os.path.realpath(__file__))
result = os.path.join(base_path, relative_path)
assert os.path.exists(result), f"File not found: {result}"
return result
# Load funny messages from a file
with open(resource_path("messages.txt"), "r") as f:
messages = [line.strip() for line in f.readlines()]
# filter out empty lines
messages = list(filter(None, messages))
def random_position_on_screen(edge_buffer=300):
"""Return a random position on the screen for a window."""
screen = QApplication.primaryScreen().availableGeometry()
x = random.randint(edge_buffer, screen.width() - edge_buffer)
y = random.randint(edge_buffer, screen.height() - edge_buffer)
return x, y
def make_rainbow(speed):
"""Create a function that generates smooth rainbow colors based on time and speed."""
def rainbow():
"""Return the current color in the rainbow."""
now = time.time()
hue = (now * speed) % 1.0
r, g, b = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
r, g, b = int(r * 255), int(g * 255), int(b * 255)
return QColor(r, g, b)
return rainbow
debug_windows = []
def set_window_icon(window):
# set icon to infinity symbol depending on the theme
if darkdetect.isDark():
icon_path = resource_path("icon_dark.svg")
else:
icon_path = resource_path("icon_light.svg")
window.setWindowIcon(QIcon(icon_path))
class MovingProgressBar(QMainWindow):
def __init__(self, movement_speed, initial_position, initial_direction):
super().__init__()
self.setWindowTitle("Loading...")
self.message = random.choice(messages)
set_window_icon(self)
self.progress_bar = QProgressBar()
self.progress_bar.setMaximum(random.randint(100, 1000))
self.set_stylesheet(QColor(255, 255, 255))
self.label = QLabel(self.message)
self.label.setStyleSheet("font-size: 50px;")
layout = QVBoxLayout()
layout.addWidget(self.progress_bar)
layout.addWidget(self.label)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.rainbow = make_rainbow(random.uniform(0.5, 2.0))
self.movement_speed = movement_speed
self.direction = initial_direction
initial_position = self.clip_to_screen(initial_position)
self.setGeometry(*initial_position, 300, 100)
self.timer_move_window = QTimer(self)
self.timer_move_window.timeout.connect(self.move_window_func)
self.timer_move_window.setInterval(10)
self.timer_move_window.start()
self.timer_progress = QTimer(self)
self.timer_progress.timeout.connect(self.progress_func)
self.timer_progress.start(self.get_progress_interval())
self.timer_rainbow = QTimer(self)
self.timer_rainbow.timeout.connect(self.rainbow_func)
self.corner_hit = 0
self.last_corner = None
windows.append(self)
def set_stylesheet(self, background_color):
"""Set the stylesheet of the progress bar."""
if background_color == QColor(255, 255, 255):
text_color = QColor(255 // 2, 255 // 2, 255 // 2)
else:
if background_color.lightnessF() > 0.5:
text_color = QColor(0, 0, 0)
else:
text_color = QColor(255, 255, 255)
self.progress_bar.setStyleSheet(
f"QProgressBar::chunk {{ background-color: {background_color.name()}; }} QProgressBar {{ color: {text_color.name()}; }}"
)
def destroy(self, destroyWindow: bool = ..., destroySubWindows: bool = ...):
# stop timers
self.timer_move_window.stop()
self.timer_progress.stop()
self.timer_rainbow.stop()
# remove from list of windows
windows.remove(self)
return super().destroy(destroyWindow, destroySubWindows)
def is_at_corner(self, tolerance=10):
"""Return True if the window is at a corner."""
screen = QApplication.primaryScreen().availableGeometry()
screen_width, screen_height = screen.width(), screen.height()
window_width, window_height = (
self.frameGeometry().width(),
self.frameGeometry().height(),
)
x, y = self.x(), self.y()
top_left = x <= tolerance and y <= tolerance
top_right = x >= screen_width - window_width - tolerance and y <= tolerance
bottom_left = x <= tolerance and y >= screen_height - window_height - tolerance
bottom_right = (
x >= screen_width - window_width - tolerance
and y >= screen_height - window_height - tolerance
)
corner_index = (
[top_left, top_right, bottom_left, bottom_right].index(True)
if any([top_left, top_right, bottom_left, bottom_right])
else None
)
if corner_index is not None and corner_index != self.last_corner:
self.last_corner = corner_index
self.corner_hit += 1
return True
return False
def clip_to_screen(self, position):
"""Clip a position to the screen."""
screen = QApplication.primaryScreen().availableGeometry()
x, y = position
x = max(0, min(x, screen.width() - self.frameGeometry().width()))
y = max(0, min(y, screen.height() - self.frameGeometry().height()))
return x, y
def get_progress_interval(self):
return random.uniform(10, 100)
def rainbow_func(self):
"""Set the color of the progress bar."""
self.set_stylesheet(self.rainbow())
# restart the timer
self.timer_rainbow.start(10)
def progress_func(self):
"""Update the progress bar."""
progress = self.progress_bar.value()
if progress >= self.progress_bar.maximum():
self.timer_progress.stop()
if not self.corner_hit:
# destroy the window
self.close()
else:
# wait a few seconds before destroying the window
QTimer.singleShot(3000, self.close)
return
self.progress_bar.setValue(progress + random.randint(0, 5))
# restart the timer
self.timer_progress.start(self.get_progress_interval())
def move_window_func(self):
x, y = self.x(), self.y()
dx, dy = self.direction
window_width, window_height = (
self.frameGeometry().width(),
self.frameGeometry().height(),
)
screen_width, screen_height = (
QApplication.primaryScreen().availableGeometry().width(),
QApplication.primaryScreen().availableGeometry().height(),
)
# update corner hit
if self.is_at_corner():
# increase speed
self.movement_speed *= 2
self.timer_rainbow.start()
if x + dx <= 0 or x + dx >= screen_width - window_width:
dx = -dx
if y + dy <= 0 or y + dy >= screen_height - window_height:
dy = -dy
x += dx * self.movement_speed
y += dy * self.movement_speed
self.direction = (dx, dy)
x, y = self.clip_to_screen((x, y))
self.move(x, y)
windows = []
def create_moving_progress_bar():
initial_position = random_position_on_screen()
initial_direction = (random.uniform(3, 6), random.uniform(3, 6))
# randomly invert either the x or y direction
if random.choice([True, False]):
initial_direction = (-initial_direction[0], initial_direction[1])
if random.choice([True, False]):
initial_direction = (initial_direction[0], -initial_direction[1])
movement_speed = random.uniform(0.5, 1.0)
new_win = MovingProgressBar(movement_speed, initial_position, initial_direction)
if app.activeWindow() is None:
new_win.setAttribute(Qt.WA_ShowWithoutActivating)
new_win.show()
app = None
class MadnessAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(MadnessAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if values.lower() == "true":
setattr(namespace, self.dest, True)
elif values.lower() == "false":
setattr(namespace, self.dest, False)
else:
try:
val = int(values)
except ValueError:
raise argparse.ArgumentTypeError(
f"Invalid value '{values}' for --madness"
)
if val < 0:
raise argparse.ArgumentTypeError(
f"Invalid value '{values}' for --madness"
)
setattr(namespace, self.dest, val)
if __name__ == "__main__":
# print pid
print("Loading...")
print("kill -9 " + str(os.getpid()))
# parse madness flag
parser = argparse.ArgumentParser()
parser.add_argument(
"--madness", action=MadnessAction, help="Enable madness (integer or boolean)"
)
args = parser.parse_args()
# print(args.madness)
new_progress_bar_interval = 2000
if args.madness is not None:
if args.madness is bool:
if args.madness:
new_progress_bar_interval = 500
else:
new_progress_bar_interval = args.madness
# Fix taskbar icon on Windows
if os.name == "nt":
import ctypes
myappid = "progress.progress_py.1.0.0"
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
app = QApplication([])
app.setQuitOnLastWindowClosed(False)
set_window_icon(app)
create_moving_progress_bar()
timer = QTimer()
timer.timeout.connect(create_moving_progress_bar)
timer.setInterval(new_progress_bar_interval)
timer.start()
signal.signal(signal.SIGINT, lambda *args: app.quit())
sys.exit(app.exec())