Release/RSL-2.17 (#128)

* fix: pull to desktop not resetting work status.

resolves #104

* Create Text File with upload size for verification

* bump version

* better public config handling

* code cleanup

Co-authored-by: Fenopy <Fenopie@Gmail.com>
This commit is contained in:
SytheZN
2022-12-05 23:42:59 +02:00
committed by GitHub
parent 67a9089952
commit d3a2c4012c
36 changed files with 1640 additions and 1228 deletions

135
ADB.cs
View File

@@ -1,19 +1,14 @@
using System;
using JR.Utils.GUI.Forms;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using JR.Utils.GUI.Forms;
using Newtonsoft.Json;
namespace AndroidSideloader
{
class ADB
internal class ADB
{
static Process adb = new Process();
private static readonly Process adb = new Process();
public static string adbFolderPath = "C:\\RSL\\platform-tools";
public static string adbFilePath = adbFolderPath + "\\adb.exe";
public static string DeviceID = "";
@@ -33,8 +28,11 @@ namespace AndroidSideloader
string logcmd = command;
if (logcmd.Contains(Environment.CurrentDirectory))
{
logcmd = logcmd.Replace($"{Environment.CurrentDirectory}", $"CurrentDirectory");
Logger.Log($"Running command: {logcmd}");
}
_ = Logger.Log($"Running command: {logcmd}");
}
adb.StartInfo.FileName = adbFilePath;
adb.StartInfo.Arguments = command;
@@ -44,7 +42,7 @@ namespace AndroidSideloader
adb.StartInfo.CreateNoWindow = true;
adb.StartInfo.UseShellExecute = false;
adb.StartInfo.WorkingDirectory = adbFolderPath;
adb.Start();
_ = adb.Start();
adb.StandardInput.WriteLine(command);
adb.StandardInput.Flush();
adb.StandardInput.Close();
@@ -67,7 +65,10 @@ namespace AndroidSideloader
}
}
else
{
adb.WaitForExit();
}
if (error.Contains("ADB_VENDOR_KEYS") && !Properties.Settings.Default.adbdebugwarned)
{
DialogResult dialogResult = FlexibleMessageBox.Show("Please check inside your headset for ADB DEBUGGING prompt, check box to \"Always allow from this computer.\" and hit OK.\nPlease note that even if you have done this\nbefore it will reset itself from time to time.\n\nPress CANCEL if you want to disable this prompt (FOR DEBUGGING ONLY, NOT RECOMMENDED).", "ADB Debugging not enabled.", MessageBoxButtons.OKCancel);
@@ -77,15 +78,20 @@ namespace AndroidSideloader
Properties.Settings.Default.Save();
}
else
{
ADB.WakeDevice();
}
}
if (error.Contains("not enough storage space"))
{
FlexibleMessageBox.Show("There is not enough room on your device to install this package. Please clear AT LEAST 2x the amount of the app you are trying to install.");
_ = FlexibleMessageBox.Show("There is not enough room on your device to install this package. Please clear AT LEAST 2x the amount of the app you are trying to install.");
}
if (!output.Contains("version") && !output.Contains("KEYCODE_WAKEUP") && !output.Contains("Filesystem") && !output.Contains("package:") && !output.Equals(null))
Logger.Log(output);
Logger.Log(error);
{
_ = Logger.Log(output);
}
_ = Logger.Log(error);
return new ProcessOutput(output, error);
}
public static ProcessOutput RunAdbCommandToStringWOADB(string result, string path)
@@ -93,8 +99,11 @@ namespace AndroidSideloader
string command = result;
string logcmd = command;
if (logcmd.Contains(Environment.CurrentDirectory))
{
logcmd = logcmd.Replace($"{Environment.CurrentDirectory}", $"CurrentDirectory");
Logger.Log($"Running command: {logcmd}");
}
_ = Logger.Log($"Running command: {logcmd}");
adb.StartInfo.FileName = "cmd.exe";
adb.StartInfo.RedirectStandardError = true;
@@ -103,7 +112,7 @@ namespace AndroidSideloader
adb.StartInfo.CreateNoWindow = true;
adb.StartInfo.UseShellExecute = false;
adb.StartInfo.WorkingDirectory = Path.GetDirectoryName(path);
adb.Start();
_ = adb.Start();
adb.StandardInput.WriteLine(command);
adb.StandardInput.Flush();
adb.StandardInput.Close();
@@ -126,7 +135,9 @@ namespace AndroidSideloader
adb.Kill();
}
else
{
adb.WaitForExit();
}
}
else if (command.Contains("install"))
{
@@ -136,9 +147,11 @@ namespace AndroidSideloader
adb.Kill();
}
else
{
adb.WaitForExit();
}
}
if (error.Contains("ADB_VENDOR_KEYS") && Properties.Settings.Default.adbdebugwarned)
{
DialogResult dialogResult = FlexibleMessageBox.Show("Please check inside your headset for ADB DEBUGGING prompt, check box to \"Always allow from this computer.\" and hit OK.\nPlease note that even if you have done this\nbefore it will reset itself from time to time.\n\nPress CANCEL if you want to disable this prompt (FOR DEBUGGING ONLY, NOT RECOMMENDED).", "ADB Debugging not enabled.", MessageBoxButtons.OKCancel);
@@ -148,10 +161,12 @@ namespace AndroidSideloader
Properties.Settings.Default.Save();
}
else
{
ADB.WakeDevice();
}
}
Logger.Log(output);
Logger.Log(error);
_ = Logger.Log(output);
_ = Logger.Log(error);
return new ProcessOutput(output, error);
}
public static ProcessOutput RunCommandToString(string result, string path = "")
@@ -159,8 +174,11 @@ namespace AndroidSideloader
string command = result;
string logcmd = command;
if (logcmd.Contains(Environment.CurrentDirectory))
{
logcmd = logcmd.Replace($"{Environment.CurrentDirectory}", $"CurrentDirectory");
Logger.Log($"Running command: {logcmd}");
}
_ = Logger.Log($"Running command: {logcmd}");
adb.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
adb.StartInfo.Arguments = command;
adb.StartInfo.RedirectStandardError = true;
@@ -169,7 +187,7 @@ namespace AndroidSideloader
adb.StartInfo.CreateNoWindow = true;
adb.StartInfo.UseShellExecute = false;
adb.StartInfo.WorkingDirectory = Path.GetDirectoryName(path);
adb.Start();
_ = adb.Start();
adb.StandardInput.WriteLine(command);
adb.StandardInput.Flush();
adb.StandardInput.Close();
@@ -193,8 +211,10 @@ namespace AndroidSideloader
}
}
else
{
adb.WaitForExit();
}
if (error.Contains("ADB_VENDOR_KEYS") && Properties.Settings.Default.adbdebugwarned)
{
DialogResult dialogResult = FlexibleMessageBox.Show("Please check inside your headset for ADB DEBUGGING prompt, check box to \"Always allow from this computer.\" and hit OK.\nPlease note that even if you have done this\nbefore it will reset itself from time to time.\n\nPress CANCEL if you want to disable this prompt (FOR DEBUGGING ONLY, NOT RECOMMENDED).", "ADB Debugging not enabled.", MessageBoxButtons.OKCancel);
@@ -204,10 +224,12 @@ namespace AndroidSideloader
Properties.Settings.Default.Save();
}
else
ADB.WakeDevice();
{
ADB.WakeDevice();
}
}
Logger.Log(output);
Logger.Log(error);
_ = Logger.Log(output);
_ = Logger.Log(error);
return new ProcessOutput(output, error);
}
@@ -228,13 +250,13 @@ namespace AndroidSideloader
long freeSize = 0;
WakeDevice();
var output = RunAdbCommandToString("shell df").Output.Split('\n');
string[] output = RunAdbCommandToString("shell df").Output.Split('\n');
foreach (string currLine in output)
{
if (currLine.StartsWith("/data/media"))
{
var foo = currLine.Split(' ');
string[] foo = currLine.Split(' ');
int i = 0;
foreach (string curr in foo)
{
@@ -245,13 +267,13 @@ namespace AndroidSideloader
case 0:
break;
case 1:
totalSize = Int64.Parse(curr) / 1000;
totalSize = long.Parse(curr) / 1000;
break;
case 2:
usedSize = Int64.Parse(curr) / 1000;
usedSize = long.Parse(curr) / 1000;
break;
case 3:
freeSize = Int64.Parse(curr) / 1000;
freeSize = long.Parse(curr) / 1000;
break;
default:
break;
@@ -262,16 +284,18 @@ namespace AndroidSideloader
}
}
return $"Total space: {String.Format("{0:0.00}", (double)totalSize / 1000)}GB\nUsed space: {String.Format("{0:0.00}", (double)usedSize / 1000)}GB\nFree space: {String.Format("{0:0.00}", (double)freeSize / 1000)}GB";
return $"Total space: {string.Format("{0:0.00}", (double)totalSize / 1000)}GB\nUsed space: {string.Format("{0:0.00}", (double)usedSize / 1000)}GB\nFree space: {string.Format("{0:0.00}", (double)freeSize / 1000)}GB";
}
public static bool wirelessadbON;
public static void WakeDevice()
{
RunAdbCommandToString("shell input keyevent KEYCODE_WAKEUP");
if (!String.IsNullOrEmpty(Properties.Settings.Default.IPAddress) && !Properties.Settings.Default.Wired)
RunAdbCommandToString(Properties.Settings.Default.IPAddress);
_ = RunAdbCommandToString("shell input keyevent KEYCODE_WAKEUP");
if (!string.IsNullOrEmpty(Properties.Settings.Default.IPAddress) && !Properties.Settings.Default.Wired)
{
_ = RunAdbCommandToString(Properties.Settings.Default.IPAddress);
}
}
@@ -284,13 +308,15 @@ namespace AndroidSideloader
string out2 = ret.Output + ret.Error;
if (out2.Contains("failed"))
{
string BackupFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"Rookie Backups");
Logger.Log(out2);
_ = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"Rookie Backups");
_ = Logger.Log(out2);
if (out2.Contains("offline") && !Properties.Settings.Default.nodevicemode)
{
DialogResult dialogResult2 = FlexibleMessageBox.Show("Device is offline. Press Yes to reconnect, or if you don't wish to connect and just want to download the game (requires unchecking \"Delete games after install\" from settings menu) then press No.", "Device offline.", MessageBoxButtons.YesNoCancel);
if (dialogResult2 == DialogResult.Yes)
{
ADB.WakeDevice();
}
}
if (out2.Contains($"signatures do not match previously") || out2.Contains("INSTALL_FAILED_VERSION_DOWNGRADE") || out2.Contains("signatures do not match") || out2.Contains("failed to install"))
{
@@ -302,20 +328,24 @@ namespace AndroidSideloader
DialogResult dialogResult1 = FlexibleMessageBox.Show("In place upgrade has failed. Rookie can attempt to backup your save data and\nreinstall the game automatically, however " +
"some games do not store their saves\nin an accessible location(less than 5%). Continue with reinstall?", "In place upgrade failed.", MessageBoxButtons.OKCancel);
if (dialogResult1 == DialogResult.Cancel)
{
return ret;
}
}
Program.form.ChangeTitle("Performing reinstall, please wait...");
ADB.RunAdbCommandToString("kill-server");
ADB.RunAdbCommandToString("devices");
ADB.RunAdbCommandToString($"pull /sdcard/Android/data/{MainForm.CurrPCKG} \"{Environment.CurrentDirectory}\"");
_ = ADB.RunAdbCommandToString("kill-server");
_ = ADB.RunAdbCommandToString("devices");
_ = ADB.RunAdbCommandToString($"pull /sdcard/Android/data/{MainForm.CurrPCKG} \"{Environment.CurrentDirectory}\"");
Program.form.ChangeTitle("Uninstalling game...");
Sideloader.UninstallGame(MainForm.CurrPCKG);
_ = Sideloader.UninstallGame(MainForm.CurrPCKG);
Program.form.ChangeTitle("Reinstalling Game");
ret += ADB.RunAdbCommandToString($"install -g \"{path}\"");
ADB.RunAdbCommandToString($"push \"{Environment.CurrentDirectory}\\{MainForm.CurrPCKG}\" /sdcard/Android/data/");
_ = ADB.RunAdbCommandToString($"push \"{Environment.CurrentDirectory}\\{MainForm.CurrPCKG}\" /sdcard/Android/data/");
if (Directory.Exists($"{Environment.CurrentDirectory}\\{MainForm.CurrPCKG}"))
{
Directory.Delete($"{Environment.CurrentDirectory}\\{MainForm.CurrPCKG}", true);
}
Program.form.ChangeTitle(" \n\n");
return ret;
@@ -331,20 +361,25 @@ namespace AndroidSideloader
Program.form.ChangeTitle("Pushing Custom QU S3 Config.JSON.");
if (!Directory.Exists($"/sdcard/android/data/{packagename}"))
RunAdbCommandToString($"shell mkdir /sdcard/android/data/{packagename}");
{
_ = RunAdbCommandToString($"shell mkdir /sdcard/android/data/{packagename}");
}
if (!Directory.Exists($"/sdcard/android/data/{packagename}/private"))
RunAdbCommandToString($"shell mkdir /sdcard/android/data/{packagename}/private");
{
_ = RunAdbCommandToString($"shell mkdir /sdcard/android/data/{packagename}/private");
}
Random r = new Random();
int x = r.Next(999999999);
int y = r.Next(9999999);
var sum = ((long)y * (long)1000000000) + (long)x;
long sum = (y * (long)1000000000) + x;
int x2 = r.Next(999999999);
int y2 = r.Next(9999999);
var sum2 = ((long)y2 * (long)1000000000) + (long)x2;
long sum2 = (y2 * (long)1000000000) + x2;
ADB.WakeDevice();
Properties.Settings.Default.QUStringF = $"{{\"user_id\":{sum},\"app_id\":\"{sum2}\",";
Properties.Settings.Default.Save();
@@ -367,11 +402,9 @@ namespace AndroidSideloader
WakeDevice();
string folder = Path.GetFileName(path);
if (!folder.Contains("+") && !folder.Contains("_") && folder.Contains("."))
{
return RunAdbCommandToString($"push \"{path}\" \"/sdcard/Android/obb\"");
}
return new ProcessOutput();
return !folder.Contains("+") && !folder.Contains("_") && folder.Contains(".")
? RunAdbCommandToString($"push \"{path}\" \"/sdcard/Android/obb\"")
: new ProcessOutput();
}
}
}

View File

@@ -1,4 +1,15 @@
RSL 2.15
RSL 2.16
- Fix misleading error message when not enough disk space
- Fix downloads silently failing in some cases
- Fix failure to detect failed extraction when archive corrupt
- Fix UI issues when resizing main form
- Various code cleanups
~SytheZN
~fenopy
RSL 2.15
- Massive UI Changes:
- Rounded buttons

View File

