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
{
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
}
}
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -25,7 +25,7 @@ namespace VRCX
private readonly Dictionary<string, LogContext> m_LogContextMap; // <FileName, LogContext>
private readonly ReaderWriterLockSlim m_LogListLock;
private readonly List<string[]> 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<string, LogContext>();
m_LogListLock = new ReaderWriterLockSlim();
m_LogList = new List<string[]>();
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
{

View File

@@ -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;

View File

@@ -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();
}

View File

@@ -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<string, object> param = null)
public int ExecuteNonQuery(string sql, IDictionary<string, object> 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<string, object> param = null)
public void Execute(IJavascriptCallback callback, string sql, IDictionary<string, object> 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();
}
}
}

View File

@@ -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();
}
}
}
}

36
VRCX.cs
View File

@@ -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<ManagementBaseObject>().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");

View File

@@ -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)

View File

@@ -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);
}
}