-
Notifications
You must be signed in to change notification settings - Fork 55
/
steam_overlay.cpp
1936 lines (1628 loc) · 75.9 KB
/
steam_overlay.cpp
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
#ifdef EMU_OVERLAY
// if you're wondering about text like: ##PopupAcceptInvite
// these are unique labels (keys) for each button/label/text,etc...
// ImGui uses the labels as keys, adding a suffic like "My Text##SomeKey"
// avoids confusing ImGui when another label has the same text "MyText"
#include "overlay/steam_overlay.h"
#include "overlay/notification.h"
#include "overlay/steam_overlay_translations.h"
#include <thread>
#include <string>
#include <sstream>
#include <cctype>
#include <utility>
#include <random>
#include "InGameOverlay/ImGui/imgui.h"
#include "dll/dll.h"
#include "dll/settings_parser.h"
#include "InGameOverlay/RendererDetector.h"
// fonts
#include "fonts/unifont.hpp"
#define URL_WINDOW_NAME "URL Window"
static constexpr int max_window_id = 10000;
static constexpr int base_notif_window_id = 0 * max_window_id;
static constexpr int base_friend_window_id = 1 * max_window_id;
static constexpr int base_friend_item_id = 2 * max_window_id;
static const char* valid_languages[] = {
"english",
"arabic",
"bulgarian",
"schinese",
"tchinese",
"czech",
"danish",
"dutch",
"finnish",
"french",
"german",
"greek",
"hungarian",
"italian",
"japanese",
"koreana",
"norwegian",
"polish",
"portuguese",
"brazilian",
"romanian",
"russian",
"spanish",
"latam",
"swedish",
"thai",
"turkish",
"ukrainian",
"vietnamese",
"croatian"
};
static ImFontAtlas fonts_atlas{};
static ImFont *font_default{};
static ImFont *font_notif{};
static std::recursive_mutex overlay_mutex{};
static std::atomic<bool> setup_overlay_called = false;
static std::map<std::string, std::vector<char>> wav_files{
{ "overlay_achievement_notification.wav", std::vector<char>{} },
{ "overlay_friend_notification.wav", std::vector<char>{} },
};
// ListBoxHeader() is deprecated and inlined inside <imgui.h>
// Helper to calculate size from items_count and height_in_items
static inline bool ImGuiHelper_BeginListBox(const char* label, int items_count) {
int min_items = items_count < 7 ? items_count : 7;
float height = ImGui::GetTextLineHeightWithSpacing() * (min_items + 0.25f) + ImGui::GetStyle().FramePadding.y * 2.0f;
return ImGui::BeginListBox(label, ImVec2(0.0f, height));
}
void Steam_Overlay::overlay_run_callback(void* object)
{
// PRINT_DEBUG_ENTRY();
Steam_Overlay* _this = reinterpret_cast<Steam_Overlay*>(object);
_this->steam_run_callback();
}
void Steam_Overlay::overlay_networking_callback(void* object, Common_Message* msg)
{
Steam_Overlay* _this = reinterpret_cast<Steam_Overlay*>(object);
_this->networking_msg_received(msg);
}
Steam_Overlay::Steam_Overlay(Settings* settings, Local_Storage *local_storage, SteamCallResults* callback_results, SteamCallBacks* callbacks, RunEveryRunCB* run_every_runcb, Networking* network) :
settings(settings),
local_storage(local_storage),
callback_results(callback_results),
callbacks(callbacks),
run_every_runcb(run_every_runcb),
network(network)
{
// don't even bother initializing the overlay
if (settings->disable_overlay) return;
strncpy(username_text, settings->get_local_name(), sizeof(username_text));
// we need these copies to show the warning only once, then disable the flag
// avoid manipulating settings->xxx
this->warn_local_save =
!settings->disable_overlay_warning_any && !settings->disable_overlay_warning_local_save && settings->overlay_warn_local_save;
this->warn_bad_appid =
!settings->disable_overlay_warning_any && !settings->disable_overlay_warning_bad_appid && settings->get_local_game_id().AppID() == 0;
current_language = 0;
const char *language = settings->get_language();
int i = 0;
for (auto &lang : valid_languages) {
if (strcmp(lang, language) == 0) {
current_language = i;
break;
}
++i;
}
this->network->setCallback(CALLBACK_ID_STEAM_MESSAGES, settings->get_local_steam_id(), &Steam_Overlay::overlay_networking_callback, this);
run_every_runcb->add(&Steam_Overlay::overlay_run_callback, this);
}
Steam_Overlay::~Steam_Overlay()
{
if (settings->disable_overlay) return;
this->network->rmCallback(CALLBACK_ID_STEAM_MESSAGES, settings->get_local_steam_id(), &Steam_Overlay::overlay_networking_callback, this);
run_every_runcb->remove(&Steam_Overlay::overlay_run_callback, this);
}
void Steam_Overlay::request_renderer_detector()
{
PRINT_DEBUG_ENTRY();
// request renderer detection
future_renderer = InGameOverlay::DetectRenderer();
}
void Steam_Overlay::renderer_detector_delay_thread()
{
PRINT_DEBUG("waiting for %i seconds", settings->overlay_hook_delay_sec);
// give games some time to init their renderer (DirectX, OpenGL, etc...)
int timeout_ctr = settings->overlay_hook_delay_sec /*seconds*/ * 1000 /*milli per second*/ / renderer_detector_polling_ms;
while (timeout_ctr > 0 && setup_overlay_called ) {
--timeout_ctr;
std::this_thread::sleep_for(std::chrono::milliseconds(renderer_detector_polling_ms));
}
// early exit before we get a chance to do anything
if (!setup_overlay_called) {
PRINT_DEBUG("early exit before renderer detection");
return;
}
// request renderer detection
request_renderer_detector();
renderer_hook_init_thread();
}
void Steam_Overlay::renderer_hook_init_thread()
{
PRINT_DEBUG_ENTRY();
int timeout_ctr = settings->overlay_renderer_detector_timeout_sec /*seconds*/ * 1000 /*milli per second*/ / renderer_detector_polling_ms;
while (timeout_ctr > 0 && setup_overlay_called && future_renderer.wait_for(std::chrono::milliseconds(renderer_detector_polling_ms)) != std::future_status::ready) {
--timeout_ctr;
}
// free detector resources and check for failure
InGameOverlay::StopRendererDetection();
InGameOverlay::FreeDetector();
// exit on failure
bool final_chance = (future_renderer.wait_for(std::chrono::milliseconds(1)) == std::future_status::ready) && future_renderer.valid();
// again check for 'setup_overlay_called' to be extra sure that the overlay wasn't deinitialized
if (!setup_overlay_called || !final_chance || timeout_ctr <= 0) {
PRINT_DEBUG("failed to detect renderer, ctr=%i, overlay was set up=%i, hook intance state=%i",
timeout_ctr, (int)setup_overlay_called, (int)final_chance
);
return;
}
// do a one time initialization
// std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
_renderer = future_renderer.get();
if (!_renderer) { // is this even possible?
PRINT_DEBUG("renderer hook was null!");
return;
}
PRINT_DEBUG("got renderer hook %p for '%s'", _renderer, _renderer->GetLibraryName().c_str());
// note: make sure to load all relevant strings before creating the font(s), otherwise some glyphs ranges will be missing
load_achievements_data();
load_audio();
create_fonts();
// setup renderer callbacks
const static std::set<InGameOverlay::ToggleKey> overlay_toggle_keys = {
InGameOverlay::ToggleKey::SHIFT, InGameOverlay::ToggleKey::TAB
};
auto overlay_toggle_callback = [this]() { open_overlay_hook(true); };
_renderer->OverlayProc = [this]() { overlay_render_proc(); };
_renderer->OverlayHookReady = [this](InGameOverlay::OverlayHookState state) {
PRINT_DEBUG("hook state changed to <%i>", (int)state);
overlay_state_hook(state == InGameOverlay::OverlayHookState::Ready || state == InGameOverlay::OverlayHookState::Reset);
};
bool started = _renderer->StartHook(overlay_toggle_callback, overlay_toggle_keys, &fonts_atlas);
PRINT_DEBUG("started renderer hook (result=%i)", (int)started);
}
// note: make sure to load all relevant strings before creating the font(s), otherwise some glyphs ranges will be missing
void Steam_Overlay::create_fonts()
{
PRINT_DEBUG_ENTRY();
// disable rounding the texture height to the next power of two
// see this: https://github.com/ocornut/imgui/blob/master/docs/FONTS.md#4-font-atlas-texture-fails-to-upload-to-gpu
fonts_atlas.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;
float font_size = settings->overlay_appearance.font_size;
static ImFontConfig font_cfg{};
font_cfg.FontDataOwnedByAtlas = false; // https://github.com/ocornut/imgui/blob/master/docs/FONTS.md#loading-font-data-from-memory
font_cfg.PixelSnapH = true;
font_cfg.OversampleH = 1;
font_cfg.OversampleV = 1;
font_cfg.SizePixels = font_size;
// non-latin characters look ugly and squeezed without this horizontal spacing
font_cfg.GlyphExtraSpacing.x = settings->overlay_appearance.font_glyph_extra_spacing_x;
font_cfg.GlyphExtraSpacing.y = settings->overlay_appearance.font_glyph_extra_spacing_y;
static ImFontGlyphRangesBuilder font_builder{};
for (const auto &ach : achievements) {
font_builder.AddText(ach.title.c_str());
font_builder.AddText(ach.description.c_str());
}
for (int i = 0; i < TRANSLATION_NUMBER_OF_LANGUAGES; i++) {
font_builder.AddText(translationChat[i]);
font_builder.AddText(translationCopyId[i]);
font_builder.AddText(translationTestAchievement[i]);
font_builder.AddText(translationInvite[i]);
font_builder.AddText(translationInviteAll[i]);
font_builder.AddText(translationJoin[i]);
font_builder.AddText(translationInvitedYouToJoinTheGame[i]);
font_builder.AddText(translationAccept[i]);
font_builder.AddText(translationRefuse[i]);
font_builder.AddText(translationSend[i]);
font_builder.AddText(translationUserPlaying[i]);
font_builder.AddText(translationRenderer[i]);
font_builder.AddText(translationShowAchievements[i]);
font_builder.AddText(translationSettings[i]);
font_builder.AddText(translationFriends[i]);
font_builder.AddText(translationAchievementWindow[i]);
font_builder.AddText(translationListOfAchievements[i]);
font_builder.AddText(translationAchievements[i]);
font_builder.AddText(translationHiddenAchievement[i]);
font_builder.AddText(translationAchievedOn[i]);
font_builder.AddText(translationNotAchieved[i]);
font_builder.AddText(translationGlobalSettingsWindow[i]);
font_builder.AddText(translationGlobalSettingsWindowDescription[i]);
font_builder.AddText(translationUsername[i]);
font_builder.AddText(translationLanguage[i]);
font_builder.AddText(translationSelectedLanguage[i]);
font_builder.AddText(translationRestartTheGameToApply[i]);
font_builder.AddText(translationSave[i]);
font_builder.AddText(translationWarning[i]);
font_builder.AddText(translationWarningWarningWarning[i]);
font_builder.AddText(translationWarningDescription_badAppid[i]);
font_builder.AddText(translationWarningDescription_localSave[i]);
font_builder.AddText(translationSteamOverlayURL[i]);
font_builder.AddText(translationClose[i]);
font_builder.AddText(translationPlaying[i]);
font_builder.AddText(translationAutoAcceptFriendInvite[i]);
}
font_builder.AddRanges(fonts_atlas.GetGlyphRangesDefault());
static ImVector<ImWchar> ranges{};
font_builder.BuildRanges(&ranges);
font_cfg.GlyphRanges = ranges.Data;
if (settings->overlay_appearance.font_override.size()) {
fonts_atlas.AddFontFromFileTTF(settings->overlay_appearance.font_override.c_str(), font_size, &font_cfg);
font_cfg.MergeMode = true; // merge next fonts into the first one, as if they were all just 1 font file
}
// note: base85 compressed arrays caused a compiler heap allocation error, regular compression is more guaranteed
ImFont *font = fonts_atlas.AddFontFromMemoryCompressedTTF(unifont_compressed_data, unifont_compressed_size, font_size, &font_cfg);
font_notif = font_default = font;
bool res = fonts_atlas.Build();
PRINT_DEBUG("created fonts atlas (result=%i)", (int)res);
reset_LastError();
}
void Steam_Overlay::load_audio()
{
PRINT_DEBUG_ENTRY();
for (auto &kv : wav_files) {
std::string file_path{};
unsigned int file_size{};
// try local location first, then try global location
for (const auto &settings_path : { Local_Storage::get_game_settings_path(), local_storage->get_global_settings_path() }) {
file_path = settings_path + Steam_Overlay::ACH_SOUNDS_FOLDER + PATH_SEPARATOR + kv.first;
file_size = file_size_(file_path);
if (file_size) break;
}
kv.second.clear();
if (file_size) {
kv.second.assign(file_size + 1, 0); // +1 because this will be treated as a null-terminated string later
int read = Local_Storage::get_file_data(file_path, (char *)&kv.second[0], file_size);
if (read <= 0) kv.second.clear();
PRINT_DEBUG("loaded '%s' (read %i/%u bytes)", file_path.c_str(), read, file_size);
}
}
}
void Steam_Overlay::load_achievements_data()
{
PRINT_DEBUG_ENTRY();
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Steam_User_Stats* steamUserStats = get_steam_client()->steam_user_stats;
uint32 achievements_num = steamUserStats->GetNumAchievements();
for (uint32 i = 0; i < achievements_num; ++i) {
Overlay_Achievement ach{};
ach.name = steamUserStats->GetAchievementName(i);
ach.title = steamUserStats->GetAchievementDisplayAttribute(ach.name.c_str(), "name");
ach.description = steamUserStats->GetAchievementDisplayAttribute(ach.name.c_str(), "desc");
const char *hidden = steamUserStats->GetAchievementDisplayAttribute(ach.name.c_str(), "hidden");
ach.hidden = hidden && hidden[0] == '1';
bool achieved = false;
uint32 unlock_time = 0;
if (steamUserStats->GetAchievementAndUnlockTime(ach.name.c_str(), &achieved, &unlock_time)) {
ach.achieved = achieved;
ach.unlock_time = unlock_time;
} else {
ach.achieved = false;
ach.unlock_time = 0;
}
ach.icon_name = steamUserStats->get_achievement_icon_name(ach.name.c_str(), true);
ach.icon_gray_name = steamUserStats->get_achievement_icon_name(ach.name.c_str(), false);
achievements.push_back(ach);
if (!setup_overlay_called) return;
}
PRINT_DEBUG("count=%u, loaded=%zu", achievements_num, achievements.size());
}
void Steam_Overlay::initial_load_achievements_icons()
{
{
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
if (late_init_ach_icons) return;
}
PRINT_DEBUG_ENTRY();
for (auto &ach : achievements) {
{
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
if (!is_ready || !setup_overlay_called) {
PRINT_DEBUG("early exit");
return;
}
}
try_load_ach_icon(ach, true);
{
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
if (!is_ready || !setup_overlay_called) {
PRINT_DEBUG("early exit");
return;
}
}
try_load_ach_icon(ach, false);
}
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
late_init_ach_icons = true;
}
// called initially and when window size is updated
void Steam_Overlay::overlay_state_hook(bool ready)
{
PRINT_DEBUG("%i", (int)ready);
// NOTE usage of local objects here cause an exception when this is called with false state
// the reason is that by the time this hook is called, the object may have been already destructed
// this is why we use global mutex
// TODO this also doesn't seem right, no idea why it happens though
// NOTE after initializing the renderer detector on another thread this was solved
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
if (!setup_overlay_called) return;
is_ready = ready;
if (ready) {
// Antichamber may crash here because ImGui Context is null!, no idea why
bool not_yet = false;
if (ImGui::GetCurrentContext() && late_init_imgui.compare_exchange_weak(not_yet, true)) {
PRINT_DEBUG("late init ImGui");
ImGuiIO &io = ImGui::GetIO();
// disable loading the default ini file
io.IniFilename = NULL;
ImGuiStyle &style = ImGui::GetStyle();
// Disable round window
style.WindowRounding = 0.0;
}
}
}
// called when the user presses SHIFT + TAB
bool Steam_Overlay::open_overlay_hook(bool toggle)
{
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
if (toggle) {
ShowOverlay(!show_overlay);
}
return show_overlay;
}
void Steam_Overlay::allow_renderer_frame_processing(bool state, bool cleaning_up_overlay)
{
// this is very important internally it calls the necessary fuctions
// to properly update ImGui window size on the next overlay_render_proc() call
if (state) {
auto new_val = ++renderer_frame_processing_requests;
if (new_val == 1) { // only take an action on first request
// allow internal frmae processing
_renderer->HideOverlayInputs(false);
PRINT_DEBUG("enabled frame processing (count=%u)", new_val);
}
} else {
if (renderer_frame_processing_requests > 0) {
auto new_val = --renderer_frame_processing_requests;
if (!new_val || cleaning_up_overlay) { // only take an action when the requests reach 0 or by force
_renderer->HideOverlayInputs(true);
PRINT_DEBUG("disabled frame processing (count=%u, force=%i)", new_val, (int)cleaning_up_overlay);
}
}
}
}
void Steam_Overlay::obscure_game_input(bool state) {
if (state) {
auto new_val = ++obscure_cursor_requests;
if (new_val == 1) { // only take an action on first request
ImGuiIO &io = ImGui::GetIO();
// force draw the cursor, otherwise games like Truberbrook will not have an overlay cursor
io.MouseDrawCursor = state;
// not necessary, just to be sure
io.WantCaptureMouse = state;
// not necessary, just to be sure
io.WantCaptureKeyboard = state;
// clip the cursor
_renderer->HideAppInputs(true);
PRINT_DEBUG("obscured app input (count=%u)", new_val);
}
} else {
if (obscure_cursor_requests > 0) {
auto new_val = --obscure_cursor_requests;
if (!new_val) { // only take an action when the requests reach 0
ImGuiIO &io = ImGui::GetIO();
// force draw the cursor, otherwise games like Truberbrook will not have an overlay cursor
io.MouseDrawCursor = state;
// not necessary, just to be sure
io.WantCaptureMouse = state;
// not necessary, just to be sure
io.WantCaptureKeyboard = state;
// restore the old cursor
_renderer->HideAppInputs(false);
PRINT_DEBUG("restored app input (count=%u)", new_val);
}
}
}
}
void Steam_Overlay::notify_sound_user_invite(friend_window_state& friend_state)
{
if (settings->disable_overlay_friend_notification) return;
if (!(friend_state.window_state & window_state_show)) {
friend_state.window_state |= window_state_need_attention;
#ifdef __WINDOWS__
auto wav_data = wav_files.find("overlay_friend_notification.wav");
if (wav_files.end() != wav_data && wav_data->second.size()) {
PlaySoundA((LPCSTR)&wav_data->second[0], NULL, SND_ASYNC | SND_MEMORY);
} else {
PlaySoundA((LPCSTR)notif_invite_wav, NULL, SND_ASYNC | SND_MEMORY);
}
#endif
}
}
void Steam_Overlay::notify_sound_user_achievement()
{
if (settings->disable_overlay_achievement_notification) return;
#ifdef __WINDOWS__
auto wav_data = wav_files.find("overlay_achievement_notification.wav");
if (wav_files.end() != wav_data && wav_data->second.size()) {
PlaySoundA((LPCSTR)&wav_data->second[0], NULL, SND_ASYNC | SND_MEMORY);
}
#endif
}
void Steam_Overlay::notify_sound_auto_accept_friend_invite()
{
#ifdef __WINDOWS__
auto wav_data = wav_files.find("overlay_friend_notification.wav");
if (wav_files.end() != wav_data && wav_data->second.size()) {
PlaySoundA((LPCSTR)&wav_data->second[0], NULL, SND_ASYNC | SND_MEMORY);
} else {
PlaySoundA((LPCSTR)notif_invite_wav, NULL, SND_ASYNC | SND_MEMORY);
}
#endif
}
int find_free_id(std::vector<int> &ids, int base)
{
std::sort(ids.begin(), ids.end());
int id = base;
for (auto i : ids)
{
if (id < i)
break;
id = i + 1;
}
return id > (base+max_window_id) ? 0 : id;
}
int find_free_friend_id(const std::map<Friend, friend_window_state, Friend_Less> &friend_windows)
{
std::vector<int> ids{};
ids.reserve(friend_windows.size());
std::for_each(friend_windows.begin(), friend_windows.end(), [&ids](std::pair<Friend const, friend_window_state> const& i)
{
ids.emplace_back(i.second.id);
});
return find_free_id(ids, base_friend_window_id);
}
int find_free_notification_id(std::vector<Notification> const& notifications)
{
std::vector<int> ids{};
ids.reserve(notifications.size());
std::for_each(notifications.begin(), notifications.end(), [&ids](Notification const& i)
{
ids.emplace_back(i.id);
});
return find_free_id(ids, base_friend_window_id);
}
bool Steam_Overlay::submit_notification(notification_type type, const std::string &msg, std::pair<const Friend, friend_window_state> *frd, const std::weak_ptr<uint64_t> &icon)
{
PRINT_DEBUG("%i", (int)type);
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
if (!Ready()) return false;
int id = find_free_notification_id(notifications);
if (id == 0) {
PRINT_DEBUG("error no free id to create a notification window");
return false;
}
Notification notif{};
notif.start_time = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch());
notif.id = id;
notif.type = (uint8)type;
notif.message = msg;
notif.frd = frd;
notif.icon = icon;
notifications.emplace_back(notif);
allow_renderer_frame_processing(true);
// uncomment this block to obscure cursor input and steal focus for these specific notifications
switch (type) {
// we want to steal focus for these ones
case notification_type::invite:
obscure_game_input(true);
break;
// not effective
case notification_type::achievement:
case notification_type::auto_accept_invite:
case notification_type::message:
// nothing
break;
default:
PRINT_DEBUG("error unhandled type %i", (int)type);
break;
}
return true;
}
void Steam_Overlay::add_chat_message_notification(std::string const &message)
{
PRINT_DEBUG("'%s'", message.c_str());
std::lock_guard<std::recursive_mutex> lock(overlay_mutex);
if (settings->disable_overlay_friend_notification) return;
submit_notification(notification_type::message, message);
}
bool Steam_Overlay::is_friend_joinable(std::pair<const Friend, friend_window_state> &f)
{
PRINT_DEBUG("%" PRIu64 "", f.first.id());
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Steam_Friends* steamFriends = get_steam_client()->steam_friends;
if (std::string(steamFriends->GetFriendRichPresence((uint64)f.first.id(), "connect")).length() > 0 ) {
PRINT_DEBUG("%" PRIu64 " true (connect string)", f.first.id());
return true;
}
FriendGameInfo_t friend_game_info{};
steamFriends->GetFriendGamePlayed((uint64)f.first.id(), &friend_game_info);
if (friend_game_info.m_steamIDLobby.IsValid() && (f.second.window_state & window_state_lobby_invite)) {
PRINT_DEBUG("%" PRIu64 " true (friend in a game)", f.first.id());
return true;
}
PRINT_DEBUG("%" PRIu64 " false", f.first.id());
return false;
}
bool Steam_Overlay::got_lobby()
{
std::lock_guard<std::recursive_mutex> lock(global_mutex);
Steam_Friends* steamFriends = get_steam_client()->steam_friends;
if (std::string(steamFriends->GetFriendRichPresence(settings->get_local_steam_id(), "connect")).length() > 0)
return true;
if (settings->get_lobby().IsValid())
return true;
return false;
}
void Steam_Overlay::build_friend_context_menu(Friend const& frd, friend_window_state& state)
{
if (ImGui::BeginPopupContextItem("Friends_ContextMenu", 1)) {
// this is set to true if any button was clicked
// otherwise, after clicking any button, the menu will be persistent
bool close_popup = false;
// user clicked on "chat"
if (ImGui::Button(translationChat[current_language])) {
close_popup = true;
state.window_state |= window_state_show;
}
// user clicked on "copy id" on a friend
if (ImGui::Button(translationCopyId[current_language])) {
close_popup = true;
auto friend_id_str = std::to_string(frd.id());
ImGui::SetClipboardText(friend_id_str.c_str());
}
// If we have the same appid, activate the invite/join buttons
if (settings->get_local_game_id().AppID() == frd.appid()) {
// user clicked on "invite to game"
std::string translationInvite_tmp(translationInvite[current_language]);
translationInvite_tmp.append("##PopupInviteToGame");
if (i_have_lobby && ImGui::Button(translationInvite_tmp.c_str())) {
close_popup = true;
state.window_state |= window_state_invite;
has_friend_action.push(frd);
}
// user clicked on "accept game invite"
std::string translationJoin_tmp(translationJoin[current_language]);
translationJoin_tmp.append("##PopupAcceptInvite");
if (state.joinable && ImGui::Button(translationJoin_tmp.c_str())) {
close_popup = true;
// don't bother adding this friend if the button "invite all" was clicked
// we will send them the invitation later in Steam_Overlay::steam_run_callback()
if (!invite_all_friends_clicked) {
state.window_state |= window_state_join;
has_friend_action.push(frd);
}
}
}
if (close_popup || invite_all_friends_clicked) {
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
void Steam_Overlay::build_friend_window(Friend const& frd, friend_window_state& state)
{
if (!(state.window_state & window_state_show))
return;
bool show = true;
bool send_chat_msg = false;
float width = ImGui::CalcTextSize("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").x;
if (state.window_state & window_state_need_attention && ImGui::IsWindowFocused()) {
state.window_state &= ~window_state_need_attention;
}
ImGui::SetNextWindowSizeConstraints(ImVec2{ width, ImGui::GetFontSize()*8 + ImGui::GetFrameHeightWithSpacing()*4 },
ImVec2{ std::numeric_limits<float>::max() , std::numeric_limits<float>::max() });
ImGui::SetNextWindowBgAlpha(0.9f);
// Window id is after the ###, the window title is the friend name
std::string friend_window_id = std::move("###" + std::to_string(state.id));
if (ImGui::Begin((state.window_title + friend_window_id).c_str(), &show)) {
if (state.window_state & window_state_need_attention && ImGui::IsWindowFocused())
{
state.window_state &= ~window_state_need_attention;
}
// Fill this with the chat box and maybe the invitation
if (state.window_state & (window_state_lobby_invite | window_state_rich_invite))
{
ImGui::LabelText("##label", translationInvitedYouToJoinTheGame[current_language], frd.name().c_str(), frd.appid());
ImGui::SameLine();
if (ImGui::Button(translationAccept[current_language]))
{
state.window_state |= window_state_join;
this->has_friend_action.push(frd);
}
ImGui::SameLine();
if (ImGui::Button(translationRefuse[current_language]))
{
state.window_state &= ~(window_state_lobby_invite | window_state_rich_invite);
}
}
ImGui::InputTextMultiline("##chat_history", &state.chat_history[0], state.chat_history.length(), { -1.0f, -2.0f * ImGui::GetFontSize() }, ImGuiInputTextFlags_ReadOnly);
// TODO: Fix the layout of the chat line + send button.
// It should be like this: chat input should fill the window size minus send button size (button size is fixed)
// |------------------------------|
// | /--------------------------\ |
// | | | |
// | | chat history | |
// | | | |
// | \--------------------------/ |
// | [____chat line______] [send] |
// |------------------------------|
//
// And it is like this
// |------------------------------|
// | /--------------------------\ |
// | | | |
// | | chat history | |
// | | | |
// | \--------------------------/ |
// | [__chat line__] [send] |
// |------------------------------|
float wnd_width = ImGui::GetContentRegionAvail().x;
ImGuiStyle &style = ImGui::GetStyle();
wnd_width -= ImGui::CalcTextSize(translationSend[current_language]).x + style.FramePadding.x * 2 + style.ItemSpacing.x + 1;
uint64_t frd_id = frd.id();
ImGui::PushID((const char *)&frd_id, (const char *)&frd_id + sizeof(frd_id));
ImGui::PushItemWidth(wnd_width);
if (ImGui::InputText("##chat_line", state.chat_input, max_chat_len, ImGuiInputTextFlags_EnterReturnsTrue))
{
send_chat_msg = true;
ImGui::SetKeyboardFocusHere(-1);
}
ImGui::PopItemWidth();
ImGui::PopID();
ImGui::SameLine();
if (ImGui::Button(translationSend[current_language]))
{
send_chat_msg = true;
}
if (send_chat_msg)
{
if (!(state.window_state & window_state_send_message))
{
has_friend_action.push(frd);
state.window_state |= window_state_send_message;
}
}
}
// User closed the friend window
if (!show)
state.window_state &= ~window_state_show;
ImGui::End();
}
// set the position of the next notification
void Steam_Overlay::set_next_notification_pos(float width, float height, const Notification ¬i, struct NotificationsIndexes &idx)
{
const float noti_width = width * Notification::width_percent;
auto &global_style = ImGui::GetStyle();
const float padding_all_sides = 2 * (global_style.WindowPadding.y + global_style.WindowPadding.x);
PRINT_DEBUG("%f", padding_all_sides);
const float msg_height = ImGui::CalcTextSize(
noti.message.c_str(),
noti.message.c_str() + noti.message.size(),
false,
noti_width - padding_all_sides - global_style.ItemSpacing.x
).y;
float noti_height = msg_height + 2 * global_style.WindowPadding.y;
// get the required position
Overlay_Appearance::NotificationPosition pos = Overlay_Appearance::default_pos;
switch ((notification_type)noti.type) {
case notification_type::achievement: {
pos = settings->overlay_appearance.ach_earned_pos;
const float new_msg_height = ImGui::CalcTextSize(
noti.message.c_str(),
noti.message.c_str() + noti.message.size(),
false,
noti_width - padding_all_sides - global_style.ItemSpacing.x - settings->overlay_appearance.icon_size
).y;
const float new_noti_height = new_msg_height + 2 * global_style.WindowPadding.y;
float biggest_noti_height = settings->overlay_appearance.icon_size + 2 * global_style.WindowPadding.y;
if (biggest_noti_height < new_noti_height) biggest_noti_height = new_noti_height;
noti_height = biggest_noti_height;
}
break;
case notification_type::invite: pos = settings->overlay_appearance.invite_pos; break;
case notification_type::message: pos = settings->overlay_appearance.chat_msg_pos; break;
default: /* satisfy compiler warning */ break;
}
// 0 on the y-axis is top, 0 on the x-axis is left
float x = 0.0f;
float y = 0.0f;
switch (pos) {
// top
case Overlay_Appearance::NotificationPosition::top_left:
x = 0.0f;
y = noti_height * idx.top_left;
++idx.top_left;
break;
case Overlay_Appearance::NotificationPosition::top_center:
x = (width / 2) - (noti_width / 2);
y = noti_height * idx.top_center;
++idx.top_center;
break;
case Overlay_Appearance::NotificationPosition::top_right:
x = width - noti_width;
y = noti_height * idx.top_right;
++idx.top_right;
break;
// bot
case Overlay_Appearance::NotificationPosition::bot_left:
x = 0.0f;
y = height - noti_height * (idx.bot_left + 1);
++idx.bot_left;
break;
case Overlay_Appearance::NotificationPosition::bot_center:
x = (width / 2) - (noti_width / 2);
y = height - noti_height * (idx.bot_center + 1);
++idx.bot_center;
break;
case Overlay_Appearance::NotificationPosition::bot_right:
x = width - noti_width;
y = height - noti_height * (idx.bot_right + 1);
++idx.bot_right;
break;
default: /* satisfy compiler warning */ break;
}
ImGui::SetNextWindowPos(ImVec2( x, y ));
ImGui::SetNextWindowSize(ImVec2(width * Notification::width_percent, noti_height));
ImGui::SetNextWindowBgAlpha(0.9f);
}
void Steam_Overlay::build_notifications(int width, int height)
{
auto now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch());
float font_size = ImGui::GetFontSize();
std::queue<Friend> friend_actions_temp{};
// Add window rounding
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, settings->overlay_appearance.notification_rounding);
NotificationsIndexes idx{};
for (auto it = notifications.begin(); it != notifications.end(); ++it) {
auto elapsed_notif = now - it->start_time;
set_next_notification_pos(width, height, *it, idx);
if ( elapsed_notif < Notification::fade_in) { // still appearing (fading in)
float alpha = settings->overlay_appearance.notification_a * (elapsed_notif.count() / static_cast<float>(Notification::fade_in.count()));
ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, alpha));
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(settings->overlay_appearance.notification_r, settings->overlay_appearance.notification_g, settings->overlay_appearance.notification_b, alpha));
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(255, 255, 255, alpha*2));
} else if ( elapsed_notif > Notification::fade_out_start) { // fading out
float alpha = settings->overlay_appearance.notification_a * ((Notification::show_time - elapsed_notif).count() / static_cast<float>(Notification::fade_out.count()));
ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, alpha));
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(settings->overlay_appearance.notification_r, settings->overlay_appearance.notification_g, settings->overlay_appearance.notification_b, alpha));
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(255, 255, 255, alpha*2));
} else { // still in the visible time limit
ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, settings->overlay_appearance.notification_a));
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(settings->overlay_appearance.notification_r, settings->overlay_appearance.notification_g, settings->overlay_appearance.notification_b, settings->overlay_appearance.notification_a));
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(255, 255, 255, settings->overlay_appearance.notification_a*2));
}
// some extra window flags for each notification type
ImGuiWindowFlags extra_flags = ImGuiWindowFlags_NoFocusOnAppearing;
switch ((notification_type)it->type) {
// games like "Mafia Definitive Edition" will pause the entire game/scene if focus was stolen
// be less intrusive for notifications that do not require interaction
case notification_type::achievement:
case notification_type::auto_accept_invite:
case notification_type::message:
extra_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoInputs;
break;
case notification_type::invite:
// nothing
break;
default:
PRINT_DEBUG("error unhandled flags for type %i", (int)it->type);
break;
}
std::string wnd_name = "NotiPopupShow" + std::to_string(it->id);
if (ImGui::Begin(wnd_name.c_str(), nullptr,
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoResize | extra_flags)) {
switch ((notification_type)it->type) {
case notification_type::achievement: {
if (!it->icon.expired() && ImGui::BeginTable("imgui_table", 2)) {
ImGui::TableSetupColumn("imgui_table_image", ImGuiTableColumnFlags_WidthFixed, settings->overlay_appearance.icon_size);
ImGui::TableSetupColumn("imgui_table_text");
ImGui::TableNextRow(ImGuiTableRowFlags_None, settings->overlay_appearance.icon_size);
ImGui::TableSetColumnIndex(0);
ImGui::Image((ImTextureID)*it->icon.lock().get(), ImVec2(settings->overlay_appearance.icon_size, settings->overlay_appearance.icon_size));
ImGui::TableSetColumnIndex(1);
ImGui::TextWrapped("%s", it->message.c_str());
ImGui::EndTable();
} else {
ImGui::TextWrapped("%s", it->message.c_str());
}
}
break;
case notification_type::invite: {
ImGui::TextWrapped("%s", it->message.c_str());