cleanup code

This commit is contained in:
pypy
2020-11-01 23:41:21 +09:00
parent 2cc00465ad
commit c051dccecf
10 changed files with 241 additions and 207 deletions

View File

@@ -8,62 +8,78 @@ using System.Threading;
namespace VRCX namespace VRCX
{ {
public static class CpuMonitor public class CpuMonitor
{ {
public static float CpuUsage { get; private set; } public static CpuMonitor Instance { get; private set; }
private static Thread m_Thread; public float CpuUsage { get; private set; }
private readonly PerformanceCounter m_Counter;
private Thread m_Thread;
public static void Init() static CpuMonitor()
{ {
m_Thread = new Thread(() => Instance = new CpuMonitor();
}
public CpuMonitor()
{
try
{
m_Counter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
}
catch
{
}
// fallback
if (m_Counter == null)
{ {
PerformanceCounter counter = null;
try try
{ {
counter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true); m_Counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
} }
catch catch
{ {
} }
try }
{
if (counter == null) m_Thread = new Thread(ThreadLoop)
{
counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
}
}
catch
{
}
if (counter != null)
{
while (m_Thread != null)
{
try
{
Thread.Sleep(1000);
}
catch
{
// ThreadInterruptedException
}
CpuUsage = counter.NextValue();
}
counter.Dispose();
}
})
{ {
IsBackground = true IsBackground = true
}; };
}
internal void Init()
{
m_Thread.Start(); m_Thread.Start();
} }
public static void Exit() internal void Exit()
{ {
var T = m_Thread; var thread = m_Thread;
m_Thread = null; m_Thread = null;
T.Interrupt(); thread.Interrupt();
T.Join(); thread.Join();
m_Counter?.Dispose();
}
private void ThreadLoop()
{
while (m_Thread != null)
{
if (m_Counter != null)
{
CpuUsage = m_Counter.NextValue();
}
try
{
Thread.Sleep(1000);
}
catch
{
// ThreadInterruptedException
}
}
} }
} }
} }

View File

