-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathMainForm.cs
More file actions
executable file
·10508 lines (9050 loc) · 426 KB
/
MainForm.cs
File metadata and controls
executable file
·10508 lines (9050 loc) · 426 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 AndroidSideloader.Models;
using AndroidSideloader.Utilities;
using JR.Utils.GUI.Forms;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using SergeUtils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AndroidSideloader
{
public partial class MainForm : Form
{
public static string repo = "nerdunit/androidsideloader"; // GitHub repo
public static string repo_branch = "master"; // GitHub branch
#if DEBUG
public static bool debugMode = true;
public bool DeviceConnected;
public bool keyheld;
public bool keyheld2;
public static string CurrAPK;
public static string CurrPCKG;
List<UploadGame> gamesToUpload = new List<UploadGame>();
public static string currremotesimple = String.Empty;
#else
public bool keyheld;
public static string CurrAPK;
public static string CurrPCKG;
private readonly List<UploadGame> gamesToUpload = new List<UploadGame>();
public static bool debugMode = false;
public bool DeviceConnected = false;
public static string currremotesimple = "";
#endif
private readonly ListViewColumnSorter lvwColumnSorter;
private static readonly SettingsManager settings = SettingsManager.Instance;
private double _totalQueueSizeMB = 0;
private double _effectiveQueueSizeMB = 0;
private Dictionary<string, double> _queueEffectiveSizes = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase);
private long _deviceFreeSpaceMB = 0;
// Shared sort state between Gallery and List views
private SortField _sharedSortField = SortField.Name;
private SortDirection _sharedSortDirection = SortDirection.Ascending;
private const int BottomMargin = 8;
private const int RightMargin = 12;
private const int PanelSpacing = 10;
private const int BottomPanelHeight = 217;
private const int ChildTopMargin = 10;
private const int ChildHorizontalPadding = 12; // default left/right
private const int NotesLeftMargin = 6; // special left margin for notes
private const int ChildRightMargin = 12;
private const int LabelHeight = 20;
private const int LabelBottomOffset = 4; // space from label bottom to panel bottom
private const int ReservedLabelHeight = 25;
private Task _adbInitTask;
public static readonly Color ColorInstalled = ColorTranslator.FromHtml("#3c91e6");
public static readonly Color ColorUpdateAvailable = ColorTranslator.FromHtml("#4daa57");
public static readonly Color ColorDonateGame = ColorTranslator.FromHtml("#cb9cf2");
private static readonly Color ColorError = ColorTranslator.FromHtml("#f52f57");
public static readonly Color ColorDownloaded = ColorTranslator.FromHtml("#67c7b1");
public static HashSet<string> DownloadedReleaseNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private bool downloadedFilter_Clicked = false;
private Panel _listViewUninstallButton;
private bool _listViewUninstallButtonHovered = false;
private ListViewItem _hoveredItemForDeleteBtn;
private bool _folderIconHovered = false;
private bool isGalleryView; // Will be set from settings in constructor
private List<ListViewItem> _galleryDataSource;
private FastGalleryPanel _fastGallery;
private const int TILE_WIDTH = 180;
private const int TILE_HEIGHT = 125;
private const int TILE_SPACING = 10;
private string freeSpaceText = "";
private string freeSpaceTextDetailed = "";
private int _questStorageProgress = 0;
private Color _mirrorPillColor = Color.FromArgb(32, 36, 44);
private DateTime _mirrorMenuClosedAt = DateTime.MinValue;
private Color _devicePillColor = Color.FromArgb(32, 36, 44);
private DateTime _deviceMenuClosedAt = DateTime.MinValue;
private bool _trailerPlayerInitialized; // player.html created and loaded
private bool _trailerHtmlLoaded; // initial navigation completed
private static readonly Dictionary<string, string> _videoIdCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // per game cache
private bool isLoading = true;
private bool _suppressMirrorRefresh = false;
public static bool _isManualMirrorSwitch = false;
public static bool isOffline = false;
public static bool noRcloneUpdating;
public static bool noAppCheck = false;
public static bool hasPublicConfig = false;
public static bool hasUploadConfig = false;
public static bool UsingPublicConfig = false;
public static bool enviromentCreated = false;
public static PublicConfig PublicConfigFile;
public static string PublicMirrorExtraArgs = " --tpslimit 1.0 --tpslimit-burst 3";
public static string storedIpPath;
public static string aaptPath;
private System.Windows.Forms.Timer _debounceTimer;
private CancellationTokenSource _cts;
private List<ListViewItem> _allItems;
private List<ListViewItem> _allItemsUnfiltered;
private Dictionary<string, List<ListViewItem>> _searchIndex;
public MainForm()
{
storedIpPath = Path.Combine(Environment.CurrentDirectory, "platform-tools", "StoredIP.txt");
aaptPath = Path.Combine(Environment.CurrentDirectory, "platform-tools", "aapt.exe");
InitializeComponent();
this.Opacity = 0;
InitializeModernPanels(); // Initialize modern rounded panels for notes and queue
// Center the initial placeholder text in notes panel
notesRichTextBox.SelectAll();
notesRichTextBox.SelectionAlignment = HorizontalAlignment.Center;
notesRichTextBox.DeselectAll();
Logger.Initialize();
InitializeTimeReferences();
CheckCommandLineArguments();
// Use same icon as the executable
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
// Load user's preferred view from settings
isGalleryView = settings.UseGalleryView;
// Always start with ListView visible so selections work properly
// We'll switch to gallery view after initListView completes if needed
gamesListView.Visible = true;
gamesGalleryView.Visible = false;
btnViewToggle.Text = isGalleryView ? "LIST" : "GALLERY";
favoriteGame.Renderer = new CenteredMenuRenderer();
// Set initial wireless ADB button text based on current state
UpdateWirelessADBButtonText();
_debounceTimer = new System.Windows.Forms.Timer { Interval = 100, Enabled = false };
_debounceTimer.Tick += async (sender, e) => await RunSearch();
SetCurrentLogPath();
StartTimers();
lvwColumnSorter = new ListViewColumnSorter();
gamesListView.ListViewItemSorter = lvwColumnSorter;
// Initialize modern ListView renderer
_listViewRenderer = new ModernListView(gamesListView, lvwColumnSorter);
// Set a larger item height for increased spacing between rows
ImageList rowSpacingImageList = new ImageList();
rowSpacingImageList.ImageSize = new Size(1, 28);
gamesListView.SmallImageList = rowSpacingImageList;
SubscribeToHoverEvents(questInfoPanel);
this.Resize += MainForm_Resize;
// Style the downloads folder icon and overlay it on the left side of btnDownloaded
openDownloadsFolderIcon.Paint += OpenDownloadsFolderIcon_Paint;
openDownloadsFolderIcon.MouseEnter += (s, ev) => { _folderIconHovered = true; openDownloadsFolderIcon.Invalidate(); };
openDownloadsFolderIcon.MouseLeave += (s, ev) => { _folderIconHovered = false; openDownloadsFolderIcon.Invalidate(); };
openDownloadsFolderIcon.Parent = btnDownloaded;
openDownloadsFolderIcon.Location = new Point(0, 0);
openDownloadsFolderIcon.Size = new Size(28, 28);
openDownloadsFolderIcon.BringToFront();
btnDownloaded.TextXOffset = 24;
// Create an uninstall button overlay for list view
_listViewUninstallButton = new Panel
{
Size = new Size(22, 22),
BackColor = Color.Transparent,
Visible = false,
Cursor = Cursors.Hand
};
_listViewUninstallButton.Paint += ListViewUninstallButton_Paint;
_listViewUninstallButton.MouseEnter += (s, ev) => { _listViewUninstallButtonHovered = true; _listViewUninstallButton.Invalidate(); };
_listViewUninstallButton.MouseLeave += (s, ev) => { _listViewUninstallButtonHovered = false; _listViewUninstallButton.Invalidate(); };
_listViewUninstallButton.Click += ListViewUninstallButton_Click;
gamesListView.Controls.Add(_listViewUninstallButton);
// Timer to keep button position synced with the selected item
var uninstallButtonTimer = new System.Windows.Forms.Timer { Interval = 16 }; // ~60fps
uninstallButtonTimer.Tick += (s, ev) =>
{
if (_listViewUninstallButton == null)
return;
var item = _hoveredItemForDeleteBtn;
// Hide if no item is hovered
if (item == null || !gamesListView.Items.Contains(item))
{
_listViewUninstallButton.Visible = false;
return;
}
// Check if item is installed
bool isInstalled = item.ForeColor.ToArgb() == ColorInstalled.ToArgb() ||
item.ForeColor.ToArgb() == ColorUpdateAvailable.ToArgb() ||
item.ForeColor.ToArgb() == ColorDonateGame.ToArgb();
if (!isInstalled)
{
_listViewUninstallButton.Visible = false;
return;
}
// Calculate header height (items start below the header)
int headerHeight = 0;
if (gamesListView.View == View.Details && gamesListView.HeaderStyle != ColumnHeaderStyle.None)
{
headerHeight = gamesListView.Font.Height;
}
// Calculate button position based on item bounds
Rectangle itemBounds = item.Bounds;
int buttonX = gamesListView.ClientSize.Width - _listViewUninstallButton.Width - 5;
int buttonY = itemBounds.Top + (itemBounds.Height - _listViewUninstallButton.Height) / 2;
// Check if item is within visible bounds (below header and above bottom)
bool isVisible = itemBounds.Top >= headerHeight &&
buttonY >= headerHeight &&
buttonY + _listViewUninstallButton.Height <= gamesListView.ClientSize.Height;
if (isVisible)
{
_listViewUninstallButton.Location = new Point(buttonX, buttonY);
_listViewUninstallButton.Tag = item; // Store reference for click handler
if (!_listViewUninstallButton.Visible)
{
_listViewUninstallButton.Visible = true;
}
}
else
{
_listViewUninstallButton.Visible = false;
}
};
uninstallButtonTimer.Start();
gamesListView.MouseMove += (s, ev) =>
{
var hitTest = gamesListView.HitTest(ev.Location);
_hoveredItemForDeleteBtn = hitTest.Item;
};
gamesListView.MouseLeave += (s, ev) =>
{
// Clear hover if mouse left the ListView bounds
Point clientPoint = gamesListView.PointToClient(Control.MousePosition);
if (!gamesListView.ClientRectangle.Contains(clientPoint))
{
_hoveredItemForDeleteBtn = null;
}
};
// Set data that apparently can't be set in designer
// We do it here so it doesn't get overwritten by designer
batteryLevImg.Parent = questStorageProgressBar;
batteryLabel.Parent = batteryLevImg;
diskLabel.Parent = questStorageProgressBar;
questInfoLabel.Parent = questStorageProgressBar;
// Subscribe to click events to unfocus search text box
this.Click += UnfocusSearchTextBox;
// Load saved window state
LoadWindowState();
}
private void CheckCommandLineArguments()
{
string[] args = Environment.GetCommandLineArgs();
foreach (string arg in args)
{
if (arg == "--offline")
{
isOffline = true;
}
if (arg == "--no-rclone-update")
{
noRcloneUpdating = true;
}
if (arg == "--disable-app-check")
{
noAppCheck = true;
}
}
}
private void InitializeTimeReferences()
{
// Initialize time references
TimeSpan newDayReference = new TimeSpan(96, 0, 0); // Time between asking for new apps if user clicks No. (DEFAULT: 96 hours)
TimeSpan newDayReference2 = new TimeSpan(72, 0, 0); // Time between asking for updates after uploading. (DEFAULT: 72 hours)
// Calculate time differences
DateTime A = settings.LastLaunch;
DateTime B = DateTime.Now;
DateTime C = settings.LastLaunch2;
TimeSpan comparison = B - A;
TimeSpan comparison2 = B - C;
// Reset properties if enough time has passed
if (comparison > newDayReference)
{
ResetPropertiesAfterTimePassed();
}
if (comparison2 > newDayReference2)
{
ResetProperties2AfterTimePassed();
}
}
private void ResetPropertiesAfterTimePassed()
{
settings.ListUpped = false;
settings.NonAppPackages = String.Empty;
settings.AppPackages = String.Empty;
settings.LastLaunch = DateTime.Now;
settings.Save();
}
private void ResetProperties2AfterTimePassed()
{
settings.LastLaunch2 = DateTime.Now;
settings.SubmittedUpdates = String.Empty;
settings.Save();
}
private void SetCurrentLogPath()
{
if (string.IsNullOrEmpty(settings.CurrentLogPath))
{
settings.CurrentLogPath = Path.Combine(Environment.CurrentDirectory, "debuglog.txt");
}
}
private void StartTimers()
{
// Start timers
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer
{
Interval = 840000 // 14 mins between wakeup commands
};
t.Tick += new EventHandler(timer_Tick);
t.Start();
System.Windows.Forms.Timer t2 = new System.Windows.Forms.Timer
{
Interval = 300 // 300ms
};
t2.Tick += new EventHandler(timer_Tick2);
t2.Start();
// Device connection check timer, runs every second
System.Windows.Forms.Timer deviceCheckTimer = new System.Windows.Forms.Timer
{
Interval = 1000 // 1 second
};
deviceCheckTimer.Tick += new EventHandler(timer_DeviceCheck);
deviceCheckTimer.Start();
}
public static string donorApps = String.Empty;
private string oldTitle = String.Empty;
public static bool updatesNotified = false;
public static string backupFolder;
private static void KillAdbProcesses()
{
try
{
foreach (var p in Process.GetProcessesByName("adb"))
{
try
{
if (!p.HasExited)
{
p.Kill();
p.WaitForExit(3000);
}
}
catch (Exception ex)
{
Logger.Log($"Failed to kill adb process (PID {p.Id}): {ex.Message}", LogLevel.WARNING);
}
}
}
catch (Exception ex)
{
Logger.Log($"Error enumerating adb processes: {ex.Message}", LogLevel.WARNING);
}
}
private async void Form1_Load(object sender, EventArgs e)
{
_ = Logger.Log("Starting AndroidSideloader Application");
// Hard kill any lingering adb.exe instances to avoid port/handle conflicts
KillAdbProcesses();
// ADB initialization in background
_adbInitTask = Task.Run(() =>
{
_ = Logger.Log("Attempting to Initialize ADB Server");
if (File.Exists(Path.Combine(Environment.CurrentDirectory, "platform-tools", "adb.exe")))
{
_ = ADB.RunAdbCommandToString("start-server");
}
});
// Basic UI setup - only center if no saved position
if (this.StartPosition != FormStartPosition.Manual)
{
CenterToScreen();
}
gamesListView.View = View.Details;
gamesListView.FullRowSelect = true;
gamesListView.GridLines = false;
speedLabel.Text = String.Empty;
diskLabel.Text = String.Empty;
settings.MainDir = Environment.CurrentDirectory;
settings.Save();
changeTitle(isOffline ? "Starting in Offline Mode..." : "Initializing...");
// Non-blocking WebView cleanup
_ = Task.Run(() =>
{
try
{
string webViewDirectoryPath = Path.Combine(Environment.CurrentDirectory, "WebView2Cache");
if (Directory.Exists(webViewDirectoryPath))
{
FileSystemUtilities.TryDeleteDirectory(webViewDirectoryPath);
}
}
catch { }
});
// Non-blocking background cleanup
_ = Task.Run(() =>
{
try
{
if (Directory.Exists(Sideloader.TempFolder))
{
FileSystemUtilities.TryDeleteDirectory(Sideloader.TempFolder);
_ = Directory.CreateDirectory(Sideloader.TempFolder);
}
}
catch (Exception ex)
{
Logger.Log($"Error cleaning temp folder: {ex.Message}", LogLevel.WARNING);
}
});
// Non-blocking log file cleanup
_ = Task.Run(() =>
{
try
{
string logFilePath = settings.CurrentLogPath;
if (File.Exists(logFilePath))
{
FileInfo fileInfo = new FileInfo(logFilePath);
if (fileInfo.Length > 5 * 1024 * 1024)
{
File.Delete(logFilePath);
}
}
}
catch { }
});
// Ensure bottom panels are properly laid out
LayoutBottomPanels();
webView21.Visible = settings.TrailersEnabled;
// Continue with Form1_Shown
this.Form1_Shown(sender, e);
}
private async void Form1_Shown(object sender, EventArgs e)
{
//searchTextBox.Enabled = false;
// Disclaimer thread
new Thread(() =>
{
Thread.Sleep(5000);
freeDisclaimer.Invoke(() =>
{
freeDisclaimer.Dispose();
freeDisclaimer.Enabled = false;
});
}).Start();
// Startup dialog:
// The dialog lets the user choose online (with a config URL) or offline mode.
// If a valid public.json exists and the server is reachable,
// skip the dialog entirely and go straight to online mode.
// The --offline flag bypasses the dialog entirely.
if (!isOffline)
{
// Try to auto-load existing config and skip the dialog
bool configAutoLoaded = false;
try
{
string configFilePath = Path.Combine(Environment.CurrentDirectory, "public.json");
if (File.Exists(configFilePath))
{
string configFileData = File.ReadAllText(configFilePath);
PublicConfig config = JsonConvert.DeserializeObject<PublicConfig>(configFileData);
if (config != null &&
!string.IsNullOrWhiteSpace(config.BaseUri) &&
!string.IsNullOrWhiteSpace(config.Password))
{
// Config file is structurally valid — test if server is reachable
string hostname = null;
string baseUri = config.BaseUri;
if (!baseUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
!baseUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
baseUri = "https://" + baseUri;
}
if (Uri.TryCreate(baseUri, UriKind.Absolute, out Uri uri))
{
hostname = uri.Host;
}
if (!string.IsNullOrEmpty(hostname))
{
bool serverReachable = false;
try
{
var addresses = Dns.GetHostAddresses(hostname);
serverReachable = addresses != null && addresses.Length > 0;
}
catch
{
serverReachable = false;
}
if (serverReachable)
{
PublicConfigFile = config;
hasPublicConfig = true;
configAutoLoaded = true;
DnsHelper.TestPublicConfigDns();
Logger.Log($"Auto-loaded valid config — server {hostname} is reachable, skipping startup dialog");
}
}
}
}
}
catch (Exception ex)
{
Logger.Log($"Auto-load config check failed: {ex.Message}", LogLevel.WARNING);
}
// If public.json auto-load failed, check for rclone/download.config with mirrors
if (!configAutoLoaded)
{
try
{
string downloadConfigFile = Path.Combine(Environment.CurrentDirectory, "rclone", "download.config");
if (File.Exists(downloadConfigFile))
{
string configText = File.ReadAllText(downloadConfigFile);
if (Regex.IsMatch(configText, @"\[.*mirror.*\]", RegexOptions.IgnoreCase))
{
configAutoLoaded = true;
Logger.Log("Found rclone/download.config with mirror remotes, skipping startup dialog");
}
}
}
catch (Exception ex)
{
Logger.Log($"Rclone config check failed: {ex.Message}", LogLevel.WARNING);
}
}
// If auto-load failed, show the startup dialog as usual
if (!configAutoLoaded)
{
using (var startupDialog = new StartupDialog())
{
var dialogResult = startupDialog.ShowDialog(this);
if (dialogResult != DialogResult.OK || startupDialog.Choice == StartupDialog.StartupChoice.None)
{
Application.Exit();
return;
}
if (startupDialog.Choice == StartupDialog.StartupChoice.Offline)
{
isOffline = true;
Logger.Log("User chose offline mode from startup dialog");
}
else if (startupDialog.Choice == StartupDialog.StartupChoice.RcloneConfig)
{
// User provided an rclone download config — proceed online without public config
Logger.Log("User provided rclone download.config from startup dialog");
}
else
{
// Online — the StartupDialog already validated, downloaded, and wrote public.json
// Load it into memory
Logger.Log("User chose online mode from startup dialog");
try
{
string configFilePath = Path.Combine(Environment.CurrentDirectory, "public.json");
if (File.Exists(configFilePath))
{
string configFileData = File.ReadAllText(configFilePath);
PublicConfig config = JsonConvert.DeserializeObject<PublicConfig>(configFileData);
if (config != null &&
!string.IsNullOrWhiteSpace(config.BaseUri) &&
!string.IsNullOrWhiteSpace(config.Password))
{
PublicConfigFile = config;
hasPublicConfig = true;
// Test DNS for the public config hostname
DnsHelper.TestPublicConfigDns();
}
}
}
catch (Exception ex)
{
Logger.Log($"Failed to load config after startup dialog: {ex.Message}", LogLevel.ERROR);
}
if (!hasPublicConfig)
{
// Should rarely happen since the dialog validated it,
// but handle gracefully.
isOffline = true;
Logger.Log("Config invalid after dialog — falling back to offline mode", LogLevel.WARNING);
}
}
}
}
// Pre-initialize trailer player in background
if (!isOffline)
{
try
{
await EnsureTrailerEnvironmentAsync();
}
catch { /* swallow – prewarm should never crash startup */ }
}
}
// Show the main form now that startup dialog is done
this.Opacity = 1;
// UI setup
remotesList.Items.Clear();
if (hasPublicConfig)
{
UsingPublicConfig = true;
_ = Logger.Log($"Using Public Mirror");
}
if (isOffline)
{
remotesList.Size = System.Drawing.Size.Empty;
_ = Logger.Log($"Using Offline Mode");
}
if (settings.NodeviceMode)
{
btnNoDevice.Text = "ENABLE SIDELOADING";
}
progressBar.IsIndeterminate = true;
progressBar.OperationType = "Loading";
// Always download dependencies (adb, aapt, 7z, runtimes) regardless of mode
await Task.Run(() =>
{
changeTitle("Downloading Dependencies...");
GetDependencies.downloadFiles();
});
// Init RCLONE only in online mode
if (!isOffline)
{
await Task.Run(() =>
{
changeTitle("Initializing RCLONE...");
RCLONE.Init();
});
}
// Update check
if (!debugMode && settings.CheckForUpdates && !isOffline)
{
Updater.AppName = "AndroidSideloader";
Updater.Repository = repo;
await Updater.Update();
}
if (!isOffline)
{
_ = Logger.Log("Initializing Servers");
changeTitle("Initializing Servers...");
await initMirrors();
}
else
{
changeTitle("Offline mode // Scanning local library...");
// Determine the scan directory; prompt the user on first run
// Self-healing: if DownloadDir is set but CustomDownloadDir was lost, recover
bool hasValidDir = !string.IsNullOrEmpty(settings.DownloadDir) && Directory.Exists(settings.DownloadDir);
if (hasValidDir && !settings.CustomDownloadDir)
{
settings.CustomDownloadDir = true;
settings.Save();
}
string dlDir = hasValidDir ? settings.DownloadDir : Environment.CurrentDirectory;
if (!settings.CustomDownloadDir)
{
var folderDialog = new FolderSelectDialog
{
Title = "Select the folder containing your downloaded games",
InitialDirectory = dlDir
};
if (folderDialog.Show(Handle))
{
dlDir = folderDialog.FileName;
settings.DownloadDir = dlDir;
settings.CustomDownloadDir = true;
settings.Save();
}
}
// In offline mode, scan the local download directory for games
await Task.Run(() =>
{
SideloaderRCLONE.ScanLocalGames(dlDir);
});
}
// Device connection and Metadata can run simultaneously
Task metadataTask = null;
Task deviceConnectionTask = null;
// Start device connection task
deviceConnectionTask = Task.Run(() =>
{
changeTitle("Connecting to device...");
if (!string.IsNullOrEmpty(settings.IPAddress))
{
string path = Path.Combine(Environment.CurrentDirectory, "platform-tools", "adb.exe");
ProcessOutput wakeywakey = ADB.RunCommandToString($"\"{path}\" shell input keyevent KEYCODE_WAKEUP", path);
if (wakeywakey.Output.Contains("more than one"))
{
settings.Wired = true;
settings.Save();
}
else if (wakeywakey.Output.Contains("found"))
{
settings.Wired = false;
settings.Save();
}
}
if (File.Exists(storedIpPath) && !settings.Wired)
{
string IPcmndfromtxt = File.ReadAllText(storedIpPath);
settings.IPAddress = IPcmndfromtxt;
settings.Save();
ProcessOutput IPoutput = ADB.RunAdbCommandToString(IPcmndfromtxt);
if (IPoutput.Output.Contains("attempt failed") || IPoutput.Output.Contains("refused"))
{
this.Invoke(() =>
{
_ = FlexibleMessageBox.Show(Program.form,
"Attempt to connect to saved IP has failed. This is usually due to rebooting the device or not having a STATIC IP set in your router.\nYou must enable Wireless ADB again!");
});
settings.IPAddress = "";
settings.Save();
try { File.Delete(storedIpPath); }
catch (Exception ex) { Logger.Log($"Unable to delete StoredIP.txt due to {ex.Message}", LogLevel.ERROR); }
}
else
{
_ = ADB.RunAdbCommandToString("shell settings put global wifi_wakeup_available 1");
_ = ADB.RunAdbCommandToString("shell settings put global wifi_wakeup_enabled 1");
}
}
else if (!File.Exists(storedIpPath))
{
settings.IPAddress = "";
settings.Save();
}
});
// Start metadata task in parallel
if (!isOffline)
{
metadataTask = Task.Run(() =>
{
if (hasPublicConfig)
{
changeTitle("Updating Metadata...");
SideloaderRCLONE.UpdateMetadataFromPublic();
changeTitle("Processing Metadata...");
SideloaderRCLONE.ProcessMetadataFromPublic();
}
if (!UsingPublicConfig)
{
changeTitle("Updating Game Notes...");
SideloaderRCLONE.UpdateGameNotes(currentRemote);
changeTitle("Updating Game Thumbnails...");
SideloaderRCLONE.UpdateGamePhotos(currentRemote);
SideloaderRCLONE.UpdateNouns(currentRemote);
if (!Directory.Exists(SideloaderRCLONE.ThumbnailsFolder) ||
!Directory.Exists(SideloaderRCLONE.NotesFolder))
{
this.Invoke(() =>
{
_ = FlexibleMessageBox.Show(Program.form,
"It seems you are missing the thumbnails and/or notes database, the first start of the sideloader takes a bit more time, so dont worry if it looks stuck!");
});
}
}
});
}
// Wait for both tasks to complete
var tasksToWait = new List<Task>();
if (deviceConnectionTask != null) tasksToWait.Add(deviceConnectionTask);
if (metadataTask != null) tasksToWait.Add(metadataTask);
if (tasksToWait.Count > 0)
{
await Task.WhenAll(tasksToWait);
}
// For non-Public mirrors, load the game list AFTER metadata processing
// completes. ProcessMetadataFromPublic() overwrites the game list with
// public data, so initGames must run afterwards to get the final word.
if (!isOffline && !UsingPublicConfig)
{
changeTitle("Grabbing the Games List...");
await Task.Run(() => SideloaderRCLONE.initGames(currentRemote));
}
string uploadConfigPath = Path.Combine(Environment.CurrentDirectory, "rclone", "upload.config");
if (File.Exists(uploadConfigPath))
hasUploadConfig = true;
progressBar.IsIndeterminate = true;
progressBar.OperationType = "Loading";
changeTitle("Populating Game List...");
_ = await CheckForDevice();
if (ADB.DeviceID.Length < 5)
{
nodeviceonstart = true;
}
// Parallel execution
await Task.WhenAll(
Task.Run(() => listAppsBtn())
);
isLoading = false;
// Initialize list view
initListView(false);
// Cleanup in background
_ = Task.Run(() =>
{
string[] files = Directory.GetFiles(Environment.CurrentDirectory);
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
if (!fileName.Contains(settings.CurrentLogName) &&
!fileName.Contains(settings.CurrentCrashName) &&
!fileName.Contains("debuglog") &&
fileName.EndsWith(".txt"))
{
try { System.IO.File.Delete(file); } catch { }
}
}
});
searchTextBox.Enabled = true;
if (isOffline)
{
remotesList.Size = System.Drawing.Size.Empty;
_ = Logger.Log($"Using Offline Mode");
}
changeTitlebarToDevice();
UpdateStatusLabels();
// Load saved download queue and offer to resume
LoadQueueFromSettings();
if (gamesQueueList.Count > 0 && !isOffline)
{
await ResumeQueuedDownloadsAsync();
}
}
private void timer_Tick(object sender, EventArgs e)
{
_ = ADB.RunAdbCommandToString("shell input keyevent KEYCODE_WAKEUP");
}
private void timer_Tick2(object sender, EventArgs e)
{
keyheld = false;
}
public async void changeTitle(string txt, bool reset = false)
{
try
{
string titleSuffix = string.IsNullOrWhiteSpace(txt) ? "" : " | " + txt;
this.Invoke(() =>
{
Text = "Rookie Sideloader " + Updater.LocalVersion + titleSuffix;
rookieStatusLabel.Text = txt;
});
if (!reset)
{
return;
}
await Task.Delay(TimeSpan.FromSeconds(5));
// Reset to base title without any status message
this.Invoke(() =>
{
Text = "Rookie Sideloader " + Updater.LocalVersion;
rookieStatusLabel.Text = "";
});
}
catch
{
}
}
private async void startsideloadbutton_Click(object sender, EventArgs e)
{
ProcessOutput output = new ProcessOutput("", "");
string path = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Android apps (*.apk)|*.apk";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
path = openFileDialog.FileName;
}
else
{
return;
}