forked from SpecialKO/SKIF
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSKIF.cpp
More file actions
5140 lines (4104 loc) · 198 KB
/
Copy pathSKIF.cpp
File metadata and controls
5140 lines (4104 loc) · 198 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
//
// Copyright 2020 - 2024 Andon "Kaldaien" Coleman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "../resource.h"
#include "../version.h"
#include <strsafe.h>
#include <cwctype>
#include <dxgi1_5.h>
#include <MinHook.h>
#include <SKIF.h>
// Plog ini includes (must be included after SKIF.h)
#include "plog/Initializers/RollingFileInitializer.h"
#include "plog/Appenders/ConsoleAppender.h"
#include "plog/Appenders/DebugOutputAppender.h"
#include <utility/plog_formatter.h>
#include <utility/utility.h>
#include <utility/skif_imgui.h>
#include <utility/gamepad.h>
#include <utility/injection.h>
#include <fonts/fa_621.h>
#include <imgui/imgui.h>
#include <imgui/imgui_impl_win32.h>
#include "imgui/imgui_impl_dx11.h"
#include <imgui/imgui_internal.h>
#include <xinput.h>
#include <utility/fsutil.h>
#include <filesystem>
#include <concurrent_queue.h>
#include <oleidl.h>
#include <utility/droptarget.hpp>
#include <d3d11.h>
#define DIRECTINPUT_VERSION 0x0800
#include <stores/Steam/app_record.h>
#include <tabs/hardware.h>
#include <tabs/settings.h>
#include <tabs/about.h>
#include <utility/registry.h>
#include <utility/updater.h>
#include <utility/drvreset.h>
#include <tabs/common_ui.h>
#include <Dbt.h>
// Header Files for Jump List features
#include <objectarray.h>
#include <shobjidl.h>
#include <propkey.h>
#include <propvarutil.h>
#include <knownfolders.h>
#include <shlobj.h>
#include <netlistmgr.h>
#include <dwmapi.h>
const int SKIF_STEAM_APPID = 1157970;
bool RecreateSwapChains = false;
bool RecreateSwapChainsPending = false;
bool RecreateWin32Windows = false;
bool RepositionSKIF = false;
bool RespectMonBoundaries = false;
bool changedHiDPIScaling = false;
bool invalidateFonts = false;
bool failedLoadFonts = false;
bool failedLoadFontsPrompt = false;
DWORD invalidatedFonts = 0;
DWORD invalidatedDevice = 0;
bool startedMinimized = false;
bool msgDontRedraw = false;
bool coverFadeActive = false;
std::atomic<bool> SKIF_Shutdown = false;
bool SKIF_NoInternet = false;
int SKIF_ExitCode = 0;
int SKIF_nCmdShow = -1;
std::atomic<int> SKIF_FrameCount = 0;
int addAdditionalFrames = 0;
DWORD dwDwmPeriod = 62500; // Assume 60 Hz (16 ms) by default
bool SteamOverlayDisabled = false;
bool allowShortcutCtrlA = true; // Used to disable the Ctrl+A when interacting with text input
bool SKIF_MouseDragMoveAllowed = true;
bool SKIF_debuggerPresent = false;
DWORD SKIF_startupTime = 0; // Used as a basis of how long the initialization took
DWORD SKIF_firstFrameTime = 0; // Used as a basis of how long the initialization took
HANDLE SteamProcessHandle = NULL;
// Shell messages (registered window messages)
UINT SHELL_TASKBAR_RESTART = 0; // TaskbarCreated
UINT SHELL_TASKBAR_BUTTON_CREATED = 0; // TaskbarButtonCreated
// A fixed size for the application window fixes the wobble that otherwise
// occurs when switching between tabs as the size isn't dynamically calculated.
// --- App Mode (regular)
ImVec2 SKIF_vecRegularMode = ImVec2 (0.0f, 0.0f); // DPI-aware
ImVec2 SKIF_vecRegularModeDefault = ImVec2 (1000.0f, 944.0f); // Does not include the status bar // SKIF_fStatusBarHeight == 31.0f
ImVec2 SKIF_vecRegularModeAdjusted = SKIF_vecRegularModeDefault; // Adjusted for status bar and tooltips (NO DPI scaling!)
// --- Service Mode
ImVec2 SKIF_vecServiceMode = ImVec2 (0.0f, 0.0f); // DPI-aware
ImVec2 SKIF_vecServiceModeDefault = ImVec2 (415.0f, 305.0f); // TODO 2024-05-05: 415px should probably be raised to 435px to allow smooth window resizing with a matched style between regular + service
// --- Horizontal Mode (used when regular mode is not available)
ImVec2 SKIF_vecHorizonMode = ImVec2 (0.0f, 0.0f); // DPI-aware
ImVec2 SKIF_vecHorizonModeDefault = ImVec2 (1000.0f, 374.0f); // Does not include the status bar (2024-01-20: 325 -> 375; 2024-05-19: 375 -> 374 to fix cover scaling at default size)
ImVec2 SKIF_vecHorizonModeAdjusted = SKIF_vecHorizonModeDefault; // Adjusted for status bar and tooltips (NO DPI scaling!)
// --- Variables
ImVec2 SKIF_vecCurrentPosition = ImVec2 (0.0f, 0.0f); // Gets updated after ImGui::EndFrame()
ImVec2 SKIF_vecCurrentMode = ImVec2 (0.0f, 0.0f); // Gets updated after ImGui::EndFrame()
ImVec2 SKIF_vecCurrentModeNext = ImVec2 (0.0f, 0.0f); // Holds the new expected size
float SKIF_fStatusBarHeight = 31.0f; // Status bar enabled // 33 ?
float SKIF_fStatusBarDisabled = 8.0f; // Status bar disabled
float SKIF_fStatusBarHeightTips = 18.0f; // Disabled tooltips (two-line status bar)
// Custom Global Key States used for moving SKIF around using WinKey + Arrows
bool KeyWinKey = false;
int SnapKeys = 0; // 2 = Left, 4 = Up, 8 = Right, 16 = Down
// Holds swapchain wait handles
std::vector<HANDLE> vSwapchainWaitHandles;
// GOG Galaxy stuff
std::wstring GOGGalaxy_Path = L"";
std::wstring GOGGalaxy_Folder = L"";
std::wstring GOGGalaxy_UserID = L"";
bool GOGGalaxy_Installed = false;
DWORD RepopulateGamesWasSet = 0;
bool RepopulateGames = false,
RefreshHardwareTab = false,
RefreshSettingsTab = false;
uint32_t SelectNewSKIFGame = 0;
bool HoverTipActive = false;
DWORD HoverTipDuration = 0;
// Notification icon stuff
static const GUID SKIF_NOTIFY_GUID = // {8142287D-5BC6-4131-95CD-709A2613E1F5}
{ 0x8142287d, 0x5bc6, 0x4131, { 0x95, 0xcd, 0x70, 0x9a, 0x26, 0x13, 0xe1, 0xf5 } };
#define SKIF_NOTIFY_ICON 0x1330 // 4912
#define SKIF_NOTIFY_EXIT 0x1331 // 4913
#define SKIF_NOTIFY_START 0x1332 // 4914
#define SKIF_NOTIFY_STOP 0x1333 // 4915
#define SKIF_NOTIFY_STARTWITHSTOP 0x1334 // 4916
#define SKIF_NOTIFY_RUN_UPDATER 0x1335 // 4917
#define WM_SKIF_NOTIFY_ICON (WM_USER + 0x150) // 1360
bool SKIF_isTrayed = false;
NOTIFYICONDATA niData;
HMENU hMenu;
// Cmd line argument stuff
SKIF_Signals _Signal;
PopupState UpdatePromptPopup = PopupState_Closed;
PopupState HistoryPopup = PopupState_Closed;
PopupState AutoUpdatePopup = PopupState_Closed;
UITab SKIF_Tab_Selected = UITab_Library,
SKIF_Tab_ChangeTo = UITab_None;
// Variables related to the display SKIF is visible on
ImVec2 windowPos;
ImRect windowRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f);
ImRect monitor_extent = ImRect(0.0f, 0.0f, 0.0f, 0.0f);
HMODULE hModSKIF = nullptr;
HMODULE hModSpecialK = nullptr;
HICON hIcon = nullptr;
#define GCL_HICON (-14)
// Texture related locks to prevent driver crashes
concurrency::concurrent_queue <IUnknown*> SKIF_ResourcesToFree; // CComPtr <IUnknown>
float fBottomDist = 0.0f;
ID3D11Device* SKIF_pd3dDevice = nullptr;
ID3D11DeviceContext* SKIF_pd3dDeviceContext = nullptr;
//ID3D11RenderTargetView* SKIF_g_mainRenderTargetView = nullptr;
// Forward declarations
bool CreateDeviceD3D (HWND hWnd);
void CleanupDeviceD3D (void);
LRESULT WINAPI SKIF_WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI SKIF_Notify_WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
void SKIF_Initialize (LPWSTR lpCmdLine);
CHandle hInjectAck (0); // Signalled when injection service should be stopped
CHandle hInjectAckEx (0); // Signalled when a successful injection occurs (minimizes SKIF)
CHandle hInjectExitAckEx (0); // Signalled when an injected game exits (restores SKIF)
// Holds current global DPI scaling, 1.0f == 100%, 1.5f == 150%.
float SKIF_ImGui_GlobalDPIScale = 1.0f;
// Holds last frame's DPI scaling
float SKIF_ImGui_GlobalDPIScale_Last = 1.0f; // Always identical to SKIF_ImGui_GlobalDPIScale within ImGui::NewFrame()
//float SKIF_ImGui_GlobalDPIScale_New = 1.0f;
float SKIF_ImGui_FontSizeDefault = 18.0f; // 18.0F
std::string SKIF_StatusBarText = "";
std::string SKIF_StatusBarHelp = "";
HWND SKIF_ImGui_hWnd = NULL;
HWND SKIF_Notify_hWnd = NULL;
HWND hWndOrigForeground;
HWND hWndForegroundFocusOnExit = nullptr; // Game HWND as reported by Special K through WM_SKIF_EVENT_SIGNAL
DWORD pidForegroundFocusOnExit = NULL; // Used to hold the game process ID that SKIF launched
void CALLBACK
SKIF_EfficiencyModeTimerProc (HWND hWnd, UINT Msg, UINT wParamIDEvent, DWORD dwTime)
{
UNREFERENCED_PARAMETER (Msg);
UNREFERENCED_PARAMETER (wParamIDEvent);
UNREFERENCED_PARAMETER (dwTime);
static SKIF_RegistrySettings& _registry = SKIF_RegistrySettings::GetInstance ( );
KillTimer (hWnd, cIDT_TIMER_EFFICIENCY);
if (_registry.bEfficiencyMode && ! _registry._EfficiencyMode && ! SKIF_ImGui_IsFocused ( ))
{
_registry._EfficiencyMode = true;
msgDontRedraw = true;
PLOG_DEBUG << "Engaging efficiency mode";
// Enable Efficiency Mode in Windows 11 (requires idle (low) priority + EcoQoS)
SKIF_Util_SetProcessPowerThrottling (SKIF_Util_GetCurrentProcess(), 1);
SetPriorityClass (SKIF_Util_GetCurrentProcess(), IDLE_PRIORITY_CLASS );
}
}
void
SKIF_Startup_SetGameAsForeground (void)
{
// Exit if there is nothing to actually do
if (pidForegroundFocusOnExit == NULL ||
hWndForegroundFocusOnExit == nullptr)
return;
DWORD _pid = 0;
if (hWndForegroundFocusOnExit != nullptr &&
hWndForegroundFocusOnExit == GetForegroundWindow ())
{
// This is a nop, bail-out before screwing things up even more
PLOG_VERBOSE << "hWndForegroundFocusOnExit is the foreground window already";
return;
}
if (GetWindowThreadProcessId (GetForegroundWindow (), &_pid))
{
if (_pid == pidForegroundFocusOnExit)
{
// This is a nop, bail-out before screwing things up even more
PLOG_VERBOSE << "pidForegroundFocusOnExit is the foreground window already";
return;
}
}
if (SKIF_ImGui_hWnd != NULL &&
SKIF_ImGui_hWnd == GetForegroundWindow ( ))
PLOG_VERBOSE << "SKIF_ImGui_hWnd is the foreground window";
if (SKIF_Notify_hWnd != NULL &&
SKIF_Notify_hWnd == GetForegroundWindow ( ))
PLOG_VERBOSE << "SKIF_Notify_hWnd is the foreground window";
PLOG_INFO << "Attempting to find game window to set as foreground...";
// Primary approach -- use the HWND reported by Special K
if (hWndForegroundFocusOnExit != nullptr)
{
if (GetWindowThreadProcessId (hWndForegroundFocusOnExit, &_pid) &&
pidForegroundFocusOnExit == _pid)
{
if (IsWindowVisible (hWndForegroundFocusOnExit))
{
PLOG_INFO << "Special K reported a game window, setting as foreground...";
if (! SetForegroundWindow (hWndForegroundFocusOnExit))
PLOG_WARNING << "SetForegroundWindow ( ) failed!";
}
return;
}
}
// Fallback approach -- attempt to find a window belonging to the process
EnumWindows ( []( HWND hWnd,
LPARAM lParam ) -> BOOL
{
DWORD _pid = 0;
if (GetWindowThreadProcessId (hWnd, &_pid))
{
if (_pid != NULL &&
_pid == (DWORD)lParam)
{
PLOG_INFO << "Found game window, setting as foreground...";
// Try to make this awful thing more reliable, by narrowing down the candidates to
// windows that show up in the taskbar when they're activated.
LONG_PTR dwExStyle =
GetWindowLongPtrW (hWnd, GWL_EXSTYLE);
// If it doesn't have this style, then don't set it foreground.
if (dwExStyle & WS_EX_APPWINDOW)
{
if (IsWindowVisible (hWnd))
{
if (! SetForegroundWindow (hWnd))
PLOG_WARNING << "SetForegroundWindow ( ) failed!";
}
return FALSE; // Stop enumeration
}
}
}
return TRUE;
}, (LPARAM)pidForegroundFocusOnExit);
}
void
SKIF_Startup_ProcessCmdLineArgs (LPWSTR lpCmdLine)
{
_Signal.Start =
StrStrIW (lpCmdLine, L"Start") != NULL;
_Signal.Temporary =
StrStrIW (lpCmdLine, L"Temp") != NULL;
_Signal.Stop =
StrStrIW (lpCmdLine, L"Stop") != NULL;
_Signal.Quit =
StrStrIW (lpCmdLine, L"Quit") != NULL;
_Signal.Minimize =
StrStrIW (lpCmdLine, L"Minimize") != NULL;
_Signal.AddSKIFGame =
StrStrIW (lpCmdLine, L"AddGame=") != NULL;
_Signal.LauncherURI =
StrStrIW (lpCmdLine, L"SKIF_URI=") != NULL;
_Signal.CheckForUpdates =
StrStrIW (lpCmdLine, L"RunUpdater") != NULL;
_Signal.ServiceMode =
StrStrIW (lpCmdLine, L"ServiceMode") != NULL;
// Both AddSKIFGame, SKIF_URI, and Launcher can include .exe in
// the argument so only set Launcher if the others are false.
if (! _Signal.AddSKIFGame &&
! _Signal.LauncherURI)
_Signal.Launcher =
StrStrIW (lpCmdLine, L".exe") != NULL;
// Check if we are dealing with a .bat target
if (! _Signal.Launcher &&
StrStrIW (lpCmdLine, L".bat") != NULL)
_Signal.Launcher =
_Signal.LauncherBAT = true;
_Signal._RunningInstance =
FindWindowExW (0, 0, SKIF_NotifyIcoClass, nullptr);
}
void
SKIF_Startup_AddGame (LPWSTR lpCmdLine)
{
if (! _Signal.AddSKIFGame)
return;
PLOG_INFO << "Adding custom game to SKIF...";
// O:\WindowsApps\DevolverDigital.MyFriendPedroWin10_1.0.6.0_x64__6kzv4j18v0c96\MyFriendPedro.exe
std::wstring cmdLine = std::wstring(lpCmdLine);
std::wstring cmdLineArgs = cmdLine;
// Transform to lowercase
std::wstring cmdLineLower = SKIF_Util_ToLowerW (cmdLine);
std::wstring splitPos1Lower = L"addgame="; // Start split
std::wstring splitEXELower = L".exe"; // Stop split (exe)
std::wstring splitLNKLower = L".lnk"; // Stop split (lnk)
// Exclude anything before "addgame=", if any
cmdLine = cmdLine.substr(cmdLineLower.find(splitPos1Lower) + splitPos1Lower.length());
// First position is a space -- skip that one
if (cmdLine.find(L" ") == 0)
cmdLine = cmdLine.substr(1);
// First position is a quotation mark -- we need to strip those
if (cmdLine.find(L"\"") == 0)
cmdLine = cmdLine.substr(1, cmdLine.find(L"\"", 1) - 1) + cmdLine.substr(cmdLine.find(L"\"", 1) + 1, std::wstring::npos);
// Update lowercase
cmdLineLower = SKIF_Util_ToLowerW (cmdLine);
// If .exe is part of the string
if (cmdLineLower.find(splitEXELower) != std::wstring::npos)
{
// Extract proxied arguments, if any
cmdLineArgs = cmdLine.substr(cmdLineLower.find(splitEXELower) + splitEXELower.length());
// Exclude anything past ".exe"
cmdLine = cmdLine.substr(0, cmdLineLower.find(splitEXELower) + splitEXELower.length());
}
// If .lnk is part of the string
else if (cmdLineLower.find(splitLNKLower) != std::wstring::npos)
{
// Exclude anything past ".lnk" since we're reading the arguments from the shortcut itself
cmdLine = cmdLine.substr(0, cmdLineLower.find(splitLNKLower) + splitLNKLower.length());
WCHAR wszTarget [MAX_PATH + 2] = { };
WCHAR wszArguments[MAX_PATH + 2] = { };
SKIF_Util_ResolveShortcut (SKIF_ImGui_hWnd, cmdLine.c_str(), wszTarget, wszArguments, MAX_PATH * sizeof (WCHAR));
cmdLine = std::wstring(wszTarget);
cmdLineArgs = std::wstring(wszArguments);
}
// Clear var if no valid path was found
else {
cmdLine.clear();
}
// Only proceed if we have an actual valid path
if (cmdLine.length() > 0)
{
// First position of the arguments is a space -- skip that one
if (cmdLineArgs.find(L" ") == 0)
cmdLineArgs = cmdLineArgs.substr(1);
extern int SKIF_AddCustomAppID (std::wstring name, std::wstring path, std::wstring args);
if (PathFileExists (cmdLine.c_str()))
{
std::wstring productName = SKIF_Util_GetProductName (cmdLine.c_str());
if (productName == L"")
productName = std::filesystem::path (cmdLine).replace_extension().filename().wstring();
SelectNewSKIFGame = (uint32_t)SKIF_AddCustomAppID (productName, cmdLine, cmdLineArgs);
// If a running instance of SKIF already exists, terminate this one as it has served its purpose
if (SelectNewSKIFGame > 0 && _Signal._RunningInstance != 0)
{
SendMessage (_Signal._RunningInstance, WM_SKIF_REFRESHGAMES, SelectNewSKIFGame, 0x0);
PLOG_INFO << "Terminating due to one of these contions were found to be true:";
PLOG_INFO << "SelectNewSKIFGame > 0: " << (SelectNewSKIFGame > 0);
PLOG_INFO << "hwndAlreadyExists != 0: " << (_Signal._RunningInstance != 0);
ExitProcess (0x0);
}
}
else {
PLOG_ERROR << "Non-valid path detected: " << cmdLine;
}
}
else {
PLOG_ERROR << "Non-valid string detected: " << lpCmdLine;
}
}
void
SKIF_Startup_LaunchGamePreparation (LPWSTR lpCmdLine)
{
if (! _Signal.Launcher)
return;
PLOG_INFO << "Preparing game path, launch options, and working directory...";
static SKIF_CommonPathsCache& _path_cache = SKIF_CommonPathsCache::GetInstance ( );
static SKIF_InjectionContext& _inject = SKIF_InjectionContext::GetInstance ( );
std::wstring cmdLine = std::wstring(lpCmdLine);
std::wstring delimiter = (_Signal.LauncherBAT) ? L".bat" : L".exe"; // split lpCmdLine at the .bat/.exe
// First position is a quotation mark -- we need to strip those
if (cmdLine.find(L"\"") == 0)
cmdLine = cmdLine.substr(1, cmdLine.find(L"\"", 1) - 1) + cmdLine.substr(cmdLine.find(L"\"", 1) + 1, std::wstring::npos);
// Transform to lowercase
std::wstring cmdLineLower = SKIF_Util_ToLowerW (cmdLine);
// Extract the SKIF_SteamAppID cmd line argument
const std::wstring argSKIF_SteamAppID = L"skif_steamappid=";
size_t posSKIF_SteamAppID_start = cmdLineLower.find (argSKIF_SteamAppID);
std::wstring steamAppId = L"";
if (posSKIF_SteamAppID_start != std::wstring::npos)
{
size_t
posSKIF_SteamAppID_end = cmdLineLower.find (L" ", posSKIF_SteamAppID_start);
if (posSKIF_SteamAppID_end == std::wstring::npos)
posSKIF_SteamAppID_end = cmdLineLower.length ( );
// Length of the substring to remove
posSKIF_SteamAppID_end -= posSKIF_SteamAppID_start;
steamAppId = cmdLineLower.substr(posSKIF_SteamAppID_start + argSKIF_SteamAppID.length ( ), posSKIF_SteamAppID_end);
// Remove substring from the original variables
cmdLine .erase (posSKIF_SteamAppID_start, posSKIF_SteamAppID_end);
cmdLineLower.erase (posSKIF_SteamAppID_start, posSKIF_SteamAppID_end);
}
// Extract the target path and any proxied command line arguments
std::wstring path = cmdLine.substr(0, cmdLineLower.find(delimiter) + delimiter.length()); // path
std::wstring proxiedCmdLine = cmdLine.substr( cmdLineLower.find(delimiter) + delimiter.length(), cmdLineLower.length()); // proxied command line
SKIF_Util_TrimSpacesW (proxiedCmdLine);
std::wstring workingDirectory = _path_cache.skif_workdir_org;
// Fall back to using the folder of the game executable if the original working directory fails a few simple checks
if (workingDirectory.empty() || _wcsicmp (_path_cache.skif_workdir_org, _path_cache.skif_workdir) == 0 || workingDirectory.find(L"system32") != std::wstring::npos)
workingDirectory = std::filesystem::path(path).parent_path().wstring();
// Path does not seem to be absolute -- add the current working directory in front of the path
if (path.find(L"\\") == std::wstring::npos)
path = SK_FormatStringW (LR"(%ws\%ws)", workingDirectory.c_str(), path.c_str()); //orgWorkingDirectory.wstring() + L"\\" + path;
PLOG_INFO << "Executable: " << path;
PLOG_INFO_IF (! proxiedCmdLine.empty()) << "Command Line Args: " << proxiedCmdLine;
PLOG_INFO << "Working Directory: " << workingDirectory;
bool isLocalBlacklisted = false,
isGlobalBlacklisted = false;
if (PathFileExists (path.c_str()))
{
_Signal._GamePath = path;
_Signal._GameArgs = proxiedCmdLine;
_Signal._GameWorkDir = workingDirectory;
if (! steamAppId.empty())
_Signal._SteamAppID = steamAppId;
std::wstring blacklistFile = SK_FormatStringW (L"%s\\SpecialK.deny.%ws",
std::filesystem::path(path).parent_path().wstring().c_str(), // full path to parent folder
std::filesystem::path(path).filename().replace_extension().wstring().c_str() // filename without extension
);
// Check if the executable is blacklisted
isLocalBlacklisted = PathFileExistsW (blacklistFile.c_str());
isGlobalBlacklisted = _inject._TestUserList (SK_WideCharToUTF8(path).c_str(), false);
_Signal._DoNotUseService = (isLocalBlacklisted || isGlobalBlacklisted);
if (! _Signal._DoNotUseService)
{
// Whitelist the path if it haven't been already
_inject.WhitelistPath (SK_WideCharToUTF8(path));
std::wstring elevationFile = SK_FormatStringW (L"%s\\SpecialK.admin.%ws",
std::filesystem::path(path).parent_path().wstring().c_str(), // full path to parent folder
std::filesystem::path(path).filename().replace_extension().wstring().c_str() // filename without extension
);
_Signal._ElevatedService = PathFileExists (elevationFile.c_str());
}
}
else {
PLOG_ERROR << "Non-valid path detected: " << path;
ExitProcess (0x0);
}
}
void
SKIF_Startup_LaunchURIPreparation (LPWSTR lpCmdLine)
{
if (! _Signal.LauncherURI)
return;
PLOG_INFO << "Preparing the shell execute call...";
if (! _Signal.Start)
_Signal._DoNotUseService = true;
static SKIF_CommonPathsCache& _path_cache = SKIF_CommonPathsCache::GetInstance ( );
//static SKIF_InjectionContext& _inject = SKIF_InjectionContext::GetInstance ( );
std::wstring cmdLine = std::wstring (lpCmdLine);
std::wstring cmdLineLower = SKIF_Util_ToLowerW (cmdLine);
const std::wstring argSKIF_URI = L"skif_uri=";
std::wstring argSKIF_URI_found = L"";
size_t posArgumentStart = cmdLineLower.find (argSKIF_URI);
// Extract the SKIF_XXX cmd line argument
if (posArgumentStart != std::wstring::npos)
{
size_t
posArgumentEnd = cmdLineLower.find (L" ", posArgumentStart);
if (posArgumentEnd == std::wstring::npos)
posArgumentEnd = cmdLineLower.length ( );
// Length of the substring to remove
posArgumentEnd -= posArgumentStart;
argSKIF_URI_found = cmdLine.substr(posArgumentStart + argSKIF_URI.length ( ), posArgumentEnd);
// Remove substring from the original variables
cmdLine .erase (posArgumentStart, posArgumentEnd);
cmdLineLower.erase (posArgumentStart, posArgumentEnd);
}
if (! argSKIF_URI_found.empty())
{
PLOG_INFO << "URI: " << argSKIF_URI_found;
_Signal._GamePath = argSKIF_URI_found;
// If we are dealing with an executable path, also find a working directory
if (StrStrIW (argSKIF_URI_found.c_str(), L".exe") != NULL)
{
std::wstring workingDirectory = _path_cache.skif_workdir_org;
// Fall back to using the folder of the game executable if the original working directory fails a few simple checks
if (workingDirectory.empty() || _wcsicmp (_path_cache.skif_workdir_org, _path_cache.skif_workdir) == 0 || workingDirectory.find(L"system32") != std::wstring::npos)
workingDirectory = std::filesystem::path (argSKIF_URI_found).parent_path().wstring();
_Signal._GameWorkDir = workingDirectory;
}
}
else {
PLOG_ERROR << "Non-valid URI detected: " << cmdLine;
ExitProcess (0x0);
}
}
void
SKIF_Startup_LaunchGameService (void)
{
if (_Signal._GamePath.empty())
return;
static SKIF_RegistrySettings& _registry = SKIF_RegistrySettings::GetInstance ( );
static SKIF_InjectionContext& _inject = SKIF_InjectionContext::GetInstance ( );
if (_Signal._DoNotUseService)
{
// 2023-11-14: I am unsure how effective _inject.bCurrentState is here...
// Is it even accurate at this point in time? // Aemony
if (_Signal._RunningInstance && (_inject.bCurrentState || _Signal.LauncherURI))
{
PLOG_INFO << "Stopping injection service...";
SendMessage (_Signal._RunningInstance, WM_SKIF_STOP, 0x0, 0x0);
}
}
else {
PLOG_INFO << "Suppressing the initial 'Please launch a game to continue' notification...";
_registry._SuppressServiceNotification = true;
PLOG_INFO << "Starting injection service...";
if (_Signal._RunningInstance)
SendMessage (_Signal._RunningInstance, WM_SKIF_LAUNCHER, _Signal._ElevatedService, 0x0);
else if (! _inject.bCurrentState)
{
_registry._ExitOnInjection = true;
_inject._StartStopInject (false, true, _Signal._ElevatedService);
}
}
}
void
SKIF_Startup_LaunchGame (void)
{
if (_Signal._GamePath.empty())
return;
PLOG_INFO << "Launching executable : " << _Signal._GamePath;
PLOG_INFO_IF(! _Signal._GameWorkDir.empty()) << " Working directory : " << _Signal._GameWorkDir;
PLOG_INFO_IF(! _Signal._GameArgs .empty()) << " Arguments : " << _Signal._GameArgs;
if (! _Signal._SteamAppID.empty ( ))
{
PLOG_INFO << " Steam App ID : " << _Signal._SteamAppID;
SetEnvironmentVariable (L"SteamAppId", _Signal._SteamAppID.c_str());
SetEnvironmentVariable (L"SteamGameId", _Signal._SteamAppID.c_str());
}
SHELLEXECUTEINFOW
sexi = { };
sexi.cbSize = sizeof (SHELLEXECUTEINFOW);
sexi.lpVerb = L"OPEN";
sexi.lpFile = _Signal._GamePath.c_str();
sexi.lpParameters = (! _Signal._GameArgs.empty()) ? _Signal._GameArgs.c_str() : NULL;
sexi.lpDirectory = _Signal._GameWorkDir.c_str();
sexi.nShow = SW_SHOWNORMAL;
sexi.fMask = SEE_MASK_NOCLOSEPROCESS | // We need the PID of the process that gets started
SEE_MASK_NOASYNC | // Never async since our own process might stop executing before the new process is ready
SEE_MASK_NOZONECHECKS; // No zone check needs to be performed
// Launch executable
ShellExecuteExW (&sexi);
if (! _Signal._SteamAppID.empty ( ))
{
SetEnvironmentVariable (L"SteamAppId", NULL);
SetEnvironmentVariable (L"SteamGameId", NULL);
}
// Set the new process as foreground window
if (sexi.hInstApp > (HINSTANCE)32 &&
sexi.hProcess != NULL)
{
pidForegroundFocusOnExit = GetProcessId (sexi.hProcess);
CloseHandle (sexi.hProcess);
}
// If a running instance of SKIF already exists, or the game was blacklisted, terminate this one as it has served its purpose
if (_Signal._RunningInstance || _Signal._DoNotUseService)
{
SKIF_Startup_SetGameAsForeground ( );
PLOG_INFO << "Terminating as this instance has fulfilled its purpose.";
ExitProcess (0x0);
}
}
void
SKIF_Startup_ProxyCommandLineArguments (void)
{
if (! _Signal._RunningInstance)
return;
if (! _Signal.Start &&
! _Signal.Stop &&
! _Signal.Minimize &&
! _Signal.CheckForUpdates &&
! _Signal.Quit)
return;
PLOG_INFO << "Proxying command line arguments...";
if (_Signal.Start)
{
// This means we proxied this cmd to ourselves, in which
// case we want to set up bExitOnInjection as well
if (SKIF_Notify_hWnd != NULL && _Signal._RunningInstance == SKIF_Notify_hWnd)
{
PostMessage (_Signal._RunningInstance, (_Signal.Temporary) ? WM_SKIF_TEMPSTARTEXIT : WM_SKIF_START, 0x0, 0x0);
_Signal.Quit = false; // Disallow using Start and Quit at the same time, but only if Temp is not being used
}
else
PostMessage (_Signal._RunningInstance, (_Signal.Temporary) ? WM_SKIF_TEMPSTART : WM_SKIF_START, 0x0, 0x0);
}
if (_Signal.Stop)
PostMessage (_Signal._RunningInstance, WM_SKIF_STOP, 0x0, 0x0);
if (_Signal.Minimize)
{
//PostMessage (_Signal._RunningInstance, WM_SKIF_MINIMIZE, 0x0, 0x0);
// Send WM_SKIF_MINIMIZE to all running instances (including ourselves, though we won't act upon it if SKIF_ImGui_hWnd hasn't been created)
EnumWindows ( []( HWND hWnd,
LPARAM lParam ) -> BOOL
{
wchar_t wszRealWindowClass [64] = { };
if (RealGetWindowClassW (hWnd, wszRealWindowClass, 64))
if (StrCmpIW ((LPWSTR)lParam, wszRealWindowClass) == 0)
PostMessage (hWnd, WM_SKIF_MINIMIZE, 0x0, 0x0);
return TRUE;
}, (LPARAM)SKIF_NotifyIcoClass);
}
if (_Signal.CheckForUpdates)
{
// PostMessage (_Signal._RunningInstance, WM_SKIF_RUN_UPDATER, 0x0, 0x0);
// Send WM_SKIF_RUN_UPDATER to all running instances (including ourselves)
EnumWindows ( []( HWND hWnd,
LPARAM lParam ) -> BOOL
{
wchar_t wszRealWindowClass [64] = { };
if (RealGetWindowClassW (hWnd, wszRealWindowClass, 64))
if (StrCmpIW ((LPWSTR)lParam, wszRealWindowClass) == 0)
PostMessage (hWnd, WM_SKIF_RUN_UPDATER, 0x0, 0x0);
return TRUE;
}, (LPARAM)SKIF_NotifyIcoClass);
}
if (_Signal.Quit)
{
// PostMessage (_Signal._RunningInstance, WM_CLOSE, 0x0, 0x0);
// Send WM_CLOSE to all running instances (including ourselves)
EnumWindows ( []( HWND hWnd,
LPARAM lParam ) -> BOOL
{
wchar_t wszRealWindowClass [64] = { };
if (RealGetWindowClassW (hWnd, wszRealWindowClass, 64))
if (StrCmpIW ((LPWSTR)lParam, wszRealWindowClass) == 0)
PostMessage (hWnd, WM_CLOSE, 0x0, 0x0);
return TRUE;
}, (LPARAM)SKIF_NotifyIcoClass);
}
// Restore the foreground state to whatever app had it before
if (SKIF_Notify_hWnd == NULL)
{
if (hWndOrigForeground != 0)
{
if (IsIconic (hWndOrigForeground))
ShowWindow (hWndOrigForeground, SW_SHOWNA);
SetForegroundWindow (hWndOrigForeground);
}
PLOG_INFO << "Terminating due to this instance having done its job.";
ExitProcess (0x0);
}
}
void
SKIF_Startup_RaiseRunningInstance (void)
{
if (! _Signal._RunningInstance)
return;
// We must allow the existing process to set the foreground window
// as this is part of the WM_SKIF_RESTORE procedure
DWORD pidAlreadyExists = 0;
GetWindowThreadProcessId (_Signal._RunningInstance, &pidAlreadyExists);
if (pidAlreadyExists)
AllowSetForegroundWindow (pidAlreadyExists);
PLOG_INFO << "Attempting to restore the running instance: " << pidAlreadyExists;
SendMessage (_Signal._RunningInstance, WM_SKIF_RESTORE, 0x0, 0x0);
PLOG_INFO << "Terminating due to this instance having done its job.";
ExitProcess (0x0);
}
void SKIF_Shell_CreateUpdateNotifyMenu (void)
{
if (hMenu != NULL)
DestroyMenu (hMenu);
static SKIF_InjectionContext& _inject = SKIF_InjectionContext::GetInstance ( );
bool svcRunning = false,
svcRunningAutoStop = false,
svcStopped = false;
if (_inject.bCurrentState && hInjectAck.m_h <= 0)
svcRunning = true;
else if (_inject.bCurrentState && hInjectAck.m_h != 0)
svcRunningAutoStop = true;
else
svcStopped = true;
hMenu = CreatePopupMenu ( );
if (hMenu != NULL)
{
AppendMenu (hMenu, MF_STRING | ((svcRunningAutoStop) ? MF_CHECKED | MF_GRAYED : (svcRunning) ? MF_GRAYED : 0x0), SKIF_NOTIFY_STARTWITHSTOP, L"Start Service");
AppendMenu (hMenu, MF_STRING | ((svcRunning) ? MF_CHECKED | MF_GRAYED : (svcRunningAutoStop) ? MF_GRAYED : 0x0), SKIF_NOTIFY_START, L"Start Service (manual stop)");
AppendMenu (hMenu, MF_STRING | ((svcStopped) ? MF_CHECKED | MF_GRAYED : 0x0), SKIF_NOTIFY_STOP, L"Stop Service");
AppendMenu (hMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hMenu, MF_STRING, SKIF_NOTIFY_RUN_UPDATER, L"Check for updates");
//AppendMenu (hMenu, MF_STRING | (( _inject.bCurrentState) ? MF_CHECKED | MF_GRAYED : 0x0), SKIF_NOTIFY_START, L"Start Injection");
//AppendMenu (hMenu, MF_STRING | ((! _inject.bCurrentState) ? MF_CHECKED | MF_GRAYED : 0x0), SKIF_NOTIFY_STOP, L"Stop Injection");
AppendMenu (hMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hMenu, MF_STRING, SKIF_NOTIFY_EXIT, L"Exit");
}
}
// This creates a notification icon
void SKIF_Shell_CreateNotifyIcon (void)
{
static SKIF_InjectionContext& _inject = SKIF_InjectionContext::GetInstance ( );
ZeroMemory (&niData, sizeof (NOTIFYICONDATA));
niData.cbSize = sizeof (NOTIFYICONDATA); // 6.0.6 or higher (Windows Vista and later)
niData.uID = SKIF_NOTIFY_ICON;
//niData.guidItem = SKIF_NOTIFY_GUID; // Prevents notification icons from appearing for separate running instances
niData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_SHOWTIP; // NIF_GUID
niData.hIcon = (_inject.bCurrentState)
? LoadIcon (hModSKIF, MAKEINTRESOURCE (IDI_SKIFONNOTIFY))
: LoadIcon (hModSKIF, MAKEINTRESOURCE (IDI_SKIF));
niData.hWnd = SKIF_Notify_hWnd;
niData.uVersion = NOTIFYICON_VERSION_4;
wcsncpy_s (niData.szTip, 128, L"Special K", 128);
niData.uCallbackMessage = WM_SKIF_NOTIFY_ICON;
Shell_NotifyIcon (NIM_ADD, &niData);
//Shell_NotifyIcon (NIM_SETVERSION, &niData); // Breaks shit, lol
}
// This populates the notification icon with the appropriate icon
void SKIF_Shell_UpdateNotifyIcon (void)
{
static SKIF_InjectionContext& _inject = SKIF_InjectionContext::GetInstance ( );
niData.uFlags = NIF_ICON;
niData.hIcon = (_inject.bCurrentState)
? LoadIcon (hModSKIF, MAKEINTRESOURCE (IDI_SKIFONNOTIFY))
: LoadIcon (hModSKIF, MAKEINTRESOURCE (IDI_SKIF));
Shell_NotifyIcon (NIM_MODIFY, &niData);
}
// This deletes the notification icon
void SKIF_Shell_DeleteNotifyIcon (void)
{
Shell_NotifyIcon (NIM_DELETE, &niData);
DeleteObject (niData.hIcon);
niData.hIcon = 0;
}
// Show a desktop notification
// SKIF_NTOAST_UPDATE - Appears always
// SKIF_NTOAST_SERVICE - Appears conditionally
void SKIF_Shell_CreateNotifyToast (UINT type, std::wstring message, std::wstring title = L"")
{
static SKIF_RegistrySettings& _registry = SKIF_RegistrySettings::GetInstance ( );
if ( (type == SKIF_NTOAST_UPDATE) ||
(_registry.iNotifications == 1) || // Always
(_registry.iNotifications == 2 && ! SKIF_ImGui_IsFocused ( )) // When Unfocused
)
{
niData.uFlags =
NIF_INFO | NIF_REALTIME; // NIF_REALTIME to indicate the notifications should be discarded if not displayed immediately
niData.dwInfoFlags =
(type == SKIF_NTOAST_SERVICE)
? NIIF_NONE | NIIF_RESPECT_QUIET_TIME | NIIF_NOSOUND // Mute the sound for service notifications
: NIIF_NONE | NIIF_RESPECT_QUIET_TIME;
wcsncpy_s (niData.szInfoTitle, 64, title.c_str(), 64);
wcsncpy_s (niData.szInfo, 256, message.c_str(), 256);
Shell_NotifyIcon (NIM_MODIFY, &niData);
// Set up a timer that automatically refreshes SKIF when the notification clears,
// allowing us to perform some maintenance and whatnot when that occurs
SetTimer (SKIF_Notify_hWnd, IDT_REFRESH_NOTIFY, _registry.iNotificationsDuration, NULL);
}
}
void SKIF_Shell_CreateJumpList (void)
{
static SKIF_CommonPathsCache& _path_cache = SKIF_CommonPathsCache::GetInstance ( );
CComPtr <ICustomDestinationList> pDestList; // The jump list
CComPtr <IObjectCollection> pObjColl; // Object collection to hold the custom tasks.
CComPtr <IShellLink> pLink; // Reused for the custom tasks
CComPtr <IObjectArray> pRemovedItems; // Not actually used since we don't carry custom destinations
PROPVARIANT pv; // Used to give the custom tasks a title
UINT cMaxSlots; // Not actually used since we don't carry custom destinations
// Create a jump list COM object.
if (SUCCEEDED (pDestList.CoCreateInstance (CLSID_DestinationList)))
{
pDestList ->SetAppID (SKIF_AppUserModelID);
pDestList ->BeginList (&cMaxSlots, IID_PPV_ARGS (&pRemovedItems));