diff --git a/CpuMonitor.cs b/CpuMonitor.cs index 658393c1..99068e9a 100644 --- a/CpuMonitor.cs +++ b/CpuMonitor.cs @@ -8,62 +8,78 @@ using System.Threading; namespace VRCX { - public static class CpuMonitor + public class CpuMonitor { - public static float CpuUsage { get; private set; } - private static Thread m_Thread; + public static CpuMonitor Instance { get; private set; } + 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 { - counter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true); + m_Counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); } catch { } - try - { - if (counter == null) - { - 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(); - } - }) + } + + m_Thread = new Thread(ThreadLoop) { IsBackground = true }; + } + + internal void Init() + { m_Thread.Start(); } - public static void Exit() + internal void Exit() { - var T = m_Thread; + var thread = m_Thread; m_Thread = null; - T.Interrupt(); - T.Join(); + thread.Interrupt(); + 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 + } + } } } } \ No newline at end of file diff --git a/Discord.cs b/Discord.cs index 0ad5d325..ced72c63 100644 --- a/Discord.cs +++ b/Discord.cs @@ -12,76 +12,92 @@ namespace VRCX public class Discord { public static Discord Instance { get; private set; } - private static readonly ReaderWriterLockSlim m_Lock = new ReaderWriterLockSlim(); - private static readonly RichPresence m_Presence = new RichPresence(); - private static Thread m_Thread; - private static bool m_Active; + private readonly ReaderWriterLockSlim m_Lock; + private readonly RichPresence m_Presence; + private DiscordRpcClient m_Client; + private Thread m_Thread; + private bool m_Active; static Discord() { Instance = new Discord(); } - public static void Init() + public Discord() { - m_Thread = new Thread(() => - { - DiscordRpcClient client = null; - 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(); - }) + m_Lock = new ReaderWriterLockSlim(); + m_Presence = new RichPresence(); + m_Thread = new Thread(ThreadLoop) { IsBackground = true }; + } + + internal void Init() + { m_Thread.Start(); } - public static void Exit() + internal void Exit() { - var T = m_Thread; + var thread = m_Thread; m_Thread = null; - T.Interrupt(); - T.Join(); + thread.Interrupt(); + 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) @@ -93,8 +109,8 @@ namespace VRCX private static string LimitByteLength(string str, int maxBytesLength) { var bytesArr = Encoding.UTF8.GetBytes(str); - int bytesToRemove = 0; - int lastIndexInString = str.Length - 1; + var bytesToRemove = 0; + var lastIndexInString = str.Length - 1; while (bytesArr.Length - bytesToRemove > maxBytesLength) { bytesToRemove += Encoding.UTF8.GetByteCount(new char[] { str[lastIndexInString] }); @@ -122,8 +138,8 @@ namespace VRCX m_Lock.EnterWriteLock(); try { - if (string.IsNullOrEmpty(largeKey) && - string.IsNullOrEmpty(smallKey)) + if (string.IsNullOrEmpty(largeKey) == true && + string.IsNullOrEmpty(smallKey) == true) { m_Presence.Assets = null; } @@ -145,18 +161,15 @@ namespace VRCX } } - // JSB Sucks 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(); try { - if (startUnixMilliseconds == 0) + if (_startUnixMilliseconds == 0) { m_Presence.Timestamps = null; } @@ -166,14 +179,16 @@ namespace VRCX { 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; } else { - m_Presence.Timestamps.EndUnixMilliseconds = endUnixMilliseconds; + m_Presence.Timestamps.EndUnixMilliseconds = _endUnixMilliseconds; } } } diff --git a/LogWatcher.cs b/LogWatcher.cs index 2f530520..270dbe1a 100644 --- a/LogWatcher.cs +++ b/LogWatcher.cs @@ -25,7 +25,7 @@ namespace VRCX private readonly Dictionary m_LogContextMap; // private readonly ReaderWriterLockSlim m_LogListLock; private readonly List m_LogList; - private Thread m_WatchThread; + private Thread m_Thread; private bool m_ResetLog; // NOTE @@ -43,29 +43,31 @@ namespace VRCX m_LogContextMap = new Dictionary(); m_LogListLock = new ReaderWriterLockSlim(); m_LogList = new List(); - m_WatchThread = new Thread(WatchLoop) + m_Thread = new Thread(ThreadLoop) { IsBackground = true }; } - public void Init() + internal void Init() { - m_WatchThread.Start(); + m_Thread.Start(); } - public void Exit() + internal void Exit() { - var watchThread = m_WatchThread; - m_WatchThread = null; - watchThread.Interrupt(); - watchThread.Join(); + var thread = m_Thread; + m_Thread = null; + thread.Interrupt(); + thread.Join(); } - private void WatchLoop() + private void ThreadLoop() { - while (m_WatchThread != null) + while (m_Thread != null) { + Update(); + try { Thread.Sleep(1000); @@ -74,8 +76,6 @@ namespace VRCX { // ThreadInterruptedException } - - Update(); } } @@ -232,7 +232,7 @@ namespace VRCX fileInfo.Name, ConvertLogTimeToISO8601(line), "hmd-model", - hmdModel + hmdModel }); return true; @@ -404,10 +404,7 @@ namespace VRCX public void Reset() { m_ResetLog = true; - if (m_WatchThread != null) - { - m_WatchThread.Interrupt(); - } + m_Thread?.Interrupt(); } public string[][] Get() @@ -418,21 +415,21 @@ namespace VRCX m_LogListLock.EnterWriteLock(); try { - string[][] array; + string[][] items; - if (m_LogList.Count > 100) + if (m_LogList.Count > 1000) { - array = new string[100][]; - m_LogList.CopyTo(0, array, 0, 100); - m_LogList.RemoveRange(0, 100); + items = new string[1000][]; + m_LogList.CopyTo(0, items, 0, 1000); + m_LogList.RemoveRange(0, 1000); } else { - array = m_LogList.ToArray(); + items = m_LogList.ToArray(); m_LogList.Clear(); } - return array; + return items; } finally { diff --git a/MainForm.cs b/MainForm.cs index a2ed267a..33f08cc2 100644 --- a/MainForm.cs +++ b/MainForm.cs @@ -16,7 +16,7 @@ namespace VRCX public partial class MainForm : Form { 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 LastLocationY; private int LastSizeWidth; diff --git a/Program.cs b/Program.cs index e96879a7..a14c7db2 100644 --- a/Program.cs +++ b/Program.cs @@ -57,17 +57,17 @@ namespace VRCX Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); VRCXStorage.Load(); - SQLite.Init(); - CpuMonitor.Init(); - Discord.Init(); + CpuMonitor.Instance.Init(); + Discord.Instance.Init(); + SQLite.Instance.Init(); LogWatcher.Instance.Init(); VRCXVR.Init(); Application.Run(new MainForm()); VRCXVR.Exit(); LogWatcher.Instance.Exit(); - Discord.Exit(); - CpuMonitor.Exit(); - SQLite.Exit(); + SQLite.Instance.Exit(); + Discord.Instance.Exit(); + CpuMonitor.Instance.Exit(); VRCXStorage.Save(); Cef.Shutdown(); } diff --git a/SQLite.cs b/SQLite.cs index c72b692c..ddd2f5d6 100644 --- a/SQLite.cs +++ b/SQLite.cs @@ -10,78 +10,84 @@ namespace VRCX public class SQLite { public static SQLite Instance { get; private set; } - private static readonly ReaderWriterLockSlim m_Lock = new ReaderWriterLockSlim(); - private static SQLiteConnection m_Connection; + private readonly ReaderWriterLockSlim m_ConnectionLock; + private readonly SQLiteConnection m_Connection; static 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(); } - public static void Exit() + internal void Exit() { m_Connection.Close(); m_Connection.Dispose(); } - public int ExecuteNonQuery(string sql, IDictionary param = null) + public int ExecuteNonQuery(string sql, IDictionary args = null) { - m_Lock.EnterWriteLock(); + m_ConnectionLock.EnterWriteLock(); 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 { - m_Lock.ExitWriteLock(); + m_ConnectionLock.ExitWriteLock(); } } - public void Execute(IJavascriptCallback callback, string sql, IDictionary param = null) + public void Execute(IJavascriptCallback callback, string sql, IDictionary args = null) { - m_Lock.EnterReadLock(); + m_ConnectionLock.EnterReadLock(); 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]; - R.GetValues(row); - callback.ExecuteAsync(row); + var values = new object[reader.FieldCount]; + reader.GetValues(values); + callback.ExecuteAsync(values); } } } } finally { - m_Lock.ExitReadLock(); + m_ConnectionLock.ExitReadLock(); } } } diff --git a/SharedVariable.cs b/SharedVariable.cs index 93010df6..edb90a1e 100644 --- a/SharedVariable.cs +++ b/SharedVariable.cs @@ -30,23 +30,7 @@ namespace VRCX m_MapLock.EnterWriteLock(); try { - if (m_Map.Count > 0) - { - m_Map.Clear(); - } - } - finally - { - m_MapLock.ExitWriteLock(); - } - } - - public bool Remove(string key) - { - m_MapLock.EnterWriteLock(); - try - { - return m_Map.Remove(key); + m_Map.Clear(); } finally { @@ -84,5 +68,18 @@ namespace VRCX m_MapLock.ExitWriteLock(); } } + + public bool Remove(string key) + { + m_MapLock.EnterWriteLock(); + try + { + return m_Map.Remove(key); + } + finally + { + m_MapLock.ExitWriteLock(); + } + } } } \ No newline at end of file diff --git a/VRCX.cs b/VRCX.cs index 10c57bd8..523b90fd 100644 --- a/VRCX.cs +++ b/VRCX.cs @@ -25,13 +25,7 @@ namespace VRCX public void ShowDevTools() { - try - { - MainForm.Browser.ShowDevTools(); - } - catch - { - } + MainForm.Instance.Browser.ShowDevTools(); } public void DeleteAllCookies() @@ -41,8 +35,9 @@ namespace VRCX public string LoginWithSteam() { - return VRChatRPC.Update() - ? VRChatRPC.GetAuthSessionTicket() + var rpc = VRChatRPC.Instance; + return rpc.Update() == true + ? rpc.GetAuthSessionTicket() : string.Empty; } @@ -55,12 +50,12 @@ namespace VRCX if (hwnd != IntPtr.Zero) { var cmdline = string.Empty; + try { - Int32 pid = 0; - WinApi.GetWindowThreadProcessId(hwnd, out pid); - using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + pid)) - using (ManagementObjectCollection objects = searcher.Get()) + WinApi.GetWindowThreadProcessId(hwnd, out uint pid); + using (var searcher = new ManagementObjectSearcher($"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {pid}")) + using (var objects = searcher.Get()) { cmdline = objects.Cast().SingleOrDefault()?["CommandLine"]?.ToString(); } @@ -89,14 +84,14 @@ namespace VRCX { // "C:\Program Files (x86)\Steam\steam.exe" -- "%1" 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 _arguments = Uri.EscapeDataString(arguments); Process.Start(new ProcessStartInfo { WorkingDirectory = path, - FileName = path + "\\steam.exe", + FileName = $"{path}\\steam.exe", UseShellExecute = false, Arguments = $"-- \"steam://rungameid/438100//{_arguments}\"" }).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" 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; Process.Start(new ProcessStartInfo { WorkingDirectory = path, - FileName = path + "\\VRChat.exe", + FileName = $"{path}\\VRChat.exe", UseShellExecute = false, Arguments = $"\"{arguments}\"" }).Close(); @@ -135,7 +130,8 @@ namespace VRCX 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(); } @@ -180,7 +176,7 @@ namespace VRCX public float CpuUsage() { - return CpuMonitor.CpuUsage; + return CpuMonitor.Instance.CpuUsage; } public void SetStartup(bool enabled) @@ -189,7 +185,7 @@ namespace VRCX { using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { - if (enabled) + if (enabled == true) { var path = Application.ExecutablePath; key.SetValue("VRCX", $"\"{path}\" --startup"); diff --git a/VRChatRPC.cs b/VRChatRPC.cs index df584a21..4d0cd2f5 100644 --- a/VRChatRPC.cs +++ b/VRChatRPC.cs @@ -9,8 +9,10 @@ using System.Text; namespace VRCX { - public static class VRChatRPC + public class VRChatRPC { + public static VRChatRPC Instance { get; private set; } + [DllImport("VRChatRPC", CallingConvention = CallingConvention.Cdecl)] private static extern bool VRChatRPC_000(); @@ -20,19 +22,24 @@ namespace VRCX [DllImport("VRChatRPC", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr VRChatRPC_002(); - public static bool Update() + static VRChatRPC() + { + Instance = new VRChatRPC(); + } + + public bool Update() { return VRChatRPC_000(); } - public static string GetAuthSessionTicket() + public string GetAuthSessionTicket() { var a = new byte[1024]; var n = VRChatRPC_001(a, 1024); return BitConverter.ToString(a, 0, n).Replace("-", string.Empty); } - public static string GetPersonaName() + public string GetPersonaName() { var ptr = VRChatRPC_002(); if (ptr != IntPtr.Zero) diff --git a/WinApi.cs b/WinApi.cs index fced2a72..c1cc0aae 100644 --- a/WinApi.cs +++ b/WinApi.cs @@ -13,10 +13,10 @@ namespace VRCX [DllImport("kernel32.dll", SetLastError = false)] 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); [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); } } \ No newline at end of file