-
Notifications
You must be signed in to change notification settings - Fork 0
/
SettingsForm.cs
424 lines (374 loc) · 18.5 KB
/
SettingsForm.cs
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
// Glucose Taskbar - Program for glucose monitoring
// Copyright (C) 2024 Rafael Assis
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
using Microsoft.Win32;
using ScottPlot;
using ScottPlot.Plottables;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace GlucoseTaskbar
{
public partial class SettingsForm : Form
{
readonly GlucoseTaskbar glucoseTaskbar;
readonly NightscoutData nightscoutData;
readonly CultureManager cultureManager;
readonly ResourceManager resourceManager;
private bool isFormLoaded = false;
private ScottPlot.Plottables.Scatter MyScatter;
private ScottPlot.Plottables.Crosshair MyCrosshair;
public SettingsForm(GlucoseTaskbar glucoseTaskbar, NightscoutData nightscoutData)
{
this.glucoseTaskbar = glucoseTaskbar;
this.nightscoutData = nightscoutData;
this.cultureManager = new CultureManager(glucoseTaskbar, nightscoutData);
resourceManager = new("GlucoseTaskbar.Resources", typeof(Program).Assembly);
LogManager.LogEvent += LogMessage;
InitializeComponent();
}
private void SettingsForm_Load(object sender, EventArgs e)
{
InitialSetupTexts();
InitialSetupValues();
//FillLastReads();
isFormLoaded = true;
}
private void InitialSetupTexts()
{
SetTextControl(this);
SetTextControl(LanguageLabel);
AdjustPositionLabel(LanguageLabel, LanguageComboBox);
SetTextControl(MainTabPage);
SetTextControl(TechnicalTabPage);
SetTextControl(MainSettingsLabel);
SetTextControl(NightscoutUrlLabel);
AdjustPositionLabel(NightscoutUrlLabel, NightscoutUrlTextBox);
SetTextControl(TokenLabel);
AdjustPositionLabel(TokenLabel, TokenTextBox);
SetTextControl(TargetGlucoseLabel);
AdjustPositionLabel(TargetGlucoseLabel, MinTargetNumericUpDown);
SetTextControl(TechnicalSettingsLabel);
SetTextControl(DataRefreshLabel);
AdjustPositionLabel(DataRefreshLabel, DataRefreshNumericUpDown);
SetTextControl(SecondsLabel);
SetTextControl(ShowBatteryLabel);
AdjustPositionLabel(ShowBatteryLabel, BatteryPanel);
SetTextControl(SensorRadioButton);
SetTextControl(CellPhoneRadioButton);
SetTextControl(BothRadioButton);
SetTextControl(NoneRadioButton);
SetTextControl(OpacityLabel);
AdjustPositionLabel(OpacityLabel, OpacityNumericUpDown);
SetTextControl(ProgramSizeLabel);
AdjustPositionLabel(ProgramSizeLabel, ProgramSizeNumericUpDown);
SetTextControl(ForceAlwaysOnTopCheckBox);
SetTextControl(AccelerateDataFetchCheckBox);
SetTextControl(WindowsStartupCheckBox);
SetTextControl(LatestReadsTabPage);
SetTextControl(LatestReadsLabel);
SetTextControl(ComingSoonLastReadsLabel);
SetTextControl(NotificationsTabPage);
SetTextControl(NotificationsLabel);
SetTextControl(ComingSoonNotificationsLabel);
SetTextControl(SaveLogsButton);
SetTextControl(ClearLogsButton);
SetTextControl(ViewSettingsScreenLabel);
SetTextControl(SaveButton);
SetTextControl(DocumentationLabel);
SetTextControl(DocLinkLabel);
AdjustPositionControl(DocumentationLabel, DocLinkLabel, -4);
}
public void LogMessage(string message)
{
if (LogsRichTextBox.Text.Length != 0) LogsRichTextBox.AppendText("\n\n");
LogsRichTextBox.AppendText(message);
LogsRichTextBox.ScrollToCaret();
}
private void InitialSetupValues()
{
LanguageComboBox.Text = Properties.Settings.Default.Language;
NightscoutUrlTextBox.Text = Properties.Settings.Default.Url;
TokenTextBox.Text = Properties.Settings.Default.Token;
MinTargetNumericUpDown.Value = Properties.Settings.Default.MinTarget;
MaxTargetNumericUpDown.Value = Properties.Settings.Default.MaxTarget;
string radioButtonBatteryName = Properties.Settings.Default.ShowBattery ?? SensorRadioButton.Name;
RadioButton radioButtonBattery = BatteryPanel.Controls.OfType<RadioButton>().FirstOrDefault(rb => rb.Name == radioButtonBatteryName) ?? SensorRadioButton;
radioButtonBattery.Checked = true;
DataRefreshNumericUpDown.Value = Properties.Settings.Default.DataRefreshInterval;
OpacityNumericUpDown.Value = Properties.Settings.Default.Opacity;
ProgramSizeNumericUpDown.Value = Properties.Settings.Default.ProgramSize;
ForceAlwaysOnTopCheckBox.Checked = Properties.Settings.Default.ForceAlwaysInFront;
AccelerateDataFetchCheckBox.Checked = Properties.Settings.Default.SpeedUpDataFetching;
WindowsStartupCheckBox.Checked = IsInStartup();
}
//Coming soon
private void FillLastReads()
{
LastReadsFormsPlot.Reset();
int[] glucoseValues = new int[nightscoutData.NsDataLastReads.Count];
int[] timeDiff = new int[nightscoutData.NsDataLastReads.Count];
for (int i = 0; i < glucoseValues.Length; i++)
{
glucoseValues[i] = int.Parse(nightscoutData.NsDataLastReads[i].Sgv);
timeDiff[i] = (int)((DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - nightscoutData.NsDataLastReads[i].Date) / 1000 / 60);
}
Array.Reverse(timeDiff);
Array.Reverse(glucoseValues);
int[] dataX = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] dataY = { 50, 200 };
int glucoseMaxRange = glucoseValues.Max() + 40 > 200 ? glucoseValues.Max() + 40 : 200;
int timeMinRange = timeDiff.Min() - 2 >= 0 ? timeDiff.Min() - 2 : 0;
MyScatter = LastReadsFormsPlot.Plot.Add.Scatter(timeDiff, glucoseValues);
MyScatter.LineWidth = 2;
MyScatter.Smooth = true;
MyScatter.MarkerSize = 7;
LastReadsFormsPlot.Plot.Axes.Bottom.Label.Text = "Tempo (em minutos)";
LastReadsFormsPlot.Plot.Axes.Left.Label.Text = "Glicemia (em mg/dl)";
LastReadsFormsPlot.Plot.Axes.SetLimitsX(timeDiff.Max() + 2, timeMinRange);
LastReadsFormsPlot.Plot.Axes.SetLimitsY(50, glucoseMaxRange);
var hl1 = LastReadsFormsPlot.Plot.Add.HorizontalLine((int)Properties.Settings.Default.MinTarget);
hl1.LineWidth = 2;
hl1.Color = Colors.Green;
hl1.LinePattern = LinePattern.DenselyDashed;
var hl2 = LastReadsFormsPlot.Plot.Add.HorizontalLine((int)Properties.Settings.Default.MaxTarget);
hl2.LineWidth = 2;
hl2.Color = Colors.Green;
hl2.LinePattern = LinePattern.DenselyDashed;
MyCrosshair = LastReadsFormsPlot.Plot.Add.Crosshair(0, 0);
MyCrosshair.IsVisible = false;
MyCrosshair.MarkerShape = MarkerShape.OpenCircle;
MyCrosshair.MarkerSize = 15;
LastReadsFormsPlot.Refresh();
//LastReadsRichTextBox.Text = "";
//foreach (NightscoutDataLastReads nsDataLastReads in nightscoutData.NsDataLastReads)
//{
// if (int.Parse(nsDataLastReads.Sgv) >= Properties.Settings.Default.MinTarget && int.Parse(nsDataLastReads.Sgv) <= Properties.Settings.Default.MaxTarget)
// {
// LastReadsRichTextBox.SelectionColor = Color.Green;
// }
// else
// {
// LastReadsRichTextBox.SelectionColor = Color.Yellow;
// }
// LastReadsRichTextBox.AppendText($"{nsDataLastReads.Sgv} {nsDataLastReads.Direction}");
// LastReadsRichTextBox.SelectionColor = Color.Red;
// LastReadsRichTextBox.AppendText($" {nsDataLastReads.Delta}");
// LastReadsRichTextBox.SelectionColor = SystemColors.ButtonFace;
// LastReadsRichTextBox.AppendText($" ({nsDataLastReads.TimeDiffLastUpdate})\n");
//}
}
//Sets the label text according to the system language
private void SetTextControl(Control control)
{
control.Text = resourceManager.GetString(control.Name);
}
//Adjusts the label position according to the control position (ex.: Text Box)
private static void AdjustPositionLabel(System.Windows.Forms.Label label, Control control, int offset = 0)
{
int textWidth = TextRenderer.MeasureText(label.Text, label.Font).Width;
label.Left = control.Left - textWidth + offset;
label.Width = textWidth;
}
private static void AdjustPositionControl(Control firstControl, Control secondControl, int offset = 0)
{
secondControl.Left = firstControl.Right + offset;
secondControl.Top = firstControl.Top;
}
private async void SaveButton_Click(object sender, EventArgs e)
{
this.Enabled = false;
Properties.Settings.Default.Language = LanguageComboBox.Text;
Properties.Settings.Default.Url = NightscoutUrlTextBox.Text;
Properties.Settings.Default.Token = TokenTextBox.Text;
Properties.Settings.Default.MinTarget = MinTargetNumericUpDown.Value;
Properties.Settings.Default.MaxTarget = MaxTargetNumericUpDown.Value;
Properties.Settings.Default.ShowBattery = GetRadioButtonBatteryChecked()?.Name;
Properties.Settings.Default.DataRefreshInterval = DataRefreshNumericUpDown.Value;
Properties.Settings.Default.Opacity = OpacityNumericUpDown.Value;
Properties.Settings.Default.ProgramSize = ProgramSizeNumericUpDown.Value;
Properties.Settings.Default.ForceAlwaysInFront = ForceAlwaysOnTopCheckBox.Checked;
Properties.Settings.Default.SpeedUpDataFetching = AccelerateDataFetchCheckBox.Checked;
try
{
MutexManager.Acquire();
Properties.Settings.Default.Save();
}
catch (Exception ex)
{
MessageBox.Show($"{resourceManager.GetString("MessageBoxSaveSettingsErrorMessage")}: {ex.Message}", resourceManager.GetString("MessageBoxTitleError"), MessageBoxButtons.OK, MessageBoxIcon.Error);
LogManager.Log($"Error: {ex.GetType()}: {ex.Message}");
}
finally
{
MutexManager.Release();
}
AddToStartup(WindowsStartupCheckBox.Checked);
glucoseTaskbar.SetOpacity();
glucoseTaskbar.SetProgramSize();
glucoseTaskbar.FixPosition();
glucoseTaskbar.SetForceAlwaysInFrontTimer();
if (await glucoseTaskbar.RefreshGlucoseData(true))
this.Close();
this.Enabled = true;
}
private void LanguageComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
cultureManager.UpdateCulture(LanguageComboBox.Text);
InitialSetupTexts();
//FillLastReads();
}
private void SettingsForm_FormClosed(object sender, FormClosedEventArgs e)
{
cultureManager.UpdateCulture(Properties.Settings.Default.Language); //Returning the culture to the value saved in the config (adjusts the culture if the new one is not saved)
}
private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
{
//Checking if any data has not been saved
if (Properties.Settings.Default.Language != LanguageComboBox.Text ||
Properties.Settings.Default.Url != NightscoutUrlTextBox.Text ||
Properties.Settings.Default.Token != TokenTextBox.Text ||
Properties.Settings.Default.MinTarget != MinTargetNumericUpDown.Value ||
Properties.Settings.Default.MaxTarget != MaxTargetNumericUpDown.Value ||
Properties.Settings.Default.ShowBattery != GetRadioButtonBatteryChecked()?.Name ||
Properties.Settings.Default.DataRefreshInterval != DataRefreshNumericUpDown.Value ||
Properties.Settings.Default.Opacity != OpacityNumericUpDown.Value ||
Properties.Settings.Default.ProgramSize != ProgramSizeNumericUpDown.Value ||
Properties.Settings.Default.ForceAlwaysInFront != ForceAlwaysOnTopCheckBox.Checked ||
Properties.Settings.Default.SpeedUpDataFetching != AccelerateDataFetchCheckBox.Checked ||
WindowsStartupCheckBox.Checked != IsInStartup())
{
DialogResult result = MessageBox.Show(resourceManager.GetString("MessageBoxDiscardMessage"), resourceManager.GetString("MessageBoxTitleWarning"), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
}
private RadioButton? GetRadioButtonBatteryChecked()
{
IEnumerable<RadioButton> radioButtonsBattery = BatteryPanel.Controls.OfType<RadioButton>();
foreach (var radioButton in radioButtonsBattery)
{
if (radioButton.Checked)
{
return radioButton;
}
};
return null;
}
private void ForceAlwaysOnTopCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (isFormLoaded && ForceAlwaysOnTopCheckBox.Checked)
{
DialogResult result = MessageBox.Show(resourceManager.GetString("MessageBoxForceAlwaysInFrontMessage"), resourceManager.GetString("MessageBoxTitleWarning"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
ForceAlwaysOnTopCheckBox.Checked = false;
}
}
}
private void SaveLogsButton_Click(object sender, EventArgs e)
{
using SaveFileDialog saveFileDialog = new SaveFileDialog();
string dateHour = DateTime.Now.ToString("yyyyMMdd_HHmmss");
saveFileDialog.FileName = $"log_{dateHour}.txt";
saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName, LogsRichTextBox.Text);
}
}
private void ClearLogsButton_Click(object sender, EventArgs e)
{
LogsRichTextBox.Clear();
}
public static void AddToStartup(bool enable)
{
string appName = "Glucose Taskbar";
string exePath = Application.ExecutablePath;
string value = $"\"{exePath}\"";
using RegistryKey? rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rk != null)
{
if (enable)
{
rk.SetValue(appName, value);
}
else
{
rk.DeleteValue(appName, false);
}
}
}
public static bool IsInStartup()
{
string appName = "Glucose Taskbar";
string exePath = Application.ExecutablePath;
using RegistryKey? rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rk != null)
{
return rk.GetValue(appName) is string registryValue && registryValue.Equals($"\"{exePath}\"", StringComparison.OrdinalIgnoreCase);
}
return false;
}
private void LastReadsFormsPlot_MouseMove(object sender, MouseEventArgs e)
{
// determine where the mouse is and get the nearest point
Pixel mousePixel = new(e.Location.X, e.Location.Y);
Coordinates mouseLocation = LastReadsFormsPlot.Plot.GetCoordinates(mousePixel);
DataPoint nearest = MyScatter.Data.GetNearest(mouseLocation, LastReadsFormsPlot.Plot.LastRender);
// place the crosshair over the highlighted point
if (nearest.IsReal)
{
MyCrosshair.IsVisible = true;
MyCrosshair.Position = nearest.Coordinates;
LastReadsFormsPlot.Refresh();
Text = $"Selected Index={nearest.Index}, X={nearest.X:0.##}, Y={nearest.Y:0.##}";
}
// hide the crosshair when no point is selected
if (!nearest.IsReal && MyCrosshair.IsVisible)
{
MyCrosshair.IsVisible = false;
LastReadsFormsPlot.Refresh();
Text = $"No point selected";
}
}
private void DocLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string url = "https://github.com/RafaelBomfim128/GlucoseTaskbar";
try
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
catch (Exception ex)
{
MessageBox.Show($"{resourceManager.GetString("OpenLinkDocError")}: {ex.Message}", resourceManager.GetString("MessageBoxTitleError"), MessageBoxButtons.OK, MessageBoxIcon.Error);
LogManager.Log($"Error: {ex.GetType()}: {ex.Message}");
}
}
}
}