forked from evsahal/TaskEX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
480 lines (384 loc) · 15.8 KB
/
Copy pathmain.py
File metadata and controls
480 lines (384 loc) · 15.8 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import os
import sys
import threading
import re
import io
import logging
import argparse
import shutil
from datetime import datetime
from pathlib import Path
from typing import Optional, List
from config.settings import get_debug_mode
def _is_cli_invocation(argv: list[str]) -> bool:
cli_flags = {"--list-instances", "--start-instance", "--stop-instance"}
return any(arg in cli_flags for arg in argv)
def _enforce_qt_imageio_suppression():
"""
Ensure noisy Qt/libpng image warnings are always suppressed, including debug mode.
"""
try:
existing_rules = os.environ.get("QT_LOGGING_RULES", "").strip()
required_rule = "qt.gui.imageio.warning=false"
if not existing_rules:
os.environ["QT_LOGGING_RULES"] = required_rule
return
tokens = [token.strip() for token in existing_rules.split(";") if token.strip()]
has_required_rule = any(token.lower() == required_rule for token in tokens)
if not has_required_rule:
tokens.append(required_rule)
os.environ["QT_LOGGING_RULES"] = ";".join(tokens)
except Exception:
pass
def _install_stderr_filter():
"""
Filter noisy native stderr lines (e.g. libpng sBIT warnings) while preserving all other output.
"""
try:
stderr_fd = sys.__stderr__.fileno()
saved_stderr_fd = os.dup(stderr_fd)
read_fd, write_fd = os.pipe()
os.dup2(write_fd, stderr_fd)
os.close(write_fd)
patterns = (
"libpng warning: sBIT: invalid",
"qt.gui.imageio: libpng warning: sBIT: invalid",
"libpng warning: sBIT: bad length",
"qt.gui.imageio: libpng warning: sBIT: bad length",
)
def _forward_stderr():
buffer = ""
with os.fdopen(read_fd, "rb", closefd=True) as reader, os.fdopen(saved_stderr_fd, "wb", closefd=True) as writer:
while True:
chunk = reader.read(4096)
if not chunk:
break
buffer += chunk.decode("utf-8", errors="replace")
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
if any(pattern in line for pattern in patterns):
continue
writer.write((line + "\n").encode("utf-8", errors="replace"))
writer.flush()
if buffer and not any(pattern in buffer for pattern in patterns):
writer.write(buffer.encode("utf-8", errors="replace"))
writer.flush()
threading.Thread(target=_forward_stderr, daemon=True).start()
except Exception:
pass
def _install_stdout_filter(aggressive: bool = False):
"""
Filter stdout noise.
- Always suppresses known libpng sBIT warnings.
- In aggressive mode (non-debug), only forwards likely error lines.
"""
try:
stdout_fd = sys.__stdout__.fileno()
saved_stdout_fd = os.dup(stdout_fd)
read_fd, write_fd = os.pipe()
os.dup2(write_fd, stdout_fd)
os.close(write_fd)
passthrough_regex = re.compile(r"error|exception|traceback|critical|failed", re.IGNORECASE)
drop_patterns = (
"libpng warning: sBIT: invalid",
"qt.gui.imageio: libpng warning: sBIT: invalid",
"libpng warning: sBIT: bad length",
"qt.gui.imageio: libpng warning: sBIT: bad length",
)
def _forward_stdout():
buffer = ""
with os.fdopen(read_fd, "rb", closefd=True) as reader, os.fdopen(saved_stdout_fd, "wb", closefd=True) as writer:
while True:
chunk = reader.read(4096)
if not chunk:
break
buffer += chunk.decode("utf-8", errors="replace")
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
if any(pattern in line for pattern in drop_patterns):
continue
if not aggressive:
writer.write((line + "\n").encode("utf-8", errors="replace"))
writer.flush()
continue
if passthrough_regex.search(line):
writer.write((line + "\n").encode("utf-8", errors="replace"))
writer.flush()
if buffer and not any(pattern in buffer for pattern in drop_patterns):
if not aggressive or passthrough_regex.search(buffer):
writer.write(buffer.encode("utf-8", errors="replace"))
writer.flush()
threading.Thread(target=_forward_stdout, daemon=True).start()
except Exception:
pass
def _runtime_base_dir() -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent
def _clear_runtime_temp_dirs(logger: Optional[logging.Logger] = None):
"""
Clear app temp folders on GUI startup.
In dev this is typically <project_root>/temp.
In frozen builds this is typically <exe_dir>/temp.
Also clear the current working directory temp folder when it differs,
since debug captures are written using relative "temp/..." paths.
"""
temp_dirs = []
runtime_temp = (_runtime_base_dir() / "temp").resolve()
temp_dirs.append(runtime_temp)
try:
cwd_temp = (Path.cwd() / "temp").resolve()
if cwd_temp not in temp_dirs:
temp_dirs.append(cwd_temp)
except Exception:
pass
for temp_dir in temp_dirs:
try:
if not temp_dir.exists():
temp_dir.mkdir(parents=True, exist_ok=True)
continue
for child in temp_dir.iterdir():
if child.is_dir():
shutil.rmtree(child, ignore_errors=False)
else:
child.unlink(missing_ok=True)
if logger is not None:
logger.info("Cleared temp directory: %s", temp_dir)
except Exception as exc:
if logger is not None:
logger.warning("Failed to clear temp directory '%s': %s", temp_dir, exc)
def _clear_runtime_log_dirs(logger: Optional[logging.Logger] = None):
"""
Clear app logs folders on GUI startup.
In dev this is typically <project_root>/logs.
In frozen builds this is typically <exe_dir>/logs.
Also clear the current working directory logs folder when it differs.
"""
log_dirs = []
runtime_logs = (_runtime_base_dir() / "logs").resolve()
log_dirs.append(runtime_logs)
try:
cwd_logs = (Path.cwd() / "logs").resolve()
if cwd_logs not in log_dirs:
log_dirs.append(cwd_logs)
except Exception:
pass
for log_dir in log_dirs:
try:
if not log_dir.exists():
log_dir.mkdir(parents=True, exist_ok=True)
continue
for child in log_dir.iterdir():
if child.is_dir():
shutil.rmtree(child, ignore_errors=False)
else:
child.unlink(missing_ok=True)
if logger is not None:
logger.info("Cleared logs directory: %s", log_dir)
except Exception as exc:
if logger is not None:
logger.warning("Failed to clear logs directory '%s': %s", log_dir, exc)
def _clear_runtime_dev_pngs(logger: Optional[logging.Logger] = None):
"""
Clear PNG debug captures from _dev on GUI startup.
Targets only top-level PNG files inside _dev (non-recursive), both in:
- runtime base directory
- current working directory (when different)
"""
dev_dirs = []
runtime_dev = (_runtime_base_dir() / "_dev").resolve()
dev_dirs.append(runtime_dev)
try:
cwd_dev = (Path.cwd() / "_dev").resolve()
if cwd_dev not in dev_dirs:
dev_dirs.append(cwd_dev)
except Exception:
pass
for dev_dir in dev_dirs:
try:
if not dev_dir.exists() or not dev_dir.is_dir():
continue
removed = 0
for child in dev_dir.iterdir():
if child.is_file() and child.suffix.lower() == ".png":
child.unlink(missing_ok=True)
removed += 1
if logger is not None:
logger.info("Cleared %d PNG file(s) from _dev directory: %s", removed, dev_dir)
except Exception as exc:
if logger is not None:
logger.warning("Failed to clear _dev PNGs in '%s': %s", dev_dir, exc)
class _StreamTee(io.TextIOBase):
def __init__(self, original_stream, log_stream):
self.original_stream = original_stream
self.log_stream = log_stream
def write(self, message):
try:
self.original_stream.write(message)
except Exception:
pass
try:
self.log_stream.write(message)
self.log_stream.flush()
except Exception:
pass
return len(message)
def flush(self):
try:
self.original_stream.flush()
except Exception:
pass
try:
self.log_stream.flush()
except Exception:
pass
def _setup_runtime_logging():
logger = logging.getLogger("taskex_boot")
logger.setLevel(logging.DEBUG)
if not logger.handlers:
logger.addHandler(logging.NullHandler())
log_file = None
if get_debug_mode():
base_dir = _runtime_base_dir()
logs_dir = base_dir / "logs"
logs_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = logs_dir / f"taskex_runtime_{timestamp}.log"
file_handler = logging.FileHandler(log_file, encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
logger.addHandler(file_handler)
should_tee_streams = getattr(sys, "frozen", False) or os.environ.get("TASKEX_LIVE_LOG", "0") == "1"
if should_tee_streams:
log_stream = open(log_file, "a", encoding="utf-8", buffering=1)
sys.stdout = _StreamTee(sys.stdout, log_stream)
sys.stderr = _StreamTee(sys.stderr, log_stream)
def _handle_uncaught_exception(exc_type, exc_value, exc_traceback):
logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
try:
sys.__excepthook__(exc_type, exc_value, exc_traceback)
except Exception:
pass
sys.excepthook = _handle_uncaught_exception
if log_file is not None:
logger.info("Runtime logging initialized: %s", log_file)
return logger, log_file
_enforce_qt_imageio_suppression()
if not _is_cli_invocation(sys.argv[1:]):
_install_stderr_filter()
_install_stdout_filter(aggressive=not get_debug_mode())
if not get_debug_mode():
os.environ.setdefault("OPENCV_LOG_LEVEL", "SILENT")
def _load_instances_from_db() -> List[dict]:
from db.db_setup import get_session, init_db
from db.models.instance import Instance
init_db()
session = get_session()
try:
rows = session.query(Instance).order_by(Instance.id.asc()).all()
return [
{
"id": row.id,
"name": (row.emulator_name or "").strip(),
"port": row.emulator_port,
"profile_id": row.profile_id,
}
for row in rows
]
finally:
session.close()
def _resolve_instance(identifier: str) -> Optional[dict]:
instances = _load_instances_from_db()
key = (identifier or "").strip()
if not key:
return None
numeric_value: Optional[int] = None
if key.isdigit():
numeric_value = int(key)
if numeric_value is not None:
by_id = next((item for item in instances if item["id"] == numeric_value), None)
if by_id:
return by_id
by_port = next((item for item in instances if item["port"] == numeric_value), None)
if by_port:
return by_port
key_lower = key.lower()
by_name_exact = next((item for item in instances if item["name"].lower() == key_lower), None)
if by_name_exact:
return by_name_exact
by_name_partial = [item for item in instances if key_lower in item["name"].lower()]
if len(by_name_partial) == 1:
return by_name_partial[0]
return None
def _cli_list_instances() -> int:
instances = _load_instances_from_db()
if not instances:
print("No registered instances found in database.")
return 0
print("Registered TaskEX instances:")
print("ID\tName\tPort\tProfile")
for item in instances:
print(f"{item['id']}\t{item['name'] or '-'}\t{item['port'] or '-'}\t{item['profile_id'] or '-'}")
return 0
def _cli_control_instance(identifier: str, start: bool) -> int:
from utils.adb_manager import ADBManager
instance = _resolve_instance(identifier)
if not instance:
print(f"Instance not found for identifier: {identifier}")
print("Use --list-instances to see valid names, ids, and ports.")
return 2
port = instance.get("port")
if not port:
print(f"Instance '{instance.get('name') or instance.get('id')}' has no port configured.")
return 2
try:
ADBManager.initialize_adb()
manager = ADBManager(str(port))
if not manager.device:
print(f"Could not connect to emulator on port {port}.")
return 3
manager.launch_evony(start=start)
state = "started" if start else "stopped"
print(f"Evony {state} on instance '{instance.get('name') or instance.get('id')}' (port {port}).")
return 0
except Exception as exc:
print(f"Failed to control instance '{identifier}': {exc}")
return 4
def _run_cli_if_requested(argv: List[str]) -> Optional[int]:
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument("--list-instances", action="store_true", help="List registered emulator instances from DB")
parser.add_argument("--start-instance", type=str, help="Start Evony on instance by id, name, or port")
parser.add_argument("--stop-instance", type=str, help="Stop Evony on instance by id, name, or port")
args, _unknown = parser.parse_known_args(argv)
if args.list_instances:
return _cli_list_instances()
if args.start_instance and args.stop_instance:
print("Use either --start-instance or --stop-instance, not both.")
return 2
if args.start_instance:
return _cli_control_instance(args.start_instance, start=True)
if args.stop_instance:
return _cli_control_instance(args.stop_instance, start=False)
return None
if __name__ == "__main__":
cli_exit_code = _run_cli_if_requested(sys.argv[1:])
if cli_exit_code is not None:
sys.exit(cli_exit_code)
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QIcon
from core.main_window import MainWindow
from core.splash_screen import SplashScreen
_clear_runtime_temp_dirs()
_clear_runtime_log_dirs()
if not getattr(sys, "frozen", False):
_clear_runtime_dev_pngs()
runtime_logger, runtime_log_file = _setup_runtime_logging()
runtime_logger.info("Starting TaskEnforcerX")
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("icon.ico"))
splash = SplashScreen() # Create and show the splash screen
window = MainWindow(splash) # Pass the splash screen instance to the main window
splash.show() # Ensure the splash screen is on top during initialization
if runtime_log_file is not None:
runtime_logger.info("Splash shown; runtime log: %s", runtime_log_file)
sys.exit(app.exec())