-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdllmain.cpp
More file actions
2319 lines (2009 loc) · 83.4 KB
/
Copy pathdllmain.cpp
File metadata and controls
2319 lines (2009 loc) · 83.4 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
#include "pch.h"
#include <ctime>
#include <process.h>
#include <string>
#include <cstdlib>
#include <windows.h>
#include <cwchar> // for std::wcstoll
#include <cwctype>
#include <commctrl.h>
#include "xmpfunc.h"
#include "xmpdsp.h"
#include "resource.h" // define IDD_SEARCH
#include "sqlite\sqlite3.h"
#include <Shlwapi.h> // PathRemoveFileSpecW
#include <shellapi.h> // for ShellExecuteW
#include <map>
#include <set>
#include <vector>
#include <urlmon.h>
#include "utf.hpp"
#include "time.hpp"
#include "http_head.hpp"
#include <memory>
#include "modland.hpp"
#include "pls.hpp"
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "Shlwapi.lib")
static InterfaceProc g_faceproc;
static XMPFUNC_MISC* xmpfmisc;
static XMPFUNC_FILE* xmpffile;
// static XMPFUNC_REGISTRY* xmpfreg;
static void *WINAPI Plugin_Init(void);
static void WINAPI Plugin_Exit(void* inst);
static const char* WINAPI Plugin_GetDescription(void* inst);
static void WINAPI MyConfig(void* inst, HWND win);
static DWORD WINAPI Plugin_GetConfig(void* inst, void* config);
static BOOL WINAPI Plugin_SetConfig(void* inst, void* config, DWORD size);
static BOOL CALLBACK SearchDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
static void WINAPI OpenSearchShortcut(void);
static bool EnsureDatabaseOpen(HWND hDlg);
static void DoSearch(HWND hDlg, bool exact = false, int randomCount = 0);
struct PluginConfig {
};
static HWND hSearchDlg = nullptr;
static bool g_initializingSearchDialog = false;
static HINSTANCE hInstance;
static HWND hWndConf = 0;
static HWND hWndXMP;
static sqlite3* g_db = nullptr;
static void LogMessage(const std::wstring& message)
{
wchar_t modulePath[MAX_PATH]{};
if (!GetModuleFileNameW(hInstance, modulePath, _countof(modulePath)))
return;
PathRemoveFileSpecW(modulePath);
wchar_t logPath[MAX_PATH]{};
if (!PathCombineW(logPath, modulePath, L"cmod.log"))
return;
HANDLE file = CreateFileW(
logPath, FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE)
return;
SYSTEMTIME now{};
GetLocalTime(&now);
wchar_t timestamp[32]{};
swprintf_s(timestamp, L"[%04u-%02u-%02u %02u:%02u:%02u] ",
now.wYear, now.wMonth, now.wDay,
now.wHour, now.wMinute, now.wSecond);
const std::string line = to_utf8(std::wstring(timestamp) + message + L"\r\n");
DWORD written = 0;
WriteFile(file, line.data(), static_cast<DWORD>(line.size()), &written, nullptr);
CloseHandle(file);
}
static void LogWin32Error(const wchar_t* operation, DWORD error)
{
wchar_t message[256]{};
swprintf_s(message, L"%s failed (Win32 0x%08X).", operation, error);
LogMessage(message);
}
static void LogSqliteError(const wchar_t* operation, int rc, sqlite3* db = nullptr)
{
std::wstring message = operation;
message += L" failed (SQLite ";
message += std::to_wstring(rc);
message += L"): ";
message += to_wide(db ? sqlite3_errmsg(db) : sqlite3_errstr(rc));
LogMessage(message);
}
// --- build info (caché en memoria) ---
static time_t g_dbBuiltUnix = 0; // epoch (UTC)
static std::wstring g_dbBuiltIsoW; // "YYYY-MM-DDTHH:MM:SSZ"
static bool g_dbBuiltAllFormats = false; // true si se reconstruyó con 'allFormats'
static std::wstring DbBadge()
{
if (!g_dbBuiltUnix) return L""; // aún no sabemos la fecha
std::tm tmLocal{};
#if defined(_WIN32)
localtime_s(&tmLocal, &g_dbBuiltUnix); // thread-safe en MSVC
#else
localtime_r(&g_dbBuiltUnix, &tmLocal);
#endif
wchar_t date[16] = L"";
if (wcsftime(date, _countof(date), L"%Y-%m-%d", &tmLocal) == 0)
return L"";
std::wstring s = L" - db: ";
s += date; // ej. 2025-03-21 (hora local)
if (g_dbBuiltAllFormats) s += L" (all formats)";
return s;
}
static int g_colInitWidth[5] = { 0, 0, 0, 0, 0 };
#define WM_DB_REBUILT (WM_APP + 100)
#define WM_CHECK_READY (WM_APP + 101)
struct CheckParams {
HWND hDlg;
};
static unsigned __stdcall CheckUpdatesThread(void* pv)
{
std::unique_ptr<CheckParams> p((CheckParams*)pv);
time_t remoteUtc = 0;
const std::wstring allmodsUrl = to_wide(modland_allmods_url());
BOOL ok = HttpHead_LastModified(allmodsUrl.c_str(), &remoteUtc) ? TRUE : FALSE;
LogMessage(L"HEAD " + allmodsUrl + (ok ? L" succeeded." : L" failed."));
// Post result back. Use LPARAM for the 64-bit time safely.
PostMessageW(p->hDlg, WM_CHECK_READY, (WPARAM)ok, (LPARAM)remoteUtc);
return 0;
}
#define IDT_SEARCH_DELAY 1
#define IDT_STATE_SAVE 2
#define SEARCH_DELAY_MS 300 // 300 ms de debounce
// xmplay supported formats only (default)
static const std::set<std::string> xmplayFormats = {
"mod","s3m","xm","it","mo3","mtm","umx"
};
// All known formats (XMPlay + optional input plug-ins). This remains the
// fallback if cmod.ini cannot be read or does not contain a usable list.
static const std::set<std::string> allFormatsFallback = {
"mptm","mod","s3m","xm","it","669","a2m","a2t","amd","amf","ams",
"c67","cff","dbm","dfm","digi","dmf","dsm","dsym","dtm","far","fmk",
"fmt","hsc","imf","ice","j2b","m15","mdl","med","mms","mt2","mtk",
"mtm","nst","okt","plm","psm","pt36","ptm","rad","sa2","sat","sfx",
"sfx2","st26","stk","stm","stx","stp","symmod","ult","wow","gdm","mo3",
"oxm","umx","xms","xpk","ppm","mmcmp","mmd0","mmd1","mmd2","mmd3","mmdc"
};
static std::set<std::string> g_allFormats = allFormatsFallback;
struct RebuildParams {
HWND hDlg;
bool all;
// HINSTANCE hInst;
// XMPFUNC_MISC* xmpfmisc;
};
static const char* g_colNames[] = {
"extension", // columna 0
"artist", // columna 1
"song", // columna 2
"size",
"full_path" // columna 3
};
static int g_sortColumn = -1; // -1 = sin ordenar todavía
static bool g_sortAsc = true; // sentido actual
struct SortData {
HWND hList;
int column;
bool asc;
};
struct CtrlInfo {
RECT rc; // rect original en coords de cliente
bool moveX; // si debe moverse horizontalmente
bool moveY; // si debe moverse verticalmente
bool sizeW; // si debe cambiar de ancho
bool sizeH; // si debe cambiar de alto
};
static RECT g_rcInitClient;
static std::map<int, CtrlInfo> g_mapCtrls;
static bool g_use_pls = true; // default if no config.ini is present
// -- config, Size, URL encode and helpers
static bool NormalizeModlandUrl(std::wstring value, std::wstring& normalized)
{
size_t begin = 0;
while (begin < value.size() && std::iswspace(value[begin])) ++begin;
size_t end = value.size();
while (end > begin && std::iswspace(value[end - 1])) --end;
value = value.substr(begin, end - begin);
const bool isHttp = value.size() > 7 &&
_wcsnicmp(value.c_str(), L"http://", 7) == 0;
const bool isHttps = value.size() > 8 &&
_wcsnicmp(value.c_str(), L"https://", 8) == 0;
if (!isHttp && !isHttps)
return false;
for (wchar_t ch : value) {
if (std::iswspace(ch) || ch < 32 || ch == L'?' || ch == L'#' || ch == L'|')
return false;
}
while (!value.empty() && value.back() == L'/')
value.pop_back();
const size_t schemeLength = isHttps ? 8 : 7;
if (value.size() <= schemeLength)
return false;
normalized = value;
return true;
}
static std::wstring FormatsToIniValue(const std::set<std::string>& formats)
{
std::wstring value;
for (const auto& format : formats) {
if (!value.empty()) value += L",";
value += to_wide(format);
}
return value;
}
static bool ParseFormatsIni(const wchar_t* value, std::set<std::string>& formats)
{
formats.clear();
std::wstring token;
auto addToken = [&]() {
if (token.rfind(L"*.", 0) == 0)
token.erase(0, 2);
else if (!token.empty() && token.front() == L'.')
token.erase(0, 1);
bool valid = !token.empty();
for (wchar_t ch : token) {
if (ch > 127 || (!std::iswalnum(ch) && ch != L'_' && ch != L'-')) {
valid = false;
break;
}
}
if (valid) {
std::string format = to_utf8(token);
for (auto& ch : format)
ch = (char)std::tolower((unsigned char)ch);
formats.insert(format);
}
token.clear();
};
for (const wchar_t* p = value; ; ++p) {
const wchar_t ch = *p;
if (ch == L',' || ch == L';' || std::iswspace(ch) || ch == L'\0')
addToken();
else
token += ch;
if (ch == L'\0') break;
}
return !formats.empty();
}
static bool GetConfigIniPath(wchar_t (&iniPath)[MAX_PATH])
{
wchar_t dllDir[MAX_PATH]{};
if (!GetModuleFileNameW(hInstance, dllDir, MAX_PATH))
return false;
PathRemoveFileSpecW(dllDir);
return PathCombineW(iniPath, dllDir, L"cmod.ini") != nullptr;
}
static bool LoadConfigIni()
{
set_modland_base_url(default_modland_base_url());
wchar_t iniPath[MAX_PATH]{};
if (!GetConfigIniPath(iniPath))
return false;
// Read use_pls under [cmod]
// (GetPrivateProfileIntW is simpler/safer than parsing a string)
const int use_pls = GetPrivateProfileIntW(L"cmod", L"use_pls", /*default*/1, iniPath);
g_use_pls = (use_pls != 0);
wchar_t modlandUrlBuffer[2048]{};
const DWORD modlandUrlChars = GetPrivateProfileStringW(
L"cmod", L"modland_url", L"", modlandUrlBuffer,
_countof(modlandUrlBuffer), iniPath);
if (modlandUrlChars == 0) {
const std::wstring defaultUrl = to_wide(default_modland_base_url());
WritePrivateProfileStringW(
L"cmod", L"modland_url", defaultUrl.c_str(), iniPath);
}
else if (modlandUrlChars < _countof(modlandUrlBuffer) - 1) {
std::wstring normalizedUrl;
if (NormalizeModlandUrl(modlandUrlBuffer, normalizedUrl))
set_modland_base_url(to_utf8(normalizedUrl));
}
// Keep a compiled-in fallback, then replace it only with a complete,
// non-empty INI value. GetPrivateProfileString reports truncation as
// buffer_size - 1 when reading a single key.
g_allFormats = allFormatsFallback;
std::vector<wchar_t> formatsBuffer(32768, L'\0');
const DWORD chars = GetPrivateProfileStringW(
L"cmod", L"formats", L"", formatsBuffer.data(),
static_cast<DWORD>(formatsBuffer.size()), iniPath);
if (chars == 0) {
const std::wstring defaults = FormatsToIniValue(allFormatsFallback);
WritePrivateProfileStringW(L"cmod", L"formats", defaults.c_str(), iniPath);
}
else if (chars < formatsBuffer.size() - 1) {
std::set<std::string> configuredFormats;
if (ParseFormatsIni(formatsBuffer.data(), configuredFormats))
g_allFormats = configuredFormats;
}
return true;
}
static void ClearSelectionNow() {
xmpfmisc->DDE("key341");
xmpfmisc->DDE("key342");
}
static std::wstring HumanSize(sqlite3_int64 bytes)
{
const wchar_t* units[] = { L"B", L"KB", L"MB", L"GB", L"TB" };
double size = static_cast<double>(bytes);
int unit = 0;
while (size >= 1024.0 && unit < 4) {
size /= 1024.0;
++unit;
}
wchar_t buf[64];
// swprintf_s is the MSVC‐safe version of swprintf
swprintf_s(buf, _countof(buf), L"%.1f %s", size, units[unit]);
return buf;
}
inline std::wstring get_window_textW(HWND h) {
int len = GetWindowTextLengthW(h);
std::wstring w(len + 1, L'\0'); // espacio para el NUL
int got = GetWindowTextW(h, &w[0], len + 1); // got no incluye el NUL
if (got < 0) got = 0;
w.resize(got); // quita el NUL
return w;
}
static std::wstring ReadSearchStateIni(const wchar_t* key, const wchar_t* fallback)
{
wchar_t iniPath[MAX_PATH]{};
if (!GetConfigIniPath(iniPath))
return fallback;
wchar_t value[4096]{};
const DWORD chars = GetPrivateProfileStringW(
L"cmod", key, fallback, value, _countof(value), iniPath);
return chars < _countof(value) - 1 ? std::wstring(value) : std::wstring(fallback);
}
static void WriteSearchStateIni(const wchar_t* key, const std::wstring& value)
{
wchar_t iniPath[MAX_PATH]{};
if (GetConfigIniPath(iniPath))
WritePrivateProfileStringW(L"cmod", key, value.c_str(), iniPath);
}
static void SaveSearchDialogState(HWND hDlg)
{
WriteSearchStateIni(L"last_search",
get_window_textW(GetDlgItem(hDlg, IDC_EDIT_SEARCH)));
const int searchBy = static_cast<int>(SendMessageW(
GetDlgItem(hDlg, IDC_COMBO_SEARCH), CB_GETCURSEL, 0, 0));
static const wchar_t* searchByValues[] = { L"artist", L"song", L"all" };
const wchar_t* searchByValue =
searchBy >= 0 && searchBy < _countof(searchByValues)
? searchByValues[searchBy] : L"all";
WriteSearchStateIni(L"search_by", searchByValue);
std::wstring format = get_window_textW(GetDlgItem(hDlg, IDC_COMBO_FORMAT));
if (format.empty()) format = L"Any";
WriteSearchStateIni(L"format", format);
std::wstring songCount = get_window_textW(GetDlgItem(hDlg, IDC_COMBO_NUMBER));
if (songCount.empty()) songCount = L"100";
WriteSearchStateIni(L"song_count", songCount);
}
static int SearchByIndexFromIni(const std::wstring& value)
{
if (_wcsicmp(value.c_str(), L"artist") == 0) return 0;
if (_wcsicmp(value.c_str(), L"song") == 0) return 1;
return 2; // "all" and invalid values fall back to All.
}
static void RestoreSearchDialogState(HWND hDlg)
{
const std::wstring search = ReadSearchStateIni(L"last_search", L"");
const std::wstring searchBy = ReadSearchStateIni(L"search_by", L"all");
const std::wstring format = ReadSearchStateIni(L"format", L"Any");
const std::wstring songCount = ReadSearchStateIni(L"song_count", L"100");
SetDlgItemTextW(hDlg, IDC_EDIT_SEARCH, search.c_str());
SendMessageW(GetDlgItem(hDlg, IDC_COMBO_SEARCH), CB_SETCURSEL,
SearchByIndexFromIni(searchBy), 0);
SetWindowTextW(GetDlgItem(hDlg, IDC_COMBO_FORMAT), format.c_str());
HWND hComboCount = GetDlgItem(hDlg, IDC_COMBO_NUMBER);
const int countIndex = static_cast<int>(SendMessageW(
hComboCount, CB_FINDSTRINGEXACT, static_cast<WPARAM>(-1),
reinterpret_cast<LPARAM>(songCount.c_str())));
SendMessageW(hComboCount, CB_SETCURSEL, countIndex == CB_ERR ? 2 : countIndex, 0);
// Also creates the four keys on first use, with the defaults above.
SaveSearchDialogState(hDlg);
}
static void ScheduleSearchStateSave(HWND hDlg)
{
KillTimer(hDlg, IDT_STATE_SAVE);
SetTimer(hDlg, IDT_STATE_SAVE, SEARCH_DELAY_MS, nullptr);
}
// -- DB build info storage/retrieval
// Guarda metadatos de build en la BBDD abierta 'db'
static void StoreDbBuildInfo(sqlite3* db, bool allFormats)
{
sqlite3_exec(db,
"CREATE TABLE IF NOT EXISTS meta("
" k TEXT PRIMARY KEY,"
" v TEXT NOT NULL"
");", nullptr, nullptr, nullptr);
const time_t now = std::time(nullptr);
const std::string nowStr = std::to_string((long long)now);
const std::string isoStr = to_iso8601_utc(now);
const char* kind = allFormats ? "all" : "default";
sqlite3_stmt* st = nullptr;
const char* sql =
"INSERT OR REPLACE INTO meta(k,v) VALUES "
" ('built_unix', ?1),"
" ('built_iso', ?2),"
" ('build_kind', ?3);";
if (sqlite3_prepare_v2(db, sql, -1, &st, nullptr) == SQLITE_OK) {
sqlite3_bind_text(st, 1, nowStr.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 2, isoStr.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 3, kind, -1, SQLITE_TRANSIENT);
sqlite3_step(st);
}
sqlite3_finalize(st);
// refresca la caché en memoria
g_dbBuiltUnix = now;
g_dbBuiltIsoW = to_wide(isoStr);
g_dbBuiltAllFormats = allFormats;
}
// Carga metadatos de build desde 'db'; si no hay tabla meta, cae al mtime del fichero
static void LoadDbBuildInfo(sqlite3* db, const std::wstring& dbPath)
{
g_dbBuiltUnix = 0;
g_dbBuiltIsoW.clear();
g_dbBuiltAllFormats = false;
auto getMeta = [&](const char* key) -> std::string {
sqlite3_stmt* st = nullptr;
std::string val;
if (sqlite3_prepare_v2(db, "SELECT v FROM meta WHERE k=?1;", -1, &st, nullptr) == SQLITE_OK) {
sqlite3_bind_text(st, 1, key, -1, SQLITE_TRANSIENT);
if (sqlite3_step(st) == SQLITE_ROW) {
const unsigned char* p = sqlite3_column_text(st, 0);
if (p) val.assign((const char*)p);
}
}
sqlite3_finalize(st);
return val;
};
// ¿existe tabla meta?
bool hasMeta = false;
{
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db,
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta';",
-1, &st, nullptr) == SQLITE_OK) {
hasMeta = (sqlite3_step(st) == SQLITE_ROW);
}
sqlite3_finalize(st);
}
if (hasMeta) {
std::string u = getMeta("built_unix");
std::string i = getMeta("built_iso");
std::string k = getMeta("build_kind");
if (!u.empty()) g_dbBuiltUnix = (time_t)_strtoi64(u.c_str(), nullptr, 10);
if (!i.empty()) g_dbBuiltIsoW = to_wide(i);
g_dbBuiltAllFormats = (_stricmp(k.c_str(), "all") == 0);
}
else {
// Fallback: mtime del archivo
time_t t = file_mtime_utc(dbPath);
if (t) {
g_dbBuiltUnix = t;
g_dbBuiltIsoW = to_wide(to_iso8601_utc(t));
g_dbBuiltAllFormats = false;
}
}
}
// -- DB rebuild
static bool RebuildDatabase(XMPFILE txtFile,
const std::wstring& dbPathW, bool all)
{
LogMessage(L"Building " + dbPathW + (all ? L" (all formats)." : L" (default formats)."));
// Remove any old DB
if (!DeleteFileW(dbPathW.c_str())) {
const DWORD error = GetLastError();
if (error != ERROR_FILE_NOT_FOUND) {
LogWin32Error(L"Delete stale cmod_new.db", error);
return false;
}
}
// Open new DB
sqlite3* db = nullptr;
const int openRc = sqlite3_open16(dbPathW.c_str(), &db);
if (openRc != SQLITE_OK) {
LogSqliteError(L"Create cmod_new.db", openRc, db);
if (db) sqlite3_close(db);
return false;
}
LogMessage(L"Created cmod_new.db.");
sqlite3_exec(db, "PRAGMA encoding='UTF-8';", nullptr, nullptr, nullptr);
// Speed tweaks: in-memory journal + no fsync
sqlite3_exec(db, "PRAGMA journal_mode = MEMORY;", nullptr, nullptr, nullptr);
sqlite3_exec(db, "PRAGMA synchronous = OFF;", nullptr, nullptr, nullptr);
// Create FTS5 table
const char* ddl =
"CREATE VIRTUAL TABLE modland USING fts5("
" tracker, extension, artist, song, full_path, size UNINDEXED"
");";
const int ddlRc = sqlite3_exec(db, ddl, nullptr, nullptr, nullptr);
if (ddlRc != SQLITE_OK) {
LogSqliteError(L"Create FTS5 table", ddlRc, db);
sqlite3_close(db);
return false;
}
// Begin one big transaction
const int beginRc = sqlite3_exec(db, "BEGIN TRANSACTION;", nullptr, nullptr, nullptr);
if (beginRc != SQLITE_OK) {
LogSqliteError(L"Begin rebuild transaction", beginRc, db);
sqlite3_close(db);
return false;
}
// Prepare insert statement once
sqlite3_stmt* ins = nullptr;
const char* sql = "INSERT INTO modland VALUES (?1,?2,?3,?4,?5,?6);";
const int prepareRc = sqlite3_prepare_v2(db, sql, -1, &ins, nullptr);
if (prepareRc != SQLITE_OK) {
LogSqliteError(L"Prepare module insert", prepareRc, db);
sqlite3_close(db);
return false;
}
// TODO allowed or allowedAncient
const std::set<std::string>& allowed = all ? g_allFormats : xmplayFormats;
const size_t CHUNK = 16 * 1024;
std::vector<char> chunkBuf(CHUNK);
std::string carry; // holds partial line across reads
sqlite3_int64 totalBytes = 0;
sqlite3_int64 insertedRows = 0;
bool readFailed = false;
bool insertFailed = false;
while (!insertFailed) {
int bytes = xmpffile->Read(txtFile, chunkBuf.data(), CHUNK);
if (bytes <= 0) {
readFailed = bytes < 0;
break;
}
totalBytes += bytes;
carry.append(chunkBuf.data(), bytes);
size_t pos;
while ((pos = carry.find('\n')) != std::string::npos) {
std::string line8 = carry.substr(0, pos);
carry.erase(0, pos + 1);
// trim trailing '\r'
if (!line8.empty() && line8.back() == '\r')
line8.pop_back();
// convert UTF-8 → UTF-16
std::wstring lineW = to_wide(line8);
if (lineW.empty()) continue;
// --- 4) Your existing parsing + binding logic: ---
auto tab = lineW.find(L'\t');
if (tab == std::wstring::npos) continue;
std::wstring wsiz = lineW.substr(0, tab);
std::wstring rest = lineW.substr(tab + 1);
auto dot = rest.rfind(L'.');
if (dot == std::wstring::npos) continue;
std::string ext = to_utf8(rest.substr(dot + 1));
for (auto& ch : ext) ch = (char)std::tolower((unsigned char)ch);
if (!allowed.count(ext)) continue;
auto firstSlash = rest.find(L'/');
auto lastSlash = rest.rfind(L'/');
if (firstSlash == std::wstring::npos ||
lastSlash == firstSlash) continue;
std::wstring tracker = rest.substr(0, firstSlash);
std::wstring artist = rest.substr(firstSlash + 1,
lastSlash - firstSlash - 1);
std::wstring song = rest.substr(lastSlash + 1);
sqlite3_bind_text(ins, 1, to_utf8(tracker).c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ins, 2, ext.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ins, 3, to_utf8(artist).c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ins, 4, to_utf8(song).c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ins, 5, to_utf8(rest).c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int64(ins, 6, std::wcstoll(wsiz.c_str(), nullptr, 10));
const int stepRc = sqlite3_step(ins);
if (stepRc != SQLITE_DONE) {
LogSqliteError(L"Insert module row", stepRc, db);
insertFailed = true;
break;
}
++insertedRows;
sqlite3_reset(ins);
}
}
LogMessage(L"Read " + std::to_wstring(totalBytes) + L" bytes and inserted " +
std::to_wstring(insertedRows) + L" module rows.");
if (readFailed || insertFailed) {
if (readFailed) LogMessage(L"Reading allmods.txt failed before EOF.");
sqlite3_finalize(ins);
sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr);
sqlite3_close(db);
return false;
}
StoreDbBuildInfo(db, /*allFormats=*/all);
// Finish up
const int finalizeRc = sqlite3_finalize(ins);
if (finalizeRc != SQLITE_OK) {
LogSqliteError(L"Finalize module insert", finalizeRc, db);
sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr);
sqlite3_close(db);
return false;
}
const int commitRc = sqlite3_exec(db, "COMMIT;", nullptr, nullptr, nullptr);
if (commitRc != SQLITE_OK) {
LogSqliteError(L"Commit rebuilt database", commitRc, db);
sqlite3_close(db);
return false;
}
const int closeRc = sqlite3_close(db);
if (closeRc != SQLITE_OK) {
LogSqliteError(L"Close rebuilt cmod_new.db", closeRc);
return false;
}
LogMessage(L"Finished building cmod_new.db.");
return true;
}
// Closes the old DB and swaps cmod_new.db in while keeping a rollback copy.
static bool SwapInNewDatabase()
{
LogMessage(L"Database swap started.");
// 1) Compute paths
wchar_t modulePath[MAX_PATH];
GetModuleFileNameW(hInstance, modulePath, MAX_PATH);
PathRemoveFileSpecW(modulePath);
std::wstring dir = modulePath;
std::wstring oldDb = dir + L"\\cmod.db";
std::wstring newDb = dir + L"\\cmod_new.db";
std::wstring backupDb = dir + L"\\cmod_old.db";
const std::string oldDbUtf8 = to_utf8(oldDb);
auto reopenDb = [&]() -> int {
sqlite3* reopened = nullptr;
const int rc = sqlite3_open_v2(
oldDbUtf8.c_str(),
&reopened,
SQLITE_OPEN_READONLY,
nullptr
);
if (rc != SQLITE_OK) {
LogSqliteError(L"Open cmod.db read-only", rc, reopened);
if (reopened) sqlite3_close(reopened);
g_db = nullptr;
return rc;
}
g_db = reopened;
LoadDbBuildInfo(g_db, oldDb);
return SQLITE_OK;
};
// 2) Close old handle
if (g_db) {
const int closeRc = sqlite3_close(g_db);
if (closeRc != SQLITE_OK) {
LogSqliteError(L"Close current cmod.db", closeRc);
std::wstring msg = L"Cannot replace the database because SQLite could not close it.\n\nSQLite error:\n";
msg += to_wide(sqlite3_errstr(closeRc));
MessageBoxW(NULL, msg.c_str(), L"SwapInNewDatabase", MB_OK | MB_ICONERROR);
return false;
}
g_db = nullptr;
LogMessage(L"Closed current cmod.db.");
}
// Recover a previous interrupted swap before starting a new one.
bool oldExists = GetFileAttributesW(oldDb.c_str()) != INVALID_FILE_ATTRIBUTES;
const bool backupExists = GetFileAttributesW(backupDb.c_str()) != INVALID_FILE_ATTRIBUTES;
if (backupExists) {
if (oldExists) {
if (!DeleteFileW(backupDb.c_str())) {
const DWORD err = GetLastError();
LogWin32Error(L"Delete stale cmod_old.db", err);
reopenDb();
wchar_t buf[192];
swprintf_s(buf, L"Could not remove stale cmod_old.db (0x%08X).", err);
MessageBoxW(NULL, buf, L"SwapInNewDatabase", MB_OK | MB_ICONERROR);
return false;
}
}
else {
if (!MoveFileW(backupDb.c_str(), oldDb.c_str())) {
const DWORD err = GetLastError();
LogWin32Error(L"Restore stale cmod_old.db", err);
wchar_t buf[192];
swprintf_s(buf, L"Could not restore cmod_old.db (0x%08X).", err);
MessageBoxW(NULL, buf, L"SwapInNewDatabase", MB_OK | MB_ICONERROR);
return false;
}
oldExists = true;
LogMessage(L"Restored cmod_old.db left by an interrupted swap.");
}
}
// 3) Move the current DB aside, then install the new DB.
if (oldExists && !MoveFileW(oldDb.c_str(), backupDb.c_str())) {
const DWORD err = GetLastError();
LogWin32Error(L"Move cmod.db to cmod_old.db", err);
reopenDb();
wchar_t buf[192];
swprintf_s(buf, L"Could not move cmod.db to cmod_old.db (0x%08X).", err);
MessageBoxW(NULL, buf, L"SwapInNewDatabase", MB_OK | MB_ICONERROR);
return false;
}
if (oldExists) LogMessage(L"Moved cmod.db to cmod_old.db.");
if (!MoveFileW(newDb.c_str(), oldDb.c_str())) {
const DWORD installErr = GetLastError();
LogWin32Error(L"Move cmod_new.db to cmod.db", installErr);
bool restored = !oldExists || MoveFileW(backupDb.c_str(), oldDb.c_str());
const DWORD restoreErr = restored ? ERROR_SUCCESS : GetLastError();
if (restored && oldExists) reopenDb();
if (restored && oldExists)
LogMessage(L"Restored cmod_old.db after install failure.");
else if (oldExists)
LogWin32Error(L"Restore cmod_old.db after install failure", restoreErr);
wchar_t buf[256];
if (restored && oldExists)
swprintf_s(buf, L"Could not install cmod_new.db (0x%08X). The old database was restored.", installErr);
else if (!oldExists)
swprintf_s(buf, L"Could not install cmod_new.db (0x%08X).", installErr);
else
swprintf_s(buf, L"Could not install cmod_new.db (0x%08X) or restore cmod_old.db (0x%08X).", installErr, restoreErr);
MessageBoxW(NULL, buf, L"SwapInNewDatabase", MB_OK | MB_ICONERROR);
return false;
}
LogMessage(L"Moved cmod_new.db to cmod.db.");
// 4) Re-open the installed DB. Roll back if it cannot be opened.
const int reopenRc = reopenDb();
if (reopenRc != SQLITE_OK) {
const bool removedNew = DeleteFileW(oldDb.c_str()) != FALSE;
const bool restored = oldExists && removedNew &&
MoveFileW(backupDb.c_str(), oldDb.c_str()) != FALSE;
if (restored && oldExists) reopenDb();
if (!removedNew)
LogWin32Error(L"Delete unusable new cmod.db", GetLastError());
if (restored)
LogMessage(L"Restored cmod_old.db after reopen failure.");
wchar_t buf[256];
if (restored)
swprintf_s(buf, L"Could not reopen the new database (SQLite error %d). The old database was restored.", reopenRc);
else if (!oldExists && removedNew)
swprintf_s(buf, L"Could not reopen the new database (SQLite error %d).", reopenRc);
else
swprintf_s(buf, L"Could not reopen the new database (SQLite error %d), and the old database could not be restored.", reopenRc);
MessageBoxW(NULL, buf, L"SwapInNewDatabase", MB_OK | MB_ICONERROR);
return false;
}
// The new DB is open and usable; the rollback copy is no longer needed.
if (oldExists && !DeleteFileW(backupDb.c_str()))
LogWin32Error(L"Delete cmod_old.db after successful swap", GetLastError());
LogMessage(L"Database swap completed successfully.");
return true;
}
static unsigned __stdcall RebuildThread(void* pv)
{
auto* p = static_cast<RebuildParams*>(pv);
HWND hDlg = p->hDlg;
bool all = p->all;
// 1) Determinar paths
wchar_t modulePath[MAX_PATH];
GetModuleFileNameW(hInstance, modulePath, MAX_PATH);
PathRemoveFileSpecW(modulePath);
std::wstring dir = modulePath;
std::wstring newDb = dir + L"\\cmod_new.db";
bool success = false;
LogMessage(all ? L"Rebuild started (all formats)." : L"Rebuild started (default formats).");
// 2) Descarga
xmpfmisc->ShowBubble("Downloading allmods...", 1000);
const std::string allmodsSource = modland_allmods_url() + "|allmods.txt";
LogMessage(L"Opening " + to_wide(allmodsSource));
XMPFILE txtFile = xmpffile->Open(allmodsSource.c_str());
if (txtFile) {
LogMessage(L"Opened allmods.zip/allmods.txt successfully.");
// read and process file here
xmpfmisc->ShowBubble("Rebuilding DB…", 1000);
if (RebuildDatabase(txtFile, newDb, all))
{
// 5) Swap
xmpfmisc->ShowBubble("Swapping in new DB...", 1000);
if (SwapInNewDatabase())
{
success = true;
}
else {
LogMessage(L"Database swap failed.");
}
}
else {
LogMessage(L"Database build failed before the swap.");
}
xmpffile->Close(txtFile);
}
else {
LogMessage(L"Could not open allmods.zip/allmods.txt through XMPlay.");
}
// 6) Notificar resultado y liberar memoria
LogMessage(success ? L"Rebuild completed successfully." : L"Rebuild failed.");
PostMessageW(hDlg, WM_DB_REBUILT, success ? TRUE : FALSE, 0);
delete p;
return 0;
}
// ---- Implementación ----
static void WINAPI Plugin_About(HWND parent) {
MessageBoxW(
parent,
L"This plugin does not need to be enabled in the plugins options.\n\n"
L"To use it, assign a shortcut key in XMPlay\n"
L"and use it to open the search dialog.",
L"cmod (modland) - Information",
MB_OK | MB_ICONINFORMATION
);
}
static void *WINAPI Plugin_Init(void) {
return nullptr;
}
static void WINAPI Plugin_Exit(void* inst) {
// Cerrar BD, detener hilos, etc.
if (g_db) {
sqlite3_close(g_db);
g_db = nullptr;
}
}
static const char* WINAPI Plugin_GetDescription(void* inst) {
return "cmod (modland) by herotyc";
}
static void WINAPI MyConfig(void* inst, HWND win) {
/*DialogBoxParam(
(HINSTANCE)g_faceproc(XMPFUNC_WINDOW_FACE),
MAKEINTRESOURCE(IDD_SEARCH),
win,
SearchDlgProc,
0
);*/
}
static DWORD WINAPI Plugin_GetConfig(void* inst, void* config) {
// Tamaño de PluginConfig
// if (config) memcpy(config, &(PluginConfig){}, sizeof(PluginConfig));
return sizeof(PluginConfig);
}
static BOOL WINAPI Plugin_SetConfig(void* inst, void* config, DWORD size) {
// Asignar config si guardas algo
return TRUE;
}
static LRESULT CALLBACK EditSubclassProc(
HWND hWnd,
UINT msg,
WPARAM wParam,
LPARAM lParam,
UINT_PTR uIdSubclass,
DWORD_PTR dwRefData
) {
switch (msg) {
case WM_GETDLGCODE:
// Queremos ENTER, ESC y el resto de teclas de diálogo
return DLGC_WANTALLKEYS;
case WM_KEYDOWN:
if (wParam == VK_RETURN) {
// We use the debounce timer to do the search, but you can do it manually still
DoSearch(GetParent(hWnd));
return 0; // come la tecla y no deje beep
}
if (wParam == VK_ESCAPE) {
// cierra el diálogo con IDCANCEL
EndDialog(GetParent(hWnd), IDCANCEL);
return 0; // come la tecla
}
break;
case WM_CHAR:
if (wParam == '\r' || wParam == '\x1B') {
// come tanto RETURN como ESC para evitar el beep