Skip to content

Commit

Permalink
- Replace DispatcherTimer with Timer to fix inconsistent update frequ…
Browse files Browse the repository at this point in the history
…encies

- Clean up game registration process
  • Loading branch information
tremwil committed Mar 30, 2022
1 parent f99607e commit d5cc233
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 86 deletions.
5 changes: 0 additions & 5 deletions SteamP2PInfo/Config/GameConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,6 @@ public class GameConfig : INotifyPropertyChanged
/// </summary>
[JsonProperty("process_name")]
public string ProcessName { get; set; } = "";
/// <summary>
/// Name of the game's window. Used to itentify which window to target with the overlay.
/// </summary>
[JsonProperty("window_name")]
public string WindowName { get; set; } = "";

/// <summary>
/// The Steam App ID of the game.
Expand Down
141 changes: 73 additions & 68 deletions SteamP2PInfo/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
Expand Down Expand Up @@ -32,9 +33,9 @@ public partial class MainWindow
{
private ObservableCollection<SteamPeerBase> peers;
private OverlayWindow overlay;
private DispatcherTimer timer;
private Timer timer;
private int timerTicks = 0;
private bool saveRequest = false;
private int overlayHotkey = 0;

private WindowSelectDialog.WindowInfo wInfo;

Expand All @@ -51,11 +52,8 @@ public MainWindow()
dataGridSession.DataContext = peers;
Title = "Steam P2P Info " + VersionCheck.CurrentVersion;

timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += Timer_Tick;

Settings.Default.PropertyChanged += (s, e) => { saveRequest = true; };
timer = new Timer(Timer_Tick, null, Timeout.Infinite, Timeout.Infinite);
Settings.Default.PropertyChanged += (s, e) => Settings.Default.Save();

Task.Run(() =>
{
Expand All @@ -75,58 +73,54 @@ public MainWindow()
});
}

private void Timer_Tick(object sender, EventArgs e)
private void Timer_Tick(object o)
{
// Necessary to close the program after the game exits, as SteamAPI_Shutdown isn't
// sufficient to have steam recognize the game is no longer running
if (!WinAPI.User32.IsWindow(wInfo.Handle))
Close();

if (HotkeyManager.Enabled && !GameConfig.Current.HotkeysEnabled)
HotkeyManager.Disable();
this.Invoke(() =>
{
// Necessary to close the program after the game exits, as SteamAPI_Shutdown isn't
// sufficient to have steam recognize the game is no longer running
if (!WinAPI.User32.IsWindow(wInfo.Handle))
Close();
if (!HotkeyManager.Enabled && GameConfig.Current.HotkeysEnabled)
HotkeyManager.Enable();
if (HotkeyManager.Enabled && !GameConfig.Current.HotkeysEnabled)
HotkeyManager.Disable();
if ((timerTicks = (timerTicks + 1) % 5) == 0)
{
// Rather not have the settings update on a loop, but
// Fody generated OnChange seems to break PropertyChanged
// for GameConfig. So do this for now.
GameConfig.Current?.Save();
SteamPeerManager.UpdatePeerList();
}
if (!HotkeyManager.Enabled && GameConfig.Current.HotkeysEnabled)
HotkeyManager.Enable();
peers.Clear();
foreach (SteamPeerBase p in SteamPeerManager.GetPeers())
peers.Add(p);
if ((timerTicks = (timerTicks + 1) % 6) == 0)
{
// Rather not have the settings update on a loop, but
// Fody generated OnChange seems to break PropertyChanged
// for GameConfig. So do this for now.
GameConfig.Current?.Save();
SteamPeerManager.UpdatePeerList();
}
// Update session info column sizes
foreach (var col in dataGridSession.Columns)
{
col.Width = new DataGridLength(1, DataGridLengthUnitType.Pixel);
col.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
}
dataGridSession.UpdateLayout();
peers.Clear();
foreach (SteamPeerBase p in SteamPeerManager.GetPeers())
peers.Add(p);
// Update overlay column sizes
foreach (var col in overlay.dataGrid.Columns)
{
col.Width = new DataGridLength(1, DataGridLengthUnitType.Pixel);
col.Width = new DataGridLength(1, DataGridLengthUnitType.SizeToCells);
}
overlay.dataGrid.UpdateLayout();
// Update session info column sizes
foreach (var col in dataGridSession.Columns)
{
col.Width = new DataGridLength(1, DataGridLengthUnitType.Pixel);
col.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
}
dataGridSession.UpdateLayout();
// Queue position update after the overlay has re-rendered
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(overlay.UpdatePosition));
overlay.UpdateVisibility();
// Update overlay column sizes
foreach (var col in overlay.dataGrid.Columns)
{
col.Width = new DataGridLength(1, DataGridLengthUnitType.Pixel);
col.Width = new DataGridLength(1, DataGridLengthUnitType.SizeToCells);
}
overlay.dataGrid.UpdateLayout();
if (saveRequest)
{
GameConfig.Current.Save();
Settings.Default.Save();
saveRequest = false;
}
// Queue position update after the overlay has re-rendered
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(overlay.UpdatePosition));
overlay.UpdateVisibility();
});
}

