-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_state.cpp
More file actions
2524 lines (2268 loc) · 96 KB
/
Copy pathclient_state.cpp
File metadata and controls
2524 lines (2268 loc) · 96 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
/**
* @file src/app/client_state.cpp
* @brief Implements client state models and transitions.
*/
// class header include
#include "src/app/client_state.h"
// standard includes
#include "src/network/host_pairing.h"
#include <algorithm>
#include <array>
#include <string_view>
#include <utility>
#include <vector>
namespace {
constexpr std::size_t OVERLAY_SCROLL_STEP = 4U;
constexpr std::size_t LOG_VIEWER_SCROLL_STEP = 1U;
constexpr std::size_t LOG_VIEWER_FAST_SCROLL_STEP = 8U;
constexpr std::size_t HOST_TOOLBAR_BUTTON_COUNT = 3U;
constexpr std::size_t DEFAULT_EMPTY_HOSTS_TOOLBAR_INDEX = HOST_TOOLBAR_BUTTON_COUNT - 1U;
constexpr std::size_t HOST_GRID_COLUMN_COUNT = 3U;
constexpr std::size_t APP_GRID_COLUMN_COUNT = 4U;
constexpr std::size_t ADD_HOST_KEYPAD_COLUMN_COUNT = 3U;
constexpr const char *DELETE_SAVED_FILE_MENU_ID_PREFIX = "delete-saved-file:";
constexpr const char *SETTINGS_CATEGORY_PREFIX = "settings-category:";
constexpr std::array<char, 11> ADD_HOST_ADDRESS_KEYPAD_CHARACTERS {'1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '0'};
constexpr std::array<char, 10> ADD_HOST_PORT_KEYPAD_CHARACTERS {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
constexpr int DEFAULT_STREAM_FRAMERATE = 30;
constexpr int DEFAULT_STREAM_BITRATE_KBPS = 1000;
constexpr std::array<int, 6> STREAM_FRAMERATE_OPTIONS {15, 20, 24, 25, 30, 60};
constexpr std::array<int, 9> STREAM_BITRATE_OPTIONS {500, 750, 1000, 1500, 2000, 2500, 3000, 4000, 5000};
constexpr std::array<app::VideoDecoderSelection, 4> VIDEO_DECODER_OPTIONS {
app::VideoDecoderSelection::autoDetect,
app::VideoDecoderSelection::h264,
app::VideoDecoderSelection::mpeg2,
app::VideoDecoderSelection::h263p,
};
/**
* @brief Describes the keypad characters available for the active add-host field.
*/
struct AddHostKeypadLayout {
const char *characters; ///< Null-terminated backing storage for the keypad characters.
std::size_t buttonCount; ///< Number of selectable keypad buttons in the layout.
};
/**
* @brief Returns the keypad character layout for the active add-host field.
*
* @param state Current client state containing the active add-host field.
* @return The keypad layout that matches the active add-host field.
*/
AddHostKeypadLayout add_host_keypad_layout(const app::ClientState &state) {
if (state.addHostDraft.activeField == app::AddHostField::address) {
return {ADD_HOST_ADDRESS_KEYPAD_CHARACTERS.data(), ADD_HOST_ADDRESS_KEYPAD_CHARACTERS.size()};
}
return {ADD_HOST_PORT_KEYPAD_CHARACTERS.data(), ADD_HOST_PORT_KEYPAD_CHARACTERS.size()};
}
/**
* @brief Returns the currently selected keypad character for the active add-host field.
*
* @param state Current client state containing the keypad selection.
* @param character Receives the selected keypad character when one is available.
* @return True when a keypad character was written to @p character.
*/
bool selected_add_host_keypad_character(const app::ClientState &state, char *character) {
const AddHostKeypadLayout layout = add_host_keypad_layout(state);
if (character == nullptr || layout.buttonCount == 0U) {
return false;
}
*character = layout.characters[state.addHostDraft.keypad.selectedButtonIndex % layout.buttonCount];
return true;
}
std::string add_host_field_menu_id(app::AddHostField field) {
return field == app::AddHostField::address ? "edit-address" : "edit-port";
}
std::string settings_category_menu_id(app::SettingsCategory category) {
switch (category) {
case app::SettingsCategory::logging:
return std::string(SETTINGS_CATEGORY_PREFIX) + "logging";
case app::SettingsCategory::display:
return std::string(SETTINGS_CATEGORY_PREFIX) + "display";
case app::SettingsCategory::input:
return std::string(SETTINGS_CATEGORY_PREFIX) + "input";
case app::SettingsCategory::reset:
return std::string(SETTINGS_CATEGORY_PREFIX) + "reset";
}
return std::string(SETTINGS_CATEGORY_PREFIX) + "logging";
}
app::SettingsCategory settings_category_from_menu_id(std::string_view itemId) {
if (itemId == settings_category_menu_id(app::SettingsCategory::display)) {
return app::SettingsCategory::display;
}
if (itemId == settings_category_menu_id(app::SettingsCategory::input)) {
return app::SettingsCategory::input;
}
if (itemId == settings_category_menu_id(app::SettingsCategory::reset)) {
return app::SettingsCategory::reset;
}
return app::SettingsCategory::logging;
}
const char *settings_category_description(app::SettingsCategory category) {
switch (category) {
case app::SettingsCategory::logging:
return "Control the runtime log file, the in-app log viewer, and xemu debugger output verbosity.";
case app::SettingsCategory::display:
return "Tune streaming video resolution, frame rate, bitrate, audio playback, and the in-stream diagnostics overlay.";
case app::SettingsCategory::input:
return "Input options will live here when controller and navigation customization is added.";
case app::SettingsCategory::reset:
return "Review and delete Moonlight saved data, or remove everything with a full factory reset.";
}
return "Control the runtime log file, the in-app log viewer, and xemu debugger output verbosity.";
}
/**
* @brief Return whether two stream-resolution entries target the same size.
*
* @param left First stream-resolution entry to compare.
* @param right Second stream-resolution entry to compare.
* @return True when both entries describe the same width and height.
*/
bool stream_resolutions_match(const VIDEO_MODE &left, const VIDEO_MODE &right) {
return left.width == right.width && left.height == right.height;
}
/**
* @brief Format one stream resolution for display in the settings menu.
*
* @param videoMode Resolution to stringify.
* @return Human-readable stream-resolution label.
*/
std::string describe_stream_resolution(const VIDEO_MODE &videoMode) {
if (videoMode.width <= 0 || videoMode.height <= 0) {
return "Unavailable";
}
return std::to_string(videoMode.width) + "x" + std::to_string(videoMode.height);
}
/**
* @brief Return the settings label for one video decoder preference.
*
* @param selection Decoder preference to describe.
* @return User-facing decoder preference label.
*/
const char *video_decoder_selection_label(app::VideoDecoderSelection selection) {
switch (selection) {
case app::VideoDecoderSelection::autoDetect:
return "Auto";
case app::VideoDecoderSelection::h264:
return "H.264";
case app::VideoDecoderSelection::mpeg2:
return "MPEG-2/H.262";
case app::VideoDecoderSelection::h263p:
return "H.263+";
}
return "Auto";
}
/**
* @brief Return the selected stream-resolution index inside the detected mode list.
*
* @param state Current client state containing the preferred mode.
* @return Zero-based index of the preferred mode, or zero when no exact match exists.
*/
std::size_t selected_stream_video_mode_index(const app::ClientState &state) {
if (!state.settings.preferredVideoModeSet || state.settings.availableVideoModes.empty()) {
return 0U;
}
for (std::size_t index = 0; index < state.settings.availableVideoModes.size(); ++index) {
if (stream_resolutions_match(state.settings.availableVideoModes[index], state.settings.preferredVideoMode)) {
return index;
}
}
return 0U;
}
/**
* @brief Advance the preferred stream resolution to the next detected Xbox video mode.
*
* @param state Current client state containing detected stream-resolution modes.
*/
void cycle_stream_video_mode(app::ClientState &state) {
if (state.settings.availableVideoModes.empty()) {
state.settings.preferredVideoMode = {};
state.settings.preferredVideoModeSet = false;
return;
}
const std::size_t nextIndex = (selected_stream_video_mode_index(state) + 1U) % state.settings.availableVideoModes.size();
state.settings.preferredVideoMode = state.settings.availableVideoModes[nextIndex];
state.settings.preferredVideoModeSet = true;
}
/**
* @brief Advance the preferred stream frame rate to the next supported option.
*
* @param state Current client state containing the preferred frame rate.
*/
void cycle_stream_framerate(app::ClientState &state) {
const auto current = std::find(STREAM_FRAMERATE_OPTIONS.begin(), STREAM_FRAMERATE_OPTIONS.end(), state.settings.streamFramerate);
if (current == STREAM_FRAMERATE_OPTIONS.end()) {
state.settings.streamFramerate = DEFAULT_STREAM_FRAMERATE;
return;
}
const std::size_t nextIndex = (static_cast<std::size_t>(std::distance(STREAM_FRAMERATE_OPTIONS.begin(), current)) + 1U) % STREAM_FRAMERATE_OPTIONS.size();
state.settings.streamFramerate = STREAM_FRAMERATE_OPTIONS[nextIndex];
}
/**
* @brief Advance the preferred stream bitrate to the next supported option.
*
* @param state Current client state containing the preferred bitrate.
*/
void cycle_stream_bitrate(app::ClientState &state) {
const auto current = std::find(STREAM_BITRATE_OPTIONS.begin(), STREAM_BITRATE_OPTIONS.end(), state.settings.streamBitrateKbps);
if (current == STREAM_BITRATE_OPTIONS.end()) {
state.settings.streamBitrateKbps = STREAM_BITRATE_OPTIONS.front();
return;
}
const std::size_t nextIndex = (static_cast<std::size_t>(std::distance(STREAM_BITRATE_OPTIONS.begin(), current)) + 1U) % STREAM_BITRATE_OPTIONS.size();
state.settings.streamBitrateKbps = STREAM_BITRATE_OPTIONS[nextIndex];
}
/**
* @brief Advance the preferred video decoder to the next supported option.
*
* @param state Current client state containing the preferred decoder.
*/
void cycle_video_decoder(app::ClientState &state) {
const auto current = std::find(VIDEO_DECODER_OPTIONS.begin(), VIDEO_DECODER_OPTIONS.end(), state.settings.videoDecoder);
if (current == VIDEO_DECODER_OPTIONS.end()) {
state.settings.videoDecoder = app::VideoDecoderSelection::autoDetect;
return;
}
const std::size_t nextIndex = (static_cast<std::size_t>(std::distance(VIDEO_DECODER_OPTIONS.begin(), current)) + 1U) % VIDEO_DECODER_OPTIONS.size();
state.settings.videoDecoder = VIDEO_DECODER_OPTIONS[nextIndex];
}
std::string pairing_reset_endpoint_key(std::string_view address, uint16_t port) {
return app::normalize_ipv4_address(address) + ":" + std::to_string(app::effective_host_port(port));
}
void remember_deleted_host_pairing(app::ClientState &state, const app::HostRecord &host) {
if (host.pairingState != app::PairingState::paired) {
return;
}
const std::string key = pairing_reset_endpoint_key(host.address, host.port);
if (key.empty()) {
return;
}
if (std::find(state.hosts.pairingResetEndpoints.begin(), state.hosts.pairingResetEndpoints.end(), key) == state.hosts.pairingResetEndpoints.end()) {
state.hosts.pairingResetEndpoints.push_back(key);
}
}
void clear_deleted_host_pairing(app::ClientState &state, const std::string &address, uint16_t port) {
const std::string key = pairing_reset_endpoint_key(address, port);
if (key.empty()) {
return;
}
state.hosts.pairingResetEndpoints.erase(
std::remove(state.hosts.pairingResetEndpoints.begin(), state.hosts.pairingResetEndpoints.end(), key),
state.hosts.pairingResetEndpoints.end()
);
}
void reset_add_host_draft(app::ClientState &state, app::ScreenId returnScreen);
void remember_host_selection(app::ClientState &state, const app::HostRecord &host) {
state.hosts.selectedAddress = host.address;
state.hosts.selectedPort = host.port;
}
void clear_active_host(app::ClientState &state) {
state.hosts.active = {};
state.hosts.activeLoaded = false;
}
void clear_active_host_app_list(app::ClientState &state) {
if (!state.hosts.activeLoaded) {
return;
}
state.hosts.active.apps.clear();
state.hosts.active.appListState = app::HostAppListState::idle;
state.hosts.active.appListStatusMessage.clear();
state.hosts.active.appListContentHash = 0U;
state.hosts.active.lastAppListRefreshTick = 0U;
state.hosts.active.runningGameId = 0U;
state.apps.selectedAppIndex = 0U;
state.apps.scrollPage = 0U;
state.apps.showHiddenApps = false;
}
void copy_host_to_active_host(app::ClientState &state, const app::HostRecord &host) {
state.hosts.active = host;
state.hosts.activeLoaded = true;
remember_host_selection(state, host);
}
void unload_hosts_page_state(app::ClientState &state) {
if (!state.hosts.loaded) {
return;
}
if (!state.hosts.items.empty() && state.hosts.selectedHostIndex < state.hosts.items.size()) {
remember_host_selection(state, state.hosts.items[state.hosts.selectedHostIndex]);
}
state.hosts.items.clear();
state.hosts.loaded = false;
state.hosts.selectedHostIndex = 0U;
state.hosts.focusArea = app::HostsFocusArea::toolbar;
}
void unload_apps_page_state(app::ClientState &state) {
if (state.hosts.activeLoaded) {
remember_host_selection(state, state.hosts.active);
}
clear_active_host_app_list(state);
}
void unload_settings_page_state(app::ClientState &state) {
state.settings.savedFiles.clear();
state.settings.savedFilesDirty = true;
state.settings.logViewerLines.clear();
state.settings.logViewerScrollOffset = 0U;
}
void unload_pair_host_screen_state(app::ClientState &state) {
state.pairingDraft = {{}, app::DEFAULT_HOST_PORT, {}, app::PairingStage::idle, {}};
}
void unload_screen_state(app::ClientState &state, app::ScreenId nextScreen) {
if (state.shell.activeScreen == nextScreen) {
return;
}
switch (state.shell.activeScreen) {
case app::ScreenId::home:
case app::ScreenId::hosts:
if (nextScreen == app::ScreenId::apps || nextScreen == app::ScreenId::pair_host || nextScreen == app::ScreenId::settings) {
unload_hosts_page_state(state);
}
return;
case app::ScreenId::apps:
unload_apps_page_state(state);
return;
case app::ScreenId::add_host:
reset_add_host_draft(state, app::ScreenId::hosts);
return;
case app::ScreenId::pair_host:
unload_pair_host_screen_state(state);
return;
case app::ScreenId::settings:
unload_settings_page_state(state);
return;
}
}
void sync_selected_settings_category_from_menu(app::ClientState &state) {
if (const ui::MenuItem *selectedItem = state.menu.selected_item(); selectedItem != nullptr) {
state.settings.selectedCategory = settings_category_from_menu_id(selectedItem->id);
}
}
bool starts_with(const std::string &value, const char *prefix) {
return value.rfind(prefix, 0U) == 0U;
}
void reset_add_host_draft(app::ClientState &state, app::ScreenId returnScreen) {
state.addHostDraft = {
{},
{},
app::AddHostField::address,
{false, 0U, {}},
returnScreen,
{},
{},
false,
};
}
void reset_confirmation(app::ClientState &state) {
state.confirmation = {};
}
void open_confirmation(
app::ClientState &state,
app::ConfirmationAction action,
std::string title,
std::vector<std::string> lines,
std::string targetPath = {}
) {
state.confirmation.action = action;
state.confirmation.targetPath = std::move(targetPath);
state.confirmation.title = std::move(title);
state.confirmation.lines = std::move(lines);
state.modal.id = app::ModalId::confirmation;
state.modal.selectedActionIndex = 0U;
}
app::HostRecord *find_host_by_endpoint(std::vector<app::HostRecord> &hosts, const std::string &address, uint16_t port) {
const auto iterator = std::find_if(hosts.begin(), hosts.end(), [&address, port](const app::HostRecord &host) {
return app::host_matches_endpoint(host, address, port);
});
return iterator == hosts.end() ? nullptr : &(*iterator);
}
app::HostRecord *find_loaded_host_by_endpoint(app::ClientState &state, const std::string &address, uint16_t port) {
if (app::HostRecord *host = find_host_by_endpoint(state.hosts.items, address, port); host != nullptr) {
return host;
}
if (state.hosts.activeLoaded && app::host_matches_endpoint(state.hosts.active, address, port)) {
return &state.hosts.active;
}
return nullptr;
}
std::vector<std::size_t> visible_app_indices(const app::HostRecord &host, bool showHiddenApps) {
std::vector<std::size_t> indices;
for (std::size_t index = 0; index < host.apps.size(); ++index) {
if (showHiddenApps || !host.apps[index].hidden) {
indices.push_back(index);
}
}
return indices;
}
const app::HostAppRecord *find_app_by_id(const std::vector<app::HostAppRecord> &apps, int appId) {
const auto iterator = std::find_if(apps.begin(), apps.end(), [appId](const app::HostAppRecord &record) {
return record.id == appId;
});
return iterator == apps.end() ? nullptr : &(*iterator);
}
std::size_t visible_app_index_for_id(const app::HostRecord &host, bool showHiddenApps, int appId) {
std::size_t visibleIndex = 0U;
for (const app::HostAppRecord &record : host.apps) {
if (!showHiddenApps && record.hidden) {
continue;
}
if (record.id == appId) {
return visibleIndex;
}
++visibleIndex;
}
return static_cast<std::size_t>(-1);
}
void refresh_running_flags(app::HostRecord *host) {
if (host == nullptr) {
return;
}
for (app::HostAppRecord &appRecord : host->apps) {
appRecord.running = static_cast<uint32_t>(appRecord.id) == host->runningGameId;
}
}
void clamp_selected_host_index(app::ClientState &state) {
if (state.hosts.items.empty()) {
state.hosts.selectedHostIndex = 0U;
state.hosts.focusArea = app::HostsFocusArea::toolbar;
state.hosts.selectedToolbarButtonIndex = DEFAULT_EMPTY_HOSTS_TOOLBAR_INDEX;
return;
}
if (state.hosts.selectedHostIndex >= state.hosts.items.size()) {
state.hosts.selectedHostIndex = state.hosts.items.size() - 1U;
}
}
void reset_hosts_home_selection(app::ClientState &state) {
if (state.hosts.items.empty()) {
state.hosts.focusArea = app::HostsFocusArea::toolbar;
state.hosts.selectedToolbarButtonIndex = DEFAULT_EMPTY_HOSTS_TOOLBAR_INDEX;
state.hosts.selectedHostIndex = 0U;
return;
}
state.hosts.focusArea = app::HostsFocusArea::grid;
state.hosts.selectedHostIndex = 0U;
}
void clamp_selected_app_index(app::ClientState &state) {
const app::HostRecord *host = app::apps_host(state);
if (host == nullptr) {
state.apps.selectedAppIndex = 0U;
return;
}
const std::vector<std::size_t> indices = visible_app_indices(*host, state.apps.showHiddenApps);
if (indices.empty()) {
state.apps.selectedAppIndex = 0U;
return;
}
if (state.apps.selectedAppIndex >= indices.size()) {
state.apps.selectedAppIndex = indices.size() - 1U;
}
}
std::vector<ui::MenuItem> build_menu_for_state(const app::ClientState &state) {
switch (state.shell.activeScreen) {
case app::ScreenId::settings:
return {
{settings_category_menu_id(app::SettingsCategory::logging), "Logging", settings_category_description(app::SettingsCategory::logging), true},
{settings_category_menu_id(app::SettingsCategory::display), "Display", settings_category_description(app::SettingsCategory::display), true},
{settings_category_menu_id(app::SettingsCategory::input), "Input", settings_category_description(app::SettingsCategory::input), true},
{settings_category_menu_id(app::SettingsCategory::reset), "Reset", settings_category_description(app::SettingsCategory::reset), true},
};
case app::ScreenId::add_host:
return {
{"edit-address", "Host Address", "Enter the IPv4 address for the PC that should be added to Moonlight.", true},
{"edit-port", "Host Port", "Override the default Moonlight host port when the PC listens on a custom value.", true},
{"test-connection", "Test Connection", "Check whether the current host address and port respond before saving anything.", true},
{"start-pairing", "Start Pairing", "Connect to the current host and begin PIN-based pairing.", true},
{"save-host", "Save Host", "Store this host in the saved host list and return to the home screen.", true},
{"cancel-add-host", "Cancel", "Discard the current host draft and return without saving.", true},
};
case app::ScreenId::pair_host:
return {
{"cancel-pairing", "Cancel", "Stop the current pairing attempt and return to the previous screen.", true},
};
case app::ScreenId::home:
case app::ScreenId::hosts:
case app::ScreenId::apps:
return {};
}
return {};
}
std::vector<ui::MenuItem> build_detail_menu_for_state(const app::ClientState &state) {
if (state.shell.activeScreen != app::ScreenId::settings) {
return {};
}
switch (state.settings.selectedCategory) {
case app::SettingsCategory::logging:
return {
{"view-log-file", "View Log File", "Open the runtime log file viewer so you can inspect the most recent log lines without leaving the shell.", true},
{"cycle-log-level", std::string("File Logging Level: ") + logging::to_string(state.settings.loggingLevel), "Choose the minimum severity written to moonlight.log. Lower levels produce more detail but increase disk writes.", true},
{"cycle-xemu-console-log-level", std::string("xemu Console Level: ") + logging::to_string(state.settings.xemuConsoleLoggingLevel), "Choose the minimum severity mirrored to xemu through DbgPrint() when you launch xemu with a serial console.", true},
};
case app::SettingsCategory::display:
return {
{
"cycle-stream-video-mode",
std::string("Stream Resolution: ") + describe_stream_resolution(state.settings.preferredVideoMode),
"Cycle through detected Xbox video modes enabled by the console settings. The selected resolution is requested from the host the next time a stream starts.",
true,
},
{
"cycle-stream-framerate",
std::string("Stream Frame Rate: ") + std::to_string(state.settings.streamFramerate) + " FPS",
"Cycle through the preferred stream frame rate. Lower frame rates can reduce video packet pressure on slower or lossy networks.",
true,
},
{
"cycle-stream-bitrate",
std::string("Stream Bitrate: ") + std::to_string(state.settings.streamBitrateKbps) + " kbps",
"Cycle through the preferred video bitrate. Lower bitrates reduce bandwidth use and can help when running Sunshine and xemu on the same NATed host.",
true,
},
{
"cycle-video-decoder",
std::string("Video Decoder: ") + video_decoder_selection_label(state.settings.videoDecoder),
"Choose automatic codec negotiation or force one FFmpeg video decoder for new streams.",
true,
},
{
"toggle-play-audio-on-pc",
std::string("Play Audio on PC: ") + (state.settings.playAudioOnPc ? "On" : "Off"),
"Toggle whether the host PC should continue local audio playback while also streaming audio to this Xbox client.",
true,
},
{
"toggle-play-audio-on-xbox",
std::string("Play Audio on Xbox: ") + (state.settings.playAudioOnXbox ? "On" : "Off"),
"Toggle local audio playback on the Xbox. Disable this to skip Opus decode work when video latency matters more than sound.",
true,
},
{
"toggle-show-performance-stats",
std::string("Show End Stream Stats: ") + (state.settings.showPerformanceStats ? "On" : "Off"),
"Toggle the performance summary shown after streaming ends.",
true,
},
};
case app::SettingsCategory::input:
return {
{"input-placeholder", "Input settings are not implemented yet", "Input-specific options are planned, but there are no adjustable controller settings in this build yet.", true},
};
case app::SettingsCategory::reset:
{
std::vector<ui::MenuItem> items = {
{"factory-reset", "Factory Reset", "Delete every Moonlight saved file, including hosts, pairing identity, cached art, and logs.", true},
};
for (const startup::SavedFileEntry &savedFile : state.settings.savedFiles) {
items.push_back({std::string(DELETE_SAVED_FILE_MENU_ID_PREFIX) + savedFile.path, "Delete " + savedFile.displayName, "Delete only this saved file from disk while leaving the rest of the Moonlight data intact.", true});
}
return items;
}
}
return {};
}
void rebuild_menu(app::ClientState &state, const std::string &preferredItemId = {}, bool preserveSelection = true) {
const std::string previousSelection = preserveSelection && state.menu.selected_item() != nullptr ? state.menu.selected_item()->id : std::string {};
state.menu.set_items(build_menu_for_state(state));
if (!preferredItemId.empty() && state.menu.select_item_by_id(preferredItemId)) {
return;
}
if (!previousSelection.empty()) {
state.menu.select_item_by_id(previousSelection);
}
const std::string previousDetailSelection = preserveSelection && state.detailMenu.selected_item() != nullptr ? state.detailMenu.selected_item()->id : std::string {};
state.detailMenu.set_items(build_detail_menu_for_state(state));
if (!preferredItemId.empty() && state.detailMenu.select_item_by_id(preferredItemId)) {
return;
}
if (!previousDetailSelection.empty()) {
state.detailMenu.select_item_by_id(previousDetailSelection);
}
}
void rebuild_settings_detail_menu(app::ClientState &state, const std::string &preferredItemId = {}, bool preserveSelection = true) {
const std::string previousSelection = preserveSelection && state.detailMenu.selected_item() != nullptr ? state.detailMenu.selected_item()->id : std::string {};
state.detailMenu.set_items(build_detail_menu_for_state(state));
if (!preferredItemId.empty() && state.detailMenu.select_item_by_id(preferredItemId)) {
return;
}
if (!previousSelection.empty()) {
state.detailMenu.select_item_by_id(previousSelection);
}
}
void close_modal(app::ClientState &state) {
state.modal = {};
reset_confirmation(state);
}
void set_screen(app::ClientState &state, app::ScreenId screen, const std::string &preferredItemId = {}) {
unload_screen_state(state, screen);
state.shell.activeScreen = screen;
if (screen == app::ScreenId::settings) {
state.settings.savedFilesDirty = true;
state.settings.focusArea = app::SettingsFocusArea::categories;
}
close_modal(state);
rebuild_menu(state, preferredItemId, false);
if (screen == app::ScreenId::settings) {
sync_selected_settings_category_from_menu(state);
rebuild_settings_detail_menu(state);
}
clamp_selected_host_index(state);
clamp_selected_app_index(state);
}
void open_modal(app::ClientState &state, app::ModalId modalId, std::size_t selectedActionIndex = 0U) {
state.modal.id = modalId;
state.modal.selectedActionIndex = selectedActionIndex;
}
void cycle_log_viewer_placement(app::ClientState &state) {
switch (state.settings.logViewerPlacement) {
case app::LogViewerPlacement::full:
state.settings.logViewerPlacement = app::LogViewerPlacement::left;
return;
case app::LogViewerPlacement::left:
state.settings.logViewerPlacement = app::LogViewerPlacement::right;
return;
case app::LogViewerPlacement::right:
state.settings.logViewerPlacement = app::LogViewerPlacement::full;
return;
}
}
void scroll_log_viewer(app::ClientState &state, bool towardOlderEntries, std::size_t step) {
if (state.settings.logViewerLines.empty() || step == 0U) {
state.settings.logViewerScrollOffset = 0U;
return;
}
const std::size_t maxOffset = state.settings.logViewerLines.size() > 1U ? state.settings.logViewerLines.size() - 1U : 0U;
if (towardOlderEntries) {
state.settings.logViewerScrollOffset = std::min(maxOffset, state.settings.logViewerScrollOffset + step);
return;
}
state.settings.logViewerScrollOffset = state.settings.logViewerScrollOffset > step ? state.settings.logViewerScrollOffset - step : 0U;
}
std::size_t modal_action_count(const app::ClientState &state) {
switch (state.modal.id) {
case app::ModalId::host_actions:
return 4U;
case app::ModalId::app_actions:
return 3U;
case app::ModalId::confirmation:
return 2U;
case app::ModalId::none:
case app::ModalId::support:
case app::ModalId::host_details:
case app::ModalId::app_details:
case app::ModalId::log_viewer:
return 0U;
}
return 0U;
}
bool move_modal_selection(app::ClientState &state, int direction) {
const std::size_t count = modal_action_count(state);
if (count == 0U) {
return false;
}
const std::size_t current = state.modal.selectedActionIndex % count;
state.modal.selectedActionIndex = direction < 0 ? (current + count - 1U) % count : (current + 1U) % count;
return state.modal.selectedActionIndex != current;
}
void open_add_host_keypad(app::ClientState &state, app::AddHostField field) {
state.addHostDraft.activeField = field;
state.addHostDraft.keypad.visible = true;
state.addHostDraft.keypad.selectedButtonIndex = 0U;
state.addHostDraft.keypad.stagedInput = field == app::AddHostField::address ? state.addHostDraft.addressInput : state.addHostDraft.portInput;
state.shell.statusMessage = field == app::AddHostField::address ? "Editing host address" : "Editing host port";
rebuild_menu(state, add_host_field_menu_id(field));
}
void close_add_host_keypad(app::ClientState &state) {
state.addHostDraft.keypad.visible = false;
state.addHostDraft.keypad.stagedInput.clear();
rebuild_menu(state, add_host_field_menu_id(state.addHostDraft.activeField));
}
void accept_add_host_keypad(app::ClientState &state) {
if (state.addHostDraft.activeField == app::AddHostField::address) {
state.addHostDraft.addressInput = state.addHostDraft.keypad.stagedInput;
state.shell.statusMessage = "Updated host address";
} else {
state.addHostDraft.portInput = state.addHostDraft.keypad.stagedInput;
state.shell.statusMessage = state.addHostDraft.portInput.empty() ? "Using default Moonlight host port 47989" : "Updated host port";
}
state.addHostDraft.validationMessage.clear();
state.addHostDraft.connectionMessage.clear();
close_add_host_keypad(state);
}
void cancel_add_host_keypad(app::ClientState &state) {
state.shell.statusMessage = state.addHostDraft.activeField == app::AddHostField::address ? "Cancelled host address edit" : "Cancelled host port edit";
close_add_host_keypad(state);
}
bool move_add_host_keypad_selection(app::ClientState &state, int rowDelta, int columnDelta) {
const AddHostKeypadLayout layout = add_host_keypad_layout(state);
if (layout.buttonCount == 0U) {
return false;
}
const auto rowCount = static_cast<int>((layout.buttonCount + ADD_HOST_KEYPAD_COLUMN_COUNT - 1U) / ADD_HOST_KEYPAD_COLUMN_COUNT);
const std::size_t currentIndex = state.addHostDraft.keypad.selectedButtonIndex % layout.buttonCount;
const auto currentRow = static_cast<int>(currentIndex / ADD_HOST_KEYPAD_COLUMN_COUNT);
const auto currentColumn = static_cast<int>(currentIndex % ADD_HOST_KEYPAD_COLUMN_COUNT);
auto wrap_index = [](int value, int count) {
if (count <= 0) {
return 0;
}
int wrappedValue = value % count;
if (wrappedValue < 0) {
wrappedValue += count;
}
return wrappedValue;
};
int targetRow = currentRow;
int targetColumn = currentColumn;
if (rowDelta != 0) {
targetRow = wrap_index(currentRow + rowDelta, rowCount);
const std::size_t rowStart = static_cast<std::size_t>(targetRow) * ADD_HOST_KEYPAD_COLUMN_COUNT;
const std::size_t rowWidth = std::min<std::size_t>(ADD_HOST_KEYPAD_COLUMN_COUNT, layout.buttonCount - rowStart);
targetColumn = static_cast<int>(std::min<std::size_t>(currentColumn, rowWidth - 1U));
}
const std::size_t targetRowStart = static_cast<std::size_t>(targetRow) * ADD_HOST_KEYPAD_COLUMN_COUNT;
if (const std::size_t targetRowWidth = std::min<std::size_t>(ADD_HOST_KEYPAD_COLUMN_COUNT, layout.buttonCount - targetRowStart); columnDelta != 0 && targetRowWidth > 0U) {
targetColumn = wrap_index(targetColumn + columnDelta, static_cast<int>(targetRowWidth));
}
const auto nextIndex = targetRowStart + static_cast<std::size_t>(targetColumn);
state.addHostDraft.keypad.selectedButtonIndex = nextIndex;
return nextIndex != currentIndex;
}
void append_to_active_add_host_field(app::ClientState &state, char character) {
state.addHostDraft.keypad.stagedInput.push_back(character);
state.addHostDraft.validationMessage.clear();
state.addHostDraft.connectionMessage.clear();
}
void backspace_active_add_host_field(app::ClientState &state) {
if (!state.addHostDraft.keypad.stagedInput.empty()) {
state.addHostDraft.keypad.stagedInput.pop_back();
}
}
bool normalize_add_host_inputs(const app::ClientState &state, std::string *normalizedAddress, uint16_t *parsedPort, std::string *errorMessage) {
const std::string address = app::normalize_ipv4_address(state.addHostDraft.addressInput);
if (address.empty()) {
if (errorMessage != nullptr) {
*errorMessage = "Enter a valid IPv4 host address";
}
return false;
}
uint16_t port = 0;
if (!state.addHostDraft.portInput.empty() && !app::try_parse_host_port(state.addHostDraft.portInput, &port)) {
if (errorMessage != nullptr) {
*errorMessage = "Enter a valid host port";
}
return false;
}
if (normalizedAddress != nullptr) {
*normalizedAddress = address;
}
if (parsedPort != nullptr) {
*parsedPort = port;
}
return true;
}
app::HostRecord make_host_record(const std::string &address, uint16_t port) {
return {
app::build_default_host_display_name(address),
address,
port,
app::PairingState::not_paired,
app::HostReachability::unknown,
{},
{},
{},
{},
{},
address,
{},
0,
0,
{},
app::HostAppListState::idle,
{},
0,
};
}
void move_toolbar_selection(app::ClientState &state, int direction) {
const std::size_t current = state.hosts.selectedToolbarButtonIndex % HOST_TOOLBAR_BUTTON_COUNT;
state.hosts.selectedToolbarButtonIndex = direction < 0 ? (current + HOST_TOOLBAR_BUTTON_COUNT - 1U) % HOST_TOOLBAR_BUTTON_COUNT : (current + 1U) % HOST_TOOLBAR_BUTTON_COUNT;
}
std::size_t grid_row_count(std::size_t itemCount, std::size_t columnCount) {
return itemCount == 0U || columnCount == 0U ? 0U : ((itemCount + columnCount - 1U) / columnCount);
}
std::size_t grid_row_start(std::size_t row, std::size_t columnCount) {
return row * columnCount;
}
std::size_t grid_row_end(std::size_t itemCount, std::size_t row, std::size_t columnCount) {
return std::min(itemCount, grid_row_start(row, columnCount) + columnCount);
}
std::size_t closest_index_in_row(std::size_t itemCount, std::size_t row, std::size_t columnCount, std::size_t preferredColumn) {
const std::size_t rowStart = grid_row_start(row, columnCount);
const std::size_t rowEnd = grid_row_end(itemCount, row, columnCount);
if (rowStart >= rowEnd) {
return itemCount == 0U ? 0U : (itemCount - 1U);
}
return rowStart + std::min(preferredColumn, (rowEnd - rowStart) - 1U);
}
bool move_grid_selection(std::size_t itemCount, std::size_t columnCount, int rowDelta, int columnDelta, std::size_t *selectedIndex, bool *movedAboveFirstRow = nullptr) {
if (movedAboveFirstRow != nullptr) {
*movedAboveFirstRow = false;
}
if (selectedIndex == nullptr || itemCount == 0U || columnCount == 0U) {
return false;
}
std::size_t currentIndex = std::min(*selectedIndex, itemCount - 1U);
const std::size_t rowCount = grid_row_count(itemCount, columnCount);
const std::size_t currentRow = currentIndex / columnCount;
const std::size_t currentColumn = currentIndex % columnCount;
if (columnDelta > 0) {
for (int step = 0; step < columnDelta; ++step) {
if (const std::size_t rowEnd = grid_row_end(itemCount, currentRow, columnCount); currentIndex + 1U < rowEnd) {
++currentIndex;
continue;
}
const std::size_t nextRow = (currentIndex / columnCount) + 1U;
if (nextRow >= rowCount) {
break;
}
currentIndex = grid_row_start(nextRow, columnCount);
}
*selectedIndex = currentIndex;
return true;
}
if (columnDelta < 0) {
for (int step = 0; step < -columnDelta; ++step) {
if ((currentIndex % columnCount) > 0U) {
--currentIndex;
continue;
}
const std::size_t currentResolvedRow = currentIndex / columnCount;
if (currentResolvedRow == 0U) {
break;
}
const std::size_t previousRow = currentResolvedRow - 1U;
currentIndex = grid_row_end(itemCount, previousRow, columnCount) - 1U;
}
*selectedIndex = currentIndex;
return true;
}
if (rowDelta == 0) {
return false;
}
const int targetRow = static_cast<int>(currentRow) + rowDelta;
if (targetRow < 0) {
if (movedAboveFirstRow != nullptr) {
*movedAboveFirstRow = true;
}
return false;
}
const std::size_t clampedRow = std::min(static_cast<std::size_t>(targetRow), rowCount - 1U);
*selectedIndex = closest_index_in_row(itemCount, clampedRow, columnCount, currentColumn);
return true;
}
void move_host_grid_selection(app::ClientState &state, int rowDelta, int columnDelta) {
if (state.hosts.items.empty()) {
state.hosts.focusArea = app::HostsFocusArea::toolbar;
return;
}
bool movedAboveFirstRow = false;
move_grid_selection(state.hosts.items.size(), HOST_GRID_COLUMN_COUNT, rowDelta, columnDelta, &state.hosts.selectedHostIndex, &movedAboveFirstRow);
if (movedAboveFirstRow) {
state.hosts.focusArea = app::HostsFocusArea::toolbar;
return;
}
state.hosts.focusArea = app::HostsFocusArea::grid;
}
void move_app_grid_selection(app::ClientState &state, int rowDelta, int columnDelta) {
const app::HostRecord *host = app::apps_host(state);
if (host == nullptr) {
state.apps.selectedAppIndex = 0U;
return;
}