-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimerForm.cs
More file actions
849 lines (711 loc) · 29.8 KB
/
TimerForm.cs
File metadata and controls
849 lines (711 loc) · 29.8 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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Media;
using System.Text.Json;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace WorkTimer
{
public partial class TimerForm : Form
{
#region Member Variables
private enum TimerState { Stopped, Running, Paused }
private TimerState _currentState = TimerState.Stopped;
// Core Timer state
private TimeSpan _totalTime;
private TimeSpan _remainingTime;
private bool _wasAutoPaused = false;
private string _currentLogFile = string.Empty;
private List<LogEntry> _logEntries = new List<LogEntry>();
// Manual Pause state for auto-unpause logic
private bool _isManuallyPaused = false;
private DateTime _manualPauseTime;
// Settings
private AppSettings _appSettings = new AppSettings();
// Charting & Absences
private Dictionary<DateTime, int> _activityData = new Dictionary<DateTime, int>();
private List<AbsencePeriod> _absences = new List<AbsencePeriod>();
private System.Windows.Forms.Timer? _chartUpdateTimer;
// Real-time Activity Meter
private GlobalActivityHook _activityHook;
private System.Windows.Forms.Timer _activityDecayTimer;
private double _activityScore = 0;
private const double MOUSE_WEIGHT = 0.5;
private const double KEYBOARD_WEIGHT = 5.0;
private const double ACTIVITY_DECAY_RATE = 0.90;
// Alarm
private System.Windows.Forms.Timer? _alarmSequenceTimer;
private int _alarmCount = 0;
#endregion
public TimerForm()
{
InitializeComponent();
_activityDecayTimer = new System.Windows.Forms.Timer();
_activityHook = new GlobalActivityHook();
_activityHook.OnActivity += _activityHook_OnActivity;
LoadSettings();
InitializeCustomComponents();
RestoreSession();
}
private void InitializeCustomComponents()
{
this.Text = "Work Timer";
SetupActivityChart();
numHours.Value = _appSettings.LastHours;
numMinutes.Value = _appSettings.LastMinutes;
numSeconds.Value = _appSettings.LastSeconds;
ResetTimerToInput();
_chartUpdateTimer = new System.Windows.Forms.Timer();
_chartUpdateTimer.Interval = 5000;
_chartUpdateTimer.Tick += ChartUpdateTimer_Tick;
_activityDecayTimer.Interval = 100;
_activityDecayTimer.Tick += ActivityDecayTimer_Tick;
_activityDecayTimer.Start();
_alarmSequenceTimer = new System.Windows.Forms.Timer();
_alarmSequenceTimer.Interval = 1000;
_alarmSequenceTimer.Tick += AlarmSequenceTimer_Tick;
}
#region Session and Settings Persistence
private string GetAppDataPath()
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WorkTimer");
Directory.CreateDirectory(path);
return path;
}
private void LoadSettings()
{
string settingsPath = Path.Combine(GetAppDataPath(), "settings.json");
try
{
if (File.Exists(settingsPath))
{
string json = File.ReadAllText(settingsPath);
_appSettings = JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
}
}
catch
{
_appSettings = new AppSettings();
}
this.TopMost = _appSettings.AlwaysOnTop;
this.Opacity = Math.Max(0.2, _appSettings.Opacity);
}
private void SaveSettings()
{
// Always save the values in the H/M/S boxes when closing.
// Since they are disabled during a run, they will reflect the session's initial time.
_appSettings.LastHours = (int)numHours.Value;
_appSettings.LastMinutes = (int)numMinutes.Value;
_appSettings.LastSeconds = (int)numSeconds.Value;
string settingsPath = Path.Combine(GetAppDataPath(), "settings.json");
try
{
string json = JsonSerializer.Serialize(_appSettings, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(settingsPath, json);
}
catch { /* Silently fail */ }
}
private void RestoreSession()
{
string sessionPath = Path.Combine(GetAppDataPath(), "session.json");
if (File.Exists(sessionPath))
{
try
{
string json = File.ReadAllText(sessionPath);
var state = JsonSerializer.Deserialize<SessionState>(json);
if (state != null)
{
_remainingTime = state.RemainingTime;
_totalTime = state.TotalTime;
txtTaskName.Text = state.TaskName;
_activityData = state.ActivityData;
_absences = state.Absences;
_logEntries = state.LogEntries;
_currentLogFile = state.LogFile;
numHours.Value = state.TotalTime.Hours;
numMinutes.Value = state.TotalTime.Minutes;
numSeconds.Value = state.TotalTime.Seconds;
var downtime = DateTime.Now - state.ExitTime;
// Subtract the downtime from the remaining timer
if (downtime.TotalSeconds > 0)
{
if (downtime > _remainingTime)
{
_remainingTime = TimeSpan.Zero;
}
else
{
_remainingTime = _remainingTime.Subtract(downtime);
}
}
// Log an absence if the downtime exceeds the idle threshold
if (downtime.TotalSeconds > _appSettings.IdleSecondsForPause)
{
_absences.Add(new AbsencePeriod { Start = state.ExitTime, End = DateTime.Now });
AddLogEntry(LogEventType.Note, $"Application was closed for {downtime:hh\\:mm\\:ss}.");
}
ResumeTimer(autoResumed: false, isNewSession: false);
ChartUpdateTimer_Tick(null, EventArgs.Empty);
File.Delete(sessionPath);
return;
}
}
catch
{
File.Delete(sessionPath);
}
}
ResetTimerToInput();
}
private void SaveSession()
{
if (_currentState == TimerState.Stopped) return;
var state = new SessionState
{
RemainingTime = _remainingTime,
TotalTime = _totalTime,
TaskName = txtTaskName.Text,
ActivityData = _activityData,
Absences = _absences,
LogEntries = _logEntries,
LogFile = _currentLogFile,
ExitTime = DateTime.Now
};
string sessionPath = Path.Combine(GetAppDataPath(), "session.json");
try
{
string json = JsonSerializer.Serialize(state, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(sessionPath, json);
}
catch { /* Silently fail */ }
}
#endregion
#region Timer Logic
private void mainTimer_Tick(object sender, EventArgs e)
{
if (_currentState == TimerState.Running)
{
_remainingTime = _remainingTime.Subtract(TimeSpan.FromSeconds(1));
progressRingPanel.Invalidate();
if (_remainingTime <= TimeSpan.Zero)
{
StopTimer(isFinished: true);
}
}
}
private void activityMonitorTimer_Tick(object sender, EventArgs e)
{
TimeSpan idleTime = UserActivityMonitor.GetIdleTime();
bool isActive = idleTime < TimeSpan.FromSeconds(1);
if (_currentState == TimerState.Running)
{
UpdateActivityData(isActive);
}
if (_currentState == TimerState.Running && !_isManuallyPaused && idleTime > TimeSpan.FromSeconds(_appSettings.IdleSecondsForPause))
{
PauseTimer(autoPaused: true);
}
if (isActive)
{
if (_wasAutoPaused)
{
ResumeTimer(autoResumed: true);
}
else if (_isManuallyPaused && (DateTime.Now - _manualPauseTime) > TimeSpan.FromSeconds(_appSettings.ManualPauseSecondsForAutoResume))
{
ResumeTimer(autoResumed: false);
}
}
}
private void StartNewSession()
{
StopAlarm();
ResetTimerToInput();
if (_remainingTime <= TimeSpan.Zero) return;
_activityData.Clear();
_absences.Clear();
_logEntries.Clear();
activityChart.Series["Activity"].Points.Clear();
_currentLogFile = string.Empty;
var chartArea = activityChart.ChartAreas[0];
chartArea.AxisX.Minimum = DateTime.Now.ToOADate();
chartArea.AxisX.Maximum = DateTime.Now.AddMinutes(10).ToOADate();
AddLogEntry(LogEventType.Start, $"Timer started for task: {txtTaskName.Text}");
ResumeTimer(autoResumed: false, isNewSession: true);
}
private void ResumeTimer(bool autoResumed, bool isNewSession = false)
{
StopAlarm();
if (!isNewSession)
{
string reason = autoResumed ? "auto-resumed due to activity" : "resumed by user";
AddLogEntry(LogEventType.Resume, $"Timer {reason}");
if (_absences.Any())
{
var lastAbsence = _absences.Last();
if (lastAbsence.End == DateTime.MaxValue)
{
_absences[^1] = new AbsencePeriod { Start = lastAbsence.Start, End = DateTime.Now };
}
}
}
_currentState = TimerState.Running;
_wasAutoPaused = false;
_isManuallyPaused = false;
btnStartPauseResume.Text = "Pause";
lblStatus.Text = "Running...";
mainTimer.Start();
activityMonitorTimer.Start();
_chartUpdateTimer?.Start();
SetTimeControlsEnabled(false);
txtTaskName.Enabled = false;
}
private void PauseTimer(bool autoPaused = false)
{
_currentState = TimerState.Paused;
btnStartPauseResume.Text = "Resume";
if (autoPaused)
{
_wasAutoPaused = true;
lblStatus.Text = "Auto-Paused (Idle)";
_remainingTime = _remainingTime.Add(TimeSpan.FromSeconds(_appSettings.IdleSecondsForPause));
var absenceStart = DateTime.Now.Subtract(TimeSpan.FromSeconds(_appSettings.IdleSecondsForPause));
_absences.Add(new AbsencePeriod { Start = absenceStart, End = DateTime.MaxValue });
AddLogEntry(LogEventType.Inactive, $"Auto-paused after {_appSettings.IdleSecondsForPause}s of inactivity.");
}
else
{
_isManuallyPaused = true;
_manualPauseTime = DateTime.Now;
lblStatus.Text = "Paused";
_absences.Add(new AbsencePeriod { Start = DateTime.Now, End = DateTime.MaxValue });
AddLogEntry(LogEventType.Pause, "Timer paused by user.");
}
}
private void StopTimer(bool isFinished)
{
mainTimer.Stop();
activityMonitorTimer.Stop();
_chartUpdateTimer?.Stop();
_currentState = TimerState.Stopped;
_wasAutoPaused = false;
_isManuallyPaused = false;
btnStartPauseResume.Text = "Start";
SetTimeControlsEnabled(true);
txtTaskName.Enabled = true;
if (isFinished)
{
_remainingTime = TimeSpan.Zero;
progressRingPanel.Invalidate();
lblStatus.Text = "Time's up! Click Reset to stop alarm.";
AddLogEntry(LogEventType.Finish, "Timer finished.");
_alarmCount = 0;
_alarmSequenceTimer?.Start();
}
else
{
lblStatus.Text = "Stopped. Click Start to begin.";
AddLogEntry(LogEventType.Stop, "Timer stopped by user.");
}
SaveLogFile();
string sessionPath = Path.Combine(GetAppDataPath(), "session.json");
if (File.Exists(sessionPath)) File.Delete(sessionPath);
}
#endregion
#region Activity and Alarm Methods
private void _activityHook_OnActivity(object? sender, GlobalActivityHook.ActivityEventArgs e)
{
if (e == null) return;
_activityScore += e.IsKeyboard ? KEYBOARD_WEIGHT : MOUSE_WEIGHT;
}
private void ActivityDecayTimer_Tick(object? sender, EventArgs e)
{
_activityScore *= ACTIVITY_DECAY_RATE;
if (_activityScore < 0.1) _activityScore = 0;
activityMeterPanel.Invalidate();
}
private void AlarmSequenceTimer_Tick(object? sender, EventArgs e)
{
SystemSounds.Exclamation.Play();
_alarmCount++;
if (_alarmCount >= 10)
{
StopAlarm();
}
}
private void StopAlarm()
{
_alarmSequenceTimer?.Stop();
_alarmCount = 0;
if (lblStatus.Text.StartsWith("Time's up!"))
{
lblStatus.Text = "Finished";
}
}
#endregion
#region UI Handlers & Methods
private void btnStartPauseResume_Click(object sender, EventArgs e)
{
switch (_currentState)
{
case TimerState.Stopped:
StartNewSession();
break;
case TimerState.Running:
PauseTimer(autoPaused: false);
break;
case TimerState.Paused:
ResumeTimer(autoResumed: false);
break;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (_currentState != TimerState.Stopped)
{
StopTimer(isFinished: false);
}
}
private void btnReset_Click(object sender, EventArgs e)
{
StopAlarm();
if (_currentState != TimerState.Stopped)
{
StopTimer(isFinished: false);
}
ResetTimerToInput();
_activityData.Clear();
_absences.Clear();
activityChart.Series["Activity"].Points.Clear();
var chartArea = activityChart.ChartAreas[0];
chartArea.AxisX.Minimum = DateTime.Now.ToOADate();
chartArea.AxisX.Maximum = DateTime.Now.AddHours(1).ToOADate();
activityChart.Invalidate();
}
private void btnSettings_Click(object sender, EventArgs e)
{
this.TopMost = false;
using (var settingsForm = new SettingsForm(_appSettings))
{
if (settingsForm.ShowDialog() == DialogResult.OK)
{
_appSettings = settingsForm.Settings;
this.TopMost = _appSettings.AlwaysOnTop;
this.Opacity = _appSettings.Opacity;
SaveSettings();
}
}
this.TopMost = _appSettings.AlwaysOnTop;
}
private void btnAddNote_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtNote.Text))
{
AddLogEntry(LogEventType.Note, txtNote.Text);
txtNote.Clear();
}
}
private void btnViewLogs_Click(object sender, EventArgs e)
{
this.TopMost = false;
List<LogEntry>? currentLog = null;
string? currentTask = null;
if (_currentState != TimerState.Stopped && _logEntries.Any())
{
currentLog = _logEntries;
currentTask = txtTaskName.Text;
}
using (var logBrowser = new LogBrowserForm(currentLog, currentTask))
{
logBrowser.ShowDialog();
}
this.TopMost = _appSettings.AlwaysOnTop;
}
private void btnManageAbsences_Click(object sender, EventArgs e)
{
this.TopMost = false;
var completedAbsences = _absences.Where(a => a.End != DateTime.MaxValue).ToList();
using (var absenceManager = new AbsenceManagerForm(completedAbsences))
{
if (absenceManager.ShowDialog() == DialogResult.OK)
{
var absencesToRemove = absenceManager.AbsencesToRemove;
if (absencesToRemove.Any())
{
foreach (var absenceToRemove in absencesToRemove)
{
var originalAbsence = _absences.FirstOrDefault(a => a.Start == absenceToRemove.Start && a.End == absenceToRemove.End);
if (originalAbsence.Start != default)
{
_absences.Remove(originalAbsence);
var duration = originalAbsence.End - originalAbsence.Start;
_remainingTime = _remainingTime.Subtract(duration);
AddLogEntry(LogEventType.Note, $"Absence from {originalAbsence.Start:HH:mm:ss} to {originalAbsence.End:HH:mm:ss} removed. Time subtracted from countdown.");
}
}
ChartUpdateTimer_Tick(null, EventArgs.Empty);
}
}
}
this.TopMost = _appSettings.AlwaysOnTop;
}
private void ResetTimerToInput()
{
_remainingTime = new TimeSpan((int)numHours.Value, (int)numMinutes.Value, (int)numSeconds.Value);
_totalTime = _remainingTime;
lblStatus.Text = "Ready to start";
progressRingPanel.Invalidate();
}
private void SetTimeControlsEnabled(bool isEnabled)
{
numHours.Enabled = isEnabled;
numMinutes.Enabled = isEnabled;
numSeconds.Enabled = isEnabled;
}
#endregion
#region Charting Methods
private void SetupActivityChart()
{
activityChart.Series.Clear();
var series = new Series("Activity")
{
ChartType = SeriesChartType.Line,
Color = Color.DodgerBlue,
BorderWidth = 2,
XValueType = ChartValueType.DateTime
};
activityChart.Series.Add(series);
var chartArea = activityChart.ChartAreas[0];
chartArea.BackColor = Color.FromArgb(245, 245, 245);
chartArea.AxisX.LabelStyle.Format = "HH:mm";
chartArea.AxisX.IntervalType = DateTimeIntervalType.Minutes;
chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
chartArea.AxisX.Title = "Time";
chartArea.AxisX.IsMarginVisible = false;
chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
chartArea.AxisY.Title = "Active Seconds";
chartArea.AxisY.Maximum = 60;
chartArea.AxisY.Interval = 10;
chartArea.AxisY.IsMarginVisible = false;
activityChart.Legends[0].Enabled = false;
activityChart.PostPaint += ActivityChart_PostPaint;
}
private void UpdateActivityData(bool isActive)
{
if (!isActive) return;
var now = DateTime.Now;
var intervalStart = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
if (!_activityData.ContainsKey(intervalStart))
{
_activityData[intervalStart] = 0;
}
_activityData[intervalStart]++;
}
private void ChartUpdateTimer_Tick(object? sender, EventArgs e)
{
var series = activityChart.Series["Activity"];
series.Points.Clear();
if (!_activityData.Any()) return;
var chartArea = activityChart.ChartAreas[0];
var orderedData = _activityData.OrderBy(kvp => kvp.Key).ToList();
foreach (var record in orderedData)
{
series.Points.AddXY(record.Key, record.Value);
}
chartArea.AxisX.Minimum = orderedData.First().Key.ToOADate();
chartArea.AxisX.Maximum = DateTime.Now.AddMinutes(1).ToOADate();
activityChart.Invalidate();
}
private void ActivityChart_PostPaint(object? sender, ChartPaintEventArgs e)
{
if (e.ChartElement is ChartArea chartArea)
{
var xAxis = chartArea.AxisX;
var yAxis = chartArea.AxisY;
RectangleF plotArea = chartArea.Position.ToRectangleF();
float plotX = plotArea.X * e.Chart.Width / 100f;
float plotY = plotArea.Y * e.Chart.Height / 100f;
float plotWidth = plotArea.Width * e.Chart.Width / 100f;
float plotHeight = plotArea.Height * e.Chart.Height / 100f;
using (var brush = new SolidBrush(Color.FromArgb(50, Color.Gray)))
{
foreach (var absence in _absences)
{
DateTime endTime = (absence.End == DateTime.MaxValue) ? DateTime.Now : absence.End;
double x1 = xAxis.ValueToPixelPosition(absence.Start.ToOADate());
double x2 = xAxis.ValueToPixelPosition(endTime.ToOADate());
double y1 = yAxis.ValueToPixelPosition(yAxis.Maximum);
double y2 = yAxis.ValueToPixelPosition(yAxis.Minimum);
x1 = Math.Max(x1, plotX);
x2 = Math.Min(x2, plotX + plotWidth);
if (x1 < x2)
{
e.ChartGraphics.Graphics.FillRectangle(brush, (float)x1, (float)y1, (float)(x2 - x1), (float)(y2 - y1));
}
}
}
}
}
#endregion
#region Painting Methods
private void progressRingPanel_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = progressRingPanel.ClientRectangle;
int diameter = Math.Min(rect.Width, rect.Height) - 20;
int x = (rect.Width - diameter) / 2;
int y = (rect.Height - diameter) / 2;
Rectangle drawRect = new Rectangle(x, y, diameter, diameter);
using (var backgroundPen = new Pen(Color.FromArgb(220, 220, 220), 15))
{
g.DrawEllipse(backgroundPen, drawRect);
}
if (_totalTime.TotalSeconds > 0 && _remainingTime.TotalSeconds > 0)
{
using (var progressPen = new Pen(Color.DodgerBlue, 15))
{
progressPen.StartCap = LineCap.Round;
progressPen.EndCap = LineCap.Round;
float percentage = (float)(_remainingTime.TotalSeconds / _totalTime.TotalSeconds);
float sweepAngle = 360 * percentage;
g.DrawArc(progressPen, drawRect, -90, sweepAngle);
}
}
string timeText = $"{_remainingTime:hh\\:mm\\:ss}";
using (var font = new Font("Segoe UI Semibold", Math.Max(8, diameter / 9f), FontStyle.Bold))
{
TextRenderer.DrawText(g, timeText, font, progressRingPanel.ClientRectangle, Color.FromArgb(64, 64, 64), TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}
}
private void activityMeterPanel_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(this.BackColor);
int ledCount = 12;
int ledGap = 4;
int barWidth = activityMeterPanel.ClientSize.Width - 10;
int barX = 5;
int totalLedHeight = activityMeterPanel.ClientSize.Height - ((ledCount - 1) * ledGap);
int ledHeight = Math.Max(1, totalLedHeight / ledCount);
double maxScorePerTick = (_appSettings.WpmForFullMeter * 5.0 / 60.0 * KEYBOARD_WEIGHT) / 10.0;
double maxReasonableScore = maxScorePerTick / (1 - ACTIVITY_DECAY_RATE);
double percentage = Math.Min(1.0, _activityScore / maxReasonableScore);
int ledsToLight = (int)(percentage * ledCount);
for (int i = 0; i < ledCount; i++)
{
int ledY = activityMeterPanel.ClientSize.Height - ((i + 1) * ledHeight) - (i * ledGap);
Rectangle ledRect = new Rectangle(barX, ledY, barWidth, ledHeight);
Color ledColor;
if (i < ledsToLight)
{
if (i < ledCount * 0.5)
ledColor = Color.LimeGreen;
else if (i < ledCount * 0.8)
ledColor = Color.Gold;
else
ledColor = Color.Crimson;
}
else
{
ledColor = Color.Gainsboro;
}
using (var brush = new SolidBrush(ledColor))
{
g.FillRectangle(brush, ledRect);
}
}
}
#endregion
#region Logging
private void AddLogEntry(LogEventType type, string message)
{
_logEntries.Add(new LogEntry(type, message));
}
private void SaveLogFile()
{
if (!_logEntries.Any()) return;
string logDir = Path.Combine(GetAppDataPath(), "WorkTimerLogs");
Directory.CreateDirectory(logDir);
if (string.IsNullOrEmpty(_currentLogFile))
{
string taskName = string.IsNullOrWhiteSpace(txtTaskName.Text) ? "Untitled" : txtTaskName.Text;
string safeTaskName = string.Join("_", taskName.Split(Path.GetInvalidFileNameChars()));
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
_currentLogFile = Path.Combine(logDir, $"{safeTaskName}_{timestamp}.log");
}
try
{
string json = JsonSerializer.Serialize(_logEntries, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_currentLogFile, json);
}
catch (Exception ex)
{
MessageBox.Show($"Failed to save log file: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
protected override void OnFormClosing(FormClosingEventArgs e)
{
SaveSettings();
SaveSession();
_activityHook?.Dispose();
base.OnFormClosing(e);
}
}
#region Data Structures
public class LogEntry
{
public DateTime Timestamp { get; set; }
public LogEventType EventType { get; set; }
public string Message { get; set; }
public LogEntry(LogEventType eventType, string message)
{
Timestamp = DateTime.Now;
EventType = eventType;
Message = message;
}
public LogEntry()
{
Message = string.Empty;
}
}
public enum LogEventType
{
Start, Stop, Pause, Resume, Inactive, Note, Finish
}
public struct AbsencePeriod
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
public class AppSettings
{
public int LastHours { get; set; } = 0;
public int LastMinutes { get; set; } = 25;
public int LastSeconds { get; set; } = 0;
public bool AlwaysOnTop { get; set; } = true;
public double Opacity { get; set; } = 1.0;
public int IdleSecondsForPause { get; set; } = 300;
public int ManualPauseSecondsForAutoResume { get; set; } = 60;
public int WpmForFullMeter { get; set; } = 60;
}
public class SessionState
{
public TimeSpan RemainingTime { get; set; }
public TimeSpan TotalTime { get; set; }
public string TaskName { get; set; } = string.Empty;
public Dictionary<DateTime, int> ActivityData { get; set; } = new Dictionary<DateTime, int>();
public List<AbsencePeriod> Absences { get; set; } = new List<AbsencePeriod>();
public List<LogEntry> LogEntries { get; set; } = new List<LogEntry>();
public string LogFile { get; set; } = string.Empty;
public DateTime ExitTime { get; set; }
}
#endregion
}