private void ShowUnhandledException(Exception err, string type, bool fatal)
Expand Down Expand Up @@ -174,37 +168,48 @@ private void labelGameState_RequestNavigate(object sender, RequestNavigateEventA
WindowSelectDialog dialog = new WindowSelectDialog();
if (dialog.ShowDialog() == true)
{
wInfo = dialog.SelectedWindow;
if (GameConfig.LoadOrCreate(wInfo.ProcessName) || GameConfig.Current.SteamAppId == 0)
GameConfig.LoadOrCreate(dialog.SelectedWindow.ProcessName);

if (!Directory.Exists(System.IO.Path.GetDirectoryName(Settings.Default.SteamLogPath)))
{
MessageBox.Show("Steam IPC log file directory does not exist", "Directory Not Found", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}

if (GameConfig.Current.SteamAppId == 0)
{
string input = Microsoft.VisualBasic.Interaction.InputBox("Please enter the Steam App ID to use with this game:", "Steam App ID Required");
if (!uint.TryParse(input, out uint result))
{
MessageBox.Show("Please input a valid number", "Input Error", MessageBoxButton.OK, MessageBoxImage.Error);
wInfo = null;
return;
}
GameConfig.Current.SteamAppId = (int)result;
}

GameConfig.Current.WindowName = wInfo.Title;

HotkeyManager.AddHotkey(wInfo.Handle, () => GameConfig.Current.OverlayConfig.Hotkey, () => GameConfig.Current.OverlayConfig.Enabled ^= true);
overlay = new OverlayWindow(wInfo.Handle, wInfo.ProcessId, wInfo.ThreadId);
overlay.dataGrid.DataContext = peers;

SteamConsoleHelper();

if (!SteamPeerManager.Init())
Environment.SetEnvironmentVariable("SteamAppId", GameConfig.Current.SteamAppId.ToString());
if (!SteamAPI.Init())
{
MessageBox.Show("Could not initialize Steam API", "Steam API Error", MessageBoxButton.OK, MessageBoxImage.Error);
wInfo = null;
MessageBox.Show("Could not initialize Steam API. Make sure the provided AppId is valid!", "Steam API Error", MessageBoxButton.OK, MessageBoxImage.Error);
GameConfig.Current.SteamAppId = 0;
GameConfig.Current.Save();
return;
}

wInfo = dialog.SelectedWindow;
SteamPeerManager.Init();
SteamConsoleHelper();

HotkeyManager.RemoveHotkey(overlayHotkey);
overlayHotkey = HotkeyManager.AddHotkey(wInfo.Handle, () => GameConfig.Current.OverlayConfig.Hotkey, () => GameConfig.Current.OverlayConfig.Enabled ^= true);

overlay = new OverlayWindow(wInfo.Handle, wInfo.ProcessId, wInfo.ThreadId);
overlay.dataGrid.DataContext = peers;
if (!overlay.InstallMsgHook())
{
MessageBox.Show("Could not setup overlay message hook", "WINAPI Error", MessageBoxButton.OK, MessageBoxImage.Error);
wInfo = null;
overlay.Close();
MessageBox.Show("Failed to setup overlay message hook", "WINAPI Error", MessageBoxButton.OK, MessageBoxImage.Error);
Close();
return;
}

Expand All @@ -215,7 +220,7 @@ private void labelGameState_RequestNavigate(object sender, RequestNavigateEventA
ConfigTab.Children.Add(configEditor);

ETWPingMonitor.Start();
timer.Start();
timer.Change(0, 1000);
}
}
}
Expand Down
30 changes: 17 additions & 13 deletions SteamP2PInfo/SteamPeerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

using SteamP2PInfo.Config;
using System.Text.RegularExpressions;
using System.Windows;

namespace SteamP2PInfo
{
Expand All @@ -33,19 +34,13 @@ static class SteamPeerManager
/// </summary>
private static Dictionary<CSteamID, SteamPeerBase> mPeers = new Dictionary<CSteamID, SteamPeerBase>();

public static bool Init()
public static void Init()
{
Environment.SetEnvironmentVariable("SteamAppId", GameConfig.Current.SteamAppId.ToString());
if (!SteamAPI.Init())
return false;

fsWatcher = new FileSystemWatcher(Path.GetDirectoryName(Settings.Default.SteamLogPath));
fsWatcher.Filter = Path.GetFileName(Settings.Default.SteamLogPath);
fsWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
fsWatcher.Changed += (e, s) => mustReopenLog = true;
fsWatcher.EnableRaisingEvents = true;

return true;
}

private static CSteamID ExtractLobby(string str)
Expand All @@ -65,17 +60,26 @@ public async static void UpdatePeerList()
if (mustReopenLog)
{
sr?.Dispose();
sr = null;

fs?.Close();
fs?.Dispose();
fs = null;

fs = new FileStream(Settings.Default.SteamLogPath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
sr = new StreamReader(fs);
sr.BaseStream.Seek(0, SeekOrigin.End);

mustReopenLog = false;
try
{
fs = new FileStream(Settings.Default.SteamLogPath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
sr = new StreamReader(fs);
sr.BaseStream.Seek(0, SeekOrigin.End);
mustReopenLog = false;
}
catch (DirectoryNotFoundException)
{
MessageBox.Show("Steam IPC log file directory does not exist", "Directory Not Found", MessageBoxButton.OK, MessageBoxImage.Error);
}
}

while (true)
while (!mustReopenLog)
{
string line = await sr.ReadLineAsync();
if (line == null) break;
Expand Down

0 comments on commit d5cc233

Please sign in to comment.