@@ -12,76 +12,92 @@ namespace VRCX
public class Discord public class Discord
{ {
public static Discord Instance { get; private set; } public static Discord Instance { get; private set; }
private static readonly ReaderWriterLockSlim m_Lock = new ReaderWriterLockSlim(); private readonly ReaderWriterLockSlim m_Lock;
private static readonly RichPresence m_Presence = new RichPresence(); private readonly RichPresence m_Presence;
private static Thread m_Thread; private DiscordRpcClient m_Client;
private static bool m_Active; private Thread m_Thread;
private bool m_Active;
static Discord() static Discord()
{ {
Instance = new Discord(); Instance = new Discord();
} }
public static void Init() public Discord()
{ {
m_Thread = new Thread(() => m_Lock = new ReaderWriterLockSlim();
{ m_Presence = new RichPresence();
DiscordRpcClient client = null; m_Thread = new Thread(ThreadLoop)
while (m_Thread != null)
{
try
{
Thread.Sleep(1000);
}
catch
{
// ThreadInterruptedException
}
if (client != null)
{
m_Lock.EnterReadLock();
try
{
client.SetPresence(m_Presence);
}
finally
{
m_Lock.ExitReadLock();
}
client.Invoke();
}
if (m_Active)
{
if (client == null)
{
client = new DiscordRpcClient("525953831020920832");
if (!client.Initialize())
{
client.Dispose();
client = null;
}
}
}
else if (client != null)
{
client.Dispose();
client = null;
}
}
client?.Dispose();
})
{ {
IsBackground = true IsBackground = true
}; };
}
internal void Init()
{
m_Thread.Start(); m_Thread.Start();
} }
public static void Exit() internal void Exit()
{ {
var T = m_Thread; var thread = m_Thread;
m_Thread = null; m_Thread = null;
T.Interrupt(); thread.Interrupt();
T.Join(); thread.Join();
m_Client?.Dispose();
}
private void ThreadLoop()
{
while (m_Thread != null)
{
Update();
try
{
Thread.Sleep(1000);
}
catch
{
// ThreadInterruptedException
}
}
}
private void Update()
{
if (m_Client != null)
{
m_Lock.EnterReadLock();
try
{
m_Client.SetPresence(m_Presence);
}
finally
{
m_Lock.ExitReadLock();
}
m_Client.Invoke();
}
if (m_Active == true)
{
if (m_Client == null)
{
m_Client = new DiscordRpcClient("525953831020920832");
if (m_Client.Initialize() == false)
{
m_Client.Dispose();
m_Client = null;
}
}
}
else if (m_Client != null)
{
m_Client.Dispose();
m_Client = null;
}
} }
public void SetActive(bool active) public void SetActive(bool active)
@@ -93,8 +109,8 @@ namespace VRCX
private static string LimitByteLength(string str, int maxBytesLength) private static string LimitByteLength(string str, int maxBytesLength)
{ {
var bytesArr = Encoding.UTF8.GetBytes(str); var bytesArr = Encoding.UTF8.GetBytes(str);
int bytesToRemove = 0; var bytesToRemove = 0;
int lastIndexInString = str.Length - 1; var lastIndexInString = str.Length - 1;
while (bytesArr.Length - bytesToRemove > maxBytesLength) while (bytesArr.Length - bytesToRemove > maxBytesLength)
{ {
bytesToRemove += Encoding.UTF8.GetByteCount(new char[] { str[lastIndexInString] }); bytesToRemove += Encoding.UTF8.GetByteCount(new char[] { str[lastIndexInString] });
@@ -122,8 +138,8 @@ namespace VRCX
m_Lock.EnterWriteLock(); m_Lock.EnterWriteLock();
try try
{ {
if (string.IsNullOrEmpty(largeKey) && if (string.IsNullOrEmpty(largeKey) == true &&
string.IsNullOrEmpty(smallKey)) string.IsNullOrEmpty(smallKey) == true)
{ {
m_Presence.Assets = null; m_Presence.Assets = null;
} }
@@ -145,18 +161,15 @@ namespace VRCX
} }
} }
// JSB Sucks
public void SetTimestamps(double startUnixMilliseconds, double endUnixMilliseconds) public void SetTimestamps(double startUnixMilliseconds, double endUnixMilliseconds)
{ {
SetTimestamps((ulong)startUnixMilliseconds, (ulong)endUnixMilliseconds); var _startUnixMilliseconds = (ulong)startUnixMilliseconds;
} var _endUnixMilliseconds = (ulong)endUnixMilliseconds;
public static void SetTimestamps(ulong startUnixMilliseconds, ulong endUnixMilliseconds)
{
m_Lock.EnterWriteLock(); m_Lock.EnterWriteLock();
try try
{ {
if (startUnixMilliseconds == 0) if (_startUnixMilliseconds == 0)
{ {
m_Presence.Timestamps = null; m_Presence.Timestamps = null;
} }
@@ -166,14 +179,16 @@ namespace VRCX
{ {
m_Presence.Timestamps = new Timestamps(); m_Presence.Timestamps = new Timestamps();
} }
m_Presence.Timestamps.StartUnixMilliseconds = startUnixMilliseconds;
if (endUnixMilliseconds == 0) m_Presence.Timestamps.StartUnixMilliseconds = _startUnixMilliseconds;
if (_endUnixMilliseconds == 0)
{ {
m_Presence.Timestamps.End = null; m_Presence.Timestamps.End = null;
} }
else else
{ {
m_Presence.Timestamps.EndUnixMilliseconds = endUnixMilliseconds; m_Presence.Timestamps.EndUnixMilliseconds = _endUnixMilliseconds;
} }
} }
} }

View File

@@ -25,7 +25,7 @@ namespace VRCX
private readonly Dictionary<string, LogContext> m_LogContextMap; // <FileName, LogContext> private readonly Dictionary<string, LogContext> m_LogContextMap; // <FileName, LogContext>
private readonly ReaderWriterLockSlim m_LogListLock; private readonly ReaderWriterLockSlim m_LogListLock;
private readonly List<string[]> m_LogList; private readonly List<string[]> m_LogList;
private Thread m_WatchThread; private Thread m_Thread;
private bool m_ResetLog; private bool m_ResetLog;
// NOTE // NOTE
@@ -43,29 +43,31 @@ namespace VRCX
m_LogContextMap = new Dictionary<string, LogContext>(); m_LogContextMap = new Dictionary<string, LogContext>();
m_LogListLock = new ReaderWriterLockSlim(); m_LogListLock = new ReaderWriterLockSlim();
m_LogList = new List<string[]>(); m_LogList = new List<string[]>();
m_WatchThread = new Thread(WatchLoop) m_Thread = new Thread(ThreadLoop)
{ {
IsBackground = true IsBackground = true
}; };
} }
public void Init() internal void Init()
{ {
m_WatchThread.Start(); m_Thread.Start();
} }
public void Exit() internal void Exit()
{ {
var watchThread = m_WatchThread; var thread = m_Thread;
m_WatchThread = null; m_Thread = null;
watchThread.Interrupt(); thread.Interrupt();
watchThread.Join(); thread.Join();
} }
private void WatchLoop() private void ThreadLoop()
{ {
while (m_WatchThread != null) while (m_Thread != null)
{ {
Update();
try try
{ {
Thread.Sleep(1000); Thread.Sleep(1000);
@@ -74,8 +76,6 @@ namespace VRCX
{ {
// ThreadInterruptedException // ThreadInterruptedException
} }
Update();
} }
} }
@@ -232,7 +232,7 @@ namespace VRCX
fileInfo.Name, fileInfo.Name,
ConvertLogTimeToISO8601(line), ConvertLogTimeToISO8601(line),
"hmd-model", "hmd-model",
hmdModel hmdModel
}); });
return true; return true;
@@ -404,10 +404,7 @@ namespace VRCX
public void Reset() public void Reset()
{ {
m_ResetLog = true; m_ResetLog = true;
if (m_WatchThread != null) m_Thread?.Interrupt();
{
m_WatchThread.Interrupt();
}
} }
public string[][] Get() public string[][] Get()
@@ -418,21 +415,21 @@ namespace VRCX
m_LogListLock.EnterWriteLock(); m_LogListLock.EnterWriteLock();
try try
{ {
string[][] array; string[][] items;
if (m_LogList.Count > 100) if (m_LogList.Count > 1000)
{ {
array = new string[100][]; items = new string[1000][];
m_LogList.CopyTo(0, array, 0, 100); m_LogList.CopyTo(0, items, 0, 1000);
m_LogList.RemoveRange(0, 100); m_LogList.RemoveRange(0, 1000);
} }
else else
{ {
array = m_LogList.ToArray(); items = m_LogList.ToArray();
m_LogList.Clear(); m_LogList.Clear();
} }
return array; return items;
} }
finally finally
{ {

View File

@@ -16,7 +16,7 @@ namespace VRCX
public partial class MainForm : Form public partial class MainForm : Form
{ {
public static MainForm Instance { get; private set; } public static MainForm Instance { get; private set; }
public static ChromiumWebBrowser Browser { get; private set; } public ChromiumWebBrowser Browser { get; private set; }
private int LastLocationX; private int LastLocationX;
private int LastLocationY; private int LastLocationY;
private int LastSizeWidth; private int LastSizeWidth;

View File

@@ -57,17 +57,17 @@ namespace VRCX
Application.EnableVisualStyles(); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
VRCXStorage.Load(); VRCXStorage.Load();
SQLite.Init(); CpuMonitor.Instance.Init();
CpuMonitor.Init(); Discord.Instance.Init();
Discord.Init(); SQLite.Instance.Init();
LogWatcher.Instance.Init(); LogWatcher.Instance.Init();
VRCXVR.Init(); VRCXVR.Init();
Application.Run(new MainForm()); Application.Run(new MainForm());
VRCXVR.Exit(); VRCXVR.Exit();
LogWatcher.Instance.Exit(); LogWatcher.Instance.Exit();
Discord.Exit(); SQLite.Instance.Exit();
CpuMonitor.Exit(); Discord.Instance.Exit();
SQLite.Exit(); CpuMonitor.Instance.Exit();
VRCXStorage.Save(); VRCXStorage.Save();
Cef.Shutdown(); Cef.Shutdown();
} }

View File

@@ -10,78 +10,84 @@ namespace VRCX
public class SQLite public class SQLite
{ {
public static SQLite Instance { get; private set; } public static SQLite Instance { get; private set; }
private static readonly ReaderWriterLockSlim m_Lock = new ReaderWriterLockSlim(); private readonly ReaderWriterLockSlim m_ConnectionLock;
private static SQLiteConnection m_Connection; private readonly SQLiteConnection m_Connection;
static SQLite() static SQLite()
{ {
Instance = new SQLite(); Instance = new SQLite();
} }
public static void Init() public SQLite()
{
m_ConnectionLock = new ReaderWriterLockSlim();
var dataSource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VRCX.sqlite3");
m_Connection = new SQLiteConnection($"Data Source=\"{dataSource}\";Version=3;PRAGMA locking_mode=NORMAL;PRAGMA busy_timeout=5000", true);
}
internal void Init()
{ {
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VRCX.sqlite3");
m_Connection = new SQLiteConnection($"Data Source=\"{path}\";Version=3;PRAGMA locking_mode=NORMAL;PRAGMA busy_timeout=5000", true);
m_Connection.Open(); m_Connection.Open();
} }
public static void Exit() internal void Exit()
{ {
m_Connection.Close(); m_Connection.Close();
m_Connection.Dispose(); m_Connection.Dispose();
} }
public int ExecuteNonQuery(string sql, IDictionary<string, object> param = null) public int ExecuteNonQuery(string sql, IDictionary<string, object> args = null)
{ {
m_Lock.EnterWriteLock(); m_ConnectionLock.EnterWriteLock();
try try
{ {
using (var C = new SQLiteCommand(sql, m_Connection)) using (var command = new SQLiteCommand(sql, m_Connection))
{ {
if (param != null) if (args != null)
{ {
foreach (var prop in param) foreach (var arg in args)
{ {
C.Parameters.Add(new SQLiteParameter(prop.Key, prop.Value)); command.Parameters.Add(new SQLiteParameter(arg.Key, arg.Value));
} }
} }
return C.ExecuteNonQuery(); return command.ExecuteNonQuery();
} }
} }
finally finally
{ {
m_Lock.ExitWriteLock(); m_ConnectionLock.ExitWriteLock();
} }
} }
public void Execute(IJavascriptCallback callback, string sql, IDictionary<string, object> param = null) public void Execute(IJavascriptCallback callback, string sql, IDictionary<string, object> args = null)
{ {
m_Lock.EnterReadLock(); m_ConnectionLock.EnterReadLock();
try try
{ {
using (var C = new SQLiteCommand(sql, m_Connection)) using (var command = new SQLiteCommand(sql, m_Connection))
{ {
if (param != null) if (args != null)
{ {
foreach (var prop in param) foreach (var arg in args)
{ {
C.Parameters.Add(new SQLiteParameter(prop.Key, prop.Value)); command.Parameters.Add(new SQLiteParameter(arg.Key, arg.Value));
} }
} }
using (var R = C.ExecuteReader()) using (var reader = command.ExecuteReader())
{ {
while (R.Read()) while (reader.Read() == true)
{ {
var row = new object[R.FieldCount]; var values = new object[reader.FieldCount];
R.GetValues(row); reader.GetValues(values);
callback.ExecuteAsync(row); callback.ExecuteAsync(values);
} }
} }
} }
} }
finally finally
{ {
m_Lock.ExitReadLock(); m_ConnectionLock.ExitReadLock();
} }
} }
} }

View File

@@ -30,23 +30,7 @@ namespace VRCX
m_MapLock.EnterWriteLock(); m_MapLock.EnterWriteLock();
try try
{ {
if (m_Map.Count > 0) m_Map.Clear();
{
m_Map.Clear();
}
}
finally
{
m_MapLock.ExitWriteLock();
}
}
public bool Remove(string key)
{
m_MapLock.EnterWriteLock();
try
{
return m_Map.Remove(key);
} }
finally finally
{ {
@@ -84,5 +68,18 @@ namespace VRCX
m_MapLock.ExitWriteLock(); m_MapLock.ExitWriteLock();
} }
} }
public bool Remove(string key)
{
m_MapLock.EnterWriteLock();
try
{
return m_Map.Remove(key);
}
finally
{
m_MapLock.ExitWriteLock();
}
}
} }
} }

