-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1207 lines (1026 loc) · 41.2 KB
/
main.cpp
File metadata and controls
1207 lines (1026 loc) · 41.2 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 <iostream>
#include "i18n.h" // Übersetzungen
#include <chrono>
#include <thread>
#include <string>
#include <iomanip>
#include <ctime>
#include <windows.h>
#include <mmsystem.h>
#include <filesystem>
#include <limits>
#include <cctype>
#include <atomic>
#include "sound_array.h" // Signalton
#include <vector> // Für täglichen Alarm
#include <sstream> // Für --every Parsing/Formatierung
#pragma comment(lib, "winmm.lib")
using namespace std;
namespace fs = std::filesystem;
// Globale Markierung, ob timeBeginPeriod(1) gesetzt wurde (für Ctrl-C Handler)
static atomic<bool> g_timePeriodSet{false};
// Maximale Millisekunden (wir nutzen die maximale long long - etwas konservativ geclamped)
constexpr long long MAX_MS = std::numeric_limits<long long>::max() / 4;
// Ctrl-C / Console Event Handler: versucht, timeEndPeriod zurückzusetzen
BOOL WINAPI ConsoleHandler(DWORD signal) {
if (g_timePeriodSet.load()) {
timeEndPeriod(1);
g_timePeriodSet.store(false);
}
// FALSE zurückgeben, damit der Standard-Handler ebenfalls ausgeführt wird (Programmterminierung)
return FALSE;
}
// RAII-Hilfe: setzt die System-Timerauflösung auf 1 ms und sorgt für sauberes Zurücksetzen beim Verlassen
struct TimePeriodGuard {
TimePeriodGuard() {
MMRESULT res = timeBeginPeriod(1);
g_timePeriodSet.store(true);
(void)res;
}
~TimePeriodGuard() {
if (g_timePeriodSet.load()) {
timeEndPeriod(1);
g_timePeriodSet.store(false);
}
}
};
// Hilfsfunktionen: sichere Konvertierung
int safeStoi(const string& s, int fallback = 0) {
try {
size_t pos = 0;
long v = stol(s, &pos, 10);
if (pos != s.size()) return fallback;
if (v < std::numeric_limits<int>::min()) return std::numeric_limits<int>::min();
if (v > std::numeric_limits<int>::max()) return std::numeric_limits<int>::max();
return static_cast<int>(v);
} catch (...) {
return fallback;
}
}
double safeStod(const string& s, double fallback = 0.0) {
try {
size_t pos = 0;
double v = stod(s, &pos);
if (pos != s.size()) return fallback;
return v;
} catch (...) {
return fallback;
}
}
// Clamp-Funktion für Millisekunden (schützt vor Überlauf)
long long clampMs(long double ms) {
if (ms <= 0.0L) return 0;
if (ms > static_cast<long double>(MAX_MS)) return MAX_MS;
long long res = static_cast<long long>(ms);
if (res < 0) return MAX_MS;
return res;
}
// Umrechnung in Millisekunden (mit Überlaufschutz, möglichst großer Bereich)
// Unterstützte Einheiten: ms, s/sec, m/min, h/hr/hour, d/day, w/wk/week,
// mo/mon/month (30d), y/yr/year (365d). Leere Einheit -> Sekunden.
long long unitToMilliseconds(double value, const string& unitPart) {
string u;
u.reserve(unitPart.size());
for (char c : unitPart)
u += static_cast<char>(tolower(static_cast<unsigned char>(c)));
if (u == "ms") return clampMs(static_cast<long double>(value));
else if (u == "s" || u == "sec" || u.empty()) return clampMs(static_cast<long double>(value) * 1000.0L);
else if (u == "m" || u == "min") return clampMs(static_cast<long double>(value) * 60.0L * 1000.0L);
else if (u == "h" || u == "hr" || u == "hour") return clampMs(static_cast<long double>(value) * 60.0L * 60.0L * 1000.0L);
else if (u == "d" || u == "day") return clampMs(static_cast<long double>(value) * 24.0L * 60.0L * 60.0L * 1000.0L);
else if (u == "w" || u == "wk" || u == "week") return clampMs(static_cast<long double>(value) * 7.0L * 24.0L * 60.0L * 60.0L * 1000.0L);
else if (u == "mo" || u == "mon" || u == "month") return clampMs(static_cast<long double>(value) * 30.0L * 24.0L * 60.0L * 60.0L * 1000.0L);
else if (u == "y" || u == "yr" || u == "year") return clampMs(static_cast<long double>(value) * 365.0L * 24.0L * 60.0L * 60.0L * 1000.0L);
else {
char buf[256];
snprintf(buf, sizeof(buf), t(Str::ERROR_UNKNOWN_UNIT), unitPart.c_str());
cout << buf;
return 0;
}
}
// Mehrteilige Zeitangabe analysieren (ohne regex, effizienter, robust)
// Unterstützt Kombinationen wie "1h20m30s" oder "1.5h" oder "90s"
long long parseTime(const string& arg) {
long long totalMs = 0;
size_t i = 0;
const size_t n = arg.size();
while (i < n) {
while (i < n && isspace(static_cast<unsigned char>(arg[i]))) ++i;
if (i >= n) break;
size_t start = i;
bool dot = false;
while (i < n && (isdigit(static_cast<unsigned char>(arg[i])) || (!dot && arg[i] == '.'))) {
if (arg[i] == '.') dot = true;
++i;
}
if (start == i) break;
string numberStr = arg.substr(start, i - start);
double value = safeStod(numberStr, -1.0);
if (value < 0) return 0;
size_t unitStart = i;
while (i < n && isalpha(static_cast<unsigned char>(arg[i]))) ++i;
string unit = arg.substr(unitStart, i - unitStart);
long long addMs = unitToMilliseconds(value, unit);
if (addMs > 0) {
if (totalMs > MAX_MS - addMs) totalMs = MAX_MS;
else totalMs += addMs;
}
}
return totalMs;
}
// Prüft, ob ein Argument eine bekannte Zeiteinheit ohne vorangestellte Zahl ist
// (Erkennt Tippfehler wie "teefax 5 min" statt "teefax 5min")
bool isStandaloneUnit(const string& arg) {
string u;
u.reserve(arg.size());
for (char c : arg)
u += static_cast<char>(tolower(static_cast<unsigned char>(c)));
static const vector<string> known = {
"ms", "s", "sec", "m", "min", "h", "hr", "hour",
"d", "day", "w", "wk", "week", "mo", "mon", "month",
"y", "yr", "year"
};
for (const auto& k : known)
if (u == k) return true;
return false;
}
// Hilfsfunktion: std::string -> std::wstring (mit Fehlerprüfung), weil Windows wstring für .WAV-Wiedergabe braucht
wstring toWide(const string& str) {
if (str.empty()) return wstring();
int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
if (size_needed == 0) return wstring();
wstring wstr;
wstr.resize(size_needed);
int rc = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &wstr[0], size_needed);
if (rc == 0) return wstring();
if (!wstr.empty() && wstr.back() == L'\0') wstr.pop_back();
return wstr;
}
// Berechnet Millisekunden bis zur nächsten angegebenen Uhrzeit
long long millisecondsUntilTime(int hour, int minute, int second = 0) {
using namespace chrono;
auto now = system_clock::now();
time_t tnow = system_clock::to_time_t(now);
tm local;
if (localtime_s(&local, &tnow) != 0) return 0;
local.tm_hour = hour;
local.tm_min = minute;
local.tm_sec = second;
local.tm_isdst = -1; // Zeitumstellung
time_t target_t = mktime(&local);
if (target_t == -1) return 0;
auto target = system_clock::from_time_t(target_t);
if (target <= now) target += hours(24);
long long diff = duration_cast<milliseconds>(target - now).count();
return clampMs(static_cast<long double>(diff));
}
// Berechnet Millisekunden bis zu einem bestimmten Datum und Uhrzeit
long long millisecondsUntilDateTime(int year, int month, int day,
int hour, int minute, int second)
{
using namespace chrono;
auto now = system_clock::now();
tm target_tm{};
target_tm.tm_year = year - 1900;
target_tm.tm_mon = month - 1;
target_tm.tm_mday = day;
target_tm.tm_hour = hour;
target_tm.tm_min = minute;
target_tm.tm_sec = second;
target_tm.tm_isdst = -1; // Sommerzeit automatisch bestimmen
time_t target_t = mktime(&target_tm);
if (target_t == -1)
return 0;
auto target = system_clock::from_time_t(target_t);
if (target <= now)
return 0; // Zeitpunkt liegt in der Vergangenheit
long long diff =
duration_cast<milliseconds>(target - now).count();
return clampMs(static_cast<long double>(diff));
}
void openFileAfterTimer(const string& filePath) {
bool isUrl = filePath.rfind("http://", 0) == 0 ||
filePath.rfind("https://", 0) == 0;
if (!isUrl) {
try {
if (!fs::exists(fs::path(filePath))) {
cout << t(Str::FILE_NOT_FOUND) << filePath << "\n";
return;
}
} catch (const fs::filesystem_error& e) {
char buf[512];
snprintf(buf, sizeof(buf), t(Str::FILE_SYSTEM_ERROR), e.what());
cout << buf << "\n";
return;
}
}
wstring wfile = toWide(filePath);
if (wfile.empty()) {
cout << t(Str::ERROR_FILE_CONVERSION) << filePath << "\n";
return;
}
HINSTANCE res = ShellExecuteW(NULL, L"open", wfile.c_str(), NULL, NULL, SW_SHOWNORMAL);
if ((INT_PTR)res <= 32) {
char buf[256];
snprintf(buf, sizeof(buf), t(Str::FILE_ERROR), (INT_PTR)res, filePath.c_str());
cout << buf;
} else {
char buf[256];
snprintf(buf, sizeof(buf), t(Str::FILE_OPENED), filePath.c_str());
cout << buf;
}
}
void runConsoleCommand(const string& command) {
if (command.empty()) {
cout << t(Str::NO_COMMAND) << "\n";
return;
}
wstring wcommand = toWide(command);
if (wcommand.empty()) {
char buf[512];
snprintf(buf, sizeof(buf), t(Str::ERROR_CMD_CONVERSION), command.c_str());
cout << buf << "\n";
return;
}
STARTUPINFOW si{};
PROCESS_INFORMATION pi{};
si.cb = sizeof(si);
wstring fullCmd = L"cmd.exe /C " + wcommand;
BOOL success = CreateProcessW(
NULL, &fullCmd[0],
NULL, NULL, TRUE, 0,
NULL, NULL, &si, &pi
);
if (!success) {
DWORD err = GetLastError();
char buf[512];
snprintf(buf, sizeof(buf), t(Str::CMD_ERROR), (int)err, command.c_str());
cout << buf << "\n";
return;
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
char buf[512];
snprintf(buf, sizeof(buf), t(Str::CMD_STARTED), command.c_str());
cout << buf << "\n";
}
// Benachrichtigung / MessageBox
void showNotification(const std::wstring& title, const std::wstring& message)
{
// Attrappenfenster, hehehehe! Um den Fokus zu schnappen.
HWND hwnd = CreateWindowExW(
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
L"STATIC",
L"",
WS_POPUP,
CW_USEDEFAULT, CW_USEDEFAULT, 0, 0,
nullptr, nullptr, GetModuleHandleW(nullptr), nullptr
);
if (hwnd)
{
// Fenster wirklich nach oben bringen
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
// Fokusanforderung
SetForegroundWindow(hwnd);
BringWindowToTop(hwnd);
SetActiveWindow(hwnd);
// MessageBox im Vordergrund anzeigen, mit MB_SETFOREGROUND als Rückversicherung
MessageBoxW(hwnd, message.c_str(), title.c_str(),
MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_SETFOREGROUND);
DestroyWindow(hwnd);
}
else
{
// Rückfall, wenn das Fenster nicht erzeugt wurde
MessageBoxW(nullptr, message.c_str(), title.c_str(),
MB_OK | MB_ICONINFORMATION | MB_TOPMOST | MB_SETFOREGROUND);
}
}
void preventSleep(bool enable)
{
#ifdef _WIN32
if (enable)
SetThreadExecutionState(
ES_CONTINUOUS |
ES_SYSTEM_REQUIRED |
ES_DISPLAY_REQUIRED
);
else
SetThreadExecutionState(ES_CONTINUOUS);
#else
// Platzhalter für Linux/macOS
#endif
}
// Hilfsfunktion: Sekunden in Jahre/Monate/Tage/Stunden/Minuten/Sekunden aufteilen
string formatVerbleibend(long long totalSec) {
constexpr int secPerMin = 60;
constexpr int secPerHour = 60 * secPerMin;
constexpr int secPerDay = 24 * secPerHour;
constexpr int secPerMonth = 30 * secPerDay;
constexpr int secPerYear = 365 * secPerDay;
long long years = totalSec / secPerYear; totalSec %= secPerYear;
long long months = totalSec / secPerMonth; totalSec %= secPerMonth;
long long days = totalSec / secPerDay; totalSec %= secPerDay;
long long hours = totalSec / secPerHour; totalSec %= secPerHour;
long long minutes = totalSec / secPerMin; totalSec %= secPerMin;
long long seconds = totalSec;
struct UnitVal { long long val; const char* unit; };
UnitVal parts[] = {
{years, "y"}, {months, "mo"}, {days, "d"},
{hours, "h"}, {minutes, "m"}, {seconds, "s"}
};
// Letzten Nicht-Null-Wert finden
int last = -1;
for (int i = 5; i >= 0; --i) {
if (parts[i].val > 0) { last = i; break; }
}
if (last == -1) return "0s";
// Ausgabe vom ersten Nicht-Null bis zum letzten Nicht-Null
stringstream ss;
bool found = false;
for (int i = 0; i <= last; ++i) {
if (parts[i].val > 0 || found) {
if (found) ss << " ";
ss << parts[i].val << parts[i].unit;
found = true;
}
}
return ss.str();
}
// Ja, das sagt dir halt, ob die Zielzeit (--at) auf den morgigen Tag fällt.
bool isTargetTomorrow(time_t targetT) {
time_t tnow = time(nullptr);
tm nowTm{};
localtime_s(&nowTm, &tnow);
// heutiger Tag +1
nowTm.tm_mday += 1;
mktime(&nowTm); // normalisiert (Monats-/Jahreswechsel)
tm targetTm{};
localtime_s(&targetTm, &targetT);
return (targetTm.tm_year == nowTm.tm_year &&
targetTm.tm_mon == nowTm.tm_mon &&
targetTm.tm_mday == nowTm.tm_mday);
}
// Zum Messen bis zum nächsten täglichen Alarm
long long millisecondsUntilNextDailyTime(const vector<tuple<int,int,int>>& times) {
using namespace chrono;
auto now = system_clock::now();
time_t tnow = system_clock::to_time_t(now);
tm local{};
localtime_s(&local, &tnow);
long long bestMs = MAX_MS;
for (const auto& t : times) {
int h, m, s;
tie(h, m, s) = t;
tm candidate = local;
candidate.tm_hour = h;
candidate.tm_min = m;
candidate.tm_sec = s;
candidate.tm_isdst = -1; // Zeitumstellung
time_t tt = mktime(&candidate);
if (tt == -1) continue;
auto target = system_clock::from_time_t(tt);
if (target <= now) {
candidate.tm_mday += 1;
candidate.tm_isdst = -1;
time_t tt_next = mktime(&candidate);
if (tt_next == -1) continue;
target = system_clock::from_time_t(tt_next);
}
long long diff = duration_cast<milliseconds>(target - now).count();
if (diff > 0 && diff < bestMs)
bestMs = diff;
}
return bestMs == MAX_MS ? 0 : bestMs;
}
chrono::system_clock::time_point nextDailyTarget(
const vector<tuple<int,int,int>>& times)
{
using namespace chrono;
auto now = system_clock::now();
time_t tnow = system_clock::to_time_t(now);
tm local{};
localtime_s(&local, &tnow);
time_t best = -1;
for (const auto& t : times) {
int h, m, s;
tie(h, m, s) = t;
tm candidate = local;
candidate.tm_hour = h;
candidate.tm_min = m;
candidate.tm_sec = s;
candidate.tm_isdst = -1;
time_t tt = mktime(&candidate);
if (tt == -1) continue;
auto target = system_clock::from_time_t(tt);
// if (target <= now) target += hours(24);
if (target <= now) {
candidate.tm_mday += 1;
candidate.tm_isdst = -1;
time_t tt_next = mktime(&candidate);
if (tt_next == -1) continue;
target = system_clock::from_time_t(tt_next);
}
time_t tt2 = system_clock::to_time_t(target);
if (best == -1 || tt2 < best)
best = tt2;
}
return best != -1
? system_clock::from_time_t(best)
: system_clock::now() + seconds(1);
}
// ── --every: Wochentag- oder Monatstag-Wiederholung ──────────────────
struct EverySpec {
enum class Type { Weekday, MonthDay } type = Type::Weekday;
vector<int> days; // Wochentage: 0=So…6=Sa | Monatstage: 1–31
int hour = 0, minute = 0, second = 0;
};
// Gibt den tm_wday-Wert (0–6) für einen Tagnamen zurück, oder -1
int parseWeekday(const string& s) {
string u;
for (char c : s) u += static_cast<char>(tolower(static_cast<unsigned char>(c)));
if (u == "sun" || u == "sunday") return 0;
if (u == "mon" || u == "monday") return 1;
if (u == "tue" || u == "tuesday") return 2;
if (u == "wed" || u == "wednesday") return 3;
if (u == "thu" || u == "thursday") return 4;
if (u == "fri" || u == "friday") return 5;
if (u == "sat" || u == "saturday") return 6;
return -1;
}
// Kommaseparierte Tag-Liste parsen: "mon,wed,fri" oder "1,15"
EverySpec parseEverySpec(const string& daysStr, int h, int m, int s) {
EverySpec spec;
spec.hour = h; spec.minute = m; spec.second = s;
istringstream ss(daysStr);
string token;
while (getline(ss, token, ',')) {
if (token.empty()) continue;
int wd = parseWeekday(token);
if (wd >= 0) {
spec.type = EverySpec::Type::Weekday;
spec.days.push_back(wd);
} else {
int day = safeStoi(token, -1);
if (day >= 1 && day <= 31) {
spec.type = EverySpec::Type::MonthDay;
spec.days.push_back(day);
}
}
}
return spec;
}
// Tage als lesbaren String ausgeben: "Mon,Wed,Fri" oder "1.,15."
string formatEveryDays(const EverySpec& spec) {
static const char* wdNames[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
ostringstream ss;
for (size_t i = 0; i < spec.days.size(); ++i) {
if (i > 0) ss << ",";
if (spec.type == EverySpec::Type::Weekday)
ss << wdNames[spec.days[i]];
else
ss << spec.days[i] << ".";
}
return ss.str();
}
// Nächsten Zielzeitpunkt für --every berechnen (bis zu 400 Tage voraus)
chrono::system_clock::time_point nextEveryTarget(const EverySpec& spec) {
using namespace chrono;
auto now = system_clock::now();
time_t tnow = system_clock::to_time_t(now);
tm base{};
localtime_s(&base, &tnow);
for (int offset = 0; offset <= 400; ++offset) {
tm candidate = base;
candidate.tm_mday += offset;
candidate.tm_hour = spec.hour;
candidate.tm_min = spec.minute;
candidate.tm_sec = spec.second;
candidate.tm_isdst = -1;
time_t tt = mktime(&candidate);
if (tt == -1) continue;
auto target = system_clock::from_time_t(tt);
if (target <= now) continue; // liegt in der Vergangenheit
bool match = false;
if (spec.type == EverySpec::Type::Weekday) {
for (int d : spec.days)
if (d == candidate.tm_wday) { match = true; break; }
} else {
for (int d : spec.days)
if (d == candidate.tm_mday) { match = true; break; }
}
if (match) return target;
}
return now + hours(24); // Fallback, sollte nie eintreten
}
// Erkennt, ob Teefax aus einer bestehenden Konsole aufgerufen wurde
// oder ob Windows selbst die Konsole erstellt hat (= Doppelklick)
bool launchedFromExistingConsole() {
HWND hwnd = GetConsoleWindow();
if (!hwnd) return false;
DWORD consoleProc = 0;
GetWindowThreadProcessId(hwnd, &consoleProc);
// Wenn die Konsole einem anderen Prozess gehört, wurde sie geerbt
return (consoleProc != GetCurrentProcessId());
}
// Hauptprogramm
int main(int argc, char* argv[])
{
//Konsolenausgaben flüssiger machen
ios::sync_with_stdio(false); // Trennt C++-Streams von C-Streams, beschleunigt cin/cout
cout.tie(nullptr); // Löst Bindung von cout an cin, verhindert automatisches Flush vor Eingabe
//Variablen definieren
string soundFile;
bool mute = false;
bool loop = false;
int maxLoops = -1;
int alarmRepeat = 1;
int alarmInterval = 2;
bool useAtTime = false;
bool useAtDateTime = false; // true wenn --at ein Datum (+ Zeit) enthält
int atYear = 0, atMonth = 0, atDay = 0;
int atHour = 0, atMinute = 0, atSecond = 0;
long long ms = 0;
bool asyncSound = false;
string openFile;
string cmdArg;
bool showMessage = true; // Standard: MessageBox ist aktiv
bool noSleep = false; // Bildschirmschoner & Standby nicht unterdrücken
int preAlarmSeconds = 0; // Sekunden vor Schluss, in denen sekündlich gepiept wird
const int barWidth = 30;
int loopCount = 0;
bool showLiveTime = false; // Für die direkte Zeitanzeige, wie der Name schon sagt.
vector<tuple<int,int,int>> dailyTimes;
bool useDailyTimes = false;
EverySpec everySpec;
bool useEvery = false;
string customMsg; // benutzerdefinierte Notiz in Benachrichtigungsfenster am Schluss
// Audio priorisieren
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
SetConsoleCtrlHandler(ConsoleHandler, TRUE);
TimePeriodGuard timeGuard;
// Sprache vorab setzen, damit currentLang() korrekt initialisiert wird
for (int i = 1; i < argc; ++i) {
string a = argv[i];
if ((a == "--lang" || a == "-la") && i + 1 < argc) {
_putenv_s("TEEFAX_LANG", argv[i + 1]);
break;
}
}
if (argc < 2) {
char buf[256];
snprintf(buf, sizeof(buf), t(Str::STARTED), PRG_VERSION);
cout << buf << ".\n\n";
cout << t(Str::USAGE_HEADER);
if (!launchedFromExistingConsole()) {
cout << "\n";
system("pause"); // oder: cout << "Druecke eine Taste..."; cin.get();
}
return 0;
}
// Argument-Parsen
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
if (arg == "--nosleep" || arg == "-ns") {
noSleep = true;
} else if (arg == "--mute" || arg == "-m") {
mute = true;
} else if (arg == "--loop" || arg == "-l") {
loop = true;
if (i + 1 < argc) {
int possibleCount = safeStoi(argv[i + 1], -1);
if (possibleCount > 0) {
maxLoops = possibleCount;
++i;
}
}
} else if (arg == "--nomsg") {
showMessage = false;
} else if (arg == "--msg" && i + 1 < argc) {
customMsg = argv[++i];
} else if ((arg == "--alarm-repeat" || arg == "-ar") && i + 1 < argc) {
alarmRepeat = safeStoi(argv[++i], 1);
if (alarmRepeat < 1) alarmRepeat = 1;
} else if ((arg == "--alarm-interval" || arg == "-ai") && i + 1 < argc) {
alarmInterval = safeStoi(argv[++i], 2);
if (alarmInterval < 1) alarmInterval = 1;
} else if (arg == "--async" || arg == "-as") {
asyncSound = true;
} else if ((arg == "--at" || arg == "-a" || arg == "--until") && i + 1 < argc) {
string first = argv[++i];
int year, month, day;
int hour = 0, minute = 0, second = 0;
// Fall 1: Datum erkannt
if (sscanf(first.c_str(), "%d-%d-%d", &year, &month, &day) == 3)
{
// Prüfen, ob danach eine Uhrzeit folgt (kein weiterer Parameter oder beginnt mit '-')
if (i + 1 < argc && argv[i + 1][0] != '-')
{
string timeStr = argv[i + 1];
int parsed = sscanf(timeStr.c_str(),
"%d:%d:%d",
&hour, &minute, &second);
if (parsed >= 2)
{
if (parsed == 2) second = 0;
++i;
}
else
{
// Keine gültige Uhrzeit, also Mitternacht verwenden
hour = 0;
minute = 0;
second = 0;
}
}
atYear = year;
atMonth = month;
atDay = day;
atHour = hour;
atMinute = minute;
atSecond = second;
useAtTime = true;
useAtDateTime = true;
ms = millisecondsUntilDateTime(
year, month, day,
hour, minute, second);
if (ms == 0)
{
cout << t(Str::ERROR_PAST_DATETIME) << "\n";
return 1;
}
}
else
{
// Fall 2: Nur Uhrzeit (wie bisher)
int parsed = sscanf(first.c_str(),
"%d:%d:%d",
&atHour, &atMinute, &atSecond);
if (parsed < 2)
{
cout << t(Str::ERROR_INVALID_AT) << "\n";
return 1;
}
if (parsed == 2) atSecond = 0;
useAtTime = true;
ms = millisecondsUntilTime(
atHour, atMinute, atSecond);
if (ms == 0)
{
cout << t(Str::ERROR_NEXT_TIME);
return 1;
}
}
} else if ((arg == "--open" || arg == "-o") && i + 1 < argc) {
openFile = argv[++i];
} else if ((arg == "--cmd" || arg == "-c") && i + 1 < argc) {
cmdArg = argv[++i];
} else if ((arg == "--prealarm" || arg == "-pa") && i + 1 < argc) { // Sekündliches Piepsen vor Schluss
preAlarmSeconds = safeStoi(argv[++i], 0);
if (preAlarmSeconds < 0) preAlarmSeconds = 0;
} else if (arg == "--time" || arg == "-t") {
showLiveTime = true;
} else if (arg == "--daily" || arg == "-d") {
useDailyTimes = true;
while (i + 1 < argc && argv[i + 1][0] != '-') {
string timeStr = argv[i + 1]; // erst schauen, noch nicht erhöhen
int h = 0, m = 0, s = 0;
int parsed = sscanf(timeStr.c_str(), "%d:%d:%d", &h, &m, &s);
if (parsed < 2) {
break; // kein Zeitformat, äußere Schleife übernimmt es (etwa Sounddatei)
}
++i; // jetzt erhöhen
if (parsed == 2) s = 0;
dailyTimes.emplace_back(h, m, s);
}
if (dailyTimes.empty()) {
cout << t(Str::ERROR_NO_DAILY_TIMES) << "\n";
return 1;
}
ms = millisecondsUntilNextDailyTime(dailyTimes);
if (ms <= 0) ms = 1000;
loop = true;
maxLoops = -1; // I seek eternal fire
} else if ((arg == "--every" || arg == "-e") && i + 1 < argc) {
string daysStr = argv[++i];
int h = 0, m = 0, s = 0;
// Optionale Uhrzeit einlesen (sofern kein anderes Argument folgt)
if (i + 1 < argc && argv[i + 1][0] != '-') {
string timeStr = argv[i + 1];
int parsed = sscanf(timeStr.c_str(), "%d:%d:%d", &h, &m, &s);
if (parsed >= 2) {
if (parsed == 2) s = 0;
++i;
}
// Kein gültiges Zeitformat, also nicht konsumieren (evtl. Sounddatei)
}
everySpec = parseEverySpec(daysStr, h, m, s);
if (everySpec.days.empty()) {
char buf[256];
snprintf(buf, sizeof(buf), t(Str::ERROR_INVALID_EVERY), daysStr.c_str());
cout << buf << "\n";
return 1;
}
useEvery = true;
loop = true;
maxLoops = -1;
auto target = nextEveryTarget(everySpec);
ms = chrono::duration_cast<chrono::milliseconds>(
target - chrono::system_clock::now()).count();
if (ms <= 0) ms = 1000;
} else if ((arg == "--lang" || arg == "-la") && i + 1 < argc) {
++i; // bereits im Vor-Durchlauf verarbeitet
} else if (arg == "--version" || arg == "-v") {
cout << PRG_VERSION << "\n";
return 0;
} else if (arg == "--help" || arg == "-h") {
cout << t(Str::USAGE_HEADER);
return 0;
} else if (arg[0] == '-') { // Falls Parameter mit "-" falsch eingegeben wurde. Muss am Ende aller --Parameter stehen.
char buf[256];
snprintf(buf, sizeof(buf), t(Str::ERROR_UNKNOWN_OPTION), arg.c_str());
cout << buf << "\n";
return 1;
} else if (!useAtTime) {
long long possible = parseTime(arg);
if (possible > 0) {
ms = possible;
} else if (isStandaloneUnit(arg)) {
char buf[256];
snprintf(buf, sizeof(buf), t(Str::ERROR_DETACHED_UNIT), arg.c_str());
cout << buf << "\n";
return 1;
} else if (soundFile.empty()) {
soundFile = arg;
}
} else if (soundFile.empty()){
soundFile = arg;
}
}
if (!useAtTime && !useDailyTimes && !useEvery && !showLiveTime && ms <= 0) {
cout << t(Str::ERROR_NO_TIME) << "\n";
return 1;
}
if (ms > MAX_MS) ms = MAX_MS;
// Bildschirrmschoner erlauben bzw. unterdrücken
if (noSleep){
preventSleep(true);
}
if (!showLiveTime){ // Wenn nur die Zeit angezeigt wird, Folgendes weglassen
char buf[256];
snprintf(buf, sizeof(buf), t(Str::STARTED), PRG_VERSION);
cout << buf;
if (useAtTime) {
char buf[256];
if (useAtDateTime) {
snprintf(buf, sizeof(buf), t(Str::TIMER_AT_DATETIME),
atYear, atMonth, atDay, atHour, atMinute, atSecond);
} else {
snprintf(buf, sizeof(buf), t(Str::TIMER_AT_TIME),
atHour, atMinute, atSecond);
}
cout << buf;
// Prüfen ob Ziel morgen liegt (prima bei reiner Uhrzeit oder nahem Datum)
auto atWallTarget = chrono::system_clock::now()
+ chrono::milliseconds(ms);
time_t atTargetT = chrono::system_clock::to_time_t(atWallTarget);
if (isTargetTomorrow(atTargetT))
cout << t(Str::TOMORROW_SUFFIX);
} else {
// hier Umrechnung in passende Einheiten
string timerStr = formatVerbleibend(ms / 1000); // ms -> Sekunden
if (useDailyTimes) {
cout << t(Str::TIMER_DAILY);
} else if (useEvery) {
char buf[256];
string daysStr = formatEveryDays(everySpec);
snprintf(buf, sizeof(buf), t(Str::TIMER_EVERY),
daysStr.c_str(), everySpec.hour, everySpec.minute, everySpec.second);
cout << buf;
} else {
char buf[256];
snprintf(buf, sizeof(buf), t(Str::TIMER_COUNTER), timerStr.c_str());
cout << buf;
// absolute Zielzeit berechnen und anhängen
auto targetWall = chrono::system_clock::now() + chrono::milliseconds(ms);
time_t targetT = chrono::system_clock::to_time_t(targetWall);
tm targetTm{};
localtime_s(&targetTm, &targetT);
char tbuf[64];
snprintf(tbuf, sizeof(tbuf), t(Str::TIMER_TARGET),
targetTm.tm_hour, targetTm.tm_min, targetTm.tm_sec);
cout << tbuf;
}
}
if (asyncSound) {
cout << t(Str::ASYNC_SUFFIX);
}
cout << "\n";
}
// Schleife Direktanzeige von Zeit und Datum
if (showLiveTime) {
system("cls"); // Konsole bereinigen, damit nur die Zeit da steht.
while (true) {
auto now = chrono::system_clock::now();
time_t tnow = chrono::system_clock::to_time_t(now);
tm local{};
localtime_s(&local, &tnow);
cout << "\r" << put_time(&local, "%Y-%m-%d %H:%M:%S") << flush;
// Berechne Millisekunden bis zur nächsten Sekunde
auto next = chrono::time_point_cast<chrono::seconds>(now) + chrono::seconds(1);
this_thread::sleep_until(next);
}
return 0; // Programm wird über Strg+C beendet
}
// Die normale Timer-Schleife
do {
if (loop) ++loopCount;
// Für --daily und --at: absoluten Wanduhr-Zielzeitpunkt frisch bestimmen
chrono::system_clock::time_point wallTarget;
if (useDailyTimes) {
wallTarget = nextDailyTarget(dailyTimes);
} else if (useEvery) {
wallTarget = nextEveryTarget(everySpec);
} else if (useAtTime) {