@@ -6,20 +6,11 @@ using System.Windows.Forms;
/// </summary>
public class ListViewColumnSorter : IComparer
{
/// <summary>
/// Specifies the column to be sorted
/// </summary>
private int ColumnToSort;
/// <summary>
/// Specifies the order in which to sort (i.e. 'Ascending').
/// </summary>
private SortOrder OrderOfSort;
/// <summary>
/// Case insensitive comparer object
/// </summary>
private CaseInsensitiveComparer ObjectCompare;
private readonly CaseInsensitiveComparer ObjectCompare;
/// <summary>
/// Class constructor. Initializes various elements
@@ -27,10 +18,10 @@ public class ListViewColumnSorter : IComparer
public ListViewColumnSorter()
{
// Initialize the column to '0'
ColumnToSort = 0;
SortColumn = 0;
// Initialize the sort order to 'none'
OrderOfSort = SortOrder.Ascending;
Order = SortOrder.Ascending;
// Initialize the CaseInsensitiveComparer object
ObjectCompare = new CaseInsensitiveComparer();
@@ -50,39 +41,30 @@ public class ListViewColumnSorter : IComparer
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
if (ColumnToSort == 5 ) {
if (SortColumn == 5)
{
try
{
int yNum = int.Parse(cleanNumber(listviewY.SubItems[ColumnToSort].Text));
int xNum = int.Parse(cleanNumber(listviewX.SubItems[ColumnToSort].Text));
if (xNum == yNum )
{
return 0;
}
else if(xNum > yNum && OrderOfSort == SortOrder.Ascending)
{
return -1;
}
else
{
return 1;
}
} catch { }
int yNum = int.Parse(cleanNumber(listviewY.SubItems[SortColumn].Text));
int xNum = int.Parse(cleanNumber(listviewX.SubItems[SortColumn].Text));
return xNum == yNum ? 0 : xNum > yNum && Order == SortOrder.Ascending ? -1 : 1;
}
catch { }
}
// Compare the two items
compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
compareResult = ObjectCompare.Compare(listviewX.SubItems[SortColumn].Text, listviewY.SubItems[SortColumn].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
if (Order == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
else if (Order == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
return -compareResult;
}
else
{
@@ -94,32 +76,12 @@ public class ListViewColumnSorter : IComparer
/// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary>
public int SortColumn
{
set
{
ColumnToSort = value;
}
get
{
return ColumnToSort;
}
}
public int SortColumn { set; get; }
/// <summary>
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
/// </summary>
public SortOrder Order
{
set
{
OrderOfSort = value;
}
get
{
return OrderOfSort;
}
}
public SortOrder Order { set; get; }
private string cleanNumber(string number)
{

View File

@@ -1,22 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace AndroidSideloader
{
class Donors
internal class Donors
{
public static int GameNameIndex = 0;
public static int PackageNameIndex = 1;
public static int VersionCodeIndex = 2;
public static int UpdateOrNew = 3;
/* Game Name
* Package Name
* Version Code
* Update or New app
*/
/* Game Name
* Package Name
* Version Code
* Update or New app
*/
public static List<string> newAppProperties = new List<string>();
public static List<string> donorGameProperties = new List<string>();
@@ -52,7 +48,7 @@ namespace AndroidSideloader
if (game.Length > 1)
{
string[] splitGame = game.Split(';');
newApps.Add(splitGame);
newApps.Add(splitGame);
}
}
}

View File

@@ -1,18 +1,6 @@
using AndroidSideloader.Utilities;
using JR.Utils.GUI.Forms;
using Newtonsoft.Json;
using SergeUtils;
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AndroidSideloader
@@ -49,16 +37,24 @@ namespace AndroidSideloader
{
MainForm.updatesnotified = true;
if (MainForm.updates && MainForm.newapps)
{
bothdet.Visible = true;
}
else if (MainForm.updates && !MainForm.newapps)
{
upddet.Visible = true;
}
else
{
newdet.Visible = true;
}
foreach (ListViewItem listItem in DonorsListView.Items)
{
{
if (listItem.SubItems[Donors.UpdateOrNew].Text.Contains("Update"))
{
listItem.BackColor = Color.FromArgb(0, 79, 97);
}
}
}
@@ -81,24 +77,29 @@ namespace AndroidSideloader
}
if (uncheckednewapps)
{
NewApps NewAppForm = new NewApps();
NewAppForm.ShowDialog();
this.Hide();
_ = NewAppForm.ShowDialog();
Hide();
}
else
this.Hide();
int count = 0;
count = DonorsListView.CheckedItems.Count;
string[] gamesToUpload;
gamesToUpload = new string[count];
{
Hide();
}
int count = DonorsListView.CheckedItems.Count;
_ = new string[count];
for (int i = 0; i < count; i++)
{
ulong vcode = Convert.ToUInt64(DonorsListView.CheckedItems[i].SubItems[Donors.VersionCodeIndex].Text);
if (DonorsListView.CheckedItems[i].SubItems[Donors.UpdateOrNew].Text.Contains("Update"))
await Program.form.extractAndPrepareGameToUploadAsync(DonorsListView.CheckedItems[i].SubItems[Donors.GameNameIndex].Text, DonorsListView.CheckedItems[i].SubItems[Donors.PackageNameIndex].Text, vcode, true);
else
await Program.form.extractAndPrepareGameToUploadAsync(DonorsListView.CheckedItems[i].SubItems[Donors.GameNameIndex].Text, DonorsListView.CheckedItems[i].SubItems[Donors.PackageNameIndex].Text, vcode, false);
{
await Program.form.extractAndPrepareGameToUploadAsync(DonorsListView.CheckedItems[i].SubItems[Donors.GameNameIndex].Text, DonorsListView.CheckedItems[i].SubItems[Donors.PackageNameIndex].Text, vcode, true);
}
else
{
await Program.form.extractAndPrepareGameToUploadAsync(DonorsListView.CheckedItems[i].SubItems[Donors.GameNameIndex].Text, DonorsListView.CheckedItems[i].SubItems[Donors.PackageNameIndex].Text, vcode, false);
}
ifuploads = true;
}
}
@@ -107,8 +108,8 @@ namespace AndroidSideloader
{
MainForm.DoUpload();
}
this.Close();
}
Close();
}
private void DonorsListView_ItemChecked(object sender, ItemCheckedEventArgs e)
{
@@ -142,9 +143,9 @@ namespace AndroidSideloader
if (uncheckednewapps)
{
NewApps NewAppForm = new NewApps();
NewAppForm.ShowDialog();
_ = NewAppForm.ShowDialog();
}
this.Close();
Close();
}
private void DonorsListViewForm_MouseDown(object sender, MouseEventArgs e)
@@ -157,9 +158,9 @@ namespace AndroidSideloader
{
if (mouseDown)
{
this.Location = new Point(
(this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
this.Update();
Location = new Point(
Location.X - lastLocation.X + e.X, Location.Y - lastLocation.Y + e.Y);
Update();
}
}

View File

@@ -254,7 +254,7 @@ namespace JR.Utils.GUI.Forms
/// The form to show the customized message box.
/// It is defined as an internal class to keep the public interface of the FlexibleMessageBox clean.
/// </summary>
class FlexibleMessageBoxForm : Form
private class FlexibleMessageBoxForm : Form
{
#region Form-Designer generated code
@@ -282,128 +282,128 @@ namespace JR.Utils.GUI.Forms
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.richTextBoxMessage = new System.Windows.Forms.RichTextBox();
this.FlexibleMessageBoxFormBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.panel1 = new System.Windows.Forms.Panel();
this.pictureBoxForIcon = new System.Windows.Forms.PictureBox();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.FlexibleMessageBoxFormBindingSource)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxForIcon)).BeginInit();
this.SuspendLayout();
components = new System.ComponentModel.Container();
button1 = new System.Windows.Forms.Button();
richTextBoxMessage = new System.Windows.Forms.RichTextBox();
FlexibleMessageBoxFormBindingSource = new System.Windows.Forms.BindingSource(components);
panel1 = new System.Windows.Forms.Panel();
pictureBoxForIcon = new System.Windows.Forms.PictureBox();
button2 = new System.Windows.Forms.Button();
button3 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)FlexibleMessageBoxFormBindingSource).BeginInit();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxForIcon).BeginInit();
SuspendLayout();
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.AutoSize = true;
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button1.Location = new System.Drawing.Point(11, 67);
this.button1.MinimumSize = new System.Drawing.Size(0, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 24);
this.button1.TabIndex = 2;
this.button1.Text = "OK";
this.button1.UseVisualStyleBackColor = true;
this.button1.Visible = false;
button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
button1.AutoSize = true;
button1.DialogResult = System.Windows.Forms.DialogResult.OK;
button1.Location = new System.Drawing.Point(11, 67);
button1.MinimumSize = new System.Drawing.Size(0, 24);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(75, 24);
button1.TabIndex = 2;
button1.Text = "OK";
button1.UseVisualStyleBackColor = true;
button1.Visible = false;
//
// richTextBoxMessage
//
this.richTextBoxMessage.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.richTextBoxMessage.BackColor = System.Drawing.Color.White;
this.richTextBoxMessage.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.richTextBoxMessage.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.FlexibleMessageBoxFormBindingSource, "MessageText", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.richTextBoxMessage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.richTextBoxMessage.Location = new System.Drawing.Point(50, 26);
this.richTextBoxMessage.Margin = new System.Windows.Forms.Padding(0);
this.richTextBoxMessage.Name = "richTextBoxMessage";
this.richTextBoxMessage.ReadOnly = true;
this.richTextBoxMessage.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
this.richTextBoxMessage.Size = new System.Drawing.Size(200, 20);
this.richTextBoxMessage.TabIndex = 0;
this.richTextBoxMessage.TabStop = false;
this.richTextBoxMessage.Text = "<Message>";
this.richTextBoxMessage.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBoxMessage_LinkClicked);
richTextBoxMessage.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom
| System.Windows.Forms.AnchorStyles.Left
| System.Windows.Forms.AnchorStyles.Right;
richTextBoxMessage.BackColor = System.Drawing.Color.White;
richTextBoxMessage.BorderStyle = System.Windows.Forms.BorderStyle.None;
richTextBoxMessage.DataBindings.Add(new System.Windows.Forms.Binding("Text", FlexibleMessageBoxFormBindingSource, "MessageText", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
richTextBoxMessage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0);
richTextBoxMessage.Location = new System.Drawing.Point(50, 26);
richTextBoxMessage.Margin = new System.Windows.Forms.Padding(0);
richTextBoxMessage.Name = "richTextBoxMessage";
richTextBoxMessage.ReadOnly = true;
richTextBoxMessage.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
richTextBoxMessage.Size = new System.Drawing.Size(200, 20);
richTextBoxMessage.TabIndex = 0;
richTextBoxMessage.TabStop = false;
richTextBoxMessage.Text = "<Message>";
richTextBoxMessage.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(richTextBoxMessage_LinkClicked);
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.Controls.Add(this.pictureBoxForIcon);
this.panel1.Controls.Add(this.richTextBoxMessage);
this.panel1.Location = new System.Drawing.Point(-3, -4);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(268, 59);
this.panel1.TabIndex = 1;
panel1.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom
| System.Windows.Forms.AnchorStyles.Left
| System.Windows.Forms.AnchorStyles.Right;
panel1.BackColor = System.Drawing.Color.White;
panel1.Controls.Add(pictureBoxForIcon);
panel1.Controls.Add(richTextBoxMessage);
panel1.Location = new System.Drawing.Point(-3, -4);
panel1.Name = "panel1";
panel1.Size = new System.Drawing.Size(268, 59);
panel1.TabIndex = 1;
//
// pictureBoxForIcon
//
this.pictureBoxForIcon.BackColor = System.Drawing.Color.Transparent;
this.pictureBoxForIcon.Location = new System.Drawing.Point(15, 19);
this.pictureBoxForIcon.Name = "pictureBoxForIcon";
this.pictureBoxForIcon.Size = new System.Drawing.Size(32, 32);
this.pictureBoxForIcon.TabIndex = 8;
this.pictureBoxForIcon.TabStop = false;
pictureBoxForIcon.BackColor = System.Drawing.Color.Transparent;
pictureBoxForIcon.Location = new System.Drawing.Point(15, 19);
pictureBoxForIcon.Name = "pictureBoxForIcon";
pictureBoxForIcon.Size = new System.Drawing.Size(32, 32);
pictureBoxForIcon.TabIndex = 8;
pictureBoxForIcon.TabStop = false;
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button2.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button2.Location = new System.Drawing.Point(92, 67);
this.button2.MinimumSize = new System.Drawing.Size(0, 24);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 24);
this.button2.TabIndex = 3;
this.button2.Text = "OK";
this.button2.UseVisualStyleBackColor = true;
this.button2.Visible = false;
button2.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
button2.DialogResult = System.Windows.Forms.DialogResult.OK;
button2.Location = new System.Drawing.Point(92, 67);
button2.MinimumSize = new System.Drawing.Size(0, 24);
button2.Name = "button2";
button2.Size = new System.Drawing.Size(75, 24);
button2.TabIndex = 3;
button2.Text = "OK";
button2.UseVisualStyleBackColor = true;
button2.Visible = false;
//
// button3
//
this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button3.AutoSize = true;
this.button3.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button3.Location = new System.Drawing.Point(173, 67);
this.button3.MinimumSize = new System.Drawing.Size(0, 24);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 24);
this.button3.TabIndex = 0;
this.button3.Text = "OK";
this.button3.UseVisualStyleBackColor = true;
this.button3.Visible = false;
button3.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
button3.AutoSize = true;
button3.DialogResult = System.Windows.Forms.DialogResult.OK;
button3.Location = new System.Drawing.Point(173, 67);
button3.MinimumSize = new System.Drawing.Size(0, 24);
button3.Name = "button3";
button3.Size = new System.Drawing.Size(75, 24);
button3.TabIndex = 0;
button3.Text = "OK";
button3.UseVisualStyleBackColor = true;
button3.Visible = false;
//
// FlexibleMessageBoxForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(260, 102);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button1);
this.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.FlexibleMessageBoxFormBindingSource, "CaptionText", true));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(276, 140);
this.Name = "FlexibleMessageBoxForm";
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "<Caption>";
this.Shown += new System.EventHandler(this.FlexibleMessageBoxForm_Shown);
((System.ComponentModel.ISupportInitialize)(this.FlexibleMessageBoxFormBindingSource)).EndInit();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxForIcon)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
ClientSize = new System.Drawing.Size(260, 102);
Controls.Add(button3);
Controls.Add(button2);
Controls.Add(panel1);
Controls.Add(button1);
DataBindings.Add(new System.Windows.Forms.Binding("Text", FlexibleMessageBoxFormBindingSource, "CaptionText", true));
MaximizeBox = false;
MinimizeBox = false;
MinimumSize = new System.Drawing.Size(276, 140);
Name = "FlexibleMessageBoxForm";
ShowIcon = false;
SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
Text = "<Caption>";
Shown += new System.EventHandler(FlexibleMessageBoxForm_Shown);
((System.ComponentModel.ISupportInitialize)FlexibleMessageBoxFormBindingSource).EndInit();
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxForIcon).EndInit();
ResumeLayout(false);
PerformLayout();
this.Activate();
Activate();
}
private System.Windows.Forms.Button button1;
@@ -419,19 +419,19 @@ namespace JR.Utils.GUI.Forms
#region Private constants
//These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox)
private static readonly String STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n";
private static readonly String STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " ";
private static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n";
private static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " ";
//These are the possible buttons (in a standard MessageBox)
private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE };
//These are the buttons texts for different languages.
//If you want to add a new language, add it here and in the GetButtonText-Function
private enum TwoLetterISOLanguageID { en, de, es, it };
private static readonly String[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language
private static readonly String[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" };
private static readonly String[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" };
private static readonly String[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" };
private static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore" }; //Note: This is also the fallback language
private static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren" };
private static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar" };
private static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora" };
#endregion
@@ -439,7 +439,7 @@ namespace JR.Utils.GUI.Forms
private MessageBoxDefaultButton defaultButton;
private int visibleButtonsCount;
private TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en;
private readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en;
#endregion
@@ -453,10 +453,10 @@ namespace JR.Utils.GUI.Forms
InitializeComponent();
//Try to evaluate the language. If this fails, the fallback language English will be used
Enum.TryParse<TwoLetterISOLanguageID>(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out this.languageID);
_ = Enum.TryParse<TwoLetterISOLanguageID>(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, out languageID);
this.KeyPreview = true;
this.KeyUp += FlexibleMessageBoxForm_KeyUp;
KeyPreview = true;
KeyUp += FlexibleMessageBoxForm_KeyUp;
}
#endregion
@@ -470,9 +470,12 @@ namespace JR.Utils.GUI.Forms
/// <returns>The string rows as 1-dimensional array</returns>
private static string[] GetStringRows(string message)
{
if (string.IsNullOrEmpty(message)) return null;
if (string.IsNullOrEmpty(message))
{
return null;
}
var messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None);
string[] messageRows = message.Split(new char[] { '\n' }, StringSplitOptions.None);
return messageRows;
}
@@ -484,15 +487,15 @@ namespace JR.Utils.GUI.Forms
/// <returns>The button text</returns>
private string GetButtonText(ButtonID buttonID)
{
var buttonTextArrayIndex = Convert.ToInt32(buttonID);
switch (this.languageID)
int buttonTextArrayIndex = Convert.ToInt32(buttonID);
switch (languageID)
{
case TwoLetterISOLanguageID.de: return BUTTON_TEXTS_GERMAN_DE[buttonTextArrayIndex];
case TwoLetterISOLanguageID.es: return BUTTON_TEXTS_SPANISH_ES[buttonTextArrayIndex];
case TwoLetterISOLanguageID.it: return BUTTON_TEXTS_ITALIAN_IT[buttonTextArrayIndex];
default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex];
default: return BUTTON_TEXTS_ENGLISH_EN[buttonTextArrayIndex];
}
}
@@ -509,10 +512,7 @@ namespace JR.Utils.GUI.Forms
const double MIN_FACTOR = 0.2;
const double MAX_FACTOR = 1.0;
if (workingAreaFactor < MIN_FACTOR) return MIN_FACTOR;
if (workingAreaFactor > MAX_FACTOR) return MAX_FACTOR;
return workingAreaFactor;
return workingAreaFactor < MIN_FACTOR ? MIN_FACTOR : workingAreaFactor > MAX_FACTOR ? MAX_FACTOR : workingAreaFactor;
}
/// <summary>
@@ -526,10 +526,10 @@ namespace JR.Utils.GUI.Forms
//If no owner given: Center on current screen
if (owner == null)
{
var screen = Screen.FromPoint(Cursor.Position);
Screen screen = Screen.FromPoint(Cursor.Position);
flexibleMessageBoxForm.StartPosition = FormStartPosition.Manual;
flexibleMessageBoxForm.Left = screen.Bounds.Left + screen.Bounds.Width / 2 - flexibleMessageBoxForm.Width / 2;
flexibleMessageBoxForm.Top = screen.Bounds.Top + screen.Bounds.Height / 2 - flexibleMessageBoxForm.Height / 2;
flexibleMessageBoxForm.Left = screen.Bounds.Left + (screen.Bounds.Width / 2) - (flexibleMessageBoxForm.Width / 2);
flexibleMessageBoxForm.Top = screen.Bounds.Top + (screen.Bounds.Height / 2) - (flexibleMessageBoxForm.Height / 2);
}
}
@@ -547,21 +547,24 @@ namespace JR.Utils.GUI.Forms
Convert.ToInt32(SystemInformation.WorkingArea.Height * FlexibleMessageBoxForm.GetCorrectedWorkingAreaFactor(MAX_HEIGHT_FACTOR)));
//Get rows. Exit if there are no rows to render...
var stringRows = GetStringRows(text);
if (stringRows == null) return;
string[] stringRows = GetStringRows(text);
if (stringRows == null)
{
return;
}
//Calculate whole text height
var textHeight = TextRenderer.MeasureText(text, FONT).Height;
int textHeight = TextRenderer.MeasureText(text, FONT).Height;
//Calculate width for longest text line
const int SCROLLBAR_WIDTH_OFFSET = 15;
var longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width);
var captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width;
var textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth);
int longestTextRowWidth = stringRows.Max(textForRow => TextRenderer.MeasureText(textForRow, FONT).Width);
int captionWidth = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width;
int textWidth = Math.Max(longestTextRowWidth + SCROLLBAR_WIDTH_OFFSET, captionWidth);
//Calculate margins
var marginWidth = flexibleMessageBoxForm.Width - flexibleMessageBoxForm.richTextBoxMessage.Width;
var marginHeight = flexibleMessageBoxForm.Height - flexibleMessageBoxForm.richTextBoxMessage.Height;
int marginWidth = flexibleMessageBoxForm.Width - flexibleMessageBoxForm.richTextBoxMessage.Width;
int marginHeight = flexibleMessageBoxForm.Height - flexibleMessageBoxForm.richTextBoxMessage.Height;
//Set calculated dialog size (if the calculated values exceed the maximums, they were cut by windows forms automatically)
flexibleMessageBoxForm.Size = new Size(textWidth + marginWidth,
@@ -625,7 +628,7 @@ namespace JR.Utils.GUI.Forms
flexibleMessageBoxForm.button3.Visible = true;
flexibleMessageBoxForm.button3.Text = flexibleMessageBoxForm.GetButtonText(ButtonID.IGNORE);
flexibleMessageBoxForm.button3.DialogResult = DialogResult.Ignore;
flexibleMessageBoxForm.ControlBox = false;
break;
@@ -715,11 +718,11 @@ namespace JR.Utils.GUI.Forms
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void FlexibleMessageBoxForm_Shown(object sender, EventArgs e)
{
int buttonIndexToFocus = 1;
Button buttonToFocus;
int buttonIndexToFocus;
//Set the default button...
switch (this.defaultButton)
switch (defaultButton)
{
case MessageBoxDefaultButton.Button1:
default:
@@ -733,22 +736,14 @@ namespace JR.Utils.GUI.Forms
break;
}
if (buttonIndexToFocus > this.visibleButtonsCount) buttonIndexToFocus = this.visibleButtonsCount;
if (buttonIndexToFocus == 3)
if (buttonIndexToFocus > visibleButtonsCount)
{
buttonToFocus = this.button3;
}
else if (buttonIndexToFocus == 2)
{
buttonToFocus = this.button2;
}
else
{
buttonToFocus = this.button1;
buttonIndexToFocus = visibleButtonsCount;
}
buttonToFocus.Focus();
buttonToFocus = buttonIndexToFocus == 3 ? button3 : buttonIndexToFocus == 2 ? button2 : button1;
_ = buttonToFocus.Focus();
}
/// <summary>
@@ -761,7 +756,7 @@ namespace JR.Utils.GUI.Forms
try
{
Cursor.Current = Cursors.WaitCursor;
Process.Start(e.LinkText);
_ = Process.Start(e.LinkText);
}
catch (Exception)
{
@@ -780,20 +775,20 @@ namespace JR.Utils.GUI.Forms
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
void FlexibleMessageBoxForm_KeyUp(object sender, KeyEventArgs e)
private void FlexibleMessageBoxForm_KeyUp(object sender, KeyEventArgs e)
{
//Handle standard key strikes for clipboard copy: "Ctrl + C" and "Ctrl + Insert"
if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert))
{
var buttonsTextLine = (this.button1.Visible ? this.button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty)
+ (this.button2.Visible ? this.button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty)
+ (this.button3.Visible ? this.button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty);
string buttonsTextLine = (button1.Visible ? button1.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty)
+ (button2.Visible ? button2.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty)
+ (button3.Visible ? button3.Text + STANDARD_MESSAGEBOX_SEPARATOR_SPACES : string.Empty);
//Build same clipboard text like the standard .Net MessageBox
var textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES
+ this.Text + Environment.NewLine
string textForClipboard = STANDARD_MESSAGEBOX_SEPARATOR_LINES
+ Text + Environment.NewLine
+ STANDARD_MESSAGEBOX_SEPARATOR_LINES
+ this.richTextBoxMessage.Text + Environment.NewLine
+ richTextBoxMessage.Text + Environment.NewLine
+ STANDARD_MESSAGEBOX_SEPARATOR_LINES
+ buttonsTextLine.Replace("&", string.Empty) + Environment.NewLine
+ STANDARD_MESSAGEBOX_SEPARATOR_LINES;
@@ -834,12 +829,14 @@ namespace JR.Utils.GUI.Forms
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
{
//Create a new instance of the FlexibleMessageBox form
var flexibleMessageBoxForm = new FlexibleMessageBoxForm();
flexibleMessageBoxForm.ShowInTaskbar = false;
FlexibleMessageBoxForm flexibleMessageBoxForm = new FlexibleMessageBoxForm
{
ShowInTaskbar = false,
//Bind the caption and the message text
flexibleMessageBoxForm.CaptionText = caption;
flexibleMessageBoxForm.MessageText = text;
//Bind the caption and the message text
CaptionText = caption,
MessageText = text
};
flexibleMessageBoxForm.FlexibleMessageBoxFormBindingSource.DataSource = flexibleMessageBoxForm;
//Set the buttons visibilities and texts. Also set a default button.

File diff suppressed because it is too large Load Diff

View File

@@ -16,10 +16,7 @@ namespace AndroidSideloader.Models
public string Password
{
get => password;
set
{
password = Encoding.UTF8.GetString(Convert.FromBase64String(value));
}
set => password = Encoding.UTF8.GetString(Convert.FromBase64String(value));
}
}
}

View File

@@ -1,11 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AndroidSideloader
@@ -30,10 +25,10 @@ namespace AndroidSideloader
{
if (mouseDown)
{
this.Location = new Point(
(this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
Location = new Point(
Location.X - lastLocation.X + e.X, Location.Y - lastLocation.Y + e.Y);
this.Update();
Update();
}
}
@@ -59,7 +54,7 @@ namespace AndroidSideloader
}
}
MainForm.newpackageupload();
this.Close();
Close();
}
private void NewApps_Load(object sender, EventArgs e)
@@ -71,7 +66,9 @@ namespace AndroidSideloader
{
ListViewItem NGame = new ListViewItem(release);
if (!NewAppList.Contains(NGame))
NewAppList.Add(NGame);
{
NewAppList.Add(NGame);
}
}
ListViewItem[] arr = NewAppList.ToArray();
NewAppsListView.BeginUpdate();