36
VRCX.cs
View File

@@ -25,13 +25,7 @@ namespace VRCX
public void ShowDevTools() public void ShowDevTools()
{ {
try MainForm.Instance.Browser.ShowDevTools();
{
MainForm.Browser.ShowDevTools();
}
catch
{
}
} }
public void DeleteAllCookies() public void DeleteAllCookies()
@@ -41,8 +35,9 @@ namespace VRCX
public string LoginWithSteam() public string LoginWithSteam()
{ {
return VRChatRPC.Update() var rpc = VRChatRPC.Instance;
? VRChatRPC.GetAuthSessionTicket() return rpc.Update() == true
? rpc.GetAuthSessionTicket()
: string.Empty; : string.Empty;
} }
@@ -55,12 +50,12 @@ namespace VRCX
if (hwnd != IntPtr.Zero) if (hwnd != IntPtr.Zero)
{ {
var cmdline = string.Empty; var cmdline = string.Empty;
try try
{ {
Int32 pid = 0; WinApi.GetWindowThreadProcessId(hwnd, out uint pid);
WinApi.GetWindowThreadProcessId(hwnd, out pid); using (var searcher = new ManagementObjectSearcher($"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {pid}"))
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + pid)) using (var objects = searcher.Get())
using (ManagementObjectCollection objects = searcher.Get())
{ {
cmdline = objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString(); cmdline = objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
} }
@@ -89,14 +84,14 @@ namespace VRCX
{ {
// "C:\Program Files (x86)\Steam\steam.exe" -- "%1" // "C:\Program Files (x86)\Steam\steam.exe" -- "%1"
var match = Regex.Match(key.GetValue(string.Empty) as string, "^\"(.+?)\\\\steam.exe\""); var match = Regex.Match(key.GetValue(string.Empty) as string, "^\"(.+?)\\\\steam.exe\"");
if (match.Success) if (match.Success == true)
{ {
var path = match.Groups[1].Value; var path = match.Groups[1].Value;
var _arguments = Uri.EscapeDataString(arguments); var _arguments = Uri.EscapeDataString(arguments);
Process.Start(new ProcessStartInfo Process.Start(new ProcessStartInfo
{ {
WorkingDirectory = path, WorkingDirectory = path,
FileName = path + "\\steam.exe", FileName = $"{path}\\steam.exe",
UseShellExecute = false, UseShellExecute = false,
Arguments = $"-- \"steam://rungameid/438100//{_arguments}\"" Arguments = $"-- \"steam://rungameid/438100//{_arguments}\""
}).Close(); }).Close();
@@ -115,13 +110,13 @@ namespace VRCX
{ {
// "C:\Program Files (x86)\Steam\steamapps\common\VRChat\launch.bat" "C:\Program Files (x86)\Steam\steamapps\common\VRChat" "%1" // "C:\Program Files (x86)\Steam\steamapps\common\VRChat\launch.bat" "C:\Program Files (x86)\Steam\steamapps\common\VRChat" "%1"
var match = Regex.Match(key.GetValue(string.Empty) as string, "^\"(.+?)\\\\launch.bat\""); var match = Regex.Match(key.GetValue(string.Empty) as string, "^\"(.+?)\\\\launch.bat\"");
if (match.Success) if (match.Success == true)
{ {
var path = match.Groups[1].Value; var path = match.Groups[1].Value;
Process.Start(new ProcessStartInfo Process.Start(new ProcessStartInfo
{ {
WorkingDirectory = path, WorkingDirectory = path,
FileName = path + "\\VRChat.exe", FileName = $"{path}\\VRChat.exe",
UseShellExecute = false, UseShellExecute = false,
Arguments = $"\"{arguments}\"" Arguments = $"\"{arguments}\""
}).Close(); }).Close();
@@ -135,7 +130,8 @@ namespace VRCX
public void OpenLink(string url) public void OpenLink(string url)
{ {
if (url.StartsWith("http://") || url.StartsWith("https://")) if (url.StartsWith("http://") == true ||
url.StartsWith("https://") == true)
{ {
Process.Start(url).Close(); Process.Start(url).Close();
} }
@@ -180,7 +176,7 @@ namespace VRCX
public float CpuUsage() public float CpuUsage()
{ {
return CpuMonitor.CpuUsage; return CpuMonitor.Instance.CpuUsage;
} }
public void SetStartup(bool enabled) public void SetStartup(bool enabled)
@@ -189,7 +185,7 @@ namespace VRCX
{ {
using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{ {
if (enabled) if (enabled == true)
{ {
var path = Application.ExecutablePath; var path = Application.ExecutablePath;
key.SetValue("VRCX", $"\"{path}\" --startup"); key.SetValue("VRCX", $"\"{path}\" --startup");

View File

@@ -9,8 +9,10 @@ using System.Text;
namespace VRCX namespace VRCX
{ {
public static class VRChatRPC public class VRChatRPC
{ {
public static VRChatRPC Instance { get; private set; }
[DllImport("VRChatRPC", CallingConvention = CallingConvention.Cdecl)] [DllImport("VRChatRPC", CallingConvention = CallingConvention.Cdecl)]
private static extern bool VRChatRPC_000(); private static extern bool VRChatRPC_000();
@@ -20,19 +22,24 @@ namespace VRCX
[DllImport("VRChatRPC", CallingConvention = CallingConvention.Cdecl)] [DllImport("VRChatRPC", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr VRChatRPC_002(); private static extern IntPtr VRChatRPC_002();
public static bool Update() static VRChatRPC()
{
Instance = new VRChatRPC();
}
public bool Update()
{ {
return VRChatRPC_000(); return VRChatRPC_000();
} }
public static string GetAuthSessionTicket() public string GetAuthSessionTicket()
{ {
var a = new byte[1024]; var a = new byte[1024];
var n = VRChatRPC_001(a, 1024); var n = VRChatRPC_001(a, 1024);
return BitConverter.ToString(a, 0, n).Replace("-", string.Empty); return BitConverter.ToString(a, 0, n).Replace("-", string.Empty);
} }
public static string GetPersonaName() public string GetPersonaName()
{ {
var ptr = VRChatRPC_002(); var ptr = VRChatRPC_002();
if (ptr != IntPtr.Zero) if (ptr != IntPtr.Zero)

View File

@@ -13,10 +13,10 @@ namespace VRCX
[DllImport("kernel32.dll", SetLastError = false)] [DllImport("kernel32.dll", SetLastError = false)]
public static extern void CopyMemory(IntPtr destination, IntPtr source, uint length); public static extern void CopyMemory(IntPtr destination, IntPtr source, uint length);
[DllImport("user32.dll")] [DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)] [DllImport("user32.dll", SetLastError = true)]
public static extern UInt32 GetWindowThreadProcessId(IntPtr hWnd, out Int32 lpdwProcessId); public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
} }
} }