upload
This commit is contained in:
commit
1c7a8cf25f
579 files changed
+83196
No files matched your search
@@ -0,0 +1,8 @@
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal enum NetworkCategory
|
||||
{
|
||||
Unknown,
|
||||
Private,
|
||||
Public
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal static class NetworkFacts
|
||||
{
|
||||
internal static string AdvertisedAddress()
|
||||
{
|
||||
IReadOnlyList<string> readOnlyList = Candidates();
|
||||
if (readOnlyList.Count <= 0)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
return readOnlyList[0];
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<string> Candidates()
|
||||
{
|
||||
try
|
||||
{
|
||||
List<(string, int)> list = new List<(string, int)>();
|
||||
List<string> list2 = new List<string>();
|
||||
NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
|
||||
foreach (NetworkInterface networkInterface in allNetworkInterfaces)
|
||||
{
|
||||
if (networkInterface.OperationalStatus != OperationalStatus.Up || networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
IPInterfaceProperties iPProperties;
|
||||
try
|
||||
{
|
||||
iPProperties = networkInterface.GetIPProperties();
|
||||
}
|
||||
catch
|
||||
{
|
||||
continue;
|
||||
}
|
||||
bool flag = iPProperties.GatewayAddresses.Any((GatewayIPAddressInformation g) => g.Address != null && g.Address.AddressFamily == AddressFamily.InterNetwork && !g.Address.Equals(IPAddress.Any));
|
||||
int item = SafeMetric(iPProperties);
|
||||
foreach (UnicastIPAddressInformation unicastAddress in iPProperties.UnicastAddresses)
|
||||
{
|
||||
if (unicastAddress.Address.AddressFamily != AddressFamily.InterNetwork || IPAddress.IsLoopback(unicastAddress.Address))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
string text = unicastAddress.Address.ToString();
|
||||
if (!text.StartsWith("169.254.", StringComparison.Ordinal))
|
||||
{
|
||||
if (flag)
|
||||
{
|
||||
list.Add((text, item));
|
||||
}
|
||||
else
|
||||
{
|
||||
list2.Add(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list.OrderBy(((string Address, int Metric) r) => r.Metric).Select(((string Address, int Metric) r) => r.Address).Concat(list2)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToList();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
}
|
||||
|
||||
private static int SafeMetric(IPInterfaceProperties props)
|
||||
{
|
||||
try
|
||||
{
|
||||
return props.GetIPv4Properties()?.Index ?? int.MaxValue;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return int.MaxValue;
|
||||
}
|
||||
}
|
||||
|
||||
internal static IReadOnlyCollection<string> LocalAddresses()
|
||||
{
|
||||
try
|
||||
{
|
||||
return (from u in (from n in NetworkInterface.GetAllNetworkInterfaces()
|
||||
where n.OperationalStatus == OperationalStatus.Up
|
||||
select n).SelectMany((NetworkInterface n) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
return n.GetIPProperties().UnicastAddresses.AsEnumerable();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Enumerable.Empty<UnicastIPAddressInformation>();
|
||||
}
|
||||
})
|
||||
where u.Address.AddressFamily == AddressFamily.InterNetwork
|
||||
select u.Address.ToString()).Distinct(StringComparer.Ordinal).ToList();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
}
|
||||
|
||||
internal static NetworkCategory Category()
|
||||
{
|
||||
try
|
||||
{
|
||||
Type typeFromCLSID = Type.GetTypeFromCLSID(new Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B"));
|
||||
if (typeFromCLSID == null)
|
||||
{
|
||||
return NetworkCategory.Unknown;
|
||||
}
|
||||
object obj = Activator.CreateInstance(typeFromCLSID);
|
||||
if (obj == null)
|
||||
{
|
||||
return NetworkCategory.Unknown;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!(typeFromCLSID.InvokeMember("GetNetworks", BindingFlags.InvokeMethod, null, obj, new object[1] { 1 }) is IEnumerable enumerable))
|
||||
{
|
||||
return NetworkCategory.Unknown;
|
||||
}
|
||||
NetworkCategory result = NetworkCategory.Unknown;
|
||||
foreach (object item in enumerable)
|
||||
{
|
||||
object obj2 = item.GetType().InvokeMember("GetCategory", BindingFlags.InvokeMethod, null, item, null);
|
||||
if (obj2 != null)
|
||||
{
|
||||
switch (Convert.ToInt32(obj2))
|
||||
{
|
||||
case 0:
|
||||
return NetworkCategory.Public;
|
||||
case 1:
|
||||
case 2:
|
||||
result = NetworkCategory.Private;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Marshal.IsComObject(obj))
|
||||
{
|
||||
Marshal.ReleaseComObject(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return NetworkCategory.Unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal sealed class PhoneBackoff
|
||||
{
|
||||
private readonly object _gate = new object();
|
||||
|
||||
private readonly Dictionary<string, (int Failures, DateTime BlockedUntil)> _bySource = new Dictionary<string, (int, DateTime)>();
|
||||
|
||||
internal bool IsBlocked(string source, DateTime now)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
(int, DateTime) value;
|
||||
return _bySource.TryGetValue(source, out value) && now < value.Item2;
|
||||
}
|
||||
}
|
||||
|
||||
internal void RecordFailure(string source, DateTime now)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_bySource.TryGetValue(source, out (int, DateTime) value);
|
||||
int num = value.Item1 + 1;
|
||||
_bySource[source] = ((num >= 10) ? (0, now + PhoneRequest.BackoffWindow) : (num, value.Item2));
|
||||
}
|
||||
}
|
||||
|
||||
internal void RecordSuccess(string source)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_bySource.Remove(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal sealed class PhoneControl : IDisposable
|
||||
{
|
||||
private const int FlushIntervalMs = 50;
|
||||
|
||||
private const int GestureIdleMs = 250;
|
||||
|
||||
private readonly VibranceEngine _engine;
|
||||
|
||||
private readonly Func<IReadOnlyList<string>> _presetNames;
|
||||
|
||||
private readonly Action<int> _applyPreset;
|
||||
|
||||
private readonly Action _changed;
|
||||
|
||||
private readonly object _gate = new object();
|
||||
|
||||
private readonly Dictionary<string, int> _pending = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
|
||||
private readonly Timer _timer;
|
||||
|
||||
private DateTime _lastSample = DateTime.MinValue;
|
||||
|
||||
private bool _gestureOpen;
|
||||
|
||||
internal PhoneControl(VibranceEngine engine, Func<IReadOnlyList<string>> presetNames, Action<int> applyPreset, Action changed)
|
||||
{
|
||||
_engine = engine;
|
||||
_presetNames = presetNames;
|
||||
_applyPreset = applyPreset;
|
||||
_changed = changed;
|
||||
_timer = new Timer
|
||||
{
|
||||
Interval = 50
|
||||
};
|
||||
_timer.Tick += (object? s, EventArgs e) =>
|
||||
{
|
||||
Flush();
|
||||
};
|
||||
_timer.Start();
|
||||
}
|
||||
|
||||
internal void Queue(string field, int value)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_pending[field] = value;
|
||||
_lastSample = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
internal string StateJson()
|
||||
{
|
||||
List<string> list = new List<string>();
|
||||
try
|
||||
{
|
||||
list.AddRange(_presetNames());
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.Append("{\"controls\":[");
|
||||
for (int i = 0; i < PhoneFields.Sliders.Length; i++)
|
||||
{
|
||||
PhoneField phoneField = PhoneFields.Sliders[i];
|
||||
if (i > 0)
|
||||
{
|
||||
stringBuilder.Append(',');
|
||||
}
|
||||
stringBuilder.Append("{\"key\":\"").Append(phoneField.Key).Append("\",\"label\":\"")
|
||||
.Append(Escape(phoneField.Label))
|
||||
.Append("\",\"min\":")
|
||||
.Append(phoneField.Min)
|
||||
.Append(",\"max\":")
|
||||
.Append(phoneField.Max)
|
||||
.Append(",\"neutral\":")
|
||||
.Append(phoneField.Neutral)
|
||||
.Append(",\"suffix\":\"")
|
||||
.Append(Escape(phoneField.Suffix))
|
||||
.Append("\",\"value\":")
|
||||
.Append(Read(phoneField.Key))
|
||||
.Append('}');
|
||||
}
|
||||
stringBuilder.Append("],\"comparing\":").Append(_engine.IsPreviewingNeutral ? "true" : "false").Append(",\"presets\":[");
|
||||
for (int j = 0; j < list.Count; j++)
|
||||
{
|
||||
if (j > 0)
|
||||
{
|
||||
stringBuilder.Append(',');
|
||||
}
|
||||
stringBuilder.Append('"').Append(Escape(list[j])).Append('"');
|
||||
}
|
||||
stringBuilder.Append("]}");
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
private int Read(string key)
|
||||
{
|
||||
return key switch
|
||||
{
|
||||
"saturation" => _engine.Saturation,
|
||||
"vibrance" => _engine.Vibrance,
|
||||
"brightness" => _engine.Brightness,
|
||||
"gamma" => _engine.Gamma,
|
||||
"contrast" => _engine.Contrast,
|
||||
"temperature" => _engine.Temperature,
|
||||
"highlights" => _engine.Tone.Highlights,
|
||||
"shadows" => _engine.Tone.Shadows,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
private static string Escape(string text)
|
||||
{
|
||||
StringBuilder stringBuilder = new StringBuilder(text.Length);
|
||||
foreach (char c in text)
|
||||
{
|
||||
if (c == '"' || c == '\\')
|
||||
{
|
||||
stringBuilder.Append('\\').Append(c);
|
||||
}
|
||||
else if (c < ' ')
|
||||
{
|
||||
stringBuilder.Append(' ');
|
||||
}
|
||||
else
|
||||
{
|
||||
stringBuilder.Append(c);
|
||||
}
|
||||
}
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
internal void PumpForTest()
|
||||
{
|
||||
Flush();
|
||||
}
|
||||
|
||||
private void Flush()
|
||||
{
|
||||
bool flag;
|
||||
KeyValuePair<string, int>[] array;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
flag = _gestureOpen && (DateTime.UtcNow - _lastSample).TotalMilliseconds > 250.0;
|
||||
if (!flag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
array = Array.Empty<KeyValuePair<string, int>>();
|
||||
}
|
||||
else
|
||||
{
|
||||
array = new KeyValuePair<string, int>[_pending.Count];
|
||||
((ICollection<KeyValuePair<string, int>>)_pending).CopyTo(array, 0);
|
||||
_pending.Clear();
|
||||
flag = false;
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
KeyValuePair<string, int>[] array2 = array;
|
||||
for (int i = 0; i < array2.Length; i++)
|
||||
{
|
||||
KeyValuePair<string, int> keyValuePair = array2[i];
|
||||
if (keyValuePair.Key == "preset")
|
||||
{
|
||||
CloseGesture();
|
||||
_applyPreset(keyValuePair.Value);
|
||||
continue;
|
||||
}
|
||||
if (keyValuePair.Key == "compare")
|
||||
{
|
||||
CloseGesture();
|
||||
_engine.PreviewNeutral(keyValuePair.Value != 0);
|
||||
continue;
|
||||
}
|
||||
if (!_gestureOpen)
|
||||
{
|
||||
_engine.BeginDrag();
|
||||
_gestureOpen = true;
|
||||
}
|
||||
if (_engine.IsPreviewingNeutral)
|
||||
{
|
||||
_engine.PreviewNeutral(on: false);
|
||||
}
|
||||
switch (keyValuePair.Key)
|
||||
{
|
||||
case "saturation":
|
||||
_engine.DriverKnobFollows = DisplayOnlyLook.Knob.Saturation;
|
||||
_engine.Saturation = keyValuePair.Value;
|
||||
break;
|
||||
case "vibrance":
|
||||
_engine.DriverKnobFollows = DisplayOnlyLook.Knob.Vibrance;
|
||||
_engine.Vibrance = keyValuePair.Value;
|
||||
break;
|
||||
case "brightness":
|
||||
_engine.Brightness = keyValuePair.Value;
|
||||
break;
|
||||
case "gamma":
|
||||
_engine.Gamma = keyValuePair.Value;
|
||||
break;
|
||||
case "contrast":
|
||||
_engine.Contrast = keyValuePair.Value;
|
||||
break;
|
||||
case "temperature":
|
||||
_engine.Temperature = keyValuePair.Value;
|
||||
break;
|
||||
case "highlights":
|
||||
_engine.Tone = _engine.Tone with
|
||||
{
|
||||
Highlights = keyValuePair.Value
|
||||
};
|
||||
break;
|
||||
case "shadows":
|
||||
_engine.Tone = _engine.Tone with
|
||||
{
|
||||
Shadows = keyValuePair.Value
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (flag)
|
||||
{
|
||||
CloseGesture();
|
||||
}
|
||||
if ((array.Length != 0) | flag)
|
||||
{
|
||||
_changed();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
CloseGesture();
|
||||
}
|
||||
}
|
||||
|
||||
private void CloseGesture()
|
||||
{
|
||||
if (_gestureOpen)
|
||||
{
|
||||
_gestureOpen = false;
|
||||
_engine.EndDrag();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer.Stop();
|
||||
_timer.Dispose();
|
||||
CloseGesture();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal readonly record struct PhoneDecision(PhoneVerdict Verdict, string Field, int Value)
|
||||
{
|
||||
public static PhoneDecision Of(PhoneVerdict verdict)
|
||||
{
|
||||
return new PhoneDecision(verdict, "", 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal readonly record struct PhoneField(string Key, string Label, int Min, int Max, int Neutral, string Suffix);
|
||||
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal static class PhoneFields
|
||||
{
|
||||
private const int ToneMin = -100;
|
||||
|
||||
private const int ToneMax = 100;
|
||||
|
||||
internal static readonly PhoneField[] Sliders = new PhoneField[8]
|
||||
{
|
||||
new PhoneField("saturation", "Saturation", 0, 300, 100, "%"),
|
||||
new PhoneField("vibrance", "Vibrance", 0, 350, 50, "%"),
|
||||
new PhoneField("brightness", "Brightness", 50, 170, 100, "%"),
|
||||
new PhoneField("gamma", "Gamma", 50, 150, 100, "%"),
|
||||
new PhoneField("contrast", "Contrast", 50, 150, 100, "%"),
|
||||
new PhoneField("temperature", "Temperature", -100, 100, 0, ""),
|
||||
new PhoneField("highlights", "Highlights", -100, 100, 0, ""),
|
||||
new PhoneField("shadows", "Shadows", -100, 100, 0, "")
|
||||
};
|
||||
|
||||
internal const string Preset = "preset";
|
||||
|
||||
internal const string Compare = "compare";
|
||||
|
||||
internal static bool TryFind(string key, out PhoneField field)
|
||||
{
|
||||
PhoneField[] sliders = Sliders;
|
||||
for (int i = 0; i < sliders.Length; i++)
|
||||
{
|
||||
PhoneField phoneField = sliders[i];
|
||||
if (string.Equals(phoneField.Key, key, StringComparison.Ordinal))
|
||||
{
|
||||
field = phoneField;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
field = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static bool IsAllowed(string key)
|
||||
{
|
||||
PhoneField field;
|
||||
if (!(key == "preset") && !(key == "compare"))
|
||||
{
|
||||
return TryFind(key, out field);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static int Clamp(string key, int value)
|
||||
{
|
||||
if (TryFind(key, out var field))
|
||||
{
|
||||
return Math.Clamp(value, field.Min, field.Max);
|
||||
}
|
||||
return Math.Clamp(value, 0, 1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal sealed class PhoneListener : IDisposable
|
||||
{
|
||||
private readonly PhoneControl _control;
|
||||
|
||||
private readonly PhoneBackoff _backoff = new PhoneBackoff();
|
||||
|
||||
private TcpListener? _listener;
|
||||
|
||||
private CancellationTokenSource? _stopping;
|
||||
|
||||
private int _everAnswered;
|
||||
|
||||
private static readonly TimeSpan HeadTimeout = TimeSpan.FromSeconds(5.0);
|
||||
|
||||
internal string Token { get; private set; } = "";
|
||||
|
||||
internal int Port { get; private set; }
|
||||
|
||||
internal string AdvertisedAddress { get; set; } = "";
|
||||
|
||||
internal bool IsRunning => _listener != null;
|
||||
|
||||
internal IPAddress BindAddress { get; set; } = IPAddress.Any;
|
||||
|
||||
internal event Action? PhoneArrived;
|
||||
|
||||
internal event Action<string, string>? WrongNetworkSeen;
|
||||
|
||||
internal PhoneListener(PhoneControl control)
|
||||
{
|
||||
_control = control;
|
||||
}
|
||||
|
||||
internal void Start()
|
||||
{
|
||||
if (_listener == null)
|
||||
{
|
||||
Token = PhoneSession.NewToken();
|
||||
_stopping = new CancellationTokenSource();
|
||||
TcpListener listener = new TcpListener(BindAddress, 0);
|
||||
listener.Start();
|
||||
_listener = listener;
|
||||
Port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
Interlocked.Exchange(ref _everAnswered, 0);
|
||||
Task.Run(() => AcceptLoopAsync(listener, _stopping.Token));
|
||||
}
|
||||
}
|
||||
|
||||
internal void Stop()
|
||||
{
|
||||
TcpListener listener = _listener;
|
||||
_listener = null;
|
||||
Token = "";
|
||||
Port = 0;
|
||||
try
|
||||
{
|
||||
_stopping?.Cancel();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
try
|
||||
{
|
||||
listener?.Stop();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
_stopping?.Dispose();
|
||||
_stopping = null;
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(TcpListener listener, CancellationToken stopping)
|
||||
{
|
||||
while (!stopping.IsCancellationRequested)
|
||||
{
|
||||
TcpClient client;
|
||||
try
|
||||
{
|
||||
client = await listener.AcceptTcpClientAsync(stopping);
|
||||
}
|
||||
catch
|
||||
{
|
||||
break;
|
||||
}
|
||||
Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await ServeAsync(client, stopping);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
client.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ServeAsync(TcpClient client, CancellationToken stopping)
|
||||
{
|
||||
client.ReceiveTimeout = 5000;
|
||||
client.SendTimeout = 5000;
|
||||
string remote = (client.Client.RemoteEndPoint as IPEndPoint)?.Address.ToString() ?? "";
|
||||
using NetworkStream stream = client.GetStream();
|
||||
using CancellationTokenSource deadline = CancellationTokenSource.CreateLinkedTokenSource(stopping);
|
||||
deadline.CancelAfter(HeadTimeout);
|
||||
(string, string, string) tuple;
|
||||
try
|
||||
{
|
||||
tuple = await ReadHeadAsync(stream, deadline.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
(string, string, string) tuple2 = tuple;
|
||||
string item = tuple2.Item1;
|
||||
string item2 = tuple2.Item2;
|
||||
string item3 = tuple2.Item3;
|
||||
PhoneDecision phoneDecision = PhoneRequest.Decide(item, item2, item3, remote, AdvertisedAddress, NetworkFacts.LocalAddresses(), Token, _backoff, DateTime.UtcNow);
|
||||
switch (phoneDecision.Verdict)
|
||||
{
|
||||
case PhoneVerdict.Page:
|
||||
await WriteAsync(stream, 200, "text/html; charset=utf-8", PhonePage.Html());
|
||||
break;
|
||||
case PhoneVerdict.State:
|
||||
NoteArrival();
|
||||
await WriteAsync(stream, 200, "application/json; charset=utf-8", _control.StateJson());
|
||||
break;
|
||||
case PhoneVerdict.Apply:
|
||||
NoteArrival();
|
||||
_control.Queue(phoneDecision.Field, phoneDecision.Value);
|
||||
await WriteAsync(stream, 200, "text/plain; charset=utf-8", "ok");
|
||||
break;
|
||||
case PhoneVerdict.BadRequest:
|
||||
await WriteAsync(stream, 400, "text/plain; charset=utf-8", "bad request");
|
||||
break;
|
||||
case PhoneVerdict.TooManyAttempts:
|
||||
await WriteAsync(stream, 429, "text/plain; charset=utf-8", "slow down");
|
||||
break;
|
||||
case PhoneVerdict.WrongNetwork:
|
||||
WrongNetworkSeen?.Invoke(remote, AdvertisedAddress);
|
||||
await WriteAsync(stream, 200, "text/html; charset=utf-8", PhonePage.WrongNetworkHtml(remote, AdvertisedAddress));
|
||||
break;
|
||||
default:
|
||||
await WriteAsync(stream, 404, "text/plain; charset=utf-8", "not found");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void NoteArrival()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _everAnswered, 1) == 0)
|
||||
{
|
||||
PhoneArrived?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<(string Method, string Target, string? Host)> ReadHeadAsync(NetworkStream stream, CancellationToken stopping)
|
||||
{
|
||||
byte[] buffer = new byte[8192];
|
||||
int filled = 0;
|
||||
while (filled < buffer.Length)
|
||||
{
|
||||
int num = await stream.ReadAsync(buffer.AsMemory(filled, buffer.Length - filled), stopping);
|
||||
if (num <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
filled += num;
|
||||
string text = Encoding.ASCII.GetString(buffer, 0, filled);
|
||||
if (text.Contains("\r\n\r\n", StringComparison.Ordinal) || text.Contains("\n\n", StringComparison.Ordinal))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
string s = Encoding.ASCII.GetString(buffer, 0, filled);
|
||||
string item = "";
|
||||
string item2 = "";
|
||||
string item3 = null;
|
||||
using StringReader stringReader = new StringReader(s);
|
||||
string text2 = stringReader.ReadLine();
|
||||
if (text2 != null)
|
||||
{
|
||||
string[] array = text2.Split(' ');
|
||||
if (array.Length >= 2)
|
||||
{
|
||||
item = array[0];
|
||||
item2 = array[1];
|
||||
}
|
||||
}
|
||||
while ((text2 = stringReader.ReadLine()) != null && text2.Length != 0)
|
||||
{
|
||||
int num2 = text2.IndexOf(':');
|
||||
if (num2 > 0 && MemoryExtensions.Equals(text2.AsSpan(0, num2).Trim(), "Host", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
item3 = text2.Substring(num2 + 1).Trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return (Method: item, Target: item2, Host: item3);
|
||||
}
|
||||
|
||||
private static async Task WriteAsync(NetworkStream stream, int status, string type, string body)
|
||||
{
|
||||
byte[] payload = Encoding.UTF8.GetBytes(body);
|
||||
string s = new StringBuilder().Append("HTTP/1.1 ").Append(status).Append(' ')
|
||||
.Append(Reason(status))
|
||||
.Append("\r\n")
|
||||
.Append("Content-Type: ")
|
||||
.Append(type)
|
||||
.Append("\r\n")
|
||||
.Append("Content-Length: ")
|
||||
.Append(payload.Length)
|
||||
.Append("\r\n")
|
||||
.Append("Cache-Control: no-store\r\n")
|
||||
.Append("X-Content-Type-Options: nosniff\r\n")
|
||||
.Append("Referrer-Policy: no-referrer\r\n")
|
||||
.Append("Connection: close\r\n\r\n")
|
||||
.ToString();
|
||||
byte[] bytes = Encoding.ASCII.GetBytes(s);
|
||||
await stream.WriteAsync(bytes);
|
||||
await stream.WriteAsync(payload);
|
||||
await stream.FlushAsync();
|
||||
}
|
||||
|
||||
private static string Reason(int status)
|
||||
{
|
||||
return status switch
|
||||
{
|
||||
200 => "OK",
|
||||
400 => "Bad Request",
|
||||
404 => "Not Found",
|
||||
429 => "Too Many Requests",
|
||||
_ => "OK",
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal static class PhonePage
|
||||
{
|
||||
internal static string Html()
|
||||
{
|
||||
return "<!doctype html>\r\n<html lang=\"en\">\r\n<head>\r\n<meta charset=\"utf-8\">\r\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,viewport-fit=cover\">\r\n<meta name=\"robots\" content=\"noindex,nofollow\">\r\n<meta name=\"theme-color\" content=\"#151515\">\r\n<title>PlexusX</title>\r\n<style>\r\n /* final/tokens.css, data-look=\"ash\". Nothing on this page is any other colour. */\r\n :root{\r\n --bg:#151515; --surface-1:#1C1C1C; --surface-2:#232323; --pressed:#393939;\r\n --border:#333333; --border-strong:#747474; --track:#3D3D3D;\r\n --text-1:#F3F3F3; --text-2:#C1C1C1; --text-3:#999999;\r\n --accent:#FFFFFF; --accent-pressed:#C4C4C4; --on-accent:#151515; --focus:#FFFFFF;\r\n --knob-ring:#1C1C1C; --success:#5ECE83; --danger:#FF9E93;\r\n --pad:16px;\r\n /* Half the 44 px touch box the knob is drawn in: where the knob's centre sits at either\r\n end of a slider, so the track, the fill and the default tick run between them. */\r\n --knob:22px;\r\n }\r\n *{box-sizing:border-box; -webkit-tap-highlight-color:transparent}\r\n html,body{overscroll-behavior-y:contain}\r\n body{\r\n /* 150 at the bottom, and it was 120. The compare bar is pinned and about 90px tall\r\n before the safe-area inset, so at 120 it sat 136px over the Scenes card - measured,\r\n and invisible from the code because the bar is out of flow. */\r\n margin:0; padding:24px var(--pad) 150px; background:var(--bg); color:var(--text-1);\r\n font:16px/1.55 -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,sans-serif;\r\n }\r\n\r\n header{display:flex; align-items:center; justify-content:space-between; margin-bottom:16px}\r\n h1{font-size:20px; line-height:1.3; font-weight:600; margin:0}\r\n\r\n /* components.md §26, inline status: the icon in the status colour, 8, the word in text-1. */\r\n .live{display:flex; align-items:center; gap:8px; font-size:14px; font-weight:600; color:var(--text-1)}\r\n .ico{width:16px; height:16px; flex:none}\r\n .live .ico{display:none}\r\n .live.ok .ico-ok, .live.bad .ico-bad{display:block}\r\n .ico-ok{color:var(--success)}\r\n .ico-bad{color:var(--danger)}\r\n\r\n /* §17: a card - surface-1, a hairline border, radius 8. */\r\n .group{background:var(--surface-1); border:1px solid var(--border); border-radius:8px;\r\n padding:8px var(--pad) 16px; margin-bottom:16px}\r\n .cap{font-size:16px; font-weight:600; color:var(--text-1); margin:8px 0 12px}\r\n\r\n .row{padding:8px 0 0}\r\n .head{display:flex; justify-content:space-between; align-items:baseline}\r\n .name{font-size:16px; color:var(--text-2)}\r\n .val{font-variant-numeric:tabular-nums; color:var(--text-1); font-weight:600; font-size:16px}\r\n .val.off{color:var(--text-3)}\r\n\r\n /* §8, drawn under the range: the 2 px track, the white fill, and the 1 px default tick.\r\n Knowing where \"untouched\" is turns a slider from a number into a decision - it is the\r\n difference between \"gamma 96\" and \"a touch under neutral\". */\r\n .wrap{position:relative}\r\n .line{position:absolute; left:var(--knob); right:var(--knob); top:50%; height:2px;\r\n margin-top:-1px; background:var(--track); pointer-events:none}\r\n .fill{position:absolute; top:50%; height:4px; margin-top:-2px; background:var(--accent);\r\n pointer-events:none}\r\n .tick{position:absolute; top:50%; width:1px; height:14px; margin-top:-7px;\r\n background:var(--text-3); pointer-events:none}\r\n\r\n input[type=range]{\r\n -webkit-appearance:none; appearance:none; width:100%; height:44px;\r\n background:transparent; margin:0; display:block; position:relative;\r\n }\r\n input[type=range]::-webkit-slider-runnable-track{height:44px; background:transparent}\r\n input[type=range]::-moz-range-track{height:44px; background:transparent}\r\n /* The knob: a white disc in its 2 px knob-ring, drawn in the middle of a 44 px touch box. */\r\n input[type=range]::-webkit-slider-thumb{\r\n -webkit-appearance:none; appearance:none; width:44px; height:44px; border:0; border-radius:50%;\r\n background:radial-gradient(circle, var(--accent) 7px, var(--knob-ring) 7px,\r\n var(--knob-ring) 9px, transparent 9px);\r\n }\r\n input[type=range]::-moz-range-thumb{\r\n width:44px; height:44px; border:0; border-radius:50%;\r\n background:radial-gradient(circle, var(--accent) 7px, var(--knob-ring) 7px,\r\n var(--knob-ring) 9px, transparent 9px);\r\n }\r\n input[type=range]:focus-visible{outline:2px solid var(--focus); outline-offset:2px}\r\n\r\n /* §3: every button Secondary but the one Primary; radius 4, 44 tall, 8 apart. */\r\n .presets{display:grid; grid-template-columns:repeat(2,1fr); gap:8px}\r\n button{font:inherit; font-weight:600; color:var(--text-1); background:transparent;\r\n border:1px solid var(--border-strong); border-radius:4px; min-height:44px;\r\n padding:12px 16px; cursor
Line truncated
|
||||
}
|
||||
|
||||
internal static string WrongNetworkHtml(string theirs, string ours)
|
||||
{
|
||||
return $"<!doctype html>\r\n<html lang=\"en\">\r\n<head>\r\n<meta charset=\"utf-8\">\r\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,viewport-fit=cover\">\r\n<meta name=\"robots\" content=\"noindex,nofollow\">\r\n<meta name=\"theme-color\" content=\"#151515\">\r\n<title>Different network - PlexusX</title>\r\n<style>\r\n body{{margin:0; padding:24px 16px; background:#151515; color:#F3F3F3;\r\n font:16px/1.55 -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,sans-serif}}\r\n h1{{font-size:20px; line-height:1.3; font-weight:600; margin:0 0 12px}}\r\n p{{color:#C1C1C1; margin:0 0 12px}}\r\n .rows{{background:#1C1C1C; border:1px solid #333333; border-radius:8px;\r\n padding:12px 16px; margin:16px 0}}\r\n .row{{display:flex; justify-content:space-between; gap:16px; padding:4px 0;\r\n font:14px/1.5 Consolas,ui-monospace,SFMono-Regular,Menlo,monospace}}\r\n .row span:first-child{{color:#999999}}\r\n ul{{color:#C1C1C1; margin:0 0 12px; padding-left:20px}}\r\n li{{margin:8px 0}}\r\n</style>\r\n</head>\r\n<body>\r\n<h1>Your phone is on a different network</h1>\r\n<p>It reached this PC, but PlexusX only takes commands from your own network.</p>\r\n<div class=\"rows\">\r\n <div class=\"row\"><span>This phone</span><span>{theirs}</span></div>\r\n <div class=\"row\"><span>Your PC</span><span>{ours}</span></div>\r\n</div>\r\n<p>Those two need to start with the same three numbers. Usually one of these fixes it:</p>\r\n<ul>\r\n <li>The phone is on a <strong>guest</strong> wifi. Switch it to your normal one.</li>\r\n <li>The phone is on <strong>mobile data</strong>, not wifi.</li>\r\n <li>Your router has two networks (often one ending 2.4G and one 5G) that it keeps apart.</li>\r\n</ul>\r\n<p>Your PC being on a cable is fine - that is not the problem.</p>\r\n</body>\r\n</html>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal static class PhoneRequest
|
||||
{
|
||||
internal const int AttemptsBeforeBackoff = 10;
|
||||
|
||||
internal static readonly TimeSpan BackoffWindow = TimeSpan.FromMinutes(1.0);
|
||||
|
||||
internal static readonly string[] Fields = BuildFieldNames();
|
||||
|
||||
private static string[] BuildFieldNames()
|
||||
{
|
||||
List<string> list = new List<string>();
|
||||
PhoneField[] sliders = PhoneFields.Sliders;
|
||||
foreach (PhoneField phoneField in sliders)
|
||||
{
|
||||
list.Add(phoneField.Key);
|
||||
}
|
||||
list.Add("preset");
|
||||
list.Add("compare");
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
internal static PhoneDecision Decide(string method, string target, string? hostHeader, string remoteAddress, string advertisedAddress, IReadOnlyCollection<string> localAddresses, string sessionToken, PhoneBackoff backoff, DateTime now)
|
||||
{
|
||||
string text = HostName(hostHeader);
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.BadRequest);
|
||||
}
|
||||
if (!IsOurs(text, localAddresses))
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.NotFound);
|
||||
}
|
||||
if (!IsAllowedSource(remoteAddress, advertisedAddress))
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.WrongNetwork);
|
||||
}
|
||||
if (backoff.IsBlocked(remoteAddress, now))
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.TooManyAttempts);
|
||||
}
|
||||
string text2 = PathOf(target);
|
||||
if (!TokensMatch(QueryValue(target, "k"), sessionToken))
|
||||
{
|
||||
if (text2 == "/" && Method(method) == "GET")
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.Page);
|
||||
}
|
||||
backoff.RecordFailure(remoteAddress, now);
|
||||
return PhoneDecision.Of(PhoneVerdict.NotFound);
|
||||
}
|
||||
backoff.RecordSuccess(remoteAddress);
|
||||
string text3 = Method(method);
|
||||
if (!(text3 == "GET"))
|
||||
{
|
||||
if (text3 == "POST" && text2 == "/a")
|
||||
{
|
||||
return ApplyFrom(target);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (text2 == "/")
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.Page);
|
||||
}
|
||||
if (text2 == "/s")
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.State);
|
||||
}
|
||||
}
|
||||
return PhoneDecision.Of(PhoneVerdict.NotFound);
|
||||
}
|
||||
|
||||
private static PhoneDecision ApplyFrom(string target)
|
||||
{
|
||||
string text = QueryValue(target, "f");
|
||||
string text2 = QueryValue(target, "v");
|
||||
if (text == null || text2 == null)
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.NotFound);
|
||||
}
|
||||
if (!PhoneFields.IsAllowed(text))
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.NotFound);
|
||||
}
|
||||
if (!int.TryParse(text2, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
|
||||
{
|
||||
return PhoneDecision.Of(PhoneVerdict.NotFound);
|
||||
}
|
||||
result = PhoneFields.Clamp(text, result);
|
||||
return new PhoneDecision(PhoneVerdict.Apply, text, result);
|
||||
}
|
||||
|
||||
internal static bool TokensMatch(string? candidate, string expected)
|
||||
{
|
||||
if (string.IsNullOrEmpty(expected))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (candidate == null || candidate.Length != expected.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
int num = 0;
|
||||
for (int i = 0; i < expected.Length; i++)
|
||||
{
|
||||
num |= candidate[i] ^ expected[i];
|
||||
}
|
||||
return num == 0;
|
||||
}
|
||||
|
||||
internal static bool IsAllowedSource(string remote, string advertised)
|
||||
{
|
||||
if (string.IsNullOrEmpty(remote))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (remote == "127.0.0.1" || remote == "::1")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (string.IsNullOrEmpty(advertised))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
string text = SubnetOf(remote);
|
||||
if (text != null && text.Length > 0)
|
||||
{
|
||||
string text2 = SubnetOf(advertised);
|
||||
if (text2 != null && text2.Length > 0)
|
||||
{
|
||||
return string.Equals(text, text2, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string SubnetOf(string address)
|
||||
{
|
||||
int num = address.LastIndexOf('.');
|
||||
if (num > 0)
|
||||
{
|
||||
return address.Substring(0, num);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
internal static bool IsOurs(string host, IReadOnlyCollection<string> localAddresses)
|
||||
{
|
||||
if (host == "localhost" || host == "127.0.0.1")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
foreach (string localAddress in localAddresses)
|
||||
{
|
||||
if (string.Equals(host, localAddress, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static string HostName(string? header)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(header))
|
||||
{
|
||||
return "";
|
||||
}
|
||||
string text = header.Trim();
|
||||
if (text.StartsWith("[", StringComparison.Ordinal))
|
||||
{
|
||||
int num = text.IndexOf(']');
|
||||
if (num <= 0)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
return text.Substring(1, num - 1);
|
||||
}
|
||||
int num2 = text.IndexOf(':');
|
||||
if (num2 < 0)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
return text.Substring(0, num2);
|
||||
}
|
||||
|
||||
internal static string Method(string method)
|
||||
{
|
||||
return (method ?? "").Trim().ToUpperInvariant();
|
||||
}
|
||||
|
||||
internal static string PathOf(string target)
|
||||
{
|
||||
if (string.IsNullOrEmpty(target))
|
||||
{
|
||||
return "/";
|
||||
}
|
||||
int num = target.IndexOf('?');
|
||||
string text = ((num >= 0) ? target.Substring(0, num) : target);
|
||||
if (!string.IsNullOrEmpty(text))
|
||||
{
|
||||
return text;
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
|
||||
internal static string? QueryValue(string target, string name)
|
||||
{
|
||||
int num = target.IndexOf('?');
|
||||
if (num < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string[] array = target.Substring(num + 1).Split('&');
|
||||
foreach (string text in array)
|
||||
{
|
||||
int num2 = text.IndexOf('=');
|
||||
if (num2 > 0 && string.Equals(text.Substring(0, num2), name, StringComparison.Ordinal))
|
||||
{
|
||||
return Uri.UnescapeDataString(text.Substring(num2 + 1));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using VibranceHud.Licensing;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal static class PhoneSession
|
||||
{
|
||||
internal static readonly TimeSpan HintAfter = TimeSpan.FromSeconds(45.0);
|
||||
|
||||
internal static string NewToken()
|
||||
{
|
||||
return NewToken(ServedPairing.Current);
|
||||
}
|
||||
|
||||
internal static string NewToken(PairingFormat format)
|
||||
{
|
||||
if (format == null || format.Withheld)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
int length = format.Alphabet.Length;
|
||||
if (length != 32)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
int num = format.TokenBits / 8;
|
||||
if (num < 8 || num > 64)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
Span<byte> span = stackalloc byte[64];
|
||||
span = span.Slice(0, num);
|
||||
RandomNumberGenerator.Fill(span);
|
||||
StringBuilder stringBuilder = new StringBuilder(format.TokenLength);
|
||||
int num2 = 0;
|
||||
int num3 = 0;
|
||||
Span<byte> span2 = span;
|
||||
for (int i = 0; i < span2.Length; i++)
|
||||
{
|
||||
byte b = span2[i];
|
||||
num3 = (num3 << 8) | b;
|
||||
num2 += 8;
|
||||
while (num2 >= 5)
|
||||
{
|
||||
num2 -= 5;
|
||||
stringBuilder.Append(format.Alphabet[(num3 >> num2) & (length - 1)]);
|
||||
}
|
||||
}
|
||||
if (num2 > 0)
|
||||
{
|
||||
stringBuilder.Append(format.Alphabet[(num3 << 5 - num2) & (length - 1)]);
|
||||
}
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
internal static string Url(string address, int port, string token)
|
||||
{
|
||||
return ServedPairing.Current.Url(address, port, token);
|
||||
}
|
||||
|
||||
internal static string FirewallAdvice(NetworkCategory category)
|
||||
{
|
||||
return category switch
|
||||
{
|
||||
NetworkCategory.Public => "Windows will ask whether to let PlexusX use the network. It will say \"Publisher: Unknown\" — that's expected, PlexusX isn't code-signed yet.\n\nYour network is set to Public, so you need to tick \"Public networks\" — the box Windows leaves unticked. The pre-ticked \"Private\" box on its own will not let your phone through.",
|
||||
NetworkCategory.Private => "Windows will ask whether to let PlexusX use the network. It will say \"Publisher: Unknown\" — that's expected, PlexusX isn't code-signed yet.\n\nYour network is set to Private, so the box Windows has already ticked is the right one. Just press Allow.",
|
||||
_ => "Windows will ask whether to let PlexusX use the network. It will say \"Publisher: Unknown\" — that's expected, PlexusX isn't code-signed yet.\n\nTick whichever box matches the network you're on. If you're not sure, tick both — your phone can only reach PlexusX through the one Windows is actually using.",
|
||||
};
|
||||
}
|
||||
|
||||
internal static string RepairAdvice()
|
||||
{
|
||||
return "If you pressed Cancel on that prompt, PlexusX cannot undo it — Windows only lets an administrator change firewall rules.\n\nOpen Windows Security → Firewall & network protection → Allow an app through firewall, find PlexusX, and tick the network you're on.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal enum PhoneVerdict
|
||||
{
|
||||
BadRequest,
|
||||
NotFound,
|
||||
WrongNetwork,
|
||||
TooManyAttempts,
|
||||
Page,
|
||||
State,
|
||||
Apply
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Drawing2D;
|
||||
using System.Windows.Forms;
|
||||
using VibranceHud.Controls;
|
||||
using VibranceHud.Design;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal sealed class PhoneWindow : SignalDialogWindow
|
||||
{
|
||||
private readonly PhoneListener _listener;
|
||||
|
||||
private readonly Label _address = new Label();
|
||||
|
||||
private readonly Label _advice = new Label();
|
||||
|
||||
private readonly Label _hint = new Label();
|
||||
|
||||
private readonly GlassButton _otherNetwork = new GlassButton();
|
||||
|
||||
private readonly GlassButton _close = new GlassButton();
|
||||
|
||||
private readonly Timer _hintTimer = new Timer();
|
||||
|
||||
private IReadOnlyList<string> _candidates = Array.Empty<string>();
|
||||
|
||||
private int _candidate;
|
||||
|
||||
private Bitmap? _qr;
|
||||
|
||||
private bool _paired;
|
||||
|
||||
private SignalIcon _statusIcon;
|
||||
|
||||
private const int QrSide = 172;
|
||||
|
||||
private const int TilePad = 16;
|
||||
|
||||
private const int TileSide = 204;
|
||||
|
||||
private const int WindowWidth = 460;
|
||||
|
||||
private const int Pad = 24;
|
||||
|
||||
private const int TitleTop = 23;
|
||||
|
||||
private const int TitleLine = 28;
|
||||
|
||||
private const int LineTop = 60;
|
||||
|
||||
private const int LineHeight = 20;
|
||||
|
||||
private const int QrTop = 96;
|
||||
|
||||
private const int AddressTop = 316;
|
||||
|
||||
private const int FieldHeight = 32;
|
||||
|
||||
private const int HelpTop = 352;
|
||||
|
||||
private const int CaptionLine = 16;
|
||||
|
||||
private const int StatusTop = 384;
|
||||
|
||||
private const int IconSize = 16;
|
||||
|
||||
private const int IconGap = 8;
|
||||
|
||||
private const int TileRadius = 8;
|
||||
|
||||
private const int FieldRadius = 4;
|
||||
|
||||
private readonly float _scale = 1f;
|
||||
|
||||
internal Rectangle QrTileForTest => Tile();
|
||||
|
||||
internal Rectangle AddressFieldForTest => _address.Bounds;
|
||||
|
||||
internal Label AddressLabelForTest => _address;
|
||||
|
||||
internal float ScaleForTest => _scale;
|
||||
|
||||
internal Label StatusLabelForTest => _hint;
|
||||
|
||||
internal SignalIcon StatusIconForTest => _statusIcon;
|
||||
|
||||
internal Color StatusInkForTest => InkFor(_statusIcon);
|
||||
|
||||
internal PhoneWindow(PhoneListener listener)
|
||||
{
|
||||
_listener = listener;
|
||||
FormBorderStyle = FormBorderStyle.None;
|
||||
StartPosition = FormStartPosition.CenterParent;
|
||||
BackColor = ControlInk.Overlay;
|
||||
DoubleBuffered = true;
|
||||
Icon = AppIcon.Value;
|
||||
KeyPreview = true;
|
||||
_scale = (float)SignalInk.DpiFor(this) / 96f;
|
||||
int num = 412;
|
||||
int num2 = (int)Math.Round((float)SignalDialogWindow.GlyphPad(Fonts.Title) / _scale);
|
||||
Controls.Add(Words("Control PlexusX from your phone", Fonts.Title, Theme.Text, new Rectangle(26 - num2, 23, num, 28), ContentAlignment.TopLeft));
|
||||
int num3 = (int)Math.Round((float)SignalDialogWindow.GlyphPad(Fonts.Body) / _scale);
|
||||
if (_scale == 1f || _scale == 2f)
|
||||
{
|
||||
num3++;
|
||||
}
|
||||
Controls.Add(Words("Scan it. Your phone has to be on the same Wi-Fi.", Fonts.Body, Theme.TextDim, new Rectangle(26 - num3, 60, num + num3 - 2, 20), ContentAlignment.TopLeft));
|
||||
_address.Bounds = new Rectangle(128, 316, 204, 32);
|
||||
_address.ForeColor = Theme.Text;
|
||||
_address.Font = Fonts.Mono;
|
||||
_address.TextAlign = ContentAlignment.MiddleCenter;
|
||||
_address.BackColor = Color.Transparent;
|
||||
_address.UseMnemonic = false;
|
||||
Controls.Add(_address);
|
||||
Controls.Add(Words("Or type that into your phone's browser.", Fonts.Caption, Theme.TextFaint, new Rectangle(24, 352, num, 16), ContentAlignment.TopCenter));
|
||||
int num4 = 48;
|
||||
int width = 436 - num4;
|
||||
int num5 = Measure(WrongNetworkLine("255.255.255.255", "255.255.255.255"), Fonts.Caption, width, 16);
|
||||
_hint.Bounds = new Rectangle(num4, 384, width, num5);
|
||||
_hint.ForeColor = Theme.Text;
|
||||
_hint.Font = Fonts.Caption;
|
||||
_hint.TextAlign = ContentAlignment.TopLeft;
|
||||
_hint.BackColor = Color.Transparent;
|
||||
_hint.UseMnemonic = false;
|
||||
_hint.Visible = false;
|
||||
Controls.Add(_hint);
|
||||
int num6 = 384 + num5 + 16;
|
||||
int num7 = 16;
|
||||
foreach (NetworkCategory value in Enum.GetValues(typeof(NetworkCategory)))
|
||||
{
|
||||
num7 = Math.Max(num7, Measure(PhoneSession.FirewallAdvice(value), Fonts.Caption, num, 16));
|
||||
}
|
||||
int num8 = (int)Math.Round((float)SignalDialogWindow.GlyphPad(Fonts.Caption) / _scale);
|
||||
if (_scale == 1f)
|
||||
{
|
||||
num8 += 2;
|
||||
}
|
||||
_advice.Bounds = new Rectangle(26 - num8, num6, num + num8 - 2, num7);
|
||||
_advice.ForeColor = Theme.TextDim;
|
||||
_advice.Font = Fonts.Caption;
|
||||
_advice.BackColor = Color.Transparent;
|
||||
_advice.UseMnemonic = false;
|
||||
Controls.Add(_advice);
|
||||
int num9 = 32;
|
||||
int num10 = num6 + num7 + 24;
|
||||
_close.Text = "Turn off and close";
|
||||
int num11 = FooterWidth(_close);
|
||||
_close.SetBounds(436 - num11, num10, num11, num9);
|
||||
_close.Click += (object? s, EventArgs e) =>
|
||||
{
|
||||
Close();
|
||||
};
|
||||
Controls.Add(_close);
|
||||
_otherNetwork.Text = "Different network?";
|
||||
int num12 = FooterWidth(_otherNetwork);
|
||||
_otherNetwork.SetBounds(_close.Left - 8 - num12, num10, num12, num9);
|
||||
_otherNetwork.Click += (object? s, EventArgs e) =>
|
||||
{
|
||||
CycleAddress();
|
||||
};
|
||||
Controls.Add(_otherNetwork);
|
||||
ClientSize = new Size(460, num10 + num9 + 20);
|
||||
_hintTimer.Interval = (int)PhoneSession.HintAfter.TotalMilliseconds;
|
||||
_hintTimer.Tick += (object? s, EventArgs e) =>
|
||||
{
|
||||
_hintTimer.Stop();
|
||||
ShowWaitingHint();
|
||||
};
|
||||
_listener.PhoneArrived += OnPhoneArrived;
|
||||
_listener.WrongNetworkSeen += OnWrongNetwork;
|
||||
if (_scale != 1f)
|
||||
{
|
||||
Scale(new SizeF(_scale, _scale));
|
||||
}
|
||||
}
|
||||
|
||||
private int Px(int logical)
|
||||
{
|
||||
return (int)Math.Round((float)logical * _scale);
|
||||
}
|
||||
|
||||
private static Label Words(string text, Font font, Color ink, Rectangle bounds, ContentAlignment align)
|
||||
{
|
||||
return new Label
|
||||
{
|
||||
Text = text,
|
||||
Font = font,
|
||||
ForeColor = ink,
|
||||
BackColor = Color.Transparent,
|
||||
AutoSize = false,
|
||||
TextAlign = align,
|
||||
UseMnemonic = false,
|
||||
Bounds = bounds
|
||||
};
|
||||
}
|
||||
|
||||
private int Measure(string text, Font font, int width, int line)
|
||||
{
|
||||
int height = TextRenderer.MeasureText(text, font, new Size(Math.Max(1, Px(width)), int.MaxValue), TextFormatFlags.NoPrefix | TextFormatFlags.WordBreak).Height;
|
||||
return Math.Max(1, (int)Math.Round((double)height / (double)Math.Max(1, font.Height))) * line;
|
||||
}
|
||||
|
||||
private int FooterWidth(GlassButton button)
|
||||
{
|
||||
return Math.Max(96, (int)Math.Ceiling((float)button.GetPreferredSize(Size.Empty).Width / _scale));
|
||||
}
|
||||
|
||||
protected override void OnLoad(EventArgs e)
|
||||
{
|
||||
base.OnLoad(e);
|
||||
_candidates = NetworkFacts.Candidates();
|
||||
_advice.Text = PhoneSession.FirewallAdvice(NetworkFacts.Category());
|
||||
_listener.Start();
|
||||
ShowCurrentAddress();
|
||||
_hintTimer.Start();
|
||||
}
|
||||
|
||||
private void CycleAddress()
|
||||
{
|
||||
if (_candidates.Count > 1)
|
||||
{
|
||||
_candidate = (_candidate + 1) % _candidates.Count;
|
||||
ShowCurrentAddress();
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowCurrentAddress()
|
||||
{
|
||||
string text = ((_candidates.Count > 0) ? _candidates[_candidate] : "");
|
||||
_listener.AdvertisedAddress = text;
|
||||
_otherNetwork.Visible = _candidates.Count > 1;
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
_address.Text = "No network found.";
|
||||
_qr?.Dispose();
|
||||
_qr = null;
|
||||
Invalidate();
|
||||
return;
|
||||
}
|
||||
string text2 = PhoneSession.Url(text, _listener.Port, _listener.Token);
|
||||
_address.Text = $"{text}:{_listener.Port}";
|
||||
_qr?.Dispose();
|
||||
_qr = RenderQr(text2);
|
||||
Invalidate();
|
||||
}
|
||||
|
||||
private void ShowWaitingHint()
|
||||
{
|
||||
if (!_paired)
|
||||
{
|
||||
ShowStatus(SignalIcon.Info, "Nothing has connected yet. Check the phone is on the same Wi-Fi.");
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowStatus(SignalIcon icon, string words)
|
||||
{
|
||||
_statusIcon = icon;
|
||||
_hint.ForeColor = Theme.Text;
|
||||
_hint.Text = words;
|
||||
_hint.Visible = true;
|
||||
Invalidate(new Rectangle(Px(24), _hint.Top, Px(16), Px(16)));
|
||||
}
|
||||
|
||||
private static Color InkFor(SignalIcon icon)
|
||||
{
|
||||
return icon switch
|
||||
{
|
||||
SignalIcon.Success => ControlInk.Success,
|
||||
SignalIcon.Warning => ControlInk.Warning,
|
||||
SignalIcon.Danger => ControlInk.Danger,
|
||||
_ => ControlInk.Info,
|
||||
};
|
||||
}
|
||||
|
||||
private void OnPhoneArrived()
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
BeginInvoke(() =>
|
||||
{
|
||||
_paired = true;
|
||||
ShowStatus(SignalIcon.Success, "Connected. Your phone is controlling this PC.");
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWrongNetwork(string theirs, string ours)
|
||||
{
|
||||
if (IsDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
BeginInvoke(() =>
|
||||
{
|
||||
if (!_paired)
|
||||
{
|
||||
_hintTimer.Stop();
|
||||
ShowStatus(SignalIcon.Warning, WrongNetworkLine(theirs, ours));
|
||||
}
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string WrongNetworkLine(string theirs, string ours)
|
||||
{
|
||||
return $"A phone on {theirs} tried to connect. This PC is on {ours} - " + "different networks. Take the phone off guest Wi-Fi or mobile data.";
|
||||
}
|
||||
|
||||
private static Bitmap RenderQr(string text)
|
||||
{
|
||||
bool[,] array = QrCode.Encode(text);
|
||||
int length = array.GetLength(0);
|
||||
int num = length + 8;
|
||||
int num2 = Math.Max(1, 172 / num);
|
||||
int num3 = num * num2;
|
||||
Bitmap bitmap = new Bitmap(num3, num3);
|
||||
using Graphics graphics = Graphics.FromImage(bitmap);
|
||||
graphics.SmoothingMode = SmoothingMode.None;
|
||||
graphics.Clear(Color.White);
|
||||
using SolidBrush brush = new SolidBrush(Color.Black);
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
for (int j = 0; j < length; j++)
|
||||
{
|
||||
if (array[i, j])
|
||||
{
|
||||
graphics.FillRectangle(brush, (j + 4) * num2, (i + 4) * num2, num2, num2);
|
||||
}
|
||||
}
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private Rectangle Tile()
|
||||
{
|
||||
int num = Px(204);
|
||||
return new Rectangle((ClientSize.Width - num) / 2, Px(96), num, num);
|
||||
}
|
||||
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaint(e);
|
||||
Graphics graphics = e.Graphics;
|
||||
GraphicsState gstate = graphics.Save();
|
||||
try
|
||||
{
|
||||
graphics.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
graphics.PixelOffsetMode = PixelOffsetMode.Half;
|
||||
Rectangle bounds = _address.Bounds;
|
||||
int num = ControlInk.Hairline(SignalInk.DpiFor(this));
|
||||
using (GraphicsPath path = Glass.RoundedPath(bounds, Px(4)))
|
||||
{
|
||||
using SolidBrush brush = new SolidBrush(ControlInk.Border);
|
||||
graphics.FillPath(brush, path);
|
||||
}
|
||||
using (GraphicsPath path2 = Glass.RoundedPath(RectangleF.Inflate(bounds, -num, -num), Math.Max(1, Px(4) - num)))
|
||||
{
|
||||
using SolidBrush brush2 = new SolidBrush(ControlInk.Surface2);
|
||||
graphics.FillPath(brush2, path2);
|
||||
}
|
||||
if (_hint.Visible && _statusIcon != SignalIcon.None)
|
||||
{
|
||||
SignalIcons.Draw(graphics, _statusIcon, new RectangleF(Px(24), _hint.Top, Px(16), Px(16)), InkFor(_statusIcon));
|
||||
}
|
||||
Bitmap qr = _qr;
|
||||
if (qr == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Rectangle rectangle = Tile();
|
||||
int num2 = Px(16);
|
||||
using (GraphicsPath path3 = Glass.RoundedPath(rectangle, Px(8)))
|
||||
{
|
||||
using SolidBrush brush3 = new SolidBrush(Color.White);
|
||||
graphics.FillPath(brush3, path3);
|
||||
}
|
||||
graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
|
||||
graphics.DrawImage(qr, new Rectangle(rectangle.X + num2, rectangle.Y + num2, rectangle.Width - 2 * num2, rectangle.Height - 2 * num2));
|
||||
}
|
||||
finally
|
||||
{
|
||||
graphics.Restore(gstate);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyCode == Keys.Escape)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
base.OnKeyDown(e);
|
||||
}
|
||||
|
||||
internal void ShowWaitingHintForTest()
|
||||
{
|
||||
ShowWaitingHint();
|
||||
}
|
||||
|
||||
internal void PhoneArrivedForTest()
|
||||
{
|
||||
OnPhoneArrived();
|
||||
}
|
||||
|
||||
internal void WrongNetworkForTest(string theirs, string ours)
|
||||
{
|
||||
OnWrongNetwork(theirs, ours);
|
||||
}
|
||||
|
||||
protected override void OnFormClosed(FormClosedEventArgs e)
|
||||
{
|
||||
_listener.PhoneArrived -= OnPhoneArrived;
|
||||
_listener.WrongNetworkSeen -= OnWrongNetwork;
|
||||
_listener.Stop();
|
||||
_hintTimer.Stop();
|
||||
_hintTimer.Dispose();
|
||||
_qr?.Dispose();
|
||||
_qr = null;
|
||||
base.OnFormClosed(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
public static class QrCode
|
||||
{
|
||||
private sealed class BitBucket
|
||||
{
|
||||
private readonly List<bool> _bits = new List<bool>();
|
||||
|
||||
public int Length => _bits.Count;
|
||||
|
||||
public void Add(int value, int bits)
|
||||
{
|
||||
for (int num = bits - 1; num >= 0; num--)
|
||||
{
|
||||
_bits.Add(((value >> num) & 1) == 1);
|
||||
}
|
||||
}
|
||||
|
||||
public void PadToByte()
|
||||
{
|
||||
while (_bits.Count % 8 != 0)
|
||||
{
|
||||
_bits.Add(item: false);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] ToBytes()
|
||||
{
|
||||
byte[] array = new byte[_bits.Count / 8];
|
||||
for (int i = 0; i < _bits.Count; i++)
|
||||
{
|
||||
if (_bits[i])
|
||||
{
|
||||
array[i / 8] |= (byte)(1 << 7 - i % 8);
|
||||
}
|
||||
}
|
||||
return array;
|
||||
}
|
||||
}
|
||||
|
||||
private const int EccLevelBits = 0;
|
||||
|
||||
public const int MinVersion = 1;
|
||||
|
||||
public const int MaxVersion = 6;
|
||||
|
||||
private static readonly (int Total, int EccPerBlock, int Blocks)[] Layout = new (int, int, int)[7]
|
||||
{
|
||||
(0, 0, 0),
|
||||
(26, 10, 1),
|
||||
(44, 16, 1),
|
||||
(70, 26, 1),
|
||||
(100, 18, 2),
|
||||
(134, 24, 2),
|
||||
(172, 16, 4)
|
||||
};
|
||||
|
||||
private static int RemainderBits(int version)
|
||||
{
|
||||
if (version != 1)
|
||||
{
|
||||
return 7;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Size(int version)
|
||||
{
|
||||
return 17 + 4 * version;
|
||||
}
|
||||
|
||||
private static int DataCodewords(int version)
|
||||
{
|
||||
var (num, num2, num3) = Layout[version];
|
||||
return num - num2 * num3;
|
||||
}
|
||||
|
||||
public static int Capacity(int version)
|
||||
{
|
||||
return DataCodewords(version) - 2;
|
||||
}
|
||||
|
||||
public static int SmallestVersionFor(string text)
|
||||
{
|
||||
int byteCount = Encoding.UTF8.GetByteCount(text ?? "");
|
||||
for (int i = 1; i <= 6; i++)
|
||||
{
|
||||
if (byteCount <= Capacity(i))
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static bool[,] Encode(string text)
|
||||
{
|
||||
if (text == null)
|
||||
{
|
||||
throw new ArgumentNullException("text");
|
||||
}
|
||||
int num = SmallestVersionFor(text);
|
||||
if (num == 0)
|
||||
{
|
||||
throw new ArgumentException($"That is {Encoding.UTF8.GetByteCount(text)} bytes and the largest symbol here holds {Capacity(6)}.", "text");
|
||||
}
|
||||
byte[] codewords = Codewords(text, num);
|
||||
bool[,] result = null;
|
||||
int num2 = int.MaxValue;
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
bool[,] array = Draw(codewords, num, i);
|
||||
int num3 = Penalty(array);
|
||||
if (num3 < num2)
|
||||
{
|
||||
num2 = num3;
|
||||
result = array;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static bool[,] EncodeExactly(string text, int version, int mask)
|
||||
{
|
||||
if (version < 1 || version > 6)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException("version");
|
||||
}
|
||||
if (mask < 0 || mask > 7)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException("mask");
|
||||
}
|
||||
return Draw(Codewords(text, version), version, mask);
|
||||
}
|
||||
|
||||
private static byte[] Codewords(string text, int version)
|
||||
{
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(text ?? "");
|
||||
if (bytes.Length > Capacity(version))
|
||||
{
|
||||
throw new ArgumentException("too long for this version", "text");
|
||||
}
|
||||
BitBucket bitBucket = new BitBucket();
|
||||
bitBucket.Add(4, 4);
|
||||
bitBucket.Add(bytes.Length, 8);
|
||||
byte[] array = bytes;
|
||||
foreach (byte value in array)
|
||||
{
|
||||
bitBucket.Add(value, 8);
|
||||
}
|
||||
int num = DataCodewords(version) * 8;
|
||||
bitBucket.Add(0, Math.Min(4, num - bitBucket.Length));
|
||||
bitBucket.PadToByte();
|
||||
byte[] array2 = bitBucket.ToBytes();
|
||||
byte[] array3 = new byte[DataCodewords(version)];
|
||||
Array.Copy(array2, array3, array2.Length);
|
||||
for (int j = array2.Length; j < array3.Length; j++)
|
||||
{
|
||||
array3[j] = (byte)(((j - array2.Length) % 2 == 0) ? 236 : 17);
|
||||
}
|
||||
return Interleave(array3, version);
|
||||
}
|
||||
|
||||
private static byte[] Interleave(byte[] data, int version)
|
||||
{
|
||||
(int Total, int EccPerBlock, int Blocks) tuple = Layout[version];
|
||||
int item = tuple.Total;
|
||||
int item2 = tuple.EccPerBlock;
|
||||
int item3 = tuple.Blocks;
|
||||
int num = data.Length / item3;
|
||||
byte[][] array = new byte[item3][];
|
||||
byte[][] array2 = new byte[item3][];
|
||||
for (int i = 0; i < item3; i++)
|
||||
{
|
||||
array[i] = new byte[num];
|
||||
Array.Copy(data, i * num, array[i], 0, num);
|
||||
array2[i] = ReedSolomon.Remainder(array[i], item2);
|
||||
}
|
||||
byte[] array3 = new byte[item];
|
||||
int num2 = 0;
|
||||
for (int j = 0; j < num; j++)
|
||||
{
|
||||
for (int k = 0; k < item3; k++)
|
||||
{
|
||||
array3[num2++] = array[k][j];
|
||||
}
|
||||
}
|
||||
for (int l = 0; l < item2; l++)
|
||||
{
|
||||
for (int m = 0; m < item3; m++)
|
||||
{
|
||||
array3[num2++] = array2[m][l];
|
||||
}
|
||||
}
|
||||
return array3;
|
||||
}
|
||||
|
||||
private static bool[,] Draw(byte[] codewords, int version, int mask)
|
||||
{
|
||||
int num = Size(version);
|
||||
bool[,] array = new bool[num, num];
|
||||
bool[,] array2 = new bool[num, num];
|
||||
PlaceFinder(array, array2, 0, 0, num);
|
||||
PlaceFinder(array, array2, 0, num - 7, num);
|
||||
PlaceFinder(array, array2, num - 7, 0, num);
|
||||
PlaceTiming(array, array2, num);
|
||||
PlaceAlignment(array, array2, version, num);
|
||||
ReserveFormat(array2, num);
|
||||
array[num - 8, 8] = true;
|
||||
array2[num - 8, 8] = true;
|
||||
PlaceData(array, array2, codewords, num, version, mask);
|
||||
PlaceFormat(array, num, mask);
|
||||
return array;
|
||||
}
|
||||
|
||||
private static void PlaceFinder(bool[,] dark, bool[,] reserved, int row, int col, int size)
|
||||
{
|
||||
for (int i = -1; i <= 7; i++)
|
||||
{
|
||||
for (int j = -1; j <= 7; j++)
|
||||
{
|
||||
int num = row + i;
|
||||
int num2 = col + j;
|
||||
if (num >= 0 && num < size && num2 >= 0 && num2 < size)
|
||||
{
|
||||
bool flag = i >= 0 && i <= 6 && j >= 0 && j <= 6;
|
||||
bool flag2 = i == 0 || i == 6 || j == 0 || j == 6;
|
||||
bool flag3 = i >= 2 && i <= 4 && j >= 2 && j <= 4;
|
||||
dark[num, num2] = flag && (flag2 | flag3);
|
||||
reserved[num, num2] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void PlaceTiming(bool[,] dark, bool[,] reserved, int size)
|
||||
{
|
||||
for (int i = 8; i < size - 8; i++)
|
||||
{
|
||||
bool flag = (dark[6, i] = i % 2 == 0);
|
||||
reserved[6, i] = true;
|
||||
dark[i, 6] = flag;
|
||||
reserved[i, 6] = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void PlaceAlignment(bool[,] dark, bool[,] reserved, int version, int size)
|
||||
{
|
||||
if (version < 2)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int num = 4 * version + 10;
|
||||
for (int i = -2; i <= 2; i++)
|
||||
{
|
||||
for (int j = -2; j <= 2; j++)
|
||||
{
|
||||
int num2 = num + i;
|
||||
int num3 = num + j;
|
||||
dark[num2, num3] = Math.Max(Math.Abs(i), Math.Abs(j)) != 1;
|
||||
reserved[num2, num3] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReserveFormat(bool[,] reserved, int size)
|
||||
{
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
if (i != 6)
|
||||
{
|
||||
reserved[8, i] = true;
|
||||
reserved[i, 8] = true;
|
||||
}
|
||||
}
|
||||
reserved[8, 6] = true;
|
||||
reserved[6, 8] = true;
|
||||
for (int j = 0; j < 8; j++)
|
||||
{
|
||||
reserved[8, size - 1 - j] = true;
|
||||
reserved[size - 1 - j, 8] = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void PlaceData(bool[,] dark, bool[,] reserved, byte[] codewords, int size, int version, int mask)
|
||||
{
|
||||
int num = 0;
|
||||
int num2 = codewords.Length * 8 + RemainderBits(version);
|
||||
bool flag = true;
|
||||
for (int num3 = size - 1; num3 >= 1; num3 -= 2)
|
||||
{
|
||||
if (num3 == 6)
|
||||
{
|
||||
num3 = 5;
|
||||
}
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
int num4 = (flag ? (size - 1 - i) : i);
|
||||
for (int j = 0; j < 2; j++)
|
||||
{
|
||||
int num5 = num3 - j;
|
||||
if (!reserved[num4, num5] && num < num2)
|
||||
{
|
||||
bool flag2 = num < codewords.Length * 8 && ((codewords[num / 8] >> 7 - num % 8) & 1) == 1;
|
||||
num++;
|
||||
dark[num4, num5] = flag2 ^ Mask(mask, num4, num5);
|
||||
}
|
||||
}
|
||||
}
|
||||
flag = !flag;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Mask(int mask, int row, int col)
|
||||
{
|
||||
return mask switch
|
||||
{
|
||||
0 => (row + col) % 2 == 0,
|
||||
1 => row % 2 == 0,
|
||||
2 => col % 3 == 0,
|
||||
3 => (row + col) % 3 == 0,
|
||||
4 => (row / 2 + col / 3) % 2 == 0,
|
||||
5 => row * col % 2 + row * col % 3 == 0,
|
||||
6 => (row * col % 2 + row * col % 3) % 2 == 0,
|
||||
7 => ((row + col) % 2 + row * col % 3) % 2 == 0,
|
||||
_ => throw new ArgumentOutOfRangeException("mask"),
|
||||
};
|
||||
}
|
||||
|
||||
private static void PlaceFormat(bool[,] dark, int size, int mask)
|
||||
{
|
||||
int num = 0 | mask;
|
||||
int num2 = num << 10;
|
||||
for (int num3 = 14; num3 >= 10; num3--)
|
||||
{
|
||||
if (((num2 >> num3) & 1) == 1)
|
||||
{
|
||||
num2 ^= 1335 << num3 - 10;
|
||||
}
|
||||
}
|
||||
int num4 = ((num << 10) | num2) ^ 0x5412;
|
||||
for (int i = 0; i < 15; i++)
|
||||
{
|
||||
bool flag = ((num4 >> 14 - i) & 1) == 1;
|
||||
if (i < 6)
|
||||
{
|
||||
dark[8, i] = flag;
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (i)
|
||||
{
|
||||
case 6:
|
||||
dark[8, 7] = flag;
|
||||
break;
|
||||
case 7:
|
||||
dark[8, 8] = flag;
|
||||
break;
|
||||
case 8:
|
||||
dark[7, 8] = flag;
|
||||
break;
|
||||
default:
|
||||
dark[14 - i, 8] = flag;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (i < 7)
|
||||
{
|
||||
dark[size - 1 - i, 8] = flag;
|
||||
}
|
||||
else
|
||||
{
|
||||
dark[8, size - 15 + i] = flag;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static int Penalty(bool[,] dark)
|
||||
{
|
||||
int length = dark.GetLength(0);
|
||||
int num = 0;
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
num += RunPenalty(dark, i, horizontal: true, length);
|
||||
num += RunPenalty(dark, i, horizontal: false, length);
|
||||
}
|
||||
for (int j = 0; j < length - 1; j++)
|
||||
{
|
||||
for (int k = 0; k < length - 1; k++)
|
||||
{
|
||||
if (dark[j, k] == dark[j, k + 1] && dark[j, k] == dark[j + 1, k] && dark[j, k] == dark[j + 1, k + 1])
|
||||
{
|
||||
num += 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
num += 40 * FinderLookalikes(dark, length);
|
||||
int num2 = 0;
|
||||
int upperBound = dark.GetUpperBound(0);
|
||||
int upperBound2 = dark.GetUpperBound(1);
|
||||
for (int l = dark.GetLowerBound(0); l <= upperBound; l++)
|
||||
{
|
||||
for (int m = dark.GetLowerBound(1); m <= upperBound2; m++)
|
||||
{
|
||||
if (dark[l, m])
|
||||
{
|
||||
num2++;
|
||||
}
|
||||
}
|
||||
}
|
||||
int num3 = num2 * 100 / (length * length);
|
||||
return num + Math.Abs(num3 - 50) / 5 * 10;
|
||||
}
|
||||
|
||||
private static int RunPenalty(bool[,] dark, int line, bool horizontal, int size)
|
||||
{
|
||||
int num = 0;
|
||||
int num2 = 1;
|
||||
for (int i = 1; i < size; i++)
|
||||
{
|
||||
bool flag = (horizontal ? dark[line, i] : dark[i, line]);
|
||||
bool flag2 = (horizontal ? dark[line, i - 1] : dark[i - 1, line]);
|
||||
if (flag == flag2)
|
||||
{
|
||||
num2++;
|
||||
continue;
|
||||
}
|
||||
if (num2 >= 5)
|
||||
{
|
||||
num += num2 - 2;
|
||||
}
|
||||
num2 = 1;
|
||||
}
|
||||
if (num2 >= 5)
|
||||
{
|
||||
num += num2 - 2;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
private static int FinderLookalikes(bool[,] dark, int size)
|
||||
{
|
||||
bool[] pattern = new bool[7] { true, false, true, true, true, false, true };
|
||||
int num = 0;
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
for (int j = 0; j + 7 <= size; j++)
|
||||
{
|
||||
if (Matches(dark, i, j, pattern, horizontal: true, size) && (Quiet(dark, i, j - 4, 4, horizontal: true, size) || Quiet(dark, i, j + 7, 4, horizontal: true, size)))
|
||||
{
|
||||
num++;
|
||||
}
|
||||
}
|
||||
for (int k = 0; k + 7 <= size; k++)
|
||||
{
|
||||
if (Matches(dark, i, k, pattern, horizontal: false, size) && (Quiet(dark, i, k - 4, 4, horizontal: false, size) || Quiet(dark, i, k + 7, 4, horizontal: false, size)))
|
||||
{
|
||||
num++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
private static bool Matches(bool[,] dark, int line, int start, bool[] pattern, bool horizontal, int size)
|
||||
{
|
||||
for (int i = 0; i < pattern.Length; i++)
|
||||
{
|
||||
int num = start + i;
|
||||
if (num < 0 || num >= size)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if ((horizontal ? dark[line, num] : dark[num, line]) != pattern[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool Quiet(bool[,] dark, int line, int start, int count, bool horizontal, int size)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
int num = start + i;
|
||||
if (num >= 0 && num < size && (horizontal ? dark[line, num] : dark[num, line]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
|
||||
namespace VibranceHud.Remote;
|
||||
|
||||
internal static class ReedSolomon
|
||||
{
|
||||
private const int Primitive = 285;
|
||||
|
||||
private static readonly byte[] Exp;
|
||||
|
||||
private static readonly byte[] Log;
|
||||
|
||||
static ReedSolomon()
|
||||
{
|
||||
Exp = new byte[512];
|
||||
Log = new byte[256];
|
||||
int num = 1;
|
||||
for (int i = 0; i < 255; i++)
|
||||
{
|
||||
Exp[i] = (byte)num;
|
||||
Log[num] = (byte)i;
|
||||
num <<= 1;
|
||||
if (num >= 256)
|
||||
{
|
||||
num ^= 0x11D;
|
||||
}
|
||||
}
|
||||
for (int j = 255; j < 512; j++)
|
||||
{
|
||||
Exp[j] = Exp[j - 255];
|
||||
}
|
||||
}
|
||||
|
||||
internal static byte Multiply(byte a, byte b)
|
||||
{
|
||||
if (a != 0 && b != 0)
|
||||
{
|
||||
return Exp[Log[a] + Log[b]];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal static byte[] Generator(int degree)
|
||||
{
|
||||
byte[] array = new byte[1] { 1 };
|
||||
for (int i = 0; i < degree; i++)
|
||||
{
|
||||
byte[] array2 = new byte[array.Length + 1];
|
||||
for (int j = 0; j < array.Length; j++)
|
||||
{
|
||||
array2[j] ^= array[j];
|
||||
array2[j + 1] ^= Multiply(array[j], Exp[i]);
|
||||
}
|
||||
array = array2;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
internal static byte[] Remainder(byte[] data, int degree)
|
||||
{
|
||||
byte[] array = Generator(degree);
|
||||
byte[] array2 = new byte[degree];
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
byte b = (byte)(data[i] ^ array2[0]);
|
||||
Array.Copy(array2, 1, array2, 0, degree - 1);
|
||||
array2[degree - 1] = 0;
|
||||
for (int j = 0; j < degree; j++)
|
||||
{
|
||||
array2[j] ^= Multiply(array[j + 1], b);
|
||||
}
|
||||
}
|
||||
return array2;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user