View File

@@ -1,19 +1,18 @@
using System;
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
using System.Drawing.Drawing2D;
using System.Security.Permissions;
using System.Windows.Forms;
namespace AndroidSideloader
{
static class Program
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
static void Main()
private static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
@@ -26,7 +25,8 @@ namespace AndroidSideloader
//form.Show();
}
public static MainForm form;
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
private static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
string date_time = DateTime.Now.ToString("dddd, MMMM dd @ hh:mmtt (UTC)");

View File

@@ -1,5 +1,4 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following

View File

@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace AndroidSideloader
@@ -28,41 +25,42 @@ namespace AndroidSideloader
if (RefreshRateComboBox.SelectedIndex != -1)
{
ADB.WakeDevice();
ADB.RunAdbCommandToString($"shell setprop debug.oculus.refreshRate {RefreshRateComboBox.SelectedItem.ToString()}");
ADB.RunAdbCommandToString($"shell settings put global 90hz_global {RefreshRateComboBox.SelectedIndex}");
ADB.RunAdbCommandToString($"shell settings put global 90hzglobal {RefreshRateComboBox.SelectedIndex}");
_ = ADB.RunAdbCommandToString($"shell setprop debug.oculus.refreshRate {RefreshRateComboBox.SelectedItem}");
_ = ADB.RunAdbCommandToString($"shell settings put global 90hz_global {RefreshRateComboBox.SelectedIndex}");
_ = ADB.RunAdbCommandToString($"shell settings put global 90hzglobal {RefreshRateComboBox.SelectedIndex}");
ChangesMade = true;
}
if (TextureResTextBox.Text.Length > 0)
{
ADB.WakeDevice();
int result;
Int32.TryParse(TextureResTextBox.Text, out result);
ADB.RunAdbCommandToString($"shell settings put global texture_size_Global {TextureResTextBox.Text}");
ADB.RunAdbCommandToString($"shell setprop debug.oculus.textureWidth {TextureResTextBox.Text}");
ADB.RunAdbCommandToString($"shell setprop debug.oculus.textureHeight {TextureResTextBox.Text}");
_ = int.TryParse(TextureResTextBox.Text, out _);
_ = ADB.RunAdbCommandToString($"shell settings put global texture_size_Global {TextureResTextBox.Text}");
_ = ADB.RunAdbCommandToString($"shell setprop debug.oculus.textureWidth {TextureResTextBox.Text}");
_ = ADB.RunAdbCommandToString($"shell setprop debug.oculus.textureHeight {TextureResTextBox.Text}");
ChangesMade = true;
}
if (CPUComboBox.SelectedIndex != -1)
{
ADB.RunAdbCommandToString($"shell setprop debug.oculus.cpuLevel {CPUComboBox.SelectedItem.ToString()}");
_ = ADB.RunAdbCommandToString($"shell setprop debug.oculus.cpuLevel {CPUComboBox.SelectedItem}");
ChangesMade = true;
}
if (GPUComboBox.SelectedIndex != -1)
{
ADB.RunAdbCommandToString($"shell setprop debug.oculus.gpuLevel {GPUComboBox.SelectedItem.ToString()}");
_ = ADB.RunAdbCommandToString($"shell setprop debug.oculus.gpuLevel {GPUComboBox.SelectedItem}");
ChangesMade = true;
}
if (ChangesMade)
MessageBox.Show("Settings applied!");
{
_ = MessageBox.Show("Settings applied!");
}
}
public static void setLength(Int32 value)
public static void setLength(int value)
{
result = new string[value];
}
@@ -71,19 +69,16 @@ namespace AndroidSideloader
public void ResetQU_click(object sender, EventArgs e)
{
ResBox.Text = ("0");
UsrBox.Text = ("Change Me");
FOVx.Text = ("0");
FOVy.Text = ("0");
ResBox.Text = "0";
UsrBox.Text = "Change Me";
FOVx.Text = "0";
FOVy.Text = "0";
QURfrRt.SelectedIndex = 0;
}
private void DeleteShots_CheckedChanged(object sender, EventArgs e)
{
if (DeleteShots.Checked)
delsh = true;
else
delsh = false;
delsh = DeleteShots.Checked;
}
private void QUon_CheckedChanged(object sender, EventArgs e)
{
@@ -127,7 +122,7 @@ namespace AndroidSideloader
label10.Visible = false;
deleteButton.Visible = false;
Properties.Settings.Default.QUturnedon = false;
MessageBox.Show("Ok, Deleted your custom settings file.\nIf you would like to re-enable return here and apply settings again");
_ = MessageBox.Show("Ok, Deleted your custom settings file.\nIf you would like to re-enable return here and apply settings again");
File.Delete($"{Environment.CurrentDirectory}\\Config.Json");
File.Delete($"{Environment.CurrentDirectory}\\delete_settings");
}
@@ -146,7 +141,7 @@ namespace AndroidSideloader
{
settingsexist = true;
MessageBox.Show("OK, any -QU packages installed will have these settings applied!\nTo delete settings: goto main app window, select a game with top menu, and click \"Remove QU Setting\"");
_ = MessageBox.Show("OK, any -QU packages installed will have these settings applied!\nTo delete settings: goto main app window, select a game with top menu, and click \"Remove QU Setting\"");
if (QUon.Checked)
{
Properties.Settings.Default.QUturnedon = true;
@@ -155,16 +150,16 @@ namespace AndroidSideloader
int x = r.Next(999999999);
int y = r.Next(9999999);
var sum = ((long)y * (long)1000000000) + (long)x;
long sum = (y * (long)1000000000) + x;
int x2 = r.Next(999999999);
int y2 = r.Next(9999999);
var sum2 = ((long)y2 * (long)1000000000) + (long)x2;
long sum2 = (y2 * (long)1000000000) + x2;
QUSon = true;
string selected = this.QURfrRt.GetItemText(this.QURfrRt.SelectedItem);
string selected = QURfrRt.GetItemText(QURfrRt.SelectedItem);
Properties.Settings.Default.QUString = $"\"refresh_rate\":{selected},\"eye_texture_width\":{ResBox.Text},\"fov_x\":{FOVx.Text},\"fov_y\":{FOVy.Text},\"username\":\"{UsrBox.Text}\"}}";
Properties.Settings.Default.QUStringF = $"{{\"user_id\":{sum},\"app_id\":\"{sum2}\",";
@@ -177,14 +172,14 @@ namespace AndroidSideloader
{
Properties.Settings.Default.QUturnedon = false;
}
}
private void QuestForm_FormClosed(object sender, FormClosedEventArgs e)
}
private void QuestForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (QUon.Checked)
{
@@ -209,10 +204,7 @@ namespace AndroidSideloader
}
private void QuestForm_Load(object sender, EventArgs e)
{
if (Properties.Settings.Default.delsh)
DeleteShots.Checked = true;
else
DeleteShots.Checked = false;
DeleteShots.Checked = Properties.Settings.Default.delsh;
if (Properties.Settings.Default.QUsett)
{
ResBox.Text = Properties.Settings.Default.QUres;
@@ -222,7 +214,9 @@ namespace AndroidSideloader
QURfrRt.Text = Properties.Settings.Default.QUhz;
QUon.Checked = true;
if (settingsexist)
QUSon = true;
{
QUSon = true;
}
}
GlobalUsername.Text = Properties.Settings.Default.GlobalUsername;
}
@@ -255,14 +249,14 @@ namespace AndroidSideloader
private void QURfrRt_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.QURfrRt.GetItemText(this.QURfrRt.SelectedItem);
string selected = QURfrRt.GetItemText(QURfrRt.SelectedItem);
Properties.Settings.Default.QUhz = selected;
Properties.Settings.Default.Save();
}
private void DeleteButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Ok, Deleted your custom settings file.\nIf you would like to re-enable return here and apply settings again");
_ = MessageBox.Show("Ok, Deleted your custom settings file.\nIf you would like to re-enable return here and apply settings again");
File.Delete($"{Properties.Settings.Default.MainDir}\\Config.Json");
}
private void questPics_Click(object sender, EventArgs e)
@@ -270,54 +264,60 @@ namespace AndroidSideloader
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!Directory.Exists($"{path}\\Quest ScreenShots"))
Directory.CreateDirectory($"{path}\\Quest ScreenShots");
MessageBox.Show("Please wait until you get the message that the transfer has finished.");
{
_ = Directory.CreateDirectory($"{path}\\Quest ScreenShots");
}
_ = MessageBox.Show("Please wait until you get the message that the transfer has finished.");
ADB.WakeDevice();
Program.form.ChangeTitle("Pulling files...");
ADB.RunAdbCommandToString($"pull \"/sdcard/Oculus/Screenshots\" \"{path}\\Quest ScreenShots\"");
_ = ADB.RunAdbCommandToString($"pull \"/sdcard/Oculus/Screenshots\" \"{path}\\Quest ScreenShots\"");
if (delsh)
{
DialogResult dialogResult = MessageBox.Show("You have chosen to delete files from headset after transferring, so be sure to move them from your desktop to somewhere safe!", "Warning!", MessageBoxButtons.OKCancel);
if (dialogResult == DialogResult.OK)
{
ADB.RunAdbCommandToString("shell rm -r /sdcard/Oculus/Screenshots");
ADB.RunAdbCommandToString("shell mkdir /sdcard/Oculus/Screenshots");
{
_ = ADB.RunAdbCommandToString("shell rm -r /sdcard/Oculus/Screenshots");
_ = ADB.RunAdbCommandToString("shell mkdir /sdcard/Oculus/Screenshots");
}
}
MessageBox.Show("Transfer finished! ScreenShots can be found in a folder named Quest Screenshots on your desktop!");
_ = MessageBox.Show("Transfer finished! ScreenShots can be found in a folder named Quest Screenshots on your desktop!");
Program.form.ChangeTitle("Done!");
}
private void questVids_Click(object sender, EventArgs e)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!Directory.Exists($"{path}\\Quest VideoShots"))
Directory.CreateDirectory($"{path}\\Quest VideoShots");
MessageBox.Show("Please wait until you get the message that the transfer has finished.");
{
_ = Directory.CreateDirectory($"{path}\\Quest VideoShots");
}
_ = MessageBox.Show("Please wait until you get the message that the transfer has finished.");
ADB.WakeDevice();
Program.form.ChangeTitle("Pulling files...");
ADB.RunAdbCommandToString($"pull \"/sdcard/Oculus/Videoshots\" \"{path}\\Quest VideoShots\"");
_ = ADB.RunAdbCommandToString($"pull \"/sdcard/Oculus/Videoshots\" \"{path}\\Quest VideoShots\"");
if (delsh)
{
DialogResult dialogResult = MessageBox.Show("You have chosen to delete files from headset after transferring, so be sure to move them from your desktop to somewhere safe!", "Warning!", MessageBoxButtons.OKCancel);
if (dialogResult == DialogResult.OK)
{
ADB.RunAdbCommandToString("shell rm -r /sdcard/Oculus/Videoshots");
ADB.RunAdbCommandToString("shell mkdir /sdcard/Oculus/Videoshots");
_ = ADB.RunAdbCommandToString("shell rm -r /sdcard/Oculus/Videoshots");
_ = ADB.RunAdbCommandToString("shell mkdir /sdcard/Oculus/Videoshots");
}
}
MessageBox.Show("Transfer finished! VideoShots can be found in a folder named Quest VideoShots on your desktop!");
_ = MessageBox.Show("Transfer finished! VideoShots can be found in a folder named Quest VideoShots on your desktop!");
Program.form.ChangeTitle("Done!");
}
private void button3_Click(object sender, EventArgs e)
{
if (GlobalUsername.Text.Contains(" "))
{
MessageBox.Show("Usernames with a space are not permitted.", "Detected a space in username!");
_ = MessageBox.Show("Usernames with a space are not permitted.", "Detected a space in username!");
}
else
{
ADB.RunAdbCommandToString($"shell settings put global username {GlobalUsername.Text}");
MessageBox.Show($"Username set as {GlobalUsername.Text}", "Success");
_ = ADB.RunAdbCommandToString($"shell settings put global username {GlobalUsername.Text}");
_ = MessageBox.Show($"Username set as {GlobalUsername.Text}", "Success");
}
}
@@ -326,14 +326,14 @@ namespace AndroidSideloader
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
Close();
}
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
Close();
return true;
}
return base.ProcessDialogKey(keyData);
@@ -341,17 +341,14 @@ namespace AndroidSideloader
private void WifiWake_Click(object sender, EventArgs e)
{
ADB.RunAdbCommandToString("shell settings put global wifi_wakeup_available 1");
ADB.RunAdbCommandToString("shell settings put global wifi_wakeup_enabled 1");
MessageBox.Show("Wake on Wifi enabled!\n\nNOTE: This requires having wireless ADB enabled to work. (Obviously)");
_ = ADB.RunAdbCommandToString("shell settings put global wifi_wakeup_available 1");
_ = ADB.RunAdbCommandToString("shell settings put global wifi_wakeup_enabled 1");
_ = MessageBox.Show("Wake on Wifi enabled!\n\nNOTE: This requires having wireless ADB enabled to work. (Obviously)");
}
private void GlobalUsername_TextChanged(object sender, EventArgs e)
{
if (GlobalUsername.TextLength > 0)
button3.Enabled = true;
else
button3.Enabled = false;
button3.Enabled = GlobalUsername.TextLength > 0;
Properties.Settings.Default.GlobalUsername = GlobalUsername.Text;
Properties.Settings.Default.Save();
}

