-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMIDI++.cpp
2054 lines (1900 loc) · 85.9 KB
/
MIDI++.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
// never writing any UI in C++ ever again
#include "PlaybackSystem.hpp"
#include "TrackControl.hpp"
#include "VelocityCurveEditor.hpp"
#include "MIDI2Key.hpp"
#include "MIDIConnect.hpp"
#include "MIDIDeviceUI.hpp"
#include "resource.h"
#include <CommCtrl.h>
#include <GdiPlus.h>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <filesystem>
#include <future>
#include <functional>
#include <iostream>
#include <locale>
#include <mutex>
#include <regex>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <cwchar>
#include <windowsx.h>
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Gdiplus.lib")
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
// -----------------------------------------------------------------------------
// RAII wrappers for HANDLE and GDI+ token
// -----------------------------------------------------------------------------
struct UniqueHandle {
HANDLE handle;
UniqueHandle(HANDLE h = nullptr) : handle(h) {}
~UniqueHandle() {
if (handle && handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
}
}
UniqueHandle(const UniqueHandle&) = delete;
UniqueHandle& operator=(const UniqueHandle&) = delete;
operator HANDLE() const { return handle; }
};
struct GdiplusTokenWrapper {
ULONG_PTR token;
GdiplusTokenWrapper() : token(0) {}
~GdiplusTokenWrapper() {
if (token != 0)
Gdiplus::GdiplusShutdown(token);
}
};
// -----------------------------------------------------------------------------
// Global objects and variables
// -----------------------------------------------------------------------------
class VirtualPianoPlayer* g_player = nullptr;
static std::unique_ptr<MIDI2Key> g_midi2key;
static std::unique_ptr<MIDIConnect> g_midiConnect;
static TrackControl g_trackControl;
int g_sustainCutoff = 64;
static int g_selectedMidiDevice = 0; // device index
static int g_selectedMidiChannel = -1; // -1 means “All channels”
// Global handles and states
static HINSTANCE g_hInst = nullptr;
static HWND g_hMainWnd = nullptr;
static HANDLE g_hSingleInstanceMutex = nullptr;
static std::mutex g_logMutex;
static std::string g_logBuffer;
static std::atomic<bool> g_guiReady{ false };
static std::chrono::steady_clock::time_point g_lastTimeUpdate;
static constexpr auto TIME_UPDATE_INTERVAL = std::chrono::milliseconds(500);
static const std::regex g_ansiPattern("\x1B\\[[0-9;]*[A-Za-z]");
static std::unordered_map<int, bool> g_toggleStates;
static bool g_randomSongEnabled = false;
// -----------------------------------------------------------------------------
// Control layout constants
// -----------------------------------------------------------------------------
namespace Layout {
// Window dimensions
static const int WIN_W = 880;
static const int WIN_H = 760;
// MIDI Files group
static const int FILES_X = 10;
static const int FILES_Y = 10;
static const int FILES_W = 240;
static const int FILES_H = 405;
// Playback (Basic) group
static const int PBASIC_X = 260;
static const int PBASIC_Y = 10;
static const int PBASIC_W = 600;
static const int PBASIC_H = 100;
static const int PB_ROW1_Y = PBASIC_Y + 25;
static const int PB_ROW2_Y = PBASIC_Y + 25 + 28 + 8;
static const int PB_BTN_WIDTH = 80;
static const int PB_BTN_HEIGHT = 28;
static const int PB_BTN_GAP = 10;
static const int PB_MIDI_QWERTY_X = PBASIC_X + 340;
static const int PB_MIDI_QWERTY_Y = PB_ROW1_Y;
static const int PB_STATIC_TIME_X = PBASIC_X + 470;
static const int PB_STATIC_TIME_Y = PBASIC_Y + 28;
static const int PB_STATIC_TIME_W = 120;
static const int PB_STATIC_TIME_H = 25;
// Advanced group
static const int PADV_X = 260;
static const int PADV_Y = PBASIC_Y + PBASIC_H + 5;
static const int PADV_W = 600;
static const int PADV_H = 100;
// Config group
static const int CFG_X = 260;
static const int CFG_Y = PADV_Y + PADV_H + 5;
static const int CFG_W = 600;
static const int CFG_H = 60;
// Details group
static const int DET_X = 260;
static const int DET_Y = CFG_Y + CFG_H + 5;
static const int DET_W = 600;
static const int DET_H = 130;
// Tracks group
static const int TRK_X = 10;
static const int TRK_Y = DET_Y + DET_H + 10;
static const int TRK_W = 850;
static const int TRK_H = 120;
// Log group
static const int LOG_X = 10;
static const int LOG_Y = TRK_Y + TRK_H + 10;
static const int LOG_W = 850;
static const int LOG_H = 150;
}
// Global sustain cutoff value box (edit control)
static HWND g_hSustainCutoffValueBox = nullptr;
// Global listbox for MIDI files (now showing folders & files) and other UI elements
static HWND g_lbMidi = nullptr;
static HWND g_editDetails = nullptr;
static HWND g_editTracks = nullptr;
static HWND g_hOpacityIndicatorBox = nullptr;
// -----------------------------------------------------------------------------
// Control IDs
// -----------------------------------------------------------------------------
enum ControlID {
// ListBox and ComboBoxes
ID_CB_SORT = 101,
ID_BTN_REFRESH,
ID_LB_MIDI,
// Basic Playback Group
ID_GRP_PLAY,
ID_BTN_LOAD,
ID_BTN_PLAY,
ID_BTN_STOP,
ID_BTN_SKIP,
ID_BTN_REW,
ID_BTN_SPEEDUP,
ID_BTN_SPEEDDN,
ID_BTN_RESTART,
// MIDI -> QWERTY and device controls
ID_BTN_MIDI2QWERTY,
ID_CB_MIDIDEV,
ID_CB_MIDICH,
ID_BTN_MIDICONNECT,
// Advanced / Extra
ID_GRP_ADV,
ID_BTN_88KEY,
ID_BTN_VOLADJ,
ID_BTN_VELOCITY,
ID_BTN_SUSTAIN,
ID_BTN_TRANSPOSE,
ID_BTN_TRANSPOSEOUT,
ID_CB_VELOCITY_CURVE,
ID_SLIDER_SUSTAIN_CUTOFF,
ID_STATIC_SUSTAIN_LABEL,
// Config
ID_GRP_CONFIG,
ID_CHK_TOP,
ID_CHK_RANDOM_SONG,
ID_SLIDER_OPACITY,
// Details
ID_GRP_DETAILS,
ID_EDIT_DETAILS,
// Tracks
ID_GRP_TRACKS,
ID_EDIT_TRACKS,
// Log
ID_GRP_LOG,
ID_BTN_REFRESH_VCURVE,
ID_EDIT_LOG,
ID_BTN_CLEARLOG,
ID_BTN_REFRESH_MIDI,
ID_BTN_VLCURVE,
// Custom messages and timers
WM_UPDATE_LOG = WM_APP + 101,
IDT_TIMELEFT_TIMER,
ID_STATIC_TIME,
// Track Mute/Solo button bases
ID_TRACK_MUTE_BASE = 2000,
ID_TRACK_SOLO_BASE = 2500,
ID_BTN_PREV_SONG = 3000,
ID_BTN_NEXT_SONG = 3001
};
static bool IsToggleButtonID(int id) {
switch (id) {
case ID_BTN_88KEY:
case ID_BTN_VOLADJ:
case ID_BTN_VELOCITY:
case ID_BTN_SUSTAIN:
case ID_BTN_TRANSPOSEOUT:
case ID_BTN_MIDI2QWERTY:
case ID_BTN_MIDICONNECT:
return true;
default:
return false;
}
}
// -----------------------------------------------------------------------------
// MIDI Folder Scanning and Sorting (with folder exploration)
// -----------------------------------------------------------------------------
struct MidiItem {
std::wstring name;
std::wstring fullPath;
bool isFolder;
std::time_t lastWrite;
};
static std::vector<MidiItem> g_midiItems;
static std::filesystem::path g_currentMidiDir = L"midi";
// bunch of kids
std::string getReadableKey(const std::string& key) {
const std::string prefix = "VK_";
if (key.compare(0, prefix.size(), prefix) == 0) {
return key.substr(prefix.size());
}
return key;
}
static void ScanMidiFolder() {
g_midiItems.clear();
std::filesystem::path currentDir = g_currentMidiDir;
if (!std::filesystem::exists(currentDir) || !std::filesystem::is_directory(currentDir)) {
std::wcout << L"[Scan] '" << currentDir.wstring() << L"' not found.\n";
return;
}
if (!std::filesystem::equivalent(currentDir, "midi")) {
MidiItem parentItem;
parentItem.name = L"..";
parentItem.fullPath = currentDir.parent_path().wstring();
parentItem.isFolder = true;
parentItem.lastWrite = 0;
g_midiItems.push_back(parentItem);
}
for (const auto& entry : std::filesystem::directory_iterator(currentDir)) {
MidiItem item;
item.name = entry.path().filename().wstring();
item.fullPath = entry.path().wstring();
item.isFolder = entry.is_directory();
if (!item.isFolder) {
auto ext = entry.path().extension().wstring();
std::wstring lw(ext.size(), L'\0');
std::transform(ext.begin(), ext.end(), lw.begin(), ::towlower);
if (lw != L".mid" && lw != L".midi")
continue; // skip non-midi files
auto ftime = std::filesystem::last_write_time(entry.path());
auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
ftime - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now()
);
item.lastWrite = std::chrono::system_clock::to_time_t(sctp);
}
else {
item.lastWrite = 0;
}
g_midiItems.push_back(item);
}
}
static int GetSortMode() {
HWND cbSort = GetDlgItem(g_hMainWnd, ID_CB_SORT);
if (!cbSort)
return 0; // default to "Name (A-Z)"
return static_cast<int>(SendMessage(cbSort, CB_GETCURSEL, 0, 0));
}
static void SortMidiItems() {
int sortMode = GetSortMode();
std::vector<MidiItem> parentItems;
std::vector<MidiItem> folders;
std::vector<MidiItem> files;
for (const auto& item : g_midiItems) {
if (item.name == L"..")
parentItems.push_back(item);
else if (item.isFolder)
folders.push_back(item);
else
files.push_back(item);
}
// Sorting function for folders.
auto folderSort = [sortMode](const MidiItem& a, const MidiItem& b) -> bool {
// Folders don’t have a valid date, so we sort them by name.
switch (sortMode) {
case 0: // Name (A-Z)
return _wcsicmp(a.name.c_str(), b.name.c_str()) < 0;
case 1: // Name (Z-A)
return _wcsicmp(a.name.c_str(), b.name.c_str()) > 0;
default:
return _wcsicmp(a.name.c_str(), b.name.c_str()) < 0;
}
};
auto fileSort = [sortMode](const MidiItem& a, const MidiItem& b) -> bool {
bool aFav = (std::filesystem::path(a.fullPath).parent_path().filename() == L"favorite");
bool bFav = (std::filesystem::path(b.fullPath).parent_path().filename() == L"favorite");
if (aFav != bFav)
return aFav;
switch (sortMode) {
case 0: // Name (A-Z)
return _wcsicmp(a.name.c_str(), b.name.c_str()) < 0;
case 1: // Name (Z-A)
return _wcsicmp(a.name.c_str(), b.name.c_str()) > 0;
case 2: // Date (Old-New)
return a.lastWrite < b.lastWrite;
case 3: // Date (New-Old)
return a.lastWrite > b.lastWrite;
default:
return _wcsicmp(a.name.c_str(), b.name.c_str()) < 0;
}
};
std::sort(folders.begin(), folders.end(), folderSort);
std::sort(files.begin(), files.end(), fileSort);
g_midiItems.clear();
for (const auto& p : parentItems)
g_midiItems.push_back(p);
for (const auto& f : folders)
g_midiItems.push_back(f);
for (const auto& f : files)
g_midiItems.push_back(f);
}
static void RefreshVelocityCurveCombo(HWND hWnd) {
HWND cbVelocity = GetDlgItem(hWnd, ID_CB_VELOCITY_CURVE);
SendMessage(cbVelocity, CB_RESETCONTENT, 0, 0);
SendMessageW(cbVelocity, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Linear Coarse"));
SendMessageW(cbVelocity, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Linear Fine"));
SendMessageW(cbVelocity, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Improved Low Volume"));
SendMessageW(cbVelocity, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Logarithmic"));
SendMessageW(cbVelocity, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Exponential"));
const auto& customCurves = midi::Config::getInstance().playback.customVelocityCurves;
for (const auto& curve : customCurves) {
std::wstring wCurveName(curve.name.begin(), curve.name.end());
SendMessageW(cbVelocity, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(wCurveName.c_str()));
}
SendMessage(cbVelocity, CB_SETCURSEL, 0, 0);
}
static void PopulateMidiList() {
if (!g_lbMidi)
return; // Guard against a NULL listbox handle
SendMessage(g_lbMidi, LB_RESETCONTENT, 0, 0);
int maxWidth = 0;
HDC hdc = GetDC(g_lbMidi);
HFONT hFont = reinterpret_cast<HFONT>(SendMessage(g_lbMidi, WM_GETFONT, 0, 0));
if (hFont)
SelectObject(hdc, hFont);
for (const auto& item : g_midiItems) {
std::wstring displayName;
if (item.name == L"..") {
displayName = L".. (Back)";
}
else if (item.isFolder) {
displayName = item.name + L"\\";
}
else {
displayName = item.name;
std::filesystem::path filePath(item.fullPath);
std::filesystem::path favFolder = std::filesystem::path(L"midi") / L"favorite";
std::filesystem::path favFile = favFolder / filePath.filename();
if (std::filesystem::exists(favFile))
displayName = L"★ " + displayName;
}
SendMessageW(g_lbMidi, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(displayName.c_str()));
SIZE textSize;
GetTextExtentPoint32W(hdc, displayName.c_str(), static_cast<int>(displayName.size()), &textSize);
if (textSize.cx > maxWidth)
maxWidth = textSize.cx;
}
ReleaseDC(g_lbMidi, hdc);
SendMessage(g_lbMidi, LB_SETHORIZONTALEXTENT, maxWidth, 0);
if (SendMessage(g_lbMidi, LB_GETCOUNT, 0, 0) > 0)
SendMessage(g_lbMidi, LB_SETCURSEL, 0, 0);
}
static std::wstring GetSelectedMidiFullPath() {
int sel = static_cast<int>(SendMessage(g_lbMidi, LB_GETCURSEL, 0, 0));
if (sel == LB_ERR || sel < 0 || sel >= static_cast<int>(g_midiItems.size()))
return L"";
const MidiItem& item = g_midiItems[sel];
if (item.isFolder)
return L"";
return item.fullPath;
}
// -----------------------------------------------------------------------------
// Logging (Redirect std::cout)
// -----------------------------------------------------------------------------
static std::streambuf* g_oldCoutBuf = nullptr;
static std::string GetTimeStamp() {
SYSTEMTIME st;
GetLocalTime(&st);
char buf[32];
sprintf_s(buf, "[%02d:%02d:%02d] ", st.wHour, st.wMinute, st.wSecond);
return buf;
}
class LogBuf : public std::streambuf {
static constexpr size_t BUFFER_SIZE = 8192;
char buffer[BUFFER_SIZE];
bool startOfLine = true;
std::string timestampCache;
void updateTimestampCache() {
SYSTEMTIME st;
GetLocalTime(&st);
char buf[32];
sprintf_s(buf, "[%02d:%02d:%02d] ", st.wHour, st.wMinute, st.wSecond);
timestampCache = buf;
}
protected:
std::streamsize xsputn(const char* s, std::streamsize n) override {
if (n <= 0)
return 0;
std::string chunk;
chunk.reserve(n + (n / 20) * timestampCache.size());
size_t start = 0;
for (size_t i = 0; i < static_cast<size_t>(n); ++i) {
if (startOfLine) {
if (timestampCache.empty()) updateTimestampCache();
chunk.append(timestampCache);
startOfLine = false;
}
if (s[i] == '\n') {
chunk.append(s + start, i - start + 1);
start = i + 1;
startOfLine = true;
}
}
if (start < static_cast<size_t>(n))
chunk.append(s + start, n - start);
chunk = std::regex_replace(chunk, g_ansiPattern, "");
{
std::lock_guard<std::mutex> lk(g_logMutex);
g_logBuffer += chunk;
}
if (g_guiReady.load(std::memory_order_acquire))
PostMessage(g_hMainWnd, WM_UPDATE_LOG, 0, 0);
return n;
}
int overflow(int c = EOF) override {
if (c == EOF) return c;
char ch = static_cast<char>(c);
return xsputn(&ch, 1);
}
};
static LogBuf g_logBuf;
static void RedirectCout() {
if (!g_oldCoutBuf)
g_oldCoutBuf = std::cout.rdbuf(&g_logBuf);
}
static void RestoreCout() {
if (g_oldCoutBuf) {
std::cout.rdbuf(g_oldCoutBuf);
g_oldCoutBuf = nullptr;
}
}
// -----------------------------------------------------------------------------
// UI Helper Functions
// -----------------------------------------------------------------------------
static void SetAlwaysOnTop(HWND hwnd, bool top) {
SetWindowPos(hwnd, (top ? HWND_TOPMOST : HWND_NOTOPMOST),
0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
static void UpdateWindowFocusability() {
if (!g_hMainWnd) return;
bool shouldBeNoActivate = false;
if ((g_midiConnect && g_midiConnect->IsActive()) ||
(g_midi2key && g_midi2key->IsActive()) ||
(g_player && g_player->midiFileSelected.load(std::memory_order_acquire) && !g_player->paused.load(std::memory_order_relaxed)))
{
shouldBeNoActivate = true;
}
LONG exStyle = GetWindowLong(g_hMainWnd, GWL_EXSTYLE);
bool currentNoActivate = (exStyle & WS_EX_NOACTIVATE) != 0;
if (shouldBeNoActivate != currentNoActivate) {
if (shouldBeNoActivate)
exStyle |= WS_EX_NOACTIVATE;
else
exStyle &= ~WS_EX_NOACTIVATE;
SetWindowLong(g_hMainWnd, GWL_EXSTYLE, exStyle);
SetWindowPos(g_hMainWnd, nullptr, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE);
}
}
static COLORREF g_colorOn = RGB(100, 255, 100);
static COLORREF g_colorOff = RGB(220, 220, 220);
static COLORREF g_colorHover = RGB(180, 180, 250);
static COLORREF g_colorPush = RGB(160, 160, 255);
static COLORREF g_colorText = RGB(0, 0, 0);
static void DrawFancyButton(const DRAWITEMSTRUCT* dis) {
if (dis->CtlType != ODT_BUTTON)
return;
int ctrlID = static_cast<int>(dis->CtlID);
bool togglable = IsToggleButtonID(ctrlID);
bool toggled = togglable ? g_toggleStates[ctrlID] : false;
HDC hdc = dis->hDC;
RECT rc = dis->rcItem;
bool isHot = (dis->itemState & ODS_HOTLIGHT) != 0;
bool isPressed = (dis->itemState & ODS_SELECTED) != 0;
bool isFocused = (dis->itemState & ODS_FOCUS) != 0;
COLORREF fill = g_colorOff;
if (ctrlID == ID_BTN_SUSTAIN && g_player != nullptr) {
switch (g_player->currentSustainMode) {
case SustainMode::IG:
fill = RGB(220, 220, 220);
break;
case SustainMode::SPACE_DOWN:
fill = RGB(100, 255, 100);
break;
case SustainMode::SPACE_UP:
fill = RGB(100, 100, 255);
break;
}
}
else if (togglable && toggled) {
fill = g_colorOn;
}
if (isPressed)
fill = g_colorPush;
else if (isHot)
fill = g_colorHover;
HBRUSH br = CreateSolidBrush(fill);
FillRect(hdc, &rc, br);
DeleteObject(br);
FrameRect(hdc, &rc, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
wchar_t text[128] = { 0 };
GetWindowTextW(dis->hwndItem, text, 128);
SetTextColor(hdc, g_colorText);
SetBkMode(hdc, TRANSPARENT);
static HFONT s_hRegularFont = nullptr;
static HFONT s_hBoldFont = nullptr;
if (!s_hRegularFont) {
s_hRegularFont = reinterpret_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT));
LOGFONT lf = {};
GetObject(s_hRegularFont, sizeof(lf), &lf);
lf.lfWeight = FW_BOLD;
s_hBoldFont = CreateFontIndirect(&lf);
}
HFONT hFontToUse = (togglable && toggled) ? s_hBoldFont : s_hRegularFont;
HFONT hOldFont = reinterpret_cast<HFONT>(SelectObject(hdc, hFontToUse));
DrawTextW(hdc, text, -1, &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
if (isFocused) {
RECT frc = rc;
InflateRect(&frc, -3, -3);
DrawFocusRect(hdc, &frc);
}
SelectObject(hdc, hOldFont);
}
// -----------------------------------------------------------------------------
// MIDI Details and Tracks Update Functions
// -----------------------------------------------------------------------------
static const char* GM_NAMES[128] = {
"Acoustic Grand Piano","Bright Acoustic Piano","Electric Grand Piano","Honky-tonk Piano","Electric Piano 1","Electric Piano 2","Harpsichord","Clavi","Celesta","Glockenspiel","Music Box","Vibraphone","Marimba","Xylophone","Tubular Bells","Dulcimer",
"Drawbar Organ","Percussive Organ","Rock Organ","Church Organ","Reed Organ","Accordion","Harmonica","Tango Accordion","Acoustic Guitar (nylon)","Acoustic Guitar (steel)","Electric Guitar (jazz)","Electric Guitar (clean)","Electric Guitar (muted)","Overdriven Guitar","Distortion Guitar","Guitar harmonics",
"Acoustic Bass","Electric Bass (finger)","Electric Bass (pick)","Fretless Bass","Slap Bass 1","Slap Bass 2","Synth Bass 1","Synth Bass 2","Violin","Viola","Cello","Contrabass","Tremolo Strings","Pizzicato Strings","Orchestral Harp","Timpani",
"String Ensemble 1","String Ensemble 2","SynthStrings 1","SynthStrings 2","Choir Aahs","Voice Oohs","Synth Voice","Orchestra Hit","Trumpet","Trombone","Tuba","Muted Trumpet","French Horn","Brass Section","SynthBrass 1","SynthBrass 2",
"Soprano Sax","Alto Sax","Tenor Sax","Baritone Sax","Oboe","English Horn","Bassoon","Clarinet","Piccolo","Flute","Recorder","Pan Flute","Blown Bottle","Shakuhachi","Whistle","Ocarina",
"Lead 1 (square)","Lead 2 (sawtooth)","Lead 3 (calliope)","Lead 4 (chiff)","Lead 5 (charang)","Lead 6 (voice)","Lead 7 (fifths)","Lead 8 (bass + lead)","Pad 1 (new age)","Pad 2 (warm)","Pad 3 (polysynth)","Pad 4 (choir)","Pad 5 (bowed)","Pad 6 (metallic)","Pad 7 (halo)","Pad 8 (sweep)",
"FX 1 (rain)","FX 2 (soundtrack)","FX 3 (crystal)","FX 4 (atmosphere)","FX 5 (brightness)","FX 6 (goblins)","FX 7 (echoes)","FX 8 (sci-fi)","Sitar","Banjo","Shamisen","Koto","Kalimba","Bag pipe","Fiddle","Shanai",
"Tinkle Bell","Agogo","Steel Drums","Woodblock","Taiko Drum","Melodic Tom","Synth Drum","Reverse Cymbal","Guitar Fret Noise","Breath Noise","Seashore","Bird Tweet","Telephone Ring","Helicopter","Applause","Gunshot"
};
static void UpdateMidiDetails() {
if (!g_player)
return;
MidiFile& mf = g_player->midi_file;
SetWindowTextW(g_editDetails, L"");
auto appendLine = [&](const std::wstring& line) {
std::wstring s = line + L"\r\n";
SendMessageW(g_editDetails, EM_REPLACESEL, FALSE, reinterpret_cast<LPARAM>(s.c_str()));
};
std::wstring wpath = GetSelectedMidiFullPath();
if (!wpath.empty()) {
std::filesystem::path p(wpath);
appendLine(L"File: " + p.filename().wstring());
}
std::wostringstream oss;
oss << std::left;
oss.str(L"");
oss << "Format: " << mf.format;
switch (mf.format) {
case 0: oss << " (single)"; break;
case 1: oss << " (multi)"; break;
case 2: oss << " (multi-song)"; break;
}
appendLine(oss.str());
int activeTracks = 0;
for (const auto& track : mf.tracks) {
if (!track.events.empty())
++activeTracks;
}
oss.str(L"");
oss << "Tracks: " << activeTracks << "/" << mf.numTracks;
int totalNotes = 0;
for (const auto& track : mf.tracks) {
for (const auto& evt : track.events) {
if ((evt.status & 0xF0) == 0x90 && evt.data2 > 0)
++totalNotes;
}
}
oss << " (" << totalNotes << " notes)";
appendLine(oss.str());
if (!mf.tempoChanges.empty()) {
double initialTempo = mf.tempoChanges[0].microsecondsPerQuarter;
double bpm = 60000000.0 / initialTempo;
oss.str(L"");
oss << "Tempo: " << std::fixed << std::setprecision(1) << bpm << " BPM";
if (mf.tempoChanges.size() > 1)
oss << " (" << (mf.tempoChanges.size() - 1) << " changes)";
appendLine(oss.str());
}
if (!mf.timeSignatures.empty()) {
auto& ts = mf.timeSignatures[0];
oss.str(L"");
oss << "Time Sig: " << static_cast<int>(ts.numerator) << "/" << static_cast<int>(ts.denominator);
if (mf.timeSignatures.size() > 1)
oss << " (" << (mf.timeSignatures.size() - 1) << " changes)";
appendLine(oss.str());
}
std::string modeStr;
switch (midi::Config::getInstance().playback.noteHandlingMode) {
case midi::NoteHandlingMode::FIFO: modeStr = "FIFO"; break;
case midi::NoteHandlingMode::LIFO: modeStr = "LIFO"; break;
default: modeStr = "None"; break;
}
std::string lastLine = "Note Mode: " + modeStr;
bool filterDrums = midi::Config::getInstance().midi.DETECT_DRUMS;
lastLine += (filterDrums ? " (Drum Detect: On)" : " (Ch10 Filter: Off)");
SendMessageA(g_editDetails, EM_REPLACESEL, FALSE, reinterpret_cast<LPARAM>(lastLine.c_str()));
}
static void UpdateTrackInfo() {
if (!g_player) {
std::vector<TrackControl::TrackInfo> empty;
g_trackControl.SetTracks(empty);
return;
}
MidiFile& mf = g_player->midi_file;
std::vector<TrackControl::TrackInfo> tracks;
for (size_t trackIndex = 0; trackIndex < mf.tracks.size(); ++trackIndex) {
TrackControl::TrackInfo info;
info.isMuted = false;
info.isSoloed = false;
info.isDrums = false; // initialize flag
if (trackIndex < g_player->trackMuted.size() && g_player->trackMuted[trackIndex])
info.isMuted = g_player->trackMuted[trackIndex]->load(std::memory_order_acquire);
if (trackIndex < g_player->trackSoloed.size() && g_player->trackSoloed[trackIndex])
info.isSoloed = g_player->trackSoloed[trackIndex]->load(std::memory_order_acquire);
const auto& track = mf.tracks[trackIndex];
int noteCount = 0;
std::unordered_map<int, int> channelCounts;
std::string trackName;
for (const auto& evt : track.events) {
if ((evt.status & 0xF0) == 0x90 && evt.data2 > 0) {
++noteCount;
channelCounts[evt.status & 0x0F]++;
}
if ((evt.status & 0xF0) == 0xC0)
info.programNumber = evt.data1 & 0x7F;
if (evt.status == 0xFF && evt.data1 == 0x03)
trackName = std::string(evt.metaData.begin(), evt.metaData.end());
}
if (!channelCounts.empty()) {
info.channel = std::max_element(channelCounts.begin(), channelCounts.end(),
[](const auto& p1, const auto& p2) {
return p1.second < p2.second;
})->first;
}
info.noteCount = noteCount;
info.trackName = trackName.empty() ? ("Track " + std::to_string(trackIndex + 1)) : trackName;
if (info.programNumber >= 0 && info.programNumber < 128) {
info.instrumentName = GM_NAMES[info.programNumber];
if (g_player->drum_flags.size() > trackIndex && g_player->drum_flags[trackIndex]) {
info.instrumentName += " (Drums)";
info.isDrums = true;
}
}
else {
info.instrumentName = "Unknown";
}
tracks.push_back(info);
}
g_trackControl.SetTracks(tracks);
}
static void FocusRobloxWindowInternal() {
HWND hRb = FindWindowW(nullptr, L"Roblox");
if (!hRb) {
std::cerr << "[WARNING] Could not find Roblox window.\n";
return;
}
if (!IsWindow(hRb)) {
std::cerr << "[ERROR] Found handle is not a valid window.\n";
return;
}
DWORD_PTR dwResult = 0;
if (SendMessageTimeout(hRb, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 500, &dwResult) == 0) {
std::cerr << "[WARNING] Roblox window is not responding; skipping focus.\n";
return;
}
if (!IsWindowVisible(hRb)) {
std::cerr << "[WARNING] Roblox window is not visible; skipping focus to avoid invasive changes.\n";
return;
}
if (IsIconic(hRb)) {
ShowWindow(hRb, SW_RESTORE);
}
else {
ShowWindow(hRb, SW_SHOWNA);
}
if (!SetForegroundWindow(hRb)) {
std::cerr << "[ERROR] Failed to bring Roblox window to foreground. Error code: " << GetLastError() << "\n";
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
static void FocusRobloxWindow() {
std::thread(FocusRobloxWindowInternal).detach();
}
static void ClearLog(HWND editLog) {
if (!editLog) return;
{
std::lock_guard<std::mutex> lk(g_logMutex);
g_logBuffer.clear();
}
if (!SetWindowTextW(editLog, L"")) {
DWORD error = GetLastError();
std::cerr << "Failed to clear log. Error code: " << error << std::endl;
}
}
static void ToggleFavorite(int index) {
if (index < 0 || index >= static_cast<int>(g_midiItems.size()))
return;
MidiItem& item = g_midiItems[index];
if (item.isFolder)
return;
std::filesystem::path filePath(item.fullPath);
std::error_code ec;
if (filePath.parent_path().filename() == L"favorite") {
std::filesystem::remove(filePath, ec);
if (!ec) {
std::filesystem::path origPath = std::filesystem::path(L"midi") / filePath.filename();
item.fullPath = origPath.wstring();
}
}
else {
std::filesystem::path destFolder = std::filesystem::path(L"midi") / L"favorite";
if (!std::filesystem::exists(destFolder)) {
std::filesystem::create_directories(destFolder, ec);
if (ec)
return; // silently fail if folder creation fails
}
std::filesystem::path destFile = destFolder / filePath.filename();
std::filesystem::copy_file(filePath, destFile, std::filesystem::copy_options::overwrite_existing, ec);
if (!ec) {
item.fullPath = destFile.wstring();
}
}
if (g_lbMidi) {
std::wstring displayName;
if (item.name == L"..") {
displayName = L".. (Back)";
}
else if (item.isFolder) {
displayName = item.name + L"\\";
}
else {
displayName = item.name;
std::filesystem::path p(item.fullPath);
if (p.parent_path().filename() == L"favorite")
displayName = L"★ " + displayName;
}
SendMessageW(g_lbMidi, LB_DELETESTRING, index, 0);
SendMessageW(g_lbMidi, LB_INSERTSTRING, index, reinterpret_cast<LPARAM>(displayName.c_str()));
}
}
static LRESULT CALLBACK MidiListSubclassProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
switch (msg)
{
case WM_RBUTTONDOWN:
{
POINT pt;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
int index = static_cast<int>(SendMessage(hwnd, LB_ITEMFROMPOINT, 0, MAKELPARAM(pt.x, pt.y)));
if (index != LB_ERR) {
ToggleFavorite(index);
}
return 0;
}
default:
return DefSubclassProc(hwnd, msg, wParam, lParam);
}
}
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
// temporary fix: this shit
case WM_NCLBUTTONDOWN:
{
if ((g_midi2key && g_midi2key->IsActive()) ||
(g_midiConnect && g_midiConnect->IsActive()) ||
(g_player &&
g_player->midiFileSelected.load(std::memory_order_acquire) &&
!g_player->paused.load(std::memory_order_acquire) &&
g_player->playback_started.load(std::memory_order_acquire) &&
(g_player->buffer_index.load(std::memory_order_acquire) < g_player->note_buffer.size()) &&
wParam == HTCAPTION))
{
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
case WM_CREATE:
{
INITCOMMONCONTROLSEX icex = {};
icex.dwSize = sizeof(icex);
icex.dwICC = ICC_BAR_CLASSES;
InitCommonControlsEx(&icex);
// MIDI Files Group
CreateWindowW(L"button", L"MIDI Files",
WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
Layout::FILES_X, Layout::FILES_Y, Layout::FILES_W, Layout::FILES_H,
hWnd, reinterpret_cast<HMENU>(1), g_hInst, nullptr);
HWND cbSort = CreateWindowW(L"combobox", nullptr,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
Layout::FILES_X + 10, Layout::FILES_Y + 20, 130, 110,
hWnd, reinterpret_cast<HMENU>(ID_CB_SORT), g_hInst, nullptr);
SendMessageW(cbSort, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Name (A-Z)"));
SendMessageW(cbSort, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Name (Z-A)"));
SendMessageW(cbSort, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Date (Old-New)"));
SendMessageW(cbSort, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(L"Date (New-Old)"));
SendMessageW(cbSort, CB_SETCURSEL, 0, 0);
CreateWindowW(L"button", L"Refresh",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
Layout::FILES_X + 150, Layout::FILES_Y + 20, 70, 25,
hWnd, reinterpret_cast<HMENU>(ID_BTN_REFRESH), g_hInst, nullptr);
g_lbMidi = CreateWindowW(L"listbox", nullptr,
WS_CHILD | WS_VISIBLE | LBS_NOTIFY | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOINTEGRALHEIGHT,
Layout::FILES_X + 10, Layout::FILES_Y + 50, 210, 350,
hWnd, reinterpret_cast<HMENU>(ID_LB_MIDI), g_hInst, nullptr);
SetWindowSubclass(g_lbMidi, MidiListSubclassProc, 0, 0);
// Playback (Basic) Group
CreateWindowW(L"button", L"Playback (Basic)",
WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
Layout::PBASIC_X, Layout::PBASIC_Y, Layout::PBASIC_W, Layout::PBASIC_H,
hWnd, reinterpret_cast<HMENU>(ID_GRP_PLAY), g_hInst, nullptr);
int bx = Layout::PBASIC_X + 20;
CreateWindowW(L"button", L"Load",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW1_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_LOAD), g_hInst, nullptr);
bx += Layout::PB_BTN_WIDTH + Layout::PB_BTN_GAP;
CreateWindowW(L"button", L"Play/Pause",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW1_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_PLAY), g_hInst, nullptr);
bx += Layout::PB_BTN_WIDTH + Layout::PB_BTN_GAP;
CreateWindowW(L"button", L"Restart",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW1_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_RESTART), g_hInst, nullptr);
bx = Layout::PBASIC_X + 20;
CreateWindowW(L"button", L"Skip+10",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW2_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_SKIP), g_hInst, nullptr);
bx += Layout::PB_BTN_WIDTH + Layout::PB_BTN_GAP;
CreateWindowW(L"button", L"Rew-10",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW2_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_REW), g_hInst, nullptr);
bx += Layout::PB_BTN_WIDTH + Layout::PB_BTN_GAP;
CreateWindowW(L"button", L"Speed++",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW2_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_SPEEDUP), g_hInst, nullptr);
bx += Layout::PB_BTN_WIDTH + Layout::PB_BTN_GAP;
CreateWindowW(L"button", L"Speed--",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW2_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_SPEEDDN), g_hInst, nullptr);
CreateWindowW(L"button", L"Midi2Key",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
Layout::PB_MIDI_QWERTY_X + 35, Layout::PB_MIDI_QWERTY_Y, 80, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_MIDI2QWERTY), g_hInst, nullptr);
CreateWindowW(L"button", L"MidiConnect",
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
bx, Layout::PB_ROW1_Y, Layout::PB_BTN_WIDTH, Layout::PB_BTN_HEIGHT,
hWnd, reinterpret_cast<HMENU>(ID_BTN_MIDICONNECT), g_hInst, nullptr);
bx += Layout::PB_BTN_WIDTH + Layout::PB_BTN_GAP;
HWND cbMidiDev = CreateWindowW(L"combobox", nullptr,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
Layout::PB_MIDI_QWERTY_X + 120, Layout::PB_MIDI_QWERTY_Y, 130, 200,
hWnd, reinterpret_cast<HMENU>(ID_CB_MIDIDEV), g_hInst, nullptr);
MIDIDeviceUI::PopulateMidiInDevices(cbMidiDev, g_selectedMidiDevice);
HWND cbMidiCh = CreateWindowW(L"combobox", nullptr,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
Layout::PB_MIDI_QWERTY_X + 120, Layout::PB_ROW2_Y, 130, 200,
hWnd, reinterpret_cast<HMENU>(ID_CB_MIDICH), g_hInst, nullptr);
MIDIDeviceUI::PopulateChannelList(cbMidiCh, g_selectedMidiChannel);
CreateWindowW(L"static", L"0:00 / 0:00",
WS_CHILD | WS_VISIBLE | SS_CENTER,
Layout::PB_STATIC_TIME_X - 90, Layout::PB_STATIC_TIME_Y + 36,
Layout::PB_STATIC_TIME_W - 50, Layout::PB_STATIC_TIME_H,