-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmainapp.py
More file actions
2135 lines (1756 loc) · 88.9 KB
/
mainapp.py
File metadata and controls
2135 lines (1756 loc) · 88.9 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
a: zak-45
d: 07/11/2025
v: 1.1.0
Overview:
This file, `mainapp.py`, is the central nervous system of the WLEDVideoSync application. It serves as the primary
entry point for the user interface, orchestrating all major components, including the web UI, the backend API,
and the core casting logic. It is built upon the NiceGUI framework, which seamlessly integrates a FastAPI web server.
The main responsibility of this file is to instantiate the core application objects, define the structure and routing
of the web pages, and manage the application's lifecycle from startup to shutdown.
Key Architectural Components:
1. **Core Object Instantiation**:
- At the top level, it creates singleton instances of the main casting classes (`Desktop`, `Media`) and the
network discovery utility (`Netdevice`).
- These objects hold the state and logic for their respective domains and are passed to other components,
acting as a form of dependency injection.
2. **UI Component Integration**:
- It instantiates the main UI components, such as `CastCenter`, `SchedulerGUI`, and `VideoPlayer`.
- It passes the core `Desktop` and `Media` objects to these UI components, allowing them to interact with and
control the application's state.
3. **API Integration (`ApiData`)**:
- It uses the `ApiData` class to provide the FastAPI endpoints (defined in `api.py`) with safe, controlled
access to the live `Desktop` and `Media` objects. This decouples the API logic from the main UI application.
4. **NiceGUI Page Routing (`@ui.page`)**:
- This file defines all the routes for the web application (e.g., `/`, `/Manage`, `/Desktop`, `/Media`).
- Each function decorated with `@ui.page` is responsible for building the content of a specific web page,
calling upon the various UI components and helper functions to do so.
5. **Application Lifecycle Management**:
- `init_actions()`: This `async` function is registered with `app.on_startup`. It handles all necessary
initialization tasks, such as creating the inter-process communication file, applying presets, and starting
the scheduler.
- `cleanup_on_shutdown()`: Registered with `app.on_shutdown`, this function ensures a graceful exit by stopping
all background threads, processes, and services (like the scheduler and `RUNColdtype` processes) before the
main application terminates.
6. **Global State Management (`CastAPI` class)**:
- The `CastAPI` class acts as a simple, global namespace for storing UI-related state that needs to be shared
across different pages and components. This includes things like the dark mode state, references to UI timers,
and the shared dictionary of live preview frames (`CastAPI.previews`).
7. **UI Timers (`ui.timer`)**:
- The application uses `ui.timer` to create background refresh loops (e.g., `root_timer_action`) that
periodically update the UI with the latest status from the casting threads, ensuring the interface remains
dynamic and responsive.
Design Philosophy:
- **Centralized Orchestration**: This file acts as the central "glue" that connects the backend logic, the API, and
the user interface.
- **Component-Based UI**: The UI is broken down into logical, reusable components (like `CastCenter` and `niceutils`)
that are assembled within the page functions.
- **Asynchronous by Default**: The extensive use of `async` functions ensures that the application remains responsive,
even when performing I/O-bound tasks like fetching data or updating the UI.
"""
import asyncio
import sys
if sys.platform == 'win32':
import winloop
import math
import pathlib
import shelve
import queue
import tkinter as tk
import webbrowser
from threading import current_thread
from datetime import datetime
from nicegui import ui, run
import psutil
from PIL import Image
from src.utl.utils import CastAPI
from src.utl.utils import check_server
from src.cst import desktop, media
from src.net.discover import HTTPDiscovery
from src.gui.niceutils import apply_custom, media_dev_view_page, discovery_net_notify, net_view_button
from src.gui.niceutils import LogElementHandler
from src.gui.niceutils import AnimatedElement as Animate
from src.gui import niceutils as nice
from src.gui.castcenter import CastCenter
from src.gui.schedulergui import SchedulerGUI
from src.txt.coldtypemp import RUNColdtype
from src.gui.pyeditor import PythonEditor
from src.gui.videoplayer import VideoPlayer
from src.utl.webviewmanager import WebviewManager
from src.gui.presets import *
from src.api.api import *
from configmanager import cfg_mgr, LoggerManager, PLATFORM, WLED_PID_TMP_FILE
logger_manager = LoggerManager(logger_name='WLEDLogger.main')
main_logger = logger_manager.logger
Desktop = desktop.CASTDesktop()
Media = media.CASTMedia()
Netdevice = HTTPDiscovery()
window_native = WebviewManager()
# to share data between threads and main
t_data_buffer = queue.Queue() # create a thread safe queue
"""
winloop
"""
def get_winloop_loop():
"""
Factory function for uvicorn to get a winloop event loop.
Windows:
There is a performance increase of about 5 times vs using the WindowsSelectorEventLoopPolicy and
WindowsProactorEventLoopPolicy which have been known to trigger ssl problems in python 3.9.
Winloop is a very good replacement for solving those ssl problems as well.
This library also has comparable performance to its brother uvloop
"""
# 1. Install winloop to patch the current process's event loop policy.
winloop.install()
# 2. Return a new event loop created by the now-patched policy.
return asyncio.new_event_loop()
"""
Define root page based on ini
"""
main_page_url = '/'
cast_center_url = '/Cast-Center'
if "NUITKA_ONEFILE_PARENT" not in os.environ and cfg_mgr.app_config is not None:
if cfg_mgr.app_config['init_screen'].lower() == 'center':
main_page_url = '/main'
cast_center_url = '/'
root_page = '/Cast-Center'
else:
root_page = '/'
"""
Actions to do at shutdown
"""
async def cleanup_on_shutdown():
"""A graceful shutdown function to prevent race conditions."""
#
# We do not want init execution when using command line arguments
#
if '--run-mobile-server' in sys.argv or '--run-sys-charts' in sys.argv:
return
main_logger.info(f"Initiating graceful shutdown for {__name__} with PID : {os.getpid()}")
# Add any other cleanup for child processes here in the future
Desktop.stopcast = True
Media.stopcast = True
# Timer
if CastAPI.root_timer is not None:
CastAPI.root_timer.cancel(with_current_invocation=True)
if CastAPI.player_timer is not None:
CastAPI.player_timer.cancel(with_current_invocation=True)
if CastAPI.info_timer is not None:
CastAPI.info_timer.cancel(with_current_invocation=True)
if center_app.cast_timer is not None:
center_app.cast_timer.cancel(with_current_invocation=True)
if 'scheduler_app' in globals() and scheduler_app.sched_timer is not None:
scheduler_app.sched_timer.cancel(with_current_invocation=True)
# Webview
window_native.close_all_webviews()
# Stop the scheduler and its worker threads
if 'scheduler_app' in globals() and scheduler_app.scheduler.is_running:
main_logger.info("Stopping scheduler...")
scheduler_app.capture.restore()
scheduler_app.scheduler.stop()
RUNColdtype.stop_all()
# Give a brief moment for processes to terminate
await asyncio.sleep(0.2)
"""
Actions to do at application initialization
"""
async def init_actions():
"""
Performs all necessary initialization tasks for the WLEDVideoSync application.
This function sets up the application's environment, applies configuration presets, initializes core resources,
and starts background services such as the scheduler. It is intended to be called at application startup.
Returns:
None
"""
#
# This is the definitive point of initialization for the temp file path.
# We update the global variable in the configmanager module so all other
# modules that import it will get the correct, process-specific path.
import configmanager
configmanager.WLED_PID_TMP_FILE = cfg_mgr.app_root_path(f"tmp/{cfg_mgr.pid}_file")
from configmanager import WLED_PID_TMP_FILE
#
# We do not want init execution when using command line arguments
#
if '--run-mobile-server' in sys.argv or '--run-sys-charts' in sys.argv:
return
# from WLEDVideoSync import check_server
server_ip = None
server_port = None
if "NUITKA_ONEFILE_PARENT" not in os.environ and cfg_mgr.server_config is not None:
server_ip, server_port = check_server()
if server_ip is None or server_port is None:
print('Exiting due to invalid server configuration.')
main_logger.error('Exiting due to invalid server configuration.')
main_logger.info('Application Terminated')
sys.exit(4)
# store server port info for others processes, add sc_area for macOS ...
# on python < 3.13 file extension will be .dat and added automatically otherwise none
with shelve.open(WLED_PID_TMP_FILE,writeback=True) as wled_proc_file:
wled_proc_file["server_port"] = server_port
wled_proc_file["media"] = None
wled_proc_file["all_hosts"] = []
# Main Event Loop
CastAPI.loop = asyncio.get_running_loop()
main_logger.debug('Running loop : {}'.format(CastAPI.loop))
# Initial, non-blocking call to psutil to establish a baseline for cpu_percent
psutil.cpu_percent(interval=None, percpu=False)
#
main_logger.info(f'Main running {current_thread().name}')
main_logger.info(f'Root page : {root_page}')
main_logger.info(f"Scheduler enabled : {cfg_mgr.scheduler_config['enable']}")
# Apply some default params only once
if not str2bool(cfg_mgr.app_config['init_config_done']):
def on_ok_click():
# Close the window when OK button is clicked
root.quit()
root.destroy()
# Create the main window
root = tk.Tk()
root.title("WLEDVideoSync Information")
root.geometry("820x460") # Set the size of the window
root.configure(bg='#657B83') # Set the background color
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'init_config_done', 'True')
# Define the window's contents
info_text = "Some Params has changed.... restart your app"
info_label = tk.Label(root, text=info_text, bg='#657B83', fg='white', justify=tk.LEFT)
info_label.pack(padx=10, pady=10)
# Create the OK button
ok_button = tk.Button(root, text="Ok", command=on_ok_click, bg='gray', fg='white')
ok_button.pack(pady=10)
root.protocol("WM_DELETE_WINDOW", on_ok_click)
# Start the Tkinter event loop
root.mainloop()
sys.exit(0)
try:
# Set Fonts path for app
if cfg_mgr.app_config['font_file'] != '':
font_dir = os.path.dirname(cfg_mgr.app_config['font_file'])
font_url = "/FontsPath"
app.add_static_files(font_url, font_dir)
# Apply presets
if str2bool(cfg_mgr.preset_config['load_at_start']):
if cfg_mgr.preset_config['filter_media'] != '':
main_logger.debug(f"apply : {cfg_mgr.preset_config['filter_media']} to filter Media")
await load_filter_preset('Media', Media, interactive=False, file_name=cfg_mgr.preset_config['filter_media'])
if cfg_mgr.preset_config['filter_desktop'] != '':
main_logger.debug(f"apply : {cfg_mgr.preset_config['filter_desktop']} to filter Desktop")
await load_filter_preset('Desktop', Desktop, interactive=False, file_name=cfg_mgr.preset_config['filter_desktop'])
if cfg_mgr.preset_config['cast_media'] != '':
main_logger.debug(f"apply : {cfg_mgr.preset_config['cast_media']} to cast Media")
await load_cast_preset('Media', Media, interactive=False, file_name=cfg_mgr.preset_config['cast_media'])
if cfg_mgr.preset_config['cast_desktop'] != '':
main_logger.debug(f"apply : {cfg_mgr.preset_config['cast_desktop']} to cast Desktop")
await load_cast_preset('Desktop', Desktop, interactive=False, file_name=cfg_mgr.preset_config['cast_desktop'])
# check if linux and wayland
if PLATFORM == 'linux' and os.getenv('WAYLAND_DISPLAY') is not None:
main_logger.error('Wayland detected, preview should not work !!. Switch to X11 session if want to see preview.')
# start scheduler
if str2bool(cfg_mgr.scheduler_config['enable']) and str2bool(cfg_mgr.scheduler_config['activate']):
main_logger.debug('start scheduler')
await scheduler_app.start_scheduler()
job_to_start = cfg_mgr.scheduler_config['start_job_name']
# execute job if set
if job_to_start != '':
from src.gui.schedulergui import jobs
main_logger.debug(f'job to start: {job_to_start}')
# put the job to queue
if jobs.get_job(job_to_start):
start_time = datetime.now()
job_to_run = jobs.get_job(job_to_start)
scheduler_app.schedule_one_time_job(start_time, job_to_run)
else:
main_logger.error(f'jobs to start not found : {job_to_start}')
except Exception as e:
main_logger.error(f"Error on app startup {e}")
"""
Class
"""
# Instantiate Cast Center with Desktop and Media
center_app = CastCenter(Desktop, Media, CastAPI, t_data_buffer, shutdown_func=cleanup_on_shutdown, grid_view_func=nice.run_preview_grid)
# Instantiate SchedulerGUI with Desktop and Media
if str2bool(cfg_mgr.scheduler_config['enable']):
scheduler_app = SchedulerGUI(Desktop, Media, CastAPI, t_data_buffer, True)
# Instantiate API to pass Desktop and Media
api_data = ApiData(Desktop, Media, Netdevice, t_data_buffer)
# Instantiate VideoPlayer with Media
video_app = VideoPlayer(Media, CastAPI, t_data_buffer)
"""
NiceGUI
"""
@ui.page(main_page_url)
async def main_page():
"""
Displays the main landing page of the WLEDVideoSync application.
This page provides access to core controls, status displays, and navigation for casting, configuration, and help.
It initializes the main UI layout, sets up timers, and integrates all major UI components for user interaction.
"""
dark = ui.dark_mode(CastAPI.dark_mode).bind_value_to(CastAPI, 'dark_mode')
await apply_custom()
if str2bool(cfg_mgr.custom_config['animate_ui']):
# Add Animate.css to the HTML head
ui.add_head_html("""
<link rel="stylesheet" href="assets/css/animate.min.css"/>
""")
"""
timer created on main page run to refresh datas
"""
CastAPI.root_timer = ui.timer(int(cfg_mgr.app_config['timer']), callback=root_timer_action)
"""
Header with button menu
"""
await nice.head_menu(name='Main', target='/', icon='home')
"""
App info
"""
if str2bool(cfg_mgr.custom_config['animate_ui']):
head_row_anim = Animate(ui.row, animation_name_in='backInDown', duration=1)
head_row = head_row_anim.create_element()
else:
head_row = ui.row()
with head_row.classes('w-full no-wrap'):
ui.label('DESKTOP: Cast Screen / Window content').classes('bg-slate-400 w-1/3')
with ui.card().classes('bg-slate-400 w-1/3'):
img = ui.image("assets/favicon.ico").classes('self-center')
img.on('click', lambda: animate_toggle(img))
img.style('cursor: pointer')
img.classes('border-2 w-8 border-white')
ui.label('MEDIA: Cast Image / Video / Capture Device (e.g. USB Camera ...)').classes('bg-slate-400 w-1/3')
"""
WLEDVideoSync image
"""
ui.separator().classes('mt-6')
CastAPI.w_image = ui.image("assets/Source-intro.png").classes('self-center')
CastAPI.w_image.classes(add='animate__animated')
CastAPI.w_image.classes('border-2 w-1/6 border-white')
"""
Grid View Container
"""
async def update_wled_image_visibility():
"""Controls the visibility of the main WLED image based on other UI elements."""
# The main image should only be visible if both the grid and the player are hidden.
is_player_visible = CastAPI.player.visible if CastAPI.player else False
if not CastAPI.grid_card.visible and not is_player_visible:
CastAPI.w_image.set_visibility(True)
else:
CastAPI.w_image.set_visibility(False)
async def toggle_grid_preview():
"""Toggles the visibility of the grid preview card with animation."""
await nice.toggle_animated(CastAPI.grid_card, 'slideInRight', 'slideOutLeft')
# The grid_timer is created inside grid_view()
if CastAPI.grid_timer:
ui.timer(0.5, lambda: nice.toggle_timer(CastAPI.grid_timer, CastAPI.grid_card), once=True)
ui.timer(1, lambda:update_wled_image_visibility(), once=True)
with ui.card().tight() as CastAPI.grid_card:
CastAPI.grid_card.classes('self-center w-full text-sm shadow-[0px_1px_4px_0px_rgba(0,0,0,0.5)_inset]')
CastAPI.grid_card.set_visibility(False)
# Set a timer to refresh the grid view periodically
# It is created inactive and will be managed by the root_timer_action.
CastAPI.grid_timer = ui.timer(float(cfg_mgr.app_config['grid_view_refresh_interval']), callback='',
active=False)
# columns
columns = int(cfg_mgr.app_config['grid_view_columns'])
# run preview on its own thread
await run.io_bound(nice.run_preview_grid, CastAPI.grid_card, columns, CastAPI.grid_timer, False)
# Add Grid View icon before player
grid = ui.button(on_click=toggle_grid_preview, icon='grid_on').classes('m-2') \
.tooltip('Show/Hide Live Grid Preview')
grid.classes('self-center')
"""
Video player
"""
if str2bool(cfg_mgr.custom_config['player']):
CastAPI.player_timer = ui.timer(int(cfg_mgr.app_config['timer']),
callback=lambda: nice.sync_button(CastAPI, Media))
await video_app.video_player_page()
CastAPI.player.set_visibility(False)
"""
Row for Cast /Filters / info / Run / Close
"""
await control_panel_page()
"""
Text Overlay Controls
"""
with ui.card().tight().classes('self-center w-full text-sm shadow-[0px_1px_4px_0px_rgba(0,0,0,0.5)_inset]'):
ui.label('TEXT Overlay').classes('self-center')
with ui.row(wrap=False).classes('self-center'):
ui.label('Font:').classes('self-center')
center_app.font_name_label = ui.label('').classes('self-center')
ui.label('Size:').classes('self-center')
center_app.font_size_label = ui.label('').classes('self-center')
with ui.row(wrap=False).classes('w-full justify-center items-center gap-4'):
with ui.row():
text_desktop = ui.button('Allow',
icon='computer',
on_click=lambda: center_app.toggle_text_desktop(text_desktop))
text_desktop.tooltip('Enable or disable text overlay for Desktop casts')
ui.button(icon='edit', on_click=lambda: center_app.animator_update(Desktop)).tooltip("Edit Desktop Text Animation")
ui.button('Fonts', on_click=center_app.font_select).tooltip('Open font selection and configuration dialog')
with ui.row():
text_media = ui.button('Allow',
icon='image',
on_click=lambda: center_app.toggle_text_media(text_media))
text_media.tooltip('Enable or disable text overlay for Media casts')
ui.button(icon='edit', on_click=lambda: center_app.animator_update(Media)).tooltip("Edit Media Text Animation")
ui.separator().classes('mt-6')
ui.separator().classes('mt-6')
"""
Log display
"""
if str2bool(cfg_mgr.app_config['log_to_main']):
with ui.expansion('Show log', icon='feed').classes('w-full'):
log_ui = ui.log(max_lines=250).classes('w-full h-30 bg-black text-white')
# handler
log_ui_handler = LogElementHandler(log_ui)
main_logger.addHandler(log_ui_handler)
ui.context.client.on_disconnect(lambda: main_logger.removeHandler(log_ui_handler))
# clear / load log file
with ui.row().classes('w-full'):
ui.button('Clear Log', on_click=lambda: log_ui.clear()).tooltip('Erase the log')
dialog = ui.dialog().classes('w-full') \
.props(add='maximized transition-show="slide-up" transition-hide="slide-down"')
with (dialog, ui.card().classes('w-full console-output')):
log_filename = cfg_mgr.app_root_path('log/WLEDVideoSync.log')
if os.path.isfile(log_filename):
# file exists
log_data = pathlib.Path(log_filename).read_text()
else:
log_data = 'ERROR Log File Not Found ERROR'
main_logger.warning(f'Log File Not Found {log_filename}')
ui.button('Close', on_click=dialog.close, color='red')
log_area = ui.textarea(value=log_data).classes('w-full').props(add='bg-color=blue-grey-4')
log_area.props(add="rows='25'")
ui.button('See Log file', on_click=dialog.open).tooltip('Load log data from file.')
"""
Footer : usefully links help
"""
async def generate_device():
ui.notify('Device List generation in progress...')
await Utils.get_all_running_hosts(WLED_PID_TMP_FILE)
with ui.footer(value=False).classes('items-center bg-red-900') as footer:
ui.switch("Light/Dark Mode", on_change=dark.toggle).classes('bg-red-900').tooltip('Change Layout Mode')
sysstat = ui.button('SysStats', on_click=lambda: Utils.run_sys_charts(WLED_PID_TMP_FILE,CastAPI.dark_mode),
color='bg-red-800')
sysstat.tooltip('Run System Stats')
sysstat_device= ui.button(icon='settings', on_click=lambda: generate_device(), color='bg-red-800')
sysstat_device.tooltip('Re-Generate device list from running casts to SysCharts')
root_page_url = Utils.root_page()
go_to_url = '/' if root_page_url == '/Cast-Center' else '/Cast-Center'
ui.button('Center', on_click=lambda: ui.navigate.to(go_to_url)).tooltip('Go to Cast Center Page')
async def open_grid_window():
"""Calculates window size and opens the grid view in a new window."""
cols = int(cfg_mgr.app_config.get('grid_view_columns', 4))
item_w = int(cfg_mgr.app_config.get('grid_preview_width', 240))
item_h = int(cfg_mgr.app_config.get('grid_preview_height', 135))
gap = int(cfg_mgr.app_config.get('grid_view_border', 2))
# --- Calculate width based on columns, item width, and gaps ---
width = (cols * item_w) + ((cols + 1) * gap) + 80 # Add some padding
# --- Calculate height based on the number of active casts ---
num_casts = len(CastAPI.previews)
if num_casts > 0:
# Calculate rows needed, ensuring at least 1 row.
rows = math.ceil(num_casts / cols)
else:
# Default to 2 rows if no casts are active for a reasonable default window size.
rows = 2
height = (rows * item_h) + ((rows + 1) * gap) + 120 # Add padding for title bar etc.
await _open_page_in_new_window('/grid_view', 'Grid View', width=width, height=height)
ui.button('Grid View', on_click=open_grid_window, icon='grid_on').classes('m-2')
ui.button('Fonts', on_click=center_app.font_select, color='bg-red-800')
ui.button('Config', on_click=lambda: ui.navigate.to('/config_editor'), color='bg-red-800')
ui.button('PYEditor', on_click=lambda: ui.navigate.to('/Pyeditor?from_menu=true'), color='bg-red-800')
ui.button('shutdown', on_click=app.shutdown)
with ui.row().classes('absolute inset-y-0 right-0.5 bg-red-900'):
ui.link('® Zak-45 ' + str(datetime.now().strftime('%Y')), 'https://github.com/zak-45', new_tab=True) \
.classes('text-white')
ui.link('On-Line Help', 'https://github.com/zak-45/WLEDVideoSync?tab=readme-ov-file#user-guide', new_tab=True) \
.tooltip('Go to documentation').classes('text-white')
with ui.page_sticky(position='bottom-right', x_offset=20, y_offset=20):
with ui.button(on_click=footer.toggle).props(add='round outline'):
ui.image('assets/favicon.ico').classes('rounded-full w-8 h-8')
@ui.page('/Manage')
async def main_page_cast_manage():
"""
Displays the cast management page for configuring and monitoring cast devices.
This page provides access to device management features, displays main tab information, and includes a footer with
network and media device controls.
"""
ui.dark_mode(CastAPI.dark_mode)
await apply_custom()
"""
Header with button menu
"""
await nice.head_menu(name='Manage', target='/Manage', icon='video_settings')
"""
Main tabs infos
"""
await tabs_info_page()
"""
Footer
"""
with ui.footer():
await net_view_button(show_only=False)
await media_dev_view_page()
@ui.page('/Player')
async def run_video_player_page():
"""
Displays the video player page for casting and controlling media playback.
This page sets up the video player interface, applies animation styles if enabled, and initializes
the player timer for synchronization.
"""
if str2bool(cfg_mgr.custom_config['animate_ui']):
# Add Animate.css to the HTML head
ui.add_head_html("""
<link rel="stylesheet" href="assets/css/animate.min.css"/>
""")
#
CastAPI.player_timer = ui.timer(int(cfg_mgr.app_config['timer']), callback=lambda: nice.sync_button(CastAPI, Media))
await video_app.video_player_page()
@ui.page('/Desktop')
async def main_page_desktop():
"""
Displays the Desktop parameters page for configuring and monitoring desktop casting.
This page provides controls for desktop capture settings, device management, multicast options, and buffer previews.
It allows users to edit parameters, view current settings, and interact with desktop casting features.
"""
ui.dark_mode(CastAPI.dark_mode)
await apply_custom()
await nice.head_menu(name='Desktop Params', target='/Desktop', icon='computer')
async def validate():
# retrieve matrix setup from wled and set w/h
if Desktop.wled:
Desktop.scale_width, Desktop.scale_height = await Utils.get_wled_matrix_dimensions(Desktop.host)
ui.navigate.reload()
def on_input_new_viinput(x):
if x.args != '':
CastAPI.new_viinput_value = x.args
async def new_viinput_option():
if CastAPI.new_viinput_value is not None and CastAPI.new_viinput_value not in new_viinput.options:
new_options = new_viinput.options
new_options.append(CastAPI.new_viinput_value)
new_viinput.set_options(new_options)
new_viinput.value = CastAPI.new_viinput_value
await update_attribute_by_name('Desktop', 'viinput', str(new_viinput.value))
if str2bool(cfg_mgr.custom_config['animate_ui']):
# Add Animate.css to the HTML head
ui.add_head_html("""
<link rel="stylesheet" href="assets/css/animate.min.css"/>
""")
columns_a = [
{'name': 'rate', 'label': 'FPS', 'field': 'rate', 'align': 'left'},
{'name': 'scale_width', 'label': 'W', 'field': 'scale_width'},
{'name': 'scale_height', 'label': 'H', 'field': 'scale_height'}
]
rows_a = [
{'id': 0, 'rate': Desktop.rate, 'scale_width': Desktop.scale_width, 'scale_height': Desktop.scale_height}
]
columns_b = [
{'name': 'wled', 'label': 'WLED', 'field': 'wled', 'align': 'left'},
{'name': 'host', 'label': 'IP', 'field': 'host'}
]
rows_b = [
{'id': 0, 'wled': Desktop.wled, 'host': Desktop.host}
]
columns_c = [
{'name': 'capture', 'label': 'Capture', 'field': 'capture_methode', 'align': 'left'},
{'name': 'viinput', 'label': 'Input', 'field': 'viinput', 'align': 'left'},
{'name': 'viformat', 'label': 'Method', 'field': 'viformat'},
{'name': 'preview', 'label': 'Preview', 'field': 'preview'}
]
rows_c = [
{'id': 0, 'capture_methode': Desktop.capture_methode,
'viinput': Desktop.viinput, 'viformat': Desktop.viformat, 'preview': Desktop.preview}
]
columns_d = [
{'name': 'vooutput', 'label': 'Output', 'field': 'vooutput', 'align': 'left'},
{'name': 'voformat', 'label': 'Format', 'field': 'voformat'},
{'name': 'vo_code', 'label': 'Codec', 'field': 'vo_codec'}
]
rows_d = [
{'id': 0, 'vooutput': Desktop.vooutput, 'voformat': Desktop.voformat, 'vo_codec': Desktop.vo_codec}
]
columns_e = [
{'name': 'multicast', 'label': 'MultiCast', 'field': 'multicast', 'align': 'left'},
{'name': 'matrix-x', 'label': 'H', 'field': 'matrix-x'},
{'name': 'matrix-y', 'label': 'V', 'field': 'matrix-y'}
]
rows_e = [
{'id': 0, 'multicast': Desktop.multicast, 'matrix-x': Desktop.cast_x, 'matrix-y': Desktop.cast_y}
]
exp_param = ui.expansion('Parameters', icon='settings', value=True)
with exp_param.classes('w-full bg-sky-800'):
with ui.row():
await nice.cast_icon(Desktop)
manage_cast_presets('Desktop', Desktop)
with ui.row():
ui.table(columns=columns_a, rows=rows_a).classes('w-60')
ui.table(columns=columns_b, rows=rows_b).classes('w-60')
ui.table(columns=columns_c, rows=rows_c).classes('w-60')
ui.table(columns=columns_d, rows=rows_d).classes('w-60')
ui.table(columns=columns_e, rows=rows_e).classes('w-60')
with ui.grid(columns=2):
ui.label('Protocol:')
ui.label(Desktop.protocol)
ui.label('Port:')
ui.label(str(Desktop.port))
ui.label('No of Packet:')
ui.label(str(Desktop.retry_number))
if str2bool(cfg_mgr.custom_config['animate_ui']):
exp_edit_param_anim = Animate(ui.expansion, animation_name_in='backInDown', duration=1)
exp_edit_param = exp_edit_param_anim.create_element()
else:
exp_edit_param = ui.expansion()
exp_edit_param.text = 'Edit'
exp_edit_param.props(add="icon='edit'")
exp_edit_param.classes('w-full bg-sky-800')
exp_edit_param.on_value_change(lambda: exp_param.close())
with exp_edit_param:
with ui.row():
ui.icon('restore_page', color='blue', size='md') \
.style('cursor: pointer').tooltip('Click to Validate/Refresh') \
.on('click', lambda: validate())
with ui.card():
await nice.edit_rate_x_y(Desktop)
with ui.card():
await nice.edit_ip(Desktop)
with ui.card():
new_capture_methode = ui.select(options=['av','mss'], label='Capture Methode').style(add='width:120px')
new_capture_methode.bind_value(Desktop,'capture_methode')
with ui.card():
input_options=['desktop','area','win=','SharedList']
if PLATFORM == 'linux':
input_options.insert(0,os.getenv('DISPLAY'))
elif PLATFORM == 'darwin':
input_options.insert(0,'default:none')
new_viinput = ui.select(options=input_options,label='Input', new_value_mode='add-unique')
new_viinput.tooltip('Type data to capture, "area" for screen selection, "win=xxxxx" for a screen or queue')
# Bind the change event to trigger the update
new_viinput.on('input-value', lambda x: on_input_new_viinput(x))
new_viinput.on('blur', lambda: new_viinput_option())
#
new_preview = ui.checkbox('Preview')
new_preview.bind_value(Desktop, 'preview')
new_preview.tooltip('Show preview window')
new_viformat = ui.input('Format', value=Desktop.viformat)
new_viformat.bind_value(Desktop, 'viformat')
new_vi_codec = ui.input('Codec', value=Desktop.vi_codec)
new_vi_codec.bind_value(Desktop, 'vi_codec')
with ui.row():
ui.number('', value=Desktop.monitor_number, min=-1, max=1).classes('w-10') \
.bind_value(Desktop, 'monitor_number', forward=lambda value: int(value or 0)) \
.tooltip('Enter monitor number')
ui.button('ScreenArea', on_click=lambda: run.io_bound(Utils.select_sc_area,Desktop)) \
.tooltip('Select area from monitor')
with ui.card():
new_vooutput = ui.input('Output', value=str(Desktop.vooutput))
new_vooutput.bind_value(Desktop, 'vooutput')
new_vooutput.tooltip('Experimental feature: enter udp:// rtsp:// etc...')
new_voformat = ui.input('Format', value=Desktop.voformat)
new_voformat.bind_value(Desktop, 'voformat')
ui.button('formats', on_click=nice.display_formats)
new_vo_codec = ui.input('Codec', value=Desktop.vo_codec)
new_vo_codec.bind_value(Desktop, 'vo_codec')
ui.button('Codecs', on_click=nice.display_codecs)
with ui.card():
await nice.edit_capture(Desktop)
with ui.card():
await nice.edit_multicast(Desktop)
with ui.card():
new_cast_devices = ui.input('Cast Devices', value=str(Desktop.cast_devices))
new_cast_devices.tooltip('Click on MANAGE to enter devices for Multicast')
new_cast_devices.on('focusout',
lambda: update_attribute_by_name('Desktop','cast_devices',
new_cast_devices.value))
ui.button('Manage', on_click=lambda: nice.cast_device_manage(Desktop, Netdevice))
with ui.card():
protocol_select = await nice.edit_protocol(Desktop)
with ui.card() as artnet_card:
artnet_card.bind_visibility_from(protocol_select, 'value', backward=lambda v: v in ['artnet', 'e131'])
await nice.edit_artnet(Desktop)
with ui.card():
new_record = ui.checkbox(text='Record', value=False).bind_value(Desktop,'record')
new_record.tooltip('Select if want to record cast')
new_record_file = ui.input('File name').bind_value(Desktop,'output_file')
new_record_file.tooltip('Provide file name for record, extension determine format eg: file.mp4')
ui.separator().classes('mt-6')
with ui.expansion('BUFFER', icon='grid_view', on_value_change=lambda: exp_edit_param.close()) \
.classes('w-full'):
if len(Desktop.frame_buffer) > 0:
with ui.row():
media_grid = ui.grid(columns=8)
with media_grid:
for i in range(len(Desktop.frame_buffer)):
# put fixed size for preview
img = CV2Utils.resize_image(Desktop.frame_buffer[i], 640, 360)
img = Image.fromarray(img)
await light_box_image(i, img, '', '', Desktop, 'frame_buffer')
with ui.carousel(animated=True, arrows=True, navigation=True).props('height=480px'):
await nice.generate_carousel(Desktop)
else:
with ui.card():
ui.label('No image to show...').classes('animate-pulse')
with ui.expansion('MULTICAST', icon='grid_view', on_value_change=lambda: exp_edit_param.close()) \
.classes('w-full'):
# columns number = cast_x, number of cards = cast_x * cast_y
if Desktop.multicast:
with ui.row():
await nice.multi_preview(Desktop)
await nice.cast_devices_view(Desktop)
if len(Desktop.cast_frame_buffer) > 0:
with ui.grid(columns=Desktop.cast_x):
try:
for i in range(Desktop.cast_x * Desktop.cast_y):
# put fixed size for preview
img = CV2Utils.resize_image(Desktop.cast_frame_buffer[i], 640, 360)
img = Image.fromarray(img)
await light_box_image(i, img, i, '', Desktop, 'cast_frame_buffer')
except Exception as m_error:
main_logger.error(traceback.format_exc())
main_logger.error(f'An exception occurred: {m_error}')
else:
with ui.card():
ui.label('No frame captured yet...').style('background: red')
else:
with ui.card():
ui.label('Multicast not set') \
.style('text-align:center; font-size: 150%; font-weight: 300') \
.classes('animate-pulse')
with ui.footer():
ui.button('Run Net discovery', on_click=discovery_net_notify, color='bg-red-800')
async def display_windows():
with ui.dialog() as dialog, ui.card():
dialog.open()
editor = ui.json_editor({'content': {'json': Desktop.windows_titles}})
await editor.run_editor_method('updateProps', {'readOnly': True})
await editor.run_editor_method(':expand', '[], relativePath => relativePath.length < 1')
ui.button('Close', on_click=dialog.close, color='red')
ui.button('Win TITLES', on_click=display_windows, color='bg-red-800').tooltip('View windows titles')
ui.button('Fetch Win TITLES', on_click=grab_windows, color='bg-red-800').tooltip('Retrieve windows titles')
@ui.page('/Media')
async def main_page_media():
"""
Displays the Media parameters page for configuring and monitoring media casting.
This page provides controls for media capture settings, device management, multicast options, and buffer previews.
It allows users to edit parameters, view current settings, and interact with media casting features.
"""
ui.dark_mode(CastAPI.dark_mode)
await apply_custom()
await nice.head_menu(name='Media Params', target='/Media', icon='image')
async def media_validate():
# retrieve matrix setup from wled and set w/h
if Media.wled:
Media.scale_width, Media.scale_height = await Utils.get_wled_matrix_dimensions(Media.host)
ui.navigate.reload()
if str2bool(cfg_mgr.custom_config['animate_ui']):
# Add Animate.css to the HTML head
ui.add_head_html("""
<link rel="stylesheet" href="assets/css/animate.min.css"/>
""")
columns_a = [
{'name': 'rate', 'label': 'FPS', 'field': 'rate', 'align': 'left'},
{'name': 'scale_width', 'label': 'W', 'field': 'scale_width'},
{'name': 'scale_height', 'label': 'H', 'field': 'scale_height'}
]
rows_a = [
{'id': 0, 'rate': Media.rate, 'scale_width': Media.scale_width, 'scale_height': Media.scale_height}
]
columns_b = [
{'name': 'wled', 'label': 'WLED', 'field': 'wled', 'align': 'left'},
{'name': 'host', 'label': 'IP', 'field': 'host'}
]
rows_b = [
{'id': 0, 'wled': Media.wled, 'host': Media.host}
]
columns_c = [
{'name': 'viinput', 'label': 'Input', 'field': 'viinput', 'align': 'left'},
{'name': 'preview', 'label': 'Preview', 'field': 'preview'}
]
rows_c = [
{'id': 0, 'viinput': Media.viinput, 'preview': Media.preview}
]
columns_d = [
{'name': 'multicast', 'label': 'MultiCast', 'field': 'multicast', 'align': 'left'},
{'name': 'matrix-x', 'label': 'H', 'field': 'matrix-x'},
{'name': 'matrix-y', 'label': 'V', 'field': 'matrix-y'}
]
rows_d = [
{'id': 0, 'multicast': Media.multicast, 'matrix-x': Media.cast_x, 'matrix-y': Media.cast_y}
]
media_exp_param = ui.expansion('Parameters', icon='settings', value=True)
with media_exp_param.classes('w-full bg-sky-800'):
with ui.row(wrap=False):
await nice.cast_icon(Media)
manage_cast_presets('Media', Media)
with ui.row():
ui.table(columns=columns_a, rows=rows_a).classes('w-60')
ui.table(columns=columns_b, rows=rows_b).classes('w-60')
ui.table(columns=columns_c, rows=rows_c).classes('w-60')
ui.table(columns=columns_d, rows=rows_d).classes('w-60')
with ui.grid(columns=2):
ui.label('Protocol:')
ui.label(Media.protocol)
ui.label('Port:')
ui.label(str(Media.port))
ui.label('No of Packet:')
ui.label(str(Media.retry_number))
if str2bool(cfg_mgr.custom_config['animate_ui']):
media_exp_edit_param_anim = Animate(ui.expansion, animation_name_in='backInDown', duration=1)
media_exp_edit_param = media_exp_edit_param_anim.create_element()
else:
media_exp_edit_param = ui.expansion()
media_exp_edit_param.text = 'Edit'
media_exp_edit_param.props(add="icon='edit'")
media_exp_edit_param.classes('w-full bg-sky-800')
media_exp_edit_param.on_value_change(lambda: media_exp_param.close())
with media_exp_edit_param:
with ui.row():
ui.icon('restore_page', color='blue', size='md') \
.style('cursor: pointer').tooltip('Click to Validate/Refresh') \
.on('click', lambda: media_validate())
with ui.card():
await nice.edit_rate_x_y(Media)
with ui.card():
new_viinput = ui.input('Input', value=str(Media.viinput))
new_viinput.on('focusout', lambda: update_attribute_by_name('Media','viinput', new_viinput.value))
new_viinput.tooltip('Enter desired input : e.g 0..n / file name etc ...')
new_preview = ui.checkbox('Preview')
new_preview.bind_value(Media, 'preview')
new_preview.tooltip('Show preview window')
with ui.card():
await nice.edit_ip(Media)