View File

@@ -1,19 +1,21 @@
using System;
using JR.Utils.GUI.Forms;
using System;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Text;
using System.Windows.Forms;
using JR.Utils.GUI.Forms;
namespace AndroidSideloader
{
class RCLONE
internal class RCLONE
{
//Kill all rclone, using a static rclone variable doesn't work for some reason #tofix
public static void killRclone()
{
foreach (var process in Process.GetProcessesByName("rclone"))
foreach (Process process in Process.GetProcessesByName("rclone"))
{
process.Kill();
}
}
//For custom configs that use a password
@@ -32,8 +34,8 @@ namespace AndroidSideloader
public static string rclonepw = "";
private static Process rclone = new Process();
private static readonly Process rclone = new Process();
//Run rclone command
public static ProcessOutput runRcloneCommand_DownloadConfig(string command, string BandwidthLimit = "")
{
@@ -61,13 +63,22 @@ namespace AndroidSideloader
//set rclonepw
if (rclonepw.Length > 0)
{
command += " --ask-password=false";
}
string logcmd = Utilities.StringUtilities.RemoveEverythingBeforeFirst(command, "rclone.exe");
if (logcmd.Contains($"\"{Properties.Settings.Default.CurrentLogPath}\""))
{
logcmd = logcmd.Replace($"\"{Properties.Settings.Default.CurrentLogPath}\"", $"\"{Properties.Settings.Default.CurrentLogName}\"");
}
if (logcmd.Contains(Environment.CurrentDirectory))
{
logcmd = logcmd.Replace($"{Environment.CurrentDirectory}", $"CurrentDirectory");
Logger.Log($"Running Rclone command: {logcmd}");
}
_ = Logger.Log($"Running Rclone command: {logcmd}");
rclone.StartInfo.FileName = Environment.CurrentDirectory + "\\rclone\\rclone.exe";
rclone.StartInfo.Arguments = command;
@@ -78,9 +89,12 @@ namespace AndroidSideloader
rclone.StartInfo.CreateNoWindow = true;
//On debug we want to see when rclone is open
if (MainForm.debugMode == true)
{
rclone.StartInfo.CreateNoWindow = false;
}
rclone.StartInfo.UseShellExecute = false;
rclone.Start();
_ = rclone.Start();
rclone.StandardInput.WriteLine(command);
rclone.StandardInput.Flush();
rclone.StandardInput.Close();
@@ -91,7 +105,7 @@ namespace AndroidSideloader
if (error.Contains("There is not enough space"))
{
FlexibleMessageBox.Show($"There isn't enough disk space to download this game.\r\nPlease ensure you have at least 200MB more the game size available in {Environment.CurrentDirectory} and try again.",
_ = FlexibleMessageBox.Show($"There isn't enough disk space to download this game.\r\nPlease ensure you have at least 200MB more the game size available in {Environment.CurrentDirectory} and try again.",
"NOT ENOUGH SPACE",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
@@ -105,7 +119,7 @@ namespace AndroidSideloader
try
{
Program.form.SwitchMirrors();
}
catch
{
@@ -123,15 +137,15 @@ namespace AndroidSideloader
{
if (!string.IsNullOrWhiteSpace(error))
{
Logger.Log($"Rclone error: {error}\n");
_ = Logger.Log($"Rclone error: {error}\n");
}
if (!string.IsNullOrWhiteSpace(output))
{
Logger.Log($"Rclone Output: {output}");
_ = Logger.Log($"Rclone Output: {output}");
}
}
return prcoutput;
return prcoutput;
}
public static ProcessOutput runRcloneCommand_UploadConfig(string command, string BandwidthLimit = "")
@@ -144,7 +158,6 @@ namespace AndroidSideloader
ProcessOutput prcoutput = new ProcessOutput();
//Rclone output is unicode, else it will show garbage instead of unicode characters
rclone.StartInfo.StandardOutputEncoding = Encoding.UTF8;
string originalCommand = command;
//set bandwidth limit
if (BandwidthLimit.Length > 0)
@@ -160,10 +173,16 @@ namespace AndroidSideloader
string logcmd = Utilities.StringUtilities.RemoveEverythingBeforeFirst(command, "rclone.exe");
if (logcmd.Contains($"\"{Properties.Settings.Default.CurrentLogPath}\""))
{
logcmd = logcmd.Replace($"\"{Properties.Settings.Default.CurrentLogPath}\"", $"\"{Properties.Settings.Default.CurrentLogName}\"");
}
if (logcmd.Contains(Environment.CurrentDirectory))
{
logcmd = logcmd.Replace($"{Environment.CurrentDirectory}", $"CurrentDirectory");
Logger.Log($"Running Rclone command: {logcmd}");
}
_ = Logger.Log($"Running Rclone command: {logcmd}");
command += " --checkers 0 --no-check-dest --retries 1";
@@ -176,9 +195,12 @@ namespace AndroidSideloader
rclone.StartInfo.CreateNoWindow = true;
//On debug we want to see when rclone is open
if (MainForm.debugMode == true)
{
rclone.StartInfo.CreateNoWindow = false;
}
rclone.StartInfo.UseShellExecute = false;
rclone.Start();
_ = rclone.Start();
rclone.StandardInput.WriteLine(command);
rclone.StandardInput.Flush();
rclone.StandardInput.Close();
@@ -190,7 +212,7 @@ namespace AndroidSideloader
//if there is one of these errors, we switch the mirrors
if (error.Contains("400 Bad Request") || error.Contains("cannot fetch token") || error.Contains("authError") || error.Contains("quota") || error.Contains("exceeded") || error.Contains("directory not found") || error.Contains("Failed to"))
{
Logger.Log(error);
_ = Logger.Log(error);
return new ProcessOutput("Upload Failed.", "Upload failed.");
}
else
@@ -203,12 +225,12 @@ namespace AndroidSideloader
{
if (!string.IsNullOrWhiteSpace(error))
{
Logger.Log($"Rclone error: {error}\n");
_ = Logger.Log($"Rclone error: {error}\n");
}
if (!string.IsNullOrWhiteSpace(output))
{
Logger.Log($"Rclone Output: {output}");
_ = Logger.Log($"Rclone Output: {output}");
}
}
return prcoutput;
@@ -224,7 +246,6 @@ namespace AndroidSideloader
ProcessOutput prcoutput = new ProcessOutput();
//Rclone output is unicode, else it will show garbage instead of unicode characters
rclone.StartInfo.StandardOutputEncoding = Encoding.UTF8;
string originalCommand = command;
//set bandwidth limit
if (BandwidthLimit.Length > 0)
@@ -234,10 +255,16 @@ namespace AndroidSideloader
string logcmd = Utilities.StringUtilities.RemoveEverythingBeforeFirst(command, "rclone.exe");
if (logcmd.Contains($"\"{Properties.Settings.Default.CurrentLogPath}\""))
{
logcmd = logcmd.Replace($"\"{Properties.Settings.Default.CurrentLogPath}\"", $"\"{Properties.Settings.Default.CurrentLogName}\"");
}
if (logcmd.Contains(Environment.CurrentDirectory))
{
logcmd = logcmd.Replace($"{Environment.CurrentDirectory}", $"CurrentDirectory");
Logger.Log($"Running Rclone command: {logcmd}");
}
_ = Logger.Log($"Running Rclone command: {logcmd}");
//set http source & args
command += $" --http-url {MainForm.PublicConfigFile.BaseUri} {MainForm.PublicMirrorExtraArgs}";
@@ -252,10 +279,12 @@ namespace AndroidSideloader
//On debug we want to see when rclone is open
if (MainForm.debugMode == true)
{
rclone.StartInfo.CreateNoWindow = false;
}
rclone.StartInfo.UseShellExecute = false;
rclone.Start();
_ = rclone.Start();
rclone.StandardInput.WriteLine(command);
rclone.StandardInput.Flush();
rclone.StandardInput.Close();
@@ -266,7 +295,7 @@ namespace AndroidSideloader
if (error.Contains("There is not enough space"))
{
FlexibleMessageBox.Show($"There isn't enough disk space to download this game.\r\nPlease ensure you have at least 2x the game size available in {Environment.CurrentDirectory} and try again.",
_ = FlexibleMessageBox.Show($"There isn't enough disk space to download this game.\r\nPlease ensure you have at least 2x the game size available in {Environment.CurrentDirectory} and try again.",
"NOT ENOUGH SPACE",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
@@ -281,7 +310,7 @@ namespace AndroidSideloader
|| error.Contains("directory not found")
|| error.Contains("Failed to"))
{
Logger.Log(error);
_ = Logger.Log(error);
return new ProcessOutput("Failed to fetch from public mirror.", "Failed to fetch from public mirror.");
}
else
@@ -294,12 +323,12 @@ namespace AndroidSideloader
{
if (!string.IsNullOrWhiteSpace(error))
{
Logger.Log($"Rclone error: {error}\n");
_ = Logger.Log($"Rclone error: {error}\n");
}
if (!string.IsNullOrWhiteSpace(output))
{
Logger.Log($"Rclone Output: {output}");
_ = Logger.Log($"Rclone Output: {output}");
}
}

View File

@@ -10,17 +10,16 @@ namespace AndroidSideloader
public class RoundButton : Control, IButtonControl
{
#region Variables
int radius;
bool transparency;
MouseState state;
RoundedRectangleF roundedRect;
Color inactive1, inactive2, active1, active2;
private int radius;
private MouseState state;
private RoundedRectangleF roundedRect;
private Color inactive1, inactive2, active1, active2;
private Color strokeColor;
private bool stroke;
public bool Stroke
{
get { return stroke; }
get => stroke;
set
{
stroke = value;
@@ -30,7 +29,7 @@ namespace AndroidSideloader
public Color StrokeColor
{
get { return strokeColor; }
get => strokeColor;
set
{
strokeColor = value;
@@ -61,21 +60,23 @@ namespace AndroidSideloader
ForeColor = Color.Black;
Font = new System.Drawing.Font("Comic Sans MS", 10, FontStyle.Bold);
state = MouseState.Leave;
transparency = false;
Transparency = false;
}
#endregion
#region Events
protected override void OnPaint(PaintEventArgs e)
{
#region Transparency
if (transparency)
if (Transparency)
{
Transparenter.MakeTransparent(this, e.Graphics);
}
#endregion
#region Drawing
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
roundedRect = new RoundedRectangleF(Width, Height, radius);
e.Graphics.FillRectangle(Brushes.Transparent, this.ClientRectangle);
e.Graphics.FillRectangle(Brushes.Transparent, ClientRectangle);
int R1 = (active1.R + inactive1.R) / 2;
int G1 = (active1.G + inactive1.G) / 2;
@@ -87,21 +88,38 @@ namespace AndroidSideloader
Rectangle rect = new Rectangle(0, 0, Width, Height);
if (this.Enabled)
if (Enabled)
{
if (state == MouseState.Leave)
{
using (LinearGradientBrush inactiveGB = new LinearGradientBrush(rect, inactive1, inactive2, 90f))
{
e.Graphics.FillPath(inactiveGB, roundedRect.Path);
}
}
else if (state == MouseState.Enter)
{
using (LinearGradientBrush activeGB = new LinearGradientBrush(rect, active1, active2, 90f))
{
e.Graphics.FillPath(activeGB, roundedRect.Path);
}
}
else if (state == MouseState.Down)
{
using (LinearGradientBrush downGB = new LinearGradientBrush(rect, Color.FromArgb(R1, G1, B1), Color.FromArgb(R2, G2, B2), 90f))
{
e.Graphics.FillPath(downGB, roundedRect.Path);
}
}
if (stroke)
{
using (Pen pen = new Pen(strokeColor, 1))
using (GraphicsPath path = new RoundedRectangleF(Width - (radius > 0 ? 0 : 1), Height - (radius > 0 ? 0 : 1), radius).Path)
{
e.Graphics.DrawPath(pen, path);
}
}
}
else
{
@@ -124,7 +142,9 @@ namespace AndroidSideloader
Alignment = StringAlignment.Center,
})
using (Brush brush = new SolidBrush(ForeColor))
e.Graphics.DrawString(Text, Font, brush, this.ClientRectangle, sf);
{
e.Graphics.DrawString(Text, Font, brush, ClientRectangle, sf);
}
#endregion
base.OnPaint(e);
}
@@ -170,7 +190,10 @@ namespace AndroidSideloader
protected override void OnMouseUp(MouseEventArgs e)
{
if (state != MouseState.Leave)
{
state = MouseState.Enter;
}
base.OnMouseUp(e);
Invalidate();
}
@@ -180,10 +203,7 @@ namespace AndroidSideloader
public int Radius
{
get
{
return radius;
}
get => radius;
set
{
radius = value;
@@ -192,10 +212,7 @@ namespace AndroidSideloader
}
public Color Inactive1
{
get
{
return inactive1;
}
get => inactive1;
set
{
inactive1 = value;
@@ -204,10 +221,7 @@ namespace AndroidSideloader
}
public Color Inactive2
{
get
{
return inactive2;
}
get => inactive2;
set
{
inactive2 = value;
@@ -216,10 +230,7 @@ namespace AndroidSideloader
}
public Color Active1
{
get
{
return active1;
}
get => active1;
set
{
active1 = value;
@@ -228,33 +239,17 @@ namespace AndroidSideloader
}
public Color Active2
{
get
{
return active2;
}
get => active2;
set
{
active2 = value;
Invalidate();
}
}
public bool Transparency
{
get
{
return transparency;
}
set
{
transparency = value;
}
}
public bool Transparency { get; set; }
public override string Text
{
get
{
return base.Text;
}
get => base.Text;
set
{
base.Text = value;
@@ -263,10 +258,7 @@ namespace AndroidSideloader
}
public override Color ForeColor
{
get
{
return base.ForeColor;
}
get => base.ForeColor;
set
{
base.ForeColor = value;
@@ -276,10 +268,7 @@ namespace AndroidSideloader
public DialogResult DialogResult
{
get
{
return System.Windows.Forms.DialogResult.OK;
}
get => System.Windows.Forms.DialogResult.OK;
set
{
}

View File

@@ -5,69 +5,44 @@ namespace AndroidSideloader
{
public class RoundedRectangleF
{
Point location;
float radius;
GraphicsPath grPath;
float x, y;
float width, height;
private Point location;
private readonly float x, y;
private readonly float width, height;
public RoundedRectangleF(float width, float height, float radius, float x = 0, float y = 0)
{
location = new Point(0, 0);
this.radius = radius;
Radius = radius;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
grPath = new GraphicsPath();
Path = new GraphicsPath();
if (radius <= 0)
{
grPath.AddRectangle(new RectangleF(x, y, width, height));
Path.AddRectangle(new RectangleF(x, y, width, height));
return;
}
RectangleF upperLeftRect = new RectangleF(x, y, 2 * radius, 2 * radius);
RectangleF upperRightRect = new RectangleF(width - 2 * radius - 1, x, 2 * radius, 2 * radius);
RectangleF lowerLeftRect = new RectangleF(x, height - 2 * radius - 1, 2 * radius, 2 * radius);
RectangleF lowerRightRect = new RectangleF(width - 2 * radius - 1, height - 2 * radius - 1, 2 * radius, 2 * radius);
RectangleF upperRightRect = new RectangleF(width - (2 * radius) - 1, x, 2 * radius, 2 * radius);
RectangleF lowerLeftRect = new RectangleF(x, height - (2 * radius) - 1, 2 * radius, 2 * radius);
RectangleF lowerRightRect = new RectangleF(width - (2 * radius) - 1, height - (2 * radius) - 1, 2 * radius, 2 * radius);
grPath.AddArc(upperLeftRect, 180, 90);
grPath.AddArc(upperRightRect, 270, 90);
grPath.AddArc(lowerRightRect, 0, 90);
grPath.AddArc(lowerLeftRect, 90, 90);
grPath.CloseAllFigures();
Path.AddArc(upperLeftRect, 180, 90);
Path.AddArc(upperRightRect, 270, 90);
Path.AddArc(lowerRightRect, 0, 90);
Path.AddArc(lowerLeftRect, 90, 90);
Path.CloseAllFigures();
}
public RoundedRectangleF()
{
}
public GraphicsPath Path
{
get
{
return grPath;
}
}
public RectangleF Rect
{
get
{
return new RectangleF(x, y, width, height);
}
}
public float Radius
{
get
{
return radius;
}
set
{
radius = value;
}
}
public GraphicsPath Path { get; }
public RectangleF Rect => new RectangleF(x, y, width, height);
public float Radius { get; set; }
}
}

View File

@@ -14,19 +14,18 @@ namespace AndroidSideloader
{
private string _initialDirectory;
private string _title;
private string _fileName = "";
public string InitialDirectory
{
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
get => string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory;
set => _initialDirectory = value;
}
public string Title
{
get { return _title ?? "Select a folder"; }
set { _title = value; }
get => _title ?? "Select a folder";
set => _title = value;
}
public string FileName { get { return _fileName; } }
public string FileName { get; private set; } = "";
public bool Show() { return Show(IntPtr.Zero); }
@@ -34,10 +33,10 @@ namespace AndroidSideloader
/// <returns>true if the user clicks OK</returns>
public bool Show(IntPtr hWndOwner)
{
var result = Environment.OSVersion.Version.Major >= 6
ShowDialogResult result = Environment.OSVersion.Version.Major >= 6
? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
: ShowXpDialog(hWndOwner, InitialDirectory, Title);
_fileName = result.FileName;
FileName = result.FileName;
return result.Result;
}
@@ -49,13 +48,13 @@ namespace AndroidSideloader
private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title)
{
var folderBrowserDialog = new FolderBrowserDialog
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog
{
Description = title,
SelectedPath = initialDirectory,
ShowNewFolderButton = false
};
var dialogResult = new ShowDialogResult();
ShowDialogResult dialogResult = new ShowDialogResult();
if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK)
{
dialogResult.Result = true;
@@ -69,26 +68,26 @@ namespace AndroidSideloader
private const string c_foldersFilter = "Folders|\n";
private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private readonly static uint s_fosPickFoldersBitFlag = (uint)s_windowsFormsAssembly
private static readonly Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private static readonly Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private static readonly MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private static readonly MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private static readonly MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private static readonly MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private static readonly uint s_fosPickFoldersBitFlag = (uint)s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialogNative+FOS")
.GetField("FOS_PICKFOLDERS")
.GetValue(null);
private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
private static readonly ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
.GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
private static readonly MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private static readonly MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private static readonly MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title)
{
var openFileDialog = new OpenFileDialog
OpenFileDialog openFileDialog = new OpenFileDialog
{
AddExtension = false,
CheckFileExists = false,
@@ -99,11 +98,11 @@ namespace AndroidSideloader
Title = title
};
var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint)s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
object iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
_ = s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
_ = s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint)s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
object[] adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
_ = s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
try
{
@@ -116,7 +115,7 @@ namespace AndroidSideloader
}
finally
{
s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
_ = s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
}
}
}
@@ -124,9 +123,8 @@ namespace AndroidSideloader
// Wrap an IWin32Window around an IntPtr
private class WindowWrapper : IWin32Window
{
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle) { _handle = handle; }
public IntPtr Handle { get { return _handle; } }
public WindowWrapper(IntPtr handle) { Handle = handle; }
public IntPtr Handle { get; }
}
}

View File

@@ -15,7 +15,7 @@ namespace AndroidSideloader
private void SettingsForm_Load(object sender, EventArgs e)
{
this.CenterToParent();
CenterToParent();
intSettings();
intToolTips();
}
@@ -39,14 +39,14 @@ namespace AndroidSideloader
}
void intToolTips()
private void intToolTips()
{
ToolTip checkForUpdatesToolTip = new ToolTip();
checkForUpdatesToolTip.SetToolTip(this.checkForUpdatesCheckBox, "If this is checked, the software will check for available updates");
checkForUpdatesToolTip.SetToolTip(checkForUpdatesCheckBox, "If this is checked, the software will check for available updates");
ToolTip enableMessageBoxesToolTip = new ToolTip();
enableMessageBoxesToolTip.SetToolTip(this.enableMessageBoxesCheckBox, "If this is checked, the software will display message boxes after every completed task");
enableMessageBoxesToolTip.SetToolTip(enableMessageBoxesCheckBox, "If this is checked, the software will display message boxes after every completed task");
ToolTip deleteAfterInstallToolTip = new ToolTip();
deleteAfterInstallToolTip.SetToolTip(this.deleteAfterInstallCheckBox, "If this is checked, the software will delete all game files after downloading and installing a game from a remote server");
deleteAfterInstallToolTip.SetToolTip(deleteAfterInstallCheckBox, "If this is checked, the software will delete all game files after downloading and installing a game from a remote server");
}
public void btnUploadDebug_click(object sender, EventArgs e)
@@ -59,8 +59,8 @@ namespace AndroidSideloader
Clipboard.SetText(UUID);
RCLONE.runRcloneCommand_UploadConfig($"copy \"{debugLogPath}\" RSL-gameuploads:DebugLogs");
MessageBox.Show($"Your debug log has been copied to the server. ID: {UUID}");
_ = RCLONE.runRcloneCommand_UploadConfig($"copy \"{debugLogPath}\" RSL-gameuploads:DebugLogs");
_ = MessageBox.Show($"Your debug log has been copied to the server. ID: {UUID}");
}
}
@@ -68,22 +68,23 @@ namespace AndroidSideloader
public void btnResetDebug_click(object sender, EventArgs e)
{
if (File.Exists($"{Properties.Settings.Default.CurrentLogPath}"))
{
File.Delete($"{Properties.Settings.Default.CurrentLogPath}");
}
if (File.Exists($"{Environment.CurrentDirectory}\\debuglog.txt"))
{
File.Delete($"{Environment.CurrentDirectory}\\debuglog.txt");
}
}
//Apply settings
private void applyButton_Click(object sender, EventArgs e)
{
if (txtBandwidth.Text.Length > 0 && txtBandwidth.Text != "0") {
Properties.Settings.Default.BandwidthLimit = $"{txtBandwidth.Text.Replace(" ", "")}M";
} else {
Properties.Settings.Default.BandwidthLimit = "";
}
Properties.Settings.Default.BandwidthLimit = txtBandwidth.Text.Length > 0 && txtBandwidth.Text != "0" ? $"{txtBandwidth.Text.Replace(" ", "")}M" : "";
Properties.Settings.Default.Save();
FlexibleMessageBox.Show("Settings applied!");
_ = FlexibleMessageBox.Show("Settings applied!");
}
private void checkForUpdatesCheckBox_CheckedChanged(object sender, EventArgs e)
@@ -121,27 +122,27 @@ namespace AndroidSideloader
{
if (e.KeyChar == (char)Keys.Escape)
{
this.Close();
Close();
}
}
private void SettingsForm_Leave(object sender, EventArgs e)
{
this.Close();
Close();
}
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
Close();
}
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
Close();
return true;
}
return base.ProcessDialogKey(keyData);
@@ -175,7 +176,9 @@ namespace AndroidSideloader
"(ideal when installing from a queue).\n\nNOTE: If your usb/wireless adb connection is extremely slow this option can\ncause larger" +
"apk file installations to fail. Enable anyway?", "WARNING", MessageBoxButtons.OKCancel);
if (dialogResult == DialogResult.Cancel)
{
AutoReinstBox.Checked = false;
}
}
}
@@ -184,7 +187,7 @@ namespace AndroidSideloader
{
if (File.Exists($"{Environment.CurrentDirectory}\\debuglog.txt"))
{
Process.Start($"{Environment.CurrentDirectory}\\debuglog.txt");
_ = Process.Start($"{Environment.CurrentDirectory}\\debuglog.txt");
}
}
}

View File

@@ -1,17 +1,13 @@
using System;
using System.Diagnostics;
using JR.Utils.GUI.Forms;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using JR.Utils.GUI.Forms;
namespace AndroidSideloader
{
class Sideloader
internal class Sideloader
{
public static string TempFolder = Path.Combine(Environment.CurrentDirectory, "temp");
public static string CrashLogPath = "crashlog.txt";
@@ -26,10 +22,10 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
public static void PushUserJsons()
{
ADB.WakeDevice();
foreach (var userJson in UsernameForm.userJsons)
foreach (string userJson in UsernameForm.userJsons)
{
UsernameForm.createUserJsonByName(Utilities.GeneralUtilities.randomString(16), userJson);
ADB.RunAdbCommandToString("push \"" + Environment.CurrentDirectory + $"\\{userJson}\" " + " /sdcard/");
_ = ADB.RunAdbCommandToString("push \"" + Environment.CurrentDirectory + $"\\{userJson}\" " + " /sdcard/");
File.Delete(userJson);
}
}
@@ -52,7 +48,7 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
{
ADB.WakeDevice();
ProcessOutput output = new ProcessOutput();
var commands = File.ReadAllLines(path);
string[] commands = File.ReadAllLines(path);
string currfolder = Path.GetDirectoryName(path);
string[] zipz = Directory.GetFiles(currfolder, "*.7z", SearchOption.AllDirectories);
foreach (string zip in zipz)
@@ -65,19 +61,23 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
{
string replacement = "";
string pattern = "adb";
if (ADB.DeviceID.Length > 1)
replacement = $"{Properties.Settings.Default.ADBPath} -s {ADB.DeviceID}";
else
replacement = $"{Properties.Settings.Default.ADBPath}";
replacement = ADB.DeviceID.Length > 1
? $"{Properties.Settings.Default.ADBPath} -s {ADB.DeviceID}"
: $"{Properties.Settings.Default.ADBPath}";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(cmd, replacement);
Program.form.ChangeTitle($"Running {result}");
Logger.Log($"Logging command: {result} from file: {path}");
_ = Logger.Log($"Logging command: {result} from file: {path}");
output += ADB.RunAdbCommandToStringWOADB(result, path);
if (output.Error.Contains("mkdir"))
{
output.Error = "";
}
if (output.Output.Contains("reserved"))
{
output.Output = "";
}
}
}
output.Output += "Custom install successful!";
@@ -97,8 +97,9 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
foreach (string f in Directory.GetFiles(FolderPath))
{
if (Path.GetExtension(f) == ".apk")
{
RecursiveOutput += ADB.Sideload(f);
}
}
foreach (string d in Directory.GetDirectories(FolderPath))
@@ -106,7 +107,7 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
RecursiveSideload(d);
}
}
catch (Exception ex) { Logger.Log(ex.Message); }
catch (Exception ex) { _ = Logger.Log(ex.Message); }
}
//Recursive copy any obb folder
@@ -124,7 +125,7 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
RecursiveCopyOBB(d);
}
}
catch (Exception ex) { Logger.Log(ex.Message); }
catch (Exception ex) { _ = Logger.Log(ex.Message); }
}
public static string BackupFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), $"Rookie Backups");
//uninstalls an app
@@ -132,16 +133,19 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
{
ADB.WakeDevice();
Program.form.ChangeTitle("Attempting to backup any savedata to Documents\\Rookie Backups...");
ProcessOutput output = new ProcessOutput("", "");
_ = new ProcessOutput("", "");
string date_str = DateTime.Today.ToString("yyyy.MM.dd");
string CurrBackups = Path.Combine(BackupFolder, date_str);
if (!Directory.Exists(CurrBackups))
Directory.CreateDirectory(CurrBackups);
ADB.RunAdbCommandToString($"pull \"/sdcard/Android/data/{packagename}\" \"{CurrBackups}\"");
output = ADB.UninstallPackage(packagename);
{
_ = Directory.CreateDirectory(CurrBackups);
}
_ = ADB.RunAdbCommandToString($"pull \"/sdcard/Android/data/{packagename}\" \"{CurrBackups}\"");
ProcessOutput output = ADB.UninstallPackage(packagename);
Program.form.ChangeTitle("");
Sideloader.RemoveFolder("/sdcard/Android/obb/" + packagename);
Sideloader.RemoveFolder("/sdcard/Android/data/" + packagename);
_ = Sideloader.RemoveFolder("/sdcard/Android/obb/" + packagename);
_ = Sideloader.RemoveFolder("/sdcard/Android/data/" + packagename);
return output;
}
@@ -154,7 +158,9 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
DialogResult dialogResult = FlexibleMessageBox.Show($"Are you sure you want to uninstall custom QU settings for {packageName}? this CANNOT be undone!", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult != DialogResult.Yes)
{
return output;
}
output = Sideloader.RemoveFile($"/sdcard/Android/data/{packageName}/private/Config.Json");
@@ -166,11 +172,11 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
{
ADB.WakeDevice();
ProcessOutput output = new ProcessOutput("", "");
_ = new ProcessOutput("", "");
string packageName = Sideloader.gameNameToPackageName(GameName);
output = ADB.RunAdbCommandToString("shell pm path " + packageName);
ProcessOutput output = ADB.RunAdbCommandToString("shell pm path " + packageName);
string apkPath = output.Output; //Get apk
@@ -178,15 +184,23 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
apkPath = apkPath.Remove(0, 8); //remove package:
apkPath = apkPath.Remove(apkPath.Length - 1);
if (File.Exists($"{Properties.Settings.Default.ADBFolder}\\base.apk"))
{
File.Delete($"{Properties.Settings.Default.ADBFolder}\\base.apk");
}
if (File.Exists($"{Properties.Settings.Default.MainDir}\\{packageName}\\{packageName}.apk"))
{
File.Delete($"{Properties.Settings.Default.MainDir}\\{packageName}\\{packageName}.apk");
}
output += ADB.RunAdbCommandToString("pull " + apkPath); //pull apk
if (Directory.Exists($"{Properties.Settings.Default.MainDir}\\{packageName}"))
{
Directory.Delete($"{Properties.Settings.Default.MainDir}\\{packageName}", true);
}
Directory.CreateDirectory($"{Properties.Settings.Default.MainDir}\\{packageName}");
_ = Directory.CreateDirectory($"{Properties.Settings.Default.MainDir}\\{packageName}");
File.Move($"{Properties.Settings.Default.ADBFolder}\\base.apk", $"{Properties.Settings.Default.MainDir}\\{packageName}\\{packageName}.apk");
return output;
@@ -197,9 +211,14 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
foreach (string[] game in SideloaderRCLONE.games)
{
if (gameName.Equals(game[SideloaderRCLONE.GameNameIndex]))
{
return game[SideloaderRCLONE.PackageNameIndex];
}
if (gameName.Equals(game[SideloaderRCLONE.ReleaseNameIndex]))
{
return game[SideloaderRCLONE.PackageNameIndex];
}
}
return gameName;
}
@@ -209,7 +228,9 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
foreach (string[] game in SideloaderRCLONE.games)
{
if (gameName.Equals(game[SideloaderRCLONE.PackageNameIndex]))
{
return game[SideloaderRCLONE.ReleaseNameIndex];
}
}
return gameName;
}
@@ -219,9 +240,14 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
foreach (string[] game in SideloaderRCLONE.games)
{
if (gameName.Equals(game[SideloaderRCLONE.GameNameIndex]))
{
return game[SideloaderRCLONE.GameNameIndex];
}
if (gameName.Equals(game[SideloaderRCLONE.ReleaseNameIndex]))
{
return game[SideloaderRCLONE.GameNameIndex];
}
}
return gameName;
}
@@ -231,7 +257,9 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
foreach (string[] game in SideloaderRCLONE.games)
{
if (gameName.Contains(game[SideloaderRCLONE.PackageNameIndex]))
{
return game[SideloaderRCLONE.GameNameIndex];
}
}
return gameName;
}
@@ -240,25 +268,38 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
//Downloads the required files
public static void downloadFiles()
{
var client = new WebClient();
WebClient client = new WebClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
if (!File.Exists("Sideloader Launcher.exe"))
{
client.DownloadFile("https://github.com/nerdunit/androidsideloader/raw/master/Sideloader%20Launcher.exe", "Sideloader Launcher.exe");
}
if (!File.Exists("Rookie Offline.cmd"))
{
client.DownloadFile("https://github.com/nerdunit/androidsideloader/raw/master/Rookie%20Offline.cmd", "Rookie Offline.cmd");
}
if (!File.Exists("C:\\RSL\\platform-tools\\aug2021.txt") || !File.Exists("C:\\RSL\\platform-tools\\adb.exe")) //if adb is not updated, download and auto extract
{
if (Directory.Exists($"C:\\RSL\\2.8.2"))
{
Directory.Delete("C:\\RSL\\2.8.2", true);
}
if (Directory.Exists($"{Properties.Settings.Default.MainDir}\\adb"))
{
Directory.Delete($"{Properties.Settings.Default.MainDir}\\adb", true);
}
if (!Directory.Exists("C:\\RSL\\platform-tools"))
Directory.CreateDirectory("C:\\RSL\\platform-tools");
{
_ = Directory.CreateDirectory("C:\\RSL\\platform-tools");
}
client.DownloadFile("https://github.com/nerdunit/androidsideloader/raw/master/adb2.zip", "Ad.7z");
Utilities.Zip.ExtractFile(Environment.CurrentDirectory + "\\Ad.7z", "C:\\RSL\\platform-tools");
File.Delete("Ad.7z");
@@ -266,11 +307,9 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
if (!Directory.Exists(Environment.CurrentDirectory + "\\rclone"))
{
string url;
if (Environment.Is64BitOperatingSystem)
url = "https://downloads.rclone.org/v1.55.1/rclone-v1.55.1-windows-amd64.zip";
else
url = "https://downloads.rclone.org/v1.55.1/rclone-v1.55.1-windows-386.zip";
string url = Environment.Is64BitOperatingSystem
? "https://downloads.rclone.org/v1.55.1/rclone-v1.55.1-windows-amd64.zip"
: "https://downloads.rclone.org/v1.55.1/rclone-v1.55.1-windows-386.zip";
//Since sideloader is build for x86, it should work on both x86 and x64 so we download the according rclone version
client.DownloadFile(url, "rclone.zip");
@@ -293,7 +332,7 @@ And all of them added to PATH, without ANY of them, the spoofer won't work!";
}
catch
{
FlexibleMessageBox.Show("Your internet is not working properly or rclone/github servers are down, some files may be missing (adb, rclone or launcher)");
_ = FlexibleMessageBox.Show("Your internet is not working properly or rclone/github servers are down, some files may be missing (adb, rclone or launcher)");
}
}
}

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndroidSideloader
namespace AndroidSideloader
{
public class ProcessOutput
{

View File

@@ -1,14 +1,14 @@
using System;
using AndroidSideloader.Utilities;
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using AndroidSideloader.Utilities;
namespace AndroidSideloader
{
class rcloneFolder
internal class rcloneFolder
{
public string Path { get; set; }
public string Name { get; set; }
@@ -16,7 +16,7 @@ namespace AndroidSideloader
public string ModTime { get; set; }
}
class SideloaderRCLONE
internal class SideloaderRCLONE
{
public static List<string> RemotesList = new List<string>();
@@ -47,50 +47,61 @@ namespace AndroidSideloader
public static void UpdateNouns(string remote)
{
Logger.Log($"Updating Nouns");
RCLONE.runRcloneCommand_DownloadConfig($"sync \"{remote}:{RcloneGamesFolder}/.meta/nouns\" \"{Nouns}\"");
_ = Logger.Log($"Updating Nouns");
_ = RCLONE.runRcloneCommand_DownloadConfig($"sync \"{remote}:{RcloneGamesFolder}/.meta/nouns\" \"{Nouns}\"");
}
public static void UpdateGamePhotos(string remote)
{
Logger.Log($"Updating Thumbnails");
RCLONE.runRcloneCommand_DownloadConfig($"sync \"{remote}:{RcloneGamesFolder}/.meta/thumbnails\" \"{ThumbnailsFolder}\"");
_ = Logger.Log($"Updating Thumbnails");
_ = RCLONE.runRcloneCommand_DownloadConfig($"sync \"{remote}:{RcloneGamesFolder}/.meta/thumbnails\" \"{ThumbnailsFolder}\"");
}
public static void UpdateGameNotes(string remote)
{
Logger.Log($"Updating Game Notes");
RCLONE.runRcloneCommand_DownloadConfig($"sync \"{remote}:{RcloneGamesFolder}/.meta/notes\" \"{NotesFolder}\"");
_ = Logger.Log($"Updating Game Notes");
_ = RCLONE.runRcloneCommand_DownloadConfig($"sync \"{remote}:{RcloneGamesFolder}/.meta/notes\" \"{NotesFolder}\"");
}
public static void UpdateMetadataFromPublic()
{
Logger.Log($"Downloading Metadata");
var rclonecommand =
_ = Logger.Log($"Downloading Metadata");
string rclonecommand =
$"sync \":http:/meta.7z\" \"{Environment.CurrentDirectory}\"";
RCLONE.runRcloneCommand_PublicConfig(rclonecommand);
_ = RCLONE.runRcloneCommand_PublicConfig(rclonecommand);
}
public static void ProcessMetadataFromPublic()
{
try
{
Logger.Log($"Extracting Metadata");
_ = Logger.Log($"Extracting Metadata");
Zip.ExtractFile($"{Environment.CurrentDirectory}\\meta.7z", $"{Environment.CurrentDirectory}\\meta",
MainForm.PublicConfigFile.Password);
Logger.Log($"Updating Metadata");
_ = Logger.Log($"Updating Metadata");
if (Directory.Exists(Nouns)) Directory.Delete(Nouns, true);
if (Directory.Exists(ThumbnailsFolder)) Directory.Delete(ThumbnailsFolder, true);
if (Directory.Exists(NotesFolder)) Directory.Delete(NotesFolder, true);
if (Directory.Exists(Nouns))
{
Directory.Delete(Nouns, true);
}
if (Directory.Exists(ThumbnailsFolder))
{
Directory.Delete(ThumbnailsFolder, true);
}
if (Directory.Exists(NotesFolder))
{
Directory.Delete(NotesFolder, true);
}
Directory.Move($"{Environment.CurrentDirectory}\\meta\\.meta\\nouns", Nouns);
Directory.Move($"{Environment.CurrentDirectory}\\meta\\.meta\\thumbnails", ThumbnailsFolder);
Directory.Move($"{Environment.CurrentDirectory}\\meta\\.meta\\notes", NotesFolder);
Logger.Log($"Initializing Games List");
var gameList = File.ReadAllText($"{Environment.CurrentDirectory}\\meta\\VRP-GameList.txt");
_ = Logger.Log($"Initializing Games List");
string gameList = File.ReadAllText($"{Environment.CurrentDirectory}\\meta\\VRP-GameList.txt");
string[] splitList = gameList.Split('\n');
splitList = splitList.Skip(1).ToArray();
@@ -107,26 +118,26 @@ namespace AndroidSideloader
}
catch (Exception e)
{
Logger.Log(e.Message);
Logger.Log(e.StackTrace);
_ = Logger.Log(e.Message);
_ = Logger.Log(e.StackTrace);
}
}
public static void RefreshRemotes()
{
Logger.Log($"Refresh / List Remotes");
_ = Logger.Log($"Refresh / List Remotes");
RemotesList.Clear();
var remotes = RCLONE.runRcloneCommand_DownloadConfig("listremotes").Output.Split('\n');
string[] remotes = RCLONE.runRcloneCommand_DownloadConfig("listremotes").Output.Split('\n');
Logger.Log("Loaded following remotes: ");
_ = Logger.Log("Loaded following remotes: ");
foreach (string r in remotes)
{
if (r.Length > 1)
{
var remote = r.Remove(r.Length - 1);
string remote = r.Remove(r.Length - 1);
if (remote.Contains("mirror"))
{
Logger.Log(remote);
_ = Logger.Log(remote);
RemotesList.Add(remote);
}
}
@@ -135,8 +146,8 @@ namespace AndroidSideloader
public static void initGames(string remote)
{
Logger.Log($"Initializing Games List");
_ = Logger.Log($"Initializing Games List");
gameProperties.Clear();
games.Clear();
string tempGameList = RCLONE.runRcloneCommand_DownloadConfig($"cat \"{remote}:{RcloneGamesFolder}/VRP-GameList.txt\"").Output;
@@ -165,7 +176,7 @@ namespace AndroidSideloader
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
Logger.Log($"Attempting to Update Download Config");
_ = Logger.Log($"Attempting to Update Download Config");
try
{
string configUrl = "https://wiki.vrpirates.club/downloads/vrp.download.config";
@@ -175,40 +186,53 @@ namespace AndroidSideloader
{
string resultString = responseReader.ReadToEnd();
Logger.Log($"Retrived updated config from: {configUrl}");
_ = Logger.Log($"Retrived updated config from: {configUrl}");
if (File.Exists(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new"))
{
File.Delete(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new");
}
File.Create(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new").Close();
File.WriteAllText(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new", resultString);
if (!File.Exists(Environment.CurrentDirectory + "\\rclone\\hash.txt"))
{
File.Create(Environment.CurrentDirectory + "\\rclone\\hash.txt").Close();
}
string newConfig = CalculateMD5(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new");
string oldConfig = File.ReadAllText(Environment.CurrentDirectory + "\\rclone\\hash.txt");
if (!File.Exists(Environment.CurrentDirectory + "\\rclone\\vrp.download.config"))
{
oldConfig = "Config Doesnt Exist!";
}
Logger.Log($"Online Config Hash: {newConfig}; Local Config Hash: {oldConfig}");
_ = Logger.Log($"Online Config Hash: {newConfig}; Local Config Hash: {oldConfig}");
if (newConfig != oldConfig)
{
Logger.Log($"Updated Config Hash is different than the current Config. Updating Configuration File.");
_ = Logger.Log($"Updated Config Hash is different than the current Config. Updating Configuration File.");
if (File.Exists(Environment.CurrentDirectory + "\\rclone\\vrp.download.config"))
{
File.Delete(Environment.CurrentDirectory + "\\rclone\\vrp.download.config");
}
File.Move(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new", Environment.CurrentDirectory + "\\rclone\\vrp.download.config");
File.WriteAllText(Environment.CurrentDirectory + "\\rclone\\hash.txt", string.Empty);
File.WriteAllText(Environment.CurrentDirectory + "\\rclone\\hash.txt", newConfig);
} else
}
else
{
Logger.Log($"Updated Config Hash matches last download. Not updating.");
_ = Logger.Log($"Updated Config Hash matches last download. Not updating.");
if (File.Exists(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new"))
{
File.Delete(Environment.CurrentDirectory + "\\rclone\\vrp.download.config_new");
}
}
}
}
@@ -221,7 +245,7 @@ namespace AndroidSideloader
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
Logger.Log($"Attempting to Update Upload Config");
_ = Logger.Log($"Attempting to Update Upload Config");
try
{
string configUrl = "https://wiki.vrpirates.club/downloads/vrp.upload.config";
@@ -231,16 +255,16 @@ namespace AndroidSideloader
{
string resultString = responseReader.ReadToEnd();
Logger.Log($"Retrived updated config from: {configUrl}");
_ = Logger.Log($"Retrived updated config from: {configUrl}");
File.WriteAllText(Environment.CurrentDirectory + "\\rclone\\vrp.upload.config", resultString);
Logger.Log("Upload config updated successfully.");
_ = Logger.Log("Upload config updated successfully.");
}
}
catch (Exception e)
{
Logger.Log($"Failed to update Upload config: {e.Message}");
_ = Logger.Log($"Failed to update Upload config: {e.Message}");
}
}
@@ -250,7 +274,7 @@ namespace AndroidSideloader
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
Logger.Log($"Attempting to Update Public Config");
_ = Logger.Log($"Attempting to Update Public Config");
try
{
string configUrl = "https://wiki.vrpirates.club/downloads/vrp-public.json";
@@ -260,27 +284,26 @@ namespace AndroidSideloader
{
string resultString = responseReader.ReadToEnd();
Logger.Log($"Retrived updated config from: {configUrl}");
_ = Logger.Log($"Retrived updated config from: {configUrl}");
File.WriteAllText(Environment.CurrentDirectory + "\\vrp-public.json", resultString);
Logger.Log("Public config updated successfully.");
_ = Logger.Log("Public config updated successfully.");
}
}
catch (Exception e)
catch (Exception e)
{
Logger.Log($"Failed to update Public config: {e.Message}");
_ = Logger.Log($"Failed to update Public config: {e.Message}");
}
}
static string CalculateMD5(string filename)
private static string CalculateMD5(string filename)
{
using (var md5 = MD5.Create())
using (MD5 md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
using (FileStream stream = File.OpenRead(filename))
{
var hash = md5.ComputeHash(stream);
byte[] hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}

View File

@@ -6,22 +6,30 @@ using System.Text;
namespace AndroidSideloader
{
class SideloaderUtilities
internal class SideloaderUtilities
{
public static bool CheckFolderIsObb(string path)
{
string[] files = Directory.GetFiles(path);
foreach (string file in files)
if (file.EndsWith(".obb") || Path.GetDirectoryName(file).Contains(".") && !Path.GetDirectoryName(file).Contains("_data"))
{
if (file.EndsWith(".obb") || (Path.GetDirectoryName(file).Contains(".") && !Path.GetDirectoryName(file).Contains("_data")))
{
return true;
}
}
return false;
}
private static string uuid = null;
public static string UUID()
{
if (uuid != null) return uuid;
if (uuid != null)
{
return uuid;
}
StringBuilder sb = new StringBuilder();
@@ -30,10 +38,10 @@ namespace AndroidSideloader
foreach (ManagementObject queryObj in searcher.Get())
{
sb.Append(queryObj["NumberOfCores"]);
sb.Append(queryObj["ProcessorId"]);
sb.Append(queryObj["Name"]);
sb.Append(queryObj["SocketDesignation"]);
_ = sb.Append(queryObj["NumberOfCores"]);
_ = sb.Append(queryObj["ProcessorId"]);
_ = sb.Append(queryObj["Name"]);
_ = sb.Append(queryObj["SocketDesignation"]);
}
searcher = new ManagementObjectSearcher("root\\CIMV2",
@@ -41,9 +49,9 @@ namespace AndroidSideloader
foreach (ManagementObject queryObj in searcher.Get())
{
sb.Append(queryObj["Manufacturer"]);
sb.Append(queryObj["Name"]);
sb.Append(queryObj["Version"]);
_ = sb.Append(queryObj["Manufacturer"]);
_ = sb.Append(queryObj["Name"]);
_ = sb.Append(queryObj["Version"]);
}
@@ -52,10 +60,10 @@ namespace AndroidSideloader
foreach (ManagementObject queryObj in searcher.Get())
{
sb.Append(queryObj["Product"]);
_ = sb.Append(queryObj["Product"]);
}
var bytes = Encoding.ASCII.GetBytes(sb.ToString());
byte[] bytes = Encoding.ASCII.GetBytes(sb.ToString());
SHA256Managed sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(bytes);

View File

@@ -1,12 +1,4 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms;
namespace AndroidSideloader
{

View File

@@ -1,9 +1,9 @@
using JR.Utils.GUI.Forms;
using System;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using Spoofer;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AndroidSideloader
{
@@ -18,7 +18,7 @@ namespace AndroidSideloader
{
if (!spoofer.HasDependencies())
{
MessageBox.Show("You are missing the dependencies... Cannot spoof games");
_ = MessageBox.Show("You are missing the dependencies... Cannot spoof games");
return;
}
string NewPackageName = PackageNameTextBox.Text;
@@ -31,9 +31,13 @@ namespace AndroidSideloader
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
path = openFileDialog.FileName;
}
else
{
return;
}
}
progressBar1.Style = ProgressBarStyle.Marquee;
@@ -44,21 +48,22 @@ namespace AndroidSideloader
{
spoofer.Init();
output += spoofer.SpoofApk(path, NewPackageName);
});
t1.IsBackground = true;
})
{
IsBackground = true
};
t1.Start();
while (t1.IsAlive)
{
await Task.Delay(100);
}
progressBar1.Style = ProgressBarStyle.Continuous;
if (output.Contains("is not recognized as an internal or external command"))
FlexibleMessageBox.Show(Sideloader.SpooferWarning);
else
FlexibleMessageBox.Show($"App spoofed from {spoofer.originalPackageName} to {NewPackageName}");
_ = output.Contains("is not recognized as an internal or external command")
? FlexibleMessageBox.Show(Sideloader.SpooferWarning)
: FlexibleMessageBox.Show($"App spoofed from {spoofer.originalPackageName} to {NewPackageName}");
}
private void SpoofForm_Load(object sender, EventArgs e)

View File

@@ -7,21 +7,36 @@ namespace AndroidSideloader
{
public static void MakeTransparent(Control control, Graphics g)
{
var parent = control.Parent;
if (parent == null) return;
var bounds = control.Bounds;
var siblings = parent.Controls;
Control parent = control.Parent;
if (parent == null)
{
return;
}
Rectangle bounds = control.Bounds;
Control.ControlCollection siblings = parent.Controls;
int index = siblings.IndexOf(control);
Bitmap behind = null;
for (int i = siblings.Count - 1; i > index; i--)
{
var c = siblings[i];
if (!c.Bounds.IntersectsWith(bounds)) continue;
Control c = siblings[i];
if (!c.Bounds.IntersectsWith(bounds))
{
continue;
}
if (behind == null)
{
behind = new Bitmap(control.Parent.ClientSize.Width, control.Parent.ClientSize.Height);
}
c.DrawToBitmap(behind, c.Bounds);
}
if (behind == null) return;
if (behind == null)
{
return;
}
g.DrawImage(behind, control.ClientRectangle, bounds, GraphicsUnit.Pixel);
behind.Dispose();
}

View File

@@ -1,11 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AndroidSideloader
@@ -18,7 +12,7 @@ namespace AndroidSideloader
public UpdateForm()
{
InitializeComponent();
this.CenterToScreen();
CenterToScreen();
CurVerLabel.Text += " " + Updater.LocalVersion;
UpdateVerLabel.Text += " " + Updater.currentVersion;
UpdateTextBox.Text = Updater.changelog;
@@ -27,12 +21,12 @@ namespace AndroidSideloader
private void YesUpdate_Click(object sender, EventArgs e)
{
Updater.doUpdate();
this.Close();
Close();
}
private void SkipUpdate_Click(object sender, EventArgs e)
{
this.Close();
Close();
}
private void UpdateTextBox_TextChanged(object sender, EventArgs e)
@@ -50,10 +44,10 @@ namespace AndroidSideloader
{
if (mouseDown)
{
this.Location = new Point(
(this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
Location = new Point(
Location.X - lastLocation.X + e.X, Location.Y - lastLocation.Y + e.Y);
this.Update();
Update();
}
}

View File

@@ -1,23 +1,17 @@
using System;
using System.Text;
using System.Diagnostics;
using JR.Utils.GUI.Forms;
using System.Diagnostics;
using System.Net;
using System.Windows.Forms;
using System.Net.Http;
using System.IO;
using AndroidSideloader;
namespace AndroidSideloader
{
class Updater
internal class Updater
{
public static string AppName { get; set; }
public static string Repostory { get; set; }
private static string RawGitHubUrl;
private static string GitHubUrl;
static readonly public string LocalVersion = "2.16";
public static readonly string LocalVersion = "2.17";
public static string currentVersion = string.Empty;
public static string changelog = string.Empty;
@@ -44,7 +38,7 @@ namespace AndroidSideloader
if (IsUpdateAvailable())
{
UpdateForm upForm = new UpdateForm();
upForm.ShowDialog(); ;
_ = upForm.ShowDialog(); ;
}
@@ -55,15 +49,15 @@ namespace AndroidSideloader
{
try
{
ADB.RunAdbCommandToString("kill-server");
var fileClient = new WebClient();
_ = ADB.RunAdbCommandToString("kill-server");
WebClient fileClient = new WebClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Logger.Log($"Downloading update from {GitHubUrl}/releases/download/v{currentVersion}/{AppName}.exe to {AppName} v{currentVersion}.exe");
_ = Logger.Log($"Downloading update from {GitHubUrl}/releases/download/v{currentVersion}/{AppName}.exe to {AppName} v{currentVersion}.exe");
fileClient.DownloadFile($"{GitHubUrl}/releases/download/v{currentVersion}/{AppName}.exe", $"{AppName} v{currentVersion}.exe");
fileClient.Dispose();
Logger.Log($"Starting {AppName} v{currentVersion}.exe");
Process.Start($"{AppName} v{currentVersion}.exe");
_ = Logger.Log($"Starting {AppName} v{currentVersion}.exe");
_ = Process.Start($"{AppName} v{currentVersion}.exe");
//Delete current version
AndroidSideloader.Utilities.GeneralUtilities.Melt();
}

View File

@@ -1,9 +1,9 @@
using System;
using System.Windows.Forms;
using System.IO;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AndroidSideloader
{
@@ -14,7 +14,7 @@ namespace AndroidSideloader
InitializeComponent();
}
string defaultText;
private string defaultText;
private void usernameForm_Load(object sender, EventArgs e)
{
@@ -26,7 +26,7 @@ namespace AndroidSideloader
{
if (textBox1.Text == defaultText || textBox1.Text.Length == 0)
{
MessageBox.Show("Please enter your username first");
_ = MessageBox.Show("Please enter your username first");
return;
}
@@ -34,12 +34,16 @@ namespace AndroidSideloader
{
createUserJson(textBox1.Text);
});
t1.IsBackground = true;
})
{
IsBackground = true
};
t1.Start();
while (t1.IsAlive)
{
await Task.Delay(100);
}
MainForm.notify("Done");
@@ -49,11 +53,11 @@ namespace AndroidSideloader
public static void createUserJson(string username)
{
ADB.RunAdbCommandToString($"shell settings put global username {username}");
foreach (var jsonFileName in userJsons)
_ = ADB.RunAdbCommandToString($"shell settings put global username {username}");
foreach (string jsonFileName in userJsons)
{
createUserJsonByName(username, jsonFileName);
ADB.RunAdbCommandToString("push \"" + Environment.CurrentDirectory + $"\\{jsonFileName}\" " + " /sdcard/");
_ = ADB.RunAdbCommandToString("push \"" + Environment.CurrentDirectory + $"\\{jsonFileName}\" " + " /sdcard/");
File.Delete(jsonFileName);
}

View File

@@ -1,17 +1,13 @@
using System;
using System.Text;
using System.Diagnostics;
using JR.Utils.GUI.Forms;
using System.Windows.Forms;
using System.Net.Http;
using System.IO;
using AndroidSideloader;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AndroidSideloader.Utilities
{
class GeneralUtilities
internal class GeneralUtilities
{
public static long GetDirectorySize(string folderPath)
{
@@ -28,13 +24,15 @@ namespace AndroidSideloader.Utilities
public static void ExecuteCommand(string command)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/c " + command)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
var process = Process.Start(processInfo);
Process process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
CommandOutput += e.Data;
@@ -51,7 +49,7 @@ namespace AndroidSideloader.Utilities
public static void Melt()
{
Process.Start(new ProcessStartInfo()
_ = Process.Start(new ProcessStartInfo()
{
Arguments = "/C choice /C Y /N /D Y /T 5 & Del \"" + Application.ExecutablePath + "\"",
WindowStyle = ProcessWindowStyle.Hidden,
@@ -60,7 +58,8 @@ namespace AndroidSideloader.Utilities
});
Environment.Exit(0);
}
static Random rand = new Random();
private static readonly Random rand = new Random();
public static string randomString(int length)
{
string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
@@ -69,7 +68,7 @@ namespace AndroidSideloader.Utilities
int randomInteger = rand.Next(0, valid.Length);
while (0 < length--)
{
res.Append(valid[randomInteger]);
_ = res.Append(valid[randomInteger]);
randomInteger = rand.Next(0, valid.Length);
}
return res.ToString();
@@ -77,7 +76,7 @@ namespace AndroidSideloader.Utilities
public static ProcessOutput startProcess(string process, string path, string command)
{
Logger.Log($"Ran process {process} with command {command} in path {path}");
_ = Logger.Log($"Ran process {process} with command {command} in path {path}");
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
@@ -86,16 +85,16 @@ namespace AndroidSideloader.Utilities
cmd.StartInfo.WorkingDirectory = path;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
_ = cmd.Start();
cmd.StandardInput.WriteLine(command);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
string error = cmd.StandardError.ReadToEnd();
string output = cmd.StandardOutput.ReadToEnd();
Logger.Log($"Output: {output}");
Logger.Log($"Error: {error}");
return new ProcessOutput(output,error);
_ = Logger.Log($"Output: {output}");
_ = Logger.Log($"Error: {error}");
return new ProcessOutput(output, error);
}
}

View File

@@ -1,23 +1,25 @@
using System;
using System.IO;
using System.Windows.Forms;
namespace AndroidSideloader
{
class Logger
internal class Logger
{
public string logfile = Properties.Settings.Default.CurrentLogPath;
public string logfile = Properties.Settings.Default.CurrentLogPath;
public static bool Log(string text, bool ret = true)
{
string time = DateTime.Now.ToString("hh:mmtt(UTC): ");
if (text.Length > 5)
{
string newline = "\n";
if (text.Length > 40 && text.Contains("\n"))
{
newline += "\n\n";
try {File.AppendAllText(Properties.Settings.Default.CurrentLogPath, time + text + newline); } catch { }
}
try { File.AppendAllText(Properties.Settings.Default.CurrentLogPath, time + text + newline); } catch { }
return ret;
}
return ret;

View File

@@ -1,18 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace AndroidSideloader.Utilities
{
class StringUtilities
internal class StringUtilities
{
public static string RemoveEverythingAfterFirst(string s, string removeMe)
{
int index = s.IndexOf(removeMe);
if (index > 0)
{
s = s.Substring(0, index);
}
return s;
}
@@ -20,7 +19,10 @@ namespace AndroidSideloader.Utilities
{
int index = s.LastIndexOf(removeMe);
if (index > 0)
{
s = s.Substring(0, index);
}
return s;
}
@@ -28,7 +30,10 @@ namespace AndroidSideloader.Utilities
{
int index = s.IndexOf(removeMe);
if (index > 0)
{
s = s.Substring(index);
}
return s;
}
@@ -50,7 +55,10 @@ namespace AndroidSideloader.Utilities
{
int index = s.LastIndexOf(removeMe);
if (index > 0)
{
s = s.Substring(index);
}
return s;
}
}

View File

@@ -1,18 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndroidSideloader.Utilities
namespace AndroidSideloader.Utilities
{
class UpdateGameData
internal class UpdateGameData
{
public UpdateGameData(String gameName, String packageName, ulong installedVersionInt)
public UpdateGameData(string gameName, string packageName, ulong installedVersionInt)
{
this.GameName = gameName;
this.Packagename = packageName;
this.InstalledVersionInt = installedVersionInt;
GameName = gameName;
Packagename = packageName;
InstalledVersionInt = installedVersionInt;
}
public string GameName { get; set; }
public string Packagename { get; set; }

View File

@@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AndroidSideloader.Utilities
namespace AndroidSideloader.Utilities
{
class UploadGame
internal class UploadGame
{
public UploadGame(string Uploadcommand, string Pckgcommand, string Uploadgamename, ulong Uploadversion, bool isUpdate)
{
@@ -17,12 +11,12 @@ namespace AndroidSideloader.Utilities
}
public UploadGame()
{
}
public bool isUpdate { get; set; }
public string Pckgcommand { get; set; }
public string Uploadgamename { get; set; }
public ulong Uploadversion { get; set; }

View File

@@ -1,24 +1,24 @@
using System;
using JR.Utils.GUI.Forms;
using System;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Linq;
using JR.Utils.GUI.Forms;
using System.Net;
using System.Windows.Forms;
namespace AndroidSideloader.Utilities
{
class Zip
internal class Zip
{
public static void ExtractFile(string sourceArchive, string destination)
{
var args = $"x \"{sourceArchive}\" -y -o\"{destination}\"";
string args = $"x \"{sourceArchive}\" -y -o\"{destination}\"";
DoExtract(args);
}
public static void ExtractFile(string sourceArchive, string destination, string password)
{
var args = $"x \"{sourceArchive}\" -y -o\"{destination}\" -p\"{password}\"";
string args = $"x \"{sourceArchive}\" -y -o\"{destination}\" -p\"{password}\"";
DoExtract(args);
}
@@ -26,23 +26,25 @@ namespace AndroidSideloader.Utilities
{
if (!File.Exists(Environment.CurrentDirectory + "\\7z.exe") || !File.Exists(Environment.CurrentDirectory + "\\7z.dll"))
{
Logger.Log("Begin download 7-zip");
_ = Logger.Log("Begin download 7-zip");
WebClient client = new WebClient();
client.DownloadFile("https://github.com/nerdunit/androidsideloader/raw/master/7z.exe", "7z.exe");
client.DownloadFile("https://github.com/nerdunit/androidsideloader/raw/master/7z.dll", "7z.dll");
Logger.Log("Complete download 7-zip");
_ = Logger.Log("Complete download 7-zip");
}
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = "7z.exe";
pro.Arguments = args;
pro.CreateNoWindow = true;
pro.UseShellExecute = false;
pro.RedirectStandardInput = true;
pro.RedirectStandardError = true;
pro.RedirectStandardOutput = true;
ProcessStartInfo pro = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "7z.exe",
Arguments = args,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardError = true,
RedirectStandardOutput = true
};
Logger.Log($"Extract: 7z {string.Join(" ", args.Split(' ').Where(a => !a.StartsWith("-p")))}");
_ = Logger.Log($"Extract: 7z {string.Join(" ", args.Split(' ').Where(a => !a.StartsWith("-p")))}");
Process x = Process.Start(pro);
x.WaitForExit();
@@ -52,13 +54,13 @@ namespace AndroidSideloader.Utilities
if (error.Contains("There is not enough space on the disk"))
{
FlexibleMessageBox.Show($"Not enough space to extract archive.\r\nCheck free space in {Environment.CurrentDirectory} and try again.",
_ = FlexibleMessageBox.Show($"Not enough space to extract archive.\r\nCheck free space in {Environment.CurrentDirectory} and try again.",
"NOT ENOUGH SPACE",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
Logger.Log(x.StandardOutput.ReadToEnd());
Logger.Log(error);
_ = Logger.Log(x.StandardOutput.ReadToEnd());
_ = Logger.Log(error);
throw new ApplicationException($"Extracting failed, status code {x.ExitCode}");
}
}

View File

@@ -1,10 +1,6 @@
RSL 2.16
RSL 2.17
- Fix misleading error message when not enough disk space
- Fix downloads silently failing in some cases
- Fix failure to detect failed extraction when archive corrupt
- Fix UI issues when resizing main form
- Various code cleanups
- Various bugfixes
~SytheZN
~fenopy

View File

@@ -2,8 +2,6 @@
using AndroidSideloader.Utilities;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
namespace Spoofer
@@ -18,7 +16,7 @@ namespace Spoofer
//If there is no keystore or details (user and pw for keystore) generate them!
if ((File.Exists("keystore.key") == false || File.Exists("details.txt") == false) && HasDependencies())
{
var rand = new Random();
Random rand = new Random();
alias = GeneralUtilities.randomString(8);
password = GeneralUtilities.randomString(16);
string subject = $"CN = {GeneralUtilities.randomString(rand.Next(2, 6))}, OU = {GeneralUtilities.randomString(rand.Next(2, 6))}, O = {GeneralUtilities.randomString(rand.Next(2, 6))}, L = {GeneralUtilities.randomString(rand.Next(2, 6))}, ST = {GeneralUtilities.randomString(rand.Next(2, 6))}, C = {GeneralUtilities.randomString(rand.Next(2, 6))}";
@@ -30,19 +28,19 @@ namespace Spoofer
cmd.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
_ = cmd.Start();
cmd.StandardInput.WriteLine($"keytool -genkeypair -alias {alias} -keyalg RSA -keysize 2048 -keystore keystore.key -keypass {password} -storepass {password} -dname \"{subject}\"");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
string keyerror = cmd.StandardError.ReadToEnd();
string keyoutput = cmd.StandardOutput.ReadToEnd();
Logger.Log($"Output: {keyoutput} Error: {keyerror}");
_ = Logger.Log($"Output: {keyoutput} Error: {keyerror}");
File.WriteAllText("details.txt", $"{alias};{password}");
}
else
{
var temp = File.ReadAllText("details.txt").Split(';');
string[] temp = File.ReadAllText("details.txt").Split(';');
alias = temp[0];
password = temp[1];
}
@@ -71,15 +69,15 @@ namespace Spoofer
{
//Rename
ProcessOutput output = new ProcessOutput("", "");
string oldGameName = Path.GetFileName(apkPath);
_ = Path.GetFileName(apkPath);
folderPath = apkPath.Replace(Path.GetFileName(apkPath), "");
File.Move(apkPath, $"{folderPath}temp.apk");
apkPath = $"{folderPath}temp.apk";
decompiledPath = apkPath.Replace(".apk", "");
//newPackageName = $"com.{Utilities.randomString(rand.Next(3, 8))}.{Utilities.randomString(rand.Next(3, 8))}";
originalPackageName = PackageName(apkPath);
Logger.Log($"Your app will be spoofed as {newPackageName}");
Logger.Log($"Folderpath: {folderPath} decompiledPaht: {decompiledPath} ");
_ = Logger.Log($"Your app will be spoofed as {newPackageName}");
_ = Logger.Log($"Folderpath: {folderPath} decompiledPaht: {decompiledPath} ");
if (obbPath.Length > 1)
{
RenameObb(obbPath, newPackageName, originalPackageName);
@@ -98,7 +96,7 @@ namespace Spoofer
File.WriteAllText(file, foo);
}
}
//spoofedApkPath = $"{Path.GetFileName(apkPath).Replace(".apk", "")}_Spoofed as {newPackageName}.apk";
spoofedApkPath = Path.GetDirectoryName(apkPath) + "\\" + spoofedFileName;
string apkDecompiledPath = Path.GetFileName(apkPath).Replace(".apk", "");
@@ -107,12 +105,18 @@ namespace Spoofer
//Sign the new apk
if (File.Exists(folderPath + "keystore.key") == false)
{
File.Copy("keystore.key", $"{folderPath}keystore.key");
}
output += SignApk(spoofedApkPath);
//Delete the copy of the key and the decompiled apk folder
if (string.Equals(folderPath, Environment.CurrentDirectory + "\\") == false)
{
File.Delete($"{folderPath}keystore.key");
}
Directory.Delete(decompiledPath, true);
File.Delete(apkPath);
@@ -130,7 +134,7 @@ namespace Spoofer
cmdSign.StartInfo.UseShellExecute = false;
cmdSign.StartInfo.RedirectStandardOutput = true; //
cmdSign.StartInfo.RedirectStandardError = true; //
cmdSign.Start();
_ = cmdSign.Start();
cmdSign.StandardInput.WriteLine($"jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore keystore.key \"{path}\" {alias}");
cmdSign.StandardInput.WriteLine(password);
cmdSign.StandardInput.Flush();
@@ -154,9 +158,7 @@ namespace Spoofer
public static bool HasDependencies()
{
if (ExistsOnPath("jarsigner") && ExistsOnPath("apktool") && ExistsOnPath("aapt"))
return true;
return false;
return ExistsOnPath("jarsigner") && ExistsOnPath("apktool") && ExistsOnPath("aapt");
}
public static bool ExistsOnPath(string exeName)
@@ -169,9 +171,9 @@ namespace Spoofer
p.StartInfo.FileName = "where";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Arguments = exeName;
p.Start();
_ = p.Start();
p.WaitForExit();
return p.ExitCode==0;
return p.ExitCode == 0;
}
}
catch
@@ -191,12 +193,14 @@ namespace Spoofer
p.StartInfo.Arguments = exeName;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
_ = p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if (p.ExitCode != 0)
{
return null;
}
// just return first match
return output.Substring(0, output.IndexOf(Environment.NewLine));
@@ -224,10 +228,10 @@ namespace Spoofer
public static string PackageName(string path)
{
Logger.Log($"aapt dump badging \"{path}\"");
_ = Logger.Log($"aapt dump badging \"{path}\"");
string originalPackageName = GeneralUtilities.startProcess("cmd.exe", path.Replace(Path.GetFileName(path), string.Empty), $"aapt dump badging \"{path}\" | findstr -i \"package: name\"").Output;
Logger.Log($"originalPackageName: {originalPackageName}");
_ = Logger.Log($"originalPackageName: {originalPackageName}");
try
{
originalPackageName = originalPackageName.Substring(originalPackageName.IndexOf("package: name='") + 15);

View File

@@ -1 +1 @@
2.16
2.17