-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1337 lines (1335 loc) · 61.5 KB
/
Program.cs
File metadata and controls
1337 lines (1335 loc) · 61.5 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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Windows.Forms;
using OtpNet;
using ZXing;
namespace AuthenticatorTray
{
static class Program
{
// Responsive scaling system - percentage-based instead of pixel-based
private static float _scaleFactor = 1.0f;
private static Graphics? _graphics = null;
private static Font? _baseFont = null;
[STAThread]
static void Main()
{
// Enable DPI awareness for crisp text rendering
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
using (var mutex = new Mutex(true, "AuthenticatorTrayApp", out bool createdNew))
{
if (!createdNew)
{
MessageBox.Show("Authenticator is already running in the system tray.", "Already Running",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Initialize responsive scaling
InitializeScaling();
GC.Collect();
GC.WaitForPendingFinalizers();
Icon appIcon;
try
{
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("AuthenticatorTray.authenticator_icon.ico"))
{
if (stream != null)
{
appIcon = new Icon(stream);
}
else
{
appIcon = SystemIcons.Shield; // Fallback if resource not found
}
}
}
catch
{
appIcon = SystemIcons.Shield; // Fallback on any error
}
NotifyIcon trayIcon = new NotifyIcon
{
Icon = appIcon,
Text = "Eric's super duper secure auth",
Visible = true
};
trayIcon.MouseClick += (s, e) =>
{
if (e.Button == MouseButtons.Left)
{
ShowPopup();
}
else if (e.Button == MouseButtons.Right)
{
trayIcon.Visible = false;
trayIcon.Dispose();
Application.Exit();
}
};
// Cleanup on application exit
Application.ApplicationExit += (s, e) =>
{
trayIcon?.Dispose();
appIcon?.Dispose();
};
Application.Run();
trayIcon.Visible = false;
appIcon?.Dispose();
}
}
static void InitializeScaling()
{
// Initialize graphics context for font measurements
_graphics = Graphics.FromHwnd(IntPtr.Zero);
_baseFont = new Font("Segoe UI", 9, FontStyle.Regular);
// Calculate scale factor purely based on DPI for crisp rendering
float dpiX = _graphics.DpiX;
float dpiY = _graphics.DpiY;
float baseDpi = 96f; // Standard Windows DPI
float dpiScale = Math.Max(dpiX, dpiY) / baseDpi;
// Snap to clean DPI scaling values for sharpness
if (dpiScale >= 2.25f) _scaleFactor = 2.5f; // 250%
else if (dpiScale >= 1.875f) _scaleFactor = 2.0f; // 200%
else if (dpiScale >= 1.375f) _scaleFactor = 1.5f; // 150%
else if (dpiScale >= 1.125f) _scaleFactor = 1.25f; // 125%
else _scaleFactor = 1.0f; // 100%
}
// Helper methods for responsive scaling using relative units
public static int ScaleValue(int value) => (int)(value * _scaleFactor);
public static float ScaleValue(float value) => value * _scaleFactor;
// Font-based measurements (like CSS em units)
public static int Em(float multiplier)
{
if (_graphics == null || _baseFont == null) return (int)(multiplier * 16 * _scaleFactor); // Fallback
var size = _graphics.MeasureString("M", _baseFont);
return (int)(size.Width * multiplier);
}
// Screen percentage-based measurements
public static int ScreenWidth(double percent)
{
var screen = Screen.PrimaryScreen?.Bounds ?? new Rectangle(0, 0, 1920, 1080);
return (int)(screen.Width * (percent / 100.0));
}
public static int ScreenHeight(double percent)
{
var screen = Screen.PrimaryScreen?.Bounds ?? new Rectangle(0, 0, 1920, 1080);
return (int)(screen.Height * (percent / 100.0));
}
public static Font ScaleFont(string fontFamily, float baseSize, FontStyle style = FontStyle.Regular)
{
// Round font sizes to nearest 0.25 for better rendering
float scaledSize = ScaleValue(baseSize);
float roundedSize = Math.Max(6.0f, (float)Math.Round(scaledSize * 4) / 4);
return new Font(fontFamily, roundedSize, style);
}
public static Size ScaleSize(Size size) => new Size(ScaleValue(size.Width), ScaleValue(size.Height));
public static Point ScalePoint(Point point) => new Point(ScaleValue(point.X), ScaleValue(point.Y));
public static Rectangle ScaleRectangle(Rectangle rect) => new Rectangle(ScaleValue(rect.X), ScaleValue(rect.Y), ScaleValue(rect.Width), ScaleValue(rect.Height));
public static Padding ScalePadding(Padding padding) => new Padding(ScaleValue(padding.Left), ScaleValue(padding.Top), ScaleValue(padding.Right), ScaleValue(padding.Bottom));
public static void ShowPopup()
{
var accounts = LoadAccounts();
// Create custom form with relative sizing (no hardcoded pixels!)
ModernPopupForm popup = new ModernPopupForm
{
FormBorderStyle = FormBorderStyle.None,
StartPosition = FormStartPosition.Manual,
BackColor = Color.FromArgb(250, 250, 250), // Very subtle off-white
TopMost = true,
Width = ScreenWidth(22), // 22% of screen width (wider)
Height = Em(3.2f) + (accounts.Count * Em(4.6f)) + Em(1.5f), // Height with card spacing
ShowInTaskbar = false // Prevent taskbar icon
};
// Truly responsive positioning using screen percentages
Rectangle screen = Screen.FromPoint(Cursor.Position).WorkingArea;
// Position popup at bottom-right using screen percentages
int offsetX = screen.Right - ScreenWidth(12) - popup.Width; // 12% from right edge
int finalY = screen.Bottom - ScreenHeight(8) - popup.Height; // 8% from bottom edge
// Ensure popup stays within screen bounds with percentage-based margins
int marginX = ScreenWidth(1); // 1% screen width margin
int marginY = ScreenHeight(1); // 1% screen height margin
offsetX = Math.Max(screen.Left + marginX, Math.Min(offsetX, screen.Right - popup.Width - marginX));
finalY = Math.Max(screen.Top + marginY, Math.Min(finalY, screen.Bottom - popup.Height - marginY));
// Fast smooth slide-up animation
popup.Location = new Point(offsetX, screen.Bottom);
popup.Show();
System.Windows.Forms.Timer slideTimer = new() { Interval = 10 }; // 100fps for smoothness
int startY = screen.Bottom;
int animationDuration = 200; // 200ms total
DateTime startTime = DateTime.Now;
slideTimer.Tick += (s, e) =>
{
double elapsed = (DateTime.Now - startTime).TotalMilliseconds;
double progress = Math.Min(elapsed / animationDuration, 1.0);
// Ease-out animation for smooth deceleration
double easeProgress = 1 - Math.Pow(1 - progress, 3);
int currentY = (int)(startY - (startY - finalY) * easeProgress);
popup.Location = new Point(offsetX, currentY);
if (progress >= 1.0)
{
slideTimer.Stop();
slideTimer.Dispose();
}
};
slideTimer.Start();
// Header with em-based sizing (more compact)
Panel header = new Panel
{
Height = Em(3.2f), // More compact header height
Dock = DockStyle.Top,
BackColor = Color.FromArgb(248, 248, 248) // Light gray
};
// Very subtle bottom border
Panel headerBorder = new Panel
{
Height = 1,
Dock = DockStyle.Bottom,
BackColor = Color.FromArgb(240, 240, 240) // Lighter border
};
header.Controls.Add(headerBorder);
Label titleLabel = new Label
{
Text = "Eric's super duper secure auth",
Font = ScaleFont("Segoe UI", 12, FontStyle.Regular), // Responsive font
ForeColor = Color.FromArgb(28, 28, 30), // Fully opaque macOS primary text
Location = new Point(0, Em(0.8f)), // Will be centered after adding to header
AutoSize = true,
BackColor = Color.Transparent
};
// Calculate initial timer value and color
int totalSeconds = 30;
double elapsed = DateTimeOffset.UtcNow.ToUnixTimeSeconds() % totalSeconds;
int initialRemaining = totalSeconds - (int)elapsed;
Color initialTimerColor = initialRemaining <= 5 ? Color.FromArgb(255, 59, 48) :
initialRemaining <= 10 ? Color.FromArgb(255, 149, 0) :
Color.FromArgb(0, 122, 255);
// Settings icon - positioned on the left
Label settingsIcon = new Label
{
Text = "⚙️",
Font = ScaleFont("Segoe UI Emoji", 12, FontStyle.Regular),
ForeColor = Color.FromArgb(0, 122, 255),
Location = new Point(Em(0.8f), Em(0.8f)), // Left side, keeping vertical position
Size = new Size(Em(2f), Em(2f)), // Keeping size
TextAlign = ContentAlignment.MiddleCenter,
Cursor = Cursors.Hand,
BackColor = Color.Transparent
};
settingsIcon.MouseEnter += (s, e) =>
{
settingsIcon.ForeColor = Color.FromArgb(0, 80, 180);
};
settingsIcon.MouseLeave += (s, e) =>
{
settingsIcon.ForeColor = Color.FromArgb(0, 122, 255);
};
settingsIcon.Click += (s, e) =>
{
using (var settingsForm = new SettingsForm(popup))
{
settingsForm.ShowDialog();
}
};
// Global timer display in header with better positioning
Label globalTimerLabel = new Label
{
Text = $"{initialRemaining}s",
Font = ScaleFont("Segoe UI", 12, FontStyle.Regular),
ForeColor = initialTimerColor,
Location = new Point(popup.Width - Em(3.5f), Em(0.8f)), // Better positioning
Size = new Size(Em(3f), Em(2f)), // Wider to ensure visibility
TextAlign = ContentAlignment.MiddleCenter, // Center the text
BackColor = Color.Transparent
};
header.Controls.Add(settingsIcon);
header.Controls.Add(titleLabel);
header.Controls.Add(globalTimerLabel);
// Center the title text after it's been added (so AutoSize has calculated the width)
titleLabel.Location = new Point((popup.Width - titleLabel.Width) / 2, Em(0.8f));
popup.Controls.Add(header);
// Main content panel with responsive sizing
Panel contentPanel = new Panel
{
Location = new Point(0, Em(3.2f)),
Size = new Size(popup.Width, popup.Height - Em(3.2f)),
BackColor = Color.FromArgb(250, 250, 250) // Very subtle off-white
};
// Inner panel with responsive margins
int panelMargin = Em(0.8f);
Panel scrollPanel = new Panel
{
Location = new Point(panelMargin, Em(0.6f)),
Size = new Size(contentPanel.Width - (panelMargin * 2), contentPanel.Height - Em(1.2f)),
AutoScroll = false, // No scrollbar
BackColor = Color.FromArgb(250, 250, 250) // Very subtle off-white
};
contentPanel.Controls.Add(scrollPanel);
popup.Controls.Add(contentPanel);
// Store references for updates (removed individual time labels and progress bars)
Dictionary<string, Label> controls = new Dictionary<string, Label>();
int yPosition = 0;
foreach (var kvp in accounts)
{
string name = kvp.Key;
Account acc = kvp.Value;
// Create responsive macOS-style card
int cardMargin = Em(0.3f);
Panel accountCard = new MacCard
{
Size = new Size(scrollPanel.Width - Em(0.6f), Em(4.2f)), // More compact card size
Location = new Point(cardMargin, yPosition), // Scaled margin
BackColor = Color.FromArgb(245, 245, 245), // Light gray for cards
Cursor = Cursors.Hand
};
// Account name with better vertical centering
Label nameLabel = new Label
{
Text = GetDisplayName(name),
Font = ScaleFont("Segoe UI", 9, FontStyle.Regular), // Responsive font
ForeColor = Color.FromArgb(60, 60, 67), // Much darker for better visibility
Location = new Point(Em(0.8f), Em(0.5f)), // Higher position
Size = new Size(Em(12f), Em(1.2f)),
TextAlign = ContentAlignment.MiddleLeft,
BackColor = Color.Transparent
};
// Calculate initial TOTP code immediately
var totp = new Totp(Base32Encoding.ToBytes(acc.Secret), step: 30, totpSize: acc.Digits);
string initialCode = totp.ComputeTotp();
string formattedInitialCode = initialCode.Length == 6 ?
$"{initialCode.Substring(0, 3)} {initialCode.Substring(3, 3)}" : initialCode;
// TOTP code with better vertical centering
Label codeLabel = new Label
{
Text = formattedInitialCode, // Show real code immediately
Font = ScaleFont("SF Mono", 16, FontStyle.Regular), // Responsive monospace font
ForeColor = Color.FromArgb(0, 122, 255), // Fully opaque macOS accent blue
Location = new Point(Em(0.8f), Em(2.0f)), // Better centered position
Size = new Size(Em(8f), Em(1.8f)),
TextAlign = ContentAlignment.MiddleLeft,
BackColor = Color.Transparent
};
// Removed individual time label and progress bar - using global timer in header instead
// Copy button with centered positioning
Label copyButton = new Label
{
Text = "📋", // Clipboard icon
Font = ScaleFont("Segoe UI Emoji", 14, FontStyle.Regular),
ForeColor = Color.FromArgb(0, 122, 255), // Fully opaque blue
Location = new Point(accountCard.Width - Em(2.5f), Em(1.4f)), // Vertically centered
Size = new Size(Em(2f), Em(2f)),
TextAlign = ContentAlignment.MiddleCenter,
Cursor = Cursors.Hand,
BackColor = Color.Transparent
};
// Strong hover effects for better visibility
accountCard.MouseEnter += (s, e) =>
{
accountCard.BackColor = Color.FromArgb(230, 235, 240); // Subtle blue-gray highlight
copyButton.ForeColor = Color.FromArgb(0, 80, 180); // Darker blue on hover
codeLabel.ForeColor = Color.FromArgb(0, 100, 200); // Slightly darker blue for code
};
accountCard.MouseLeave += (s, e) =>
{
accountCard.BackColor = Color.FromArgb(245, 245, 245); // Back to light gray
copyButton.ForeColor = Color.FromArgb(0, 122, 255); // Back to original
codeLabel.ForeColor = Color.FromArgb(0, 122, 255); // Back to original
};
string accountName = name; // Capture for closure
// Copy functionality for both card and button
EventHandler copyAction = (sender, args) =>
{
var totp = new Totp(Base32Encoding.ToBytes(acc.Secret), step: 30, totpSize: acc.Digits);
string code = totp.ComputeTotp();
Clipboard.SetText(code);
// Subtle visual feedback with icon
copyButton.Text = "✅"; // Checkmark icon
copyButton.ForeColor = Color.FromArgb(52, 199, 89); // Success green
accountCard.BackColor = Color.FromArgb(240, 248, 242); // Light green tint
System.Windows.Forms.Timer feedbackTimer = new () { Interval = 800 };
feedbackTimer.Tick += (s, e) =>
{
copyButton.Text = "📋"; // Back to clipboard icon
copyButton.ForeColor = Color.FromArgb(0, 122, 255);
accountCard.BackColor = Color.FromArgb(245, 245, 245); // Back to light gray
feedbackTimer.Stop();
feedbackTimer.Dispose();
};
feedbackTimer.Start();
// Show minimal copied tooltip
ShowCopiedTooltip(popup, accountCard);
};
accountCard.Click += copyAction;
copyButton.Click += copyAction;
accountCard.Controls.Add(nameLabel);
accountCard.Controls.Add(codeLabel);
accountCard.Controls.Add(copyButton);
scrollPanel.Controls.Add(accountCard);
controls[name] = codeLabel;
yPosition += Em(4.6f); // Add gap between cards (4.2f card + 0.4f spacing)
}
// Single update timer - reduced frequency for efficiency
var timer = new System.Windows.Forms.Timer { Interval = 500 }; // Update every 500ms instead of 100ms
timer.Tick += (s, e) =>
{
int totalSeconds = 30;
double elapsed = DateTimeOffset.UtcNow.ToUnixTimeSeconds() % totalSeconds;
int remaining = totalSeconds - (int)elapsed;
double progress = (totalSeconds - elapsed) / totalSeconds;
// Update global timer in header
globalTimerLabel.Text = $"{remaining}s";
// Color transitions for global timer
if (remaining <= 5)
{
globalTimerLabel.ForeColor = Color.FromArgb(255, 59, 48);
}
else if (remaining <= 10)
{
globalTimerLabel.ForeColor = Color.FromArgb(255, 149, 0);
}
else
{
globalTimerLabel.ForeColor = Color.FromArgb(0, 122, 255);
}
foreach (var kvp in accounts)
{
string name = kvp.Key;
Account acc = kvp.Value;
var totp = new Totp(Base32Encoding.ToBytes(acc.Secret), step: 30, totpSize: acc.Digits);
string code = totp.ComputeTotp();
string formattedCode = code.Length == 6 ?
$"{code.Substring(0, 3)} {code.Substring(3, 3)}" : code;
if (controls.ContainsKey(name))
{
var codeLabel = controls[name];
if (!codeLabel.Text.Equals(formattedCode))
{
codeLabel.Text = formattedCode;
AnimateLabel(codeLabel);
}
}
}
};
timer.Start();
popup.Deactivate += (s, e) =>
{
timer.Stop();
timer.Dispose();
popup.Close();
// Force garbage collection to free up memory after closing popup
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
};
popup.Activate();
}
static void AnimateLabel(Label label)
{
var originalColor = label.ForeColor;
label.ForeColor = Color.FromArgb(150, originalColor);
System.Windows.Forms.Timer animTimer = new () { Interval = 40 };
int alpha = 150;
animTimer.Tick += (s, e) =>
{
alpha += 25;
if (alpha >= 255)
{
label.ForeColor = originalColor;
animTimer.Stop();
animTimer.Dispose();
}
else
{
label.ForeColor = Color.FromArgb(alpha, originalColor);
}
};
animTimer.Start();
}
static void ShowCopiedTooltip(Form parent, Control nearControl)
{
Label tooltip = new Label
{
Text = "Copied",
Font = ScaleFont("Segoe UI", 8, FontStyle.Regular),
ForeColor = Color.White,
BackColor = Color.FromArgb(80, 80, 80), // Subtle dark tooltip
AutoSize = true,
Padding = new Padding(Em(0.3f), Em(0.15f), Em(0.3f), Em(0.15f)) // Responsive padding in em
};
Point loc = nearControl.PointToScreen(Point.Empty);
loc = parent.PointToClient(loc);
tooltip.Location = new Point(loc.X + nearControl.Width / 2 - Em(1.5f), loc.Y - Em(1.5f));
parent.Controls.Add(tooltip);
tooltip.BringToFront();
System.Windows.Forms.Timer fadeTimer = new () { Interval = 600 };
fadeTimer.Tick += (s, e) =>
{
parent.Controls.Remove(tooltip);
tooltip.Dispose();
fadeTimer.Stop();
fadeTimer.Dispose();
};
fadeTimer.Start();
}
static string GetDisplayName(string fullName)
{
if (fullName.Contains("("))
{
return fullName.Substring(0, fullName.IndexOf("(")).Trim();
}
return fullName.Length > 22 ? fullName.Substring(0, 19) + "..." : fullName;
}
public static string? DecodeQrCodeFromImage(string imagePath)
{
if (!File.Exists(imagePath))
{
throw new FileNotFoundException($"Image file not found: {imagePath}");
}
try
{
// Load the image
using (var originalBitmap = new Bitmap(imagePath))
{
// Ensure we have valid dimensions
if (originalBitmap.Width <= 0 || originalBitmap.Height <= 0)
{
throw new Exception($"Invalid image dimensions: {originalBitmap.Width}x{originalBitmap.Height}");
}
// Try multiple scales if the image is small
List<int> scalesToTry = new List<int>();
if (originalBitmap.Width < 300 || originalBitmap.Height < 300)
{
scalesToTry.AddRange(new[] { 3, 2, 1 }); // Try 3x, 2x, then original
}
else
{
scalesToTry.Add(1); // Just try original size
}
foreach (int scale in scalesToTry)
{
int width = originalBitmap.Width * scale;
int height = originalBitmap.Height * scale;
// Convert to RGB24 format for consistent processing
using (var bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
{
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
graphics.DrawImage(originalBitmap, 0, 0, width, height);
}
var reader = new BarcodeReaderGeneric();
var options = new ZXing.Common.DecodingOptions
{
TryHarder = true,
TryInverted = true,
PossibleFormats = new List<ZXing.BarcodeFormat>
{
ZXing.BarcodeFormat.QR_CODE
}
};
reader.Options = options;
// Method 1: Try with RGB24 format
var bitmapData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
try
{
int stride = Math.Abs(bitmapData.Stride);
int bytes = stride * bitmap.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, rgbValues, 0, bytes);
var luminanceSource = new ZXing.RGBLuminanceSource(
rgbValues,
bitmap.Width,
bitmap.Height,
ZXing.RGBLuminanceSource.BitmapFormat.RGB24);
var result = reader.Decode(luminanceSource);
if (result != null)
{
return result.Text;
}
// Try inverted
var invertedSource = new ZXing.InvertedLuminanceSource(luminanceSource);
result = reader.Decode(invertedSource);
if (result != null)
{
return result.Text;
}
}
finally
{
bitmap.UnlockBits(bitmapData);
}
// Method 2: Try with grayscale conversion
// Re-lock bits to get RGB data for grayscale conversion
var bitmapData2 = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
try
{
int stride2 = Math.Abs(bitmapData2.Stride);
int bytes2 = stride2 * bitmap.Height;
byte[] rgbValues2 = new byte[bytes2];
System.Runtime.InteropServices.Marshal.Copy(bitmapData2.Scan0, rgbValues2, 0, bytes2);
// Convert RGB24 to grayscale manually
int grayWidth = bitmap.Width;
int grayHeight = bitmap.Height;
byte[] grayValues = new byte[grayWidth * grayHeight];
// Convert RGB to grayscale using luminance formula
for (int y = 0; y < grayHeight; y++)
{
for (int x = 0; x < grayWidth; x++)
{
int rgbIndex = (y * stride2) + (x * 3);
if (rgbIndex + 2 < rgbValues2.Length)
{
byte r = rgbValues2[rgbIndex + 2]; // BGR order
byte g = rgbValues2[rgbIndex + 1];
byte b = rgbValues2[rgbIndex];
// Luminance formula: 0.299*R + 0.587*G + 0.114*B
byte gray = (byte)((r * 77 + g * 150 + b * 29) >> 8);
grayValues[y * grayWidth + x] = gray;
}
}
}
var grayLuminanceSource = new ZXing.RGBLuminanceSource(
grayValues,
grayWidth,
grayHeight,
ZXing.RGBLuminanceSource.BitmapFormat.Gray8);
var grayResult = reader.Decode(grayLuminanceSource);
if (grayResult != null)
{
return grayResult.Text;
}
// Try inverted grayscale
var invertedGraySource = new ZXing.InvertedLuminanceSource(grayLuminanceSource);
grayResult = reader.Decode(invertedGraySource);
if (grayResult != null)
{
return grayResult.Text;
}
}
finally
{
bitmap.UnlockBits(bitmapData2);
}
}
} // End of foreach scale
}
}
catch (Exception ex)
{
throw new Exception($"Failed to decode QR code: {ex.Message}", ex);
}
return null;
}
public static AccountJson? ParseOtpAuthUrl(string url)
{
try
{
if (string.IsNullOrEmpty(url))
{
return null;
}
if (!url.StartsWith("otpauth://"))
{
return null;
}
var uri = new Uri(url);
if (uri.Scheme != "otpauth")
{
return null;
}
// Extract label (path without leading /)
string label = Uri.UnescapeDataString(uri.AbsolutePath.TrimStart('/'));
// Parse query parameters
var queryParams = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(uri.Query))
{
var query = uri.Query.TrimStart('?');
foreach (var param in query.Split('&'))
{
var parts = param.Split('=', 2);
if (parts.Length == 2)
{
queryParams[Uri.UnescapeDataString(parts[0])] = Uri.UnescapeDataString(parts[1]);
}
}
}
// Get secret (required)
if (!queryParams.TryGetValue("secret", out string? secret) || string.IsNullOrEmpty(secret))
{
return null;
}
// Get issuer and account name
string? issuer = queryParams.TryGetValue("issuer", out string? issuerValue) ? issuerValue : null;
string accountName = label;
// Parse label format: "Issuer:AccountName" or just "AccountName"
if (label.Contains(":"))
{
var parts = label.Split(new[] { ':' }, 2);
if (parts.Length == 2)
{
if (string.IsNullOrEmpty(issuer))
{
issuer = parts[0];
}
accountName = parts[1];
}
}
string displayName;
if (!string.IsNullOrEmpty(issuer) && !string.IsNullOrEmpty(accountName))
{
displayName = $"{issuer} ({accountName})";
}
else if (!string.IsNullOrEmpty(issuer))
{
displayName = issuer;
}
else if (!string.IsNullOrEmpty(accountName))
{
displayName = accountName;
}
else
{
displayName = "Unknown";
}
string algorithm = queryParams.TryGetValue("algorithm", out string? algValue) ? algValue.ToUpper() : "SHA1";
if (algorithm != "SHA1" && algorithm != "SHA256" && algorithm != "SHA512" && algorithm != "MD5")
{
algorithm = "SHA1";
}
int digits = 6;
if (queryParams.TryGetValue("digits", out string? digitsValue))
{
if (int.TryParse(digitsValue, out int parsedDigits) && (parsedDigits == 6 || parsedDigits == 7 || parsedDigits == 8))
{
digits = parsedDigits;
}
}
return new AccountJson
{
Name = displayName,
Secret = secret,
Digits = digits,
Algorithm = algorithm
};
}
catch (Exception ex)
{
throw new Exception($"Failed to parse otpauth URL: {ex.Message}", ex);
}
}
static string GetAccountsJsonPath()
{
string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
return Path.Combine(appDirectory, "accounts.json");
}
public static Dictionary<string, Account> LoadAccounts()
{
string accountsPath = GetAccountsJsonPath();
if (File.Exists(accountsPath))
{
try
{
var json = File.ReadAllText(accountsPath);
var accountsData = JsonSerializer.Deserialize<AccountsRoot>(json);
var accounts = new Dictionary<string, Account>();
if (accountsData?.Accounts != null)
{
foreach (var accountJson in accountsData.Accounts)
{
accounts[accountJson.Name] = new Account
{
Secret = accountJson.Secret,
Digits = accountJson.Digits,
Algorithm = accountJson.Algorithm
};
}
}
return accounts;
}
catch (Exception ex)
{
MessageBox.Show($"Error loading accounts from file: {ex.Message}\nTrying embedded resource...",
"Loading Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
try
{
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("AuthenticatorTray.accounts.json"))
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var json = reader.ReadToEnd();
var accountsData = JsonSerializer.Deserialize<AccountsRoot>(json);
var accounts = new Dictionary<string, Account>();
if (accountsData?.Accounts != null)
{
foreach (var accountJson in accountsData.Accounts)
{
accounts[accountJson.Name] = new Account
{
Secret = accountJson.Secret,
Digits = accountJson.Digits,
Algorithm = accountJson.Algorithm
};
}
}
return accounts;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error loading accounts: {ex.Message}\nUsing empty accounts.",
"Loading Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
return new Dictionary<string, Account>();
}
public static void SaveAccounts(Dictionary<string, Account> accounts)
{
try
{
string accountsPath = GetAccountsJsonPath();
var accountsList = new List<AccountJson>();
foreach (var kvp in accounts)
{
accountsList.Add(new AccountJson
{
Name = kvp.Key,
Secret = kvp.Value.Secret,
Digits = kvp.Value.Digits,
Algorithm = kvp.Value.Algorithm
});
}
var accountsRoot = new AccountsRoot { Accounts = accountsList };
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(accountsRoot, options);
File.WriteAllText(accountsPath, json);
}
catch (Exception ex)
{
MessageBox.Show($"Error saving accounts: {ex.Message}",
"Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
}
public class Account
{
public string Secret { get; set; } = string.Empty;
public int Digits { get; set; } = 6;
public string Algorithm { get; set; } = "SHA1";
}
public class AccountsRoot
{
[JsonPropertyName("accounts")]
public List<AccountJson> Accounts { get; set; } = new List<AccountJson>();
}
public class AccountJson
{
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("secret")]
public string Secret { get; set; } = string.Empty;
[JsonPropertyName("digits")]
public int Digits { get; set; } = 6;
[JsonPropertyName("algorithm")]
public string Algorithm { get; set; } = "SHA1";
}
public class SettingsForm : Form
{
private TextBox? nameTextBox;
private TextBox? secretTextBox;
private TextBox? digitsTextBox;
private TextBox? algorithmTextBox;
private Button? addButton;
private AccountJson? pendingAccount;
private ModernPopupForm? parentPopup;
public SettingsForm(ModernPopupForm parent)
{
parentPopup = parent;
InitializeComponent();
}
private void InitializeComponent()
{
this.Text = "Add 2FA Account";
this.FormBorderStyle = FormBorderStyle.None;
this.StartPosition = FormStartPosition.CenterParent;
this.BackColor = Color.FromArgb(250, 250, 250);
this.Width = Program.ScreenWidth(25);
this.Height = Program.Em(28f); // Increased for more fields
this.TopMost = true;
this.ShowInTaskbar = false;
Panel header = new Panel
{
Height = Program.Em(3.5f),
Dock = DockStyle.Top,
BackColor = Color.FromArgb(248, 248, 248)
};
Label titleLabel = new Label
{
Text = "Add 2FA Account",
Font = Program.ScaleFont("Segoe UI", 12, FontStyle.Regular),
ForeColor = Color.FromArgb(28, 28, 30),
Location = new Point(Program.Em(1.5f), Program.Em(1.2f)),
AutoSize = true,
BackColor = Color.Transparent
};
header.Controls.Add(titleLabel);
this.Controls.Add(header);
Panel contentPanel = new Panel
{
Location = new Point(0, Program.Em(3.5f)),
Size = new Size(this.Width, this.Height - Program.Em(3.5f)),
BackColor = Color.FromArgb(250, 250, 250)
};
Button scanButton = new Button
{
Text = "📷 Scan QR Code from Image",
Font = Program.ScaleFont("Segoe UI", 10, FontStyle.Regular),
ForeColor = Color.White,
BackColor = Color.FromArgb(0, 122, 255),
FlatStyle = FlatStyle.Flat,
Location = new Point(Program.Em(1.5f), Program.Em(2f)),
Size = new Size(this.Width - Program.Em(3f), Program.Em(2.5f)),
Cursor = Cursors.Hand
};
scanButton.FlatAppearance.BorderSize = 0;
scanButton.Click += ScanButton_Click;
int fieldY = Program.Em(5.5f);
int fieldHeight = Program.Em(2.5f);
int fieldSpacing = Program.Em(2.8f);
int labelWidth = Program.Em(6f);
int fieldWidth = this.Width - Program.Em(3f) - labelWidth - Program.Em(1f);
Label nameLabel = new Label
{
Text = "Name:",
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
ForeColor = Color.FromArgb(60, 60, 67),
Location = new Point(Program.Em(1.5f), fieldY + Program.Em(0.5f)),
Size = new Size(labelWidth, Program.Em(1.5f)),
TextAlign = ContentAlignment.MiddleLeft
};
nameTextBox = new TextBox
{
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
Location = new Point(Program.Em(1.5f) + labelWidth, fieldY),
Size = new Size(fieldWidth, fieldHeight),
PlaceholderText = "Account name",
Enabled = false
};
fieldY += fieldSpacing;
Label secretLabel = new Label
{
Text = "Secret:",
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
ForeColor = Color.FromArgb(60, 60, 67),
Location = new Point(Program.Em(1.5f), fieldY + Program.Em(0.5f)),
Size = new Size(labelWidth, Program.Em(1.5f)),
TextAlign = ContentAlignment.MiddleLeft
};
secretTextBox = new TextBox
{
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
Location = new Point(Program.Em(1.5f) + labelWidth, fieldY),
Size = new Size(fieldWidth, fieldHeight),
PlaceholderText = "Base32 secret key",
Enabled = false
};
fieldY += fieldSpacing;
Label digitsLabel = new Label
{
Text = "Digits:",
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
ForeColor = Color.FromArgb(60, 60, 67),
Location = new Point(Program.Em(1.5f), fieldY + Program.Em(0.5f)),
Size = new Size(labelWidth, Program.Em(1.5f)),
TextAlign = ContentAlignment.MiddleLeft
};
digitsTextBox = new TextBox
{
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
Location = new Point(Program.Em(1.5f) + labelWidth, fieldY),
Size = new Size(fieldWidth, fieldHeight),
PlaceholderText = "6",
Enabled = false
};
fieldY += fieldSpacing;
Label algorithmLabel = new Label
{
Text = "Algorithm:",
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
ForeColor = Color.FromArgb(60, 60, 67),
Location = new Point(Program.Em(1.5f), fieldY + Program.Em(0.5f)),
Size = new Size(labelWidth, Program.Em(1.5f)),
TextAlign = ContentAlignment.MiddleLeft
};
algorithmTextBox = new TextBox
{
Font = Program.ScaleFont("Segoe UI", 9, FontStyle.Regular),
Location = new Point(Program.Em(1.5f) + labelWidth, fieldY),
Size = new Size(fieldWidth, fieldHeight),
PlaceholderText = "SHA1",
Enabled = false
};
fieldY += fieldSpacing + Program.Em(1f);
addButton = new Button
{
Text = "Add Account",