Skip to content

Commit

Permalink
Add log window
Browse files Browse the repository at this point in the history
  • Loading branch information
Xeeynamo committed Mar 19, 2021
1 parent 9da11e7 commit 720d1c6
Show file tree
Hide file tree
Showing 9 changed files with 134 additions and 10 deletions.
5 changes: 5 additions & 0 deletions OpenKh.Patcher/PatcherProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public void Patch(string originalAssets, string outputDir, Metadata metadata, st
}
catch (Exception ex)
{
Log.Err($"Patcher failed: {ex.Message}");
throw new PatcherException(metadata, ex);
}
}
Expand Down Expand Up @@ -123,6 +124,10 @@ private static void PatchFile(Context context, AssetFile assetFile, Stream strea
case "areadatascript":
PatchAreaDataScript(context, assetFile.Source, stream);
break;
default:
Log.Warn($"Method '{assetFile.Method}' not recognized for '{assetFile.Name}'. Falling back to 'copy'");
CopyFile(context, assetFile, stream);
break;
}

stream.SetLength(stream.Position);
Expand Down
8 changes: 8 additions & 0 deletions OpenKh.Tools.ModsManager/Interfaces/IDebugging.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace OpenKh.Tools.ModsManager.Interfaces
{
public interface IDebugging
{
void HideDebugger();
void Log(long ms, string tag, string str);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.IO;

namespace OpenKh.Tools.ModsManager.Services
namespace OpenKh.Tools.ModsManager.Interfaces
{
public interface IOperationDispatcher
{
Expand Down
2 changes: 2 additions & 0 deletions OpenKh.Tools.ModsManager/Services/ModsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ public static Task RunPacherAsync() => Task.Run(() =>
for (var i = modsList.Count - 1; i >= 0; i--)
{
var mod = modsList[i];
Log.Info($"Patching using {mod.Name} from {mod.Path}");

patcherProcessor.Patch(
ConfigurationService.GameDataLocation,
ConfigurationService.GameModPath,
Expand Down
5 changes: 5 additions & 0 deletions OpenKh.Tools.ModsManager/Services/OperationDispatcher.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using OpenKh.Common;
using OpenKh.Tools.ModsManager.Interfaces;
using System.Collections.Generic;
using System.IO;

Expand All @@ -24,12 +25,16 @@ public class OperationDispatcher : IOperationDispatcher
public int LoadFile(Stream outStream, string fileName)
{
if (GetFinalNamePath(fileName, out var finalFileName))
{
Log.Info($"Load file {fileName}");
return File.OpenRead(finalFileName).Using(x =>
{
x.CopyTo(outStream, 512 * 1024);
return (int)x.Length;
});
}

Log.Warn($"File {fileName} not found, falling back");
return 0;
}

Expand Down
30 changes: 24 additions & 6 deletions OpenKh.Tools.ModsManager/Services/Pcsx2Injector.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using OpenKh.Common;
using OpenKh.Tools.Common;
using OpenKh.Tools.ModsManager.Interfaces;
using System.Diagnostics;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -285,6 +286,8 @@ public enum Operation
private Task _injectorTask;
private uint _hookPtr;
private uint _nextHookPtr;
private string game;
private Offsets _myOffsets;

public Pcsx2Injector(IOperationDispatcher operationDispatcher)
{
Expand All @@ -295,16 +298,29 @@ public Pcsx2Injector(IOperationDispatcher operationDispatcher)
public string Region { get; set; }
public string Language { get; set; }

public void Run(Process process)
public void Run(Process process, IDebugging debugging)
{
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
_injectorTask = Task.Run(async () =>
{
Log.Info("Waiting for the game to boot");
var gameName = await Pcsx2MemoryService.GetPcsx2ApplicationName(process, _cancellationToken);
using var processStream = new ProcessStream(process, 0x20000000, 0x2000000);
WritePatch(processStream, gameName);
MainLoop(processStream);

Log.Info("Injecting code");
_myOffsets = _offsets.FirstOrDefault(x => x.GameName == gameName);
if (_myOffsets == null)
{
Log.Err($"Game {gameName} not recognized. Exiting from the injector service.");
return;
}

WritePatch(processStream, _myOffsets);

Log.Info("Executing the injector main loop");
MainLoop(processStream, debugging);
debugging.HideDebugger();
}, _cancellationToken);
}

Expand All @@ -314,7 +330,7 @@ public void Stop()
_injectorTask.Wait();
}

private void MainLoop(Stream stream)
private void MainLoop(Stream stream, IDebugging debugging)
{
var isProcessDead = false;
while (!_cancellationToken.IsCancellationRequested && !isProcessDead)
Expand Down Expand Up @@ -371,15 +387,15 @@ private void OperationGetFileSize(Stream stream)
stream.SetPosition(OperationAddress - 4).Write(returnValue);
}

private void WritePatch(Stream stream, string game)
private void WritePatch(Stream stream, Offsets offsets)
{
ResetHooks();
var bufferedStream = new BufferedStream(stream);
var offsets = _offsets.FirstOrDefault(x => x.GameName == game);
if (offsets != null)
{
if (offsets.LoadFile > 0)
{
Log.Info("Injeting LoadFile function");
WritePatch(bufferedStream, offsets.LoadFile,
ADDIU(T4, RA, 0),
JAL(WriteHook(bufferedStream, LoadFileHook)),
Expand All @@ -388,6 +404,7 @@ private void WritePatch(Stream stream, string game)

if (offsets.GetFileSize > 0)
{
Log.Info("Injeting GetFileSize function");
var subGetFileSizePtr = stream.SetPosition(offsets.GetFileSize + 8).ReadUInt32();
WritePatch(bufferedStream, offsets.GetFileSize,
ADDIU(T4, RA, 0),
Expand All @@ -405,6 +422,7 @@ private void WritePatch(Stream stream, string game)

if (RegionId >= 0)
{
Log.Info("Injeting SetupRegion function");
WritePatch(bufferedStream, offsets.RegionInit, RegionInitPatch);
WritePatch(bufferedStream, offsets.RegionForce, Region);
WritePatch(bufferedStream, offsets.RegionForce + 8, Language);
Expand Down
15 changes: 12 additions & 3 deletions OpenKh.Tools.ModsManager/ViewModels/MainViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using OpenKh.Common;
using OpenKh.Tools.Common;
using OpenKh.Tools.ModsManager.Models;
using OpenKh.Tools.ModsManager.Services;
Expand All @@ -23,6 +24,7 @@ public interface IChangeModEnableState
public class MainViewModel : BaseNotifyPropertyChanged, IChangeModEnableState
{
private static string ApplicationName = Utilities.GetApplicationName();
private readonly DebuggingWindow _debuggingWindow = new DebuggingWindow();
private ModViewModel _selectedValue;
private Pcsx2Injector _pcsx2Injector;

Expand Down Expand Up @@ -51,6 +53,9 @@ public ModViewModel SelectedValue

public MainViewModel()
{
Log.OnLogDispatch += (long ms, string tag, string message) =>
_debuggingWindow.Log(ms, tag, message);

ReloadModsList();
SelectedValue = ModsList.FirstOrDefault();
AddModCommand = new RelayCommand(_ =>
Expand Down Expand Up @@ -119,9 +124,13 @@ await ModsService.InstallMod(name, isZipFile, progress =>
}, _ => SelectedValue != null);
MoveUp = new RelayCommand(_ => MoveSelectedModUp(), _ => CanSelectedModMoveUp());
MoveDown = new RelayCommand(_ => MoveSelectedModDown(), _ => CanSelectedModMoveDown());
BuildCommand = new RelayCommand(_ =>
BuildCommand = new RelayCommand(async _ =>
{
ModsService.RunPacherAsync();
if (!_debuggingWindow.IsLoaded)
_debuggingWindow.Show();
_debuggingWindow.ClearLogs();

await ModsService.RunPacherAsync();
switch (ConfigurationService.GameEdition)
{
case 0:
Expand Down Expand Up @@ -152,7 +161,7 @@ await ModsService.InstallMod(name, isZipFile, progress =>
FileName = ConfigurationService.Pcsx2Location,
WorkingDirectory = Path.GetDirectoryName(ConfigurationService.Pcsx2Location),
Arguments = $"\"{ConfigurationService.IsoLocation}\""
}));
}), _debuggingWindow);
break;
case 2:
break;
Expand Down
12 changes: 12 additions & 0 deletions OpenKh.Tools.ModsManager/Views/DebuggingWindow.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Window x:Class="OpenKh.Tools.ModsManager.Views.DebuggingWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:OpenKh.Tools.ModsManager.Views"
mc:Ignorable="d"
Title="Debug window" Height="450" Width="800" FontFamily="Courier New" Background="#FF282C34">
<ScrollViewer>
<StackPanel x:Name="LogPanel"/>
</ScrollViewer>
</Window>
65 changes: 65 additions & 0 deletions OpenKh.Tools.ModsManager/Views/DebuggingWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using OpenKh.Tools.ModsManager.Interfaces;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace OpenKh.Tools.ModsManager.Views
{
/// <summary>
/// Interaction logic for DebuggingWindow.xaml
/// </summary>
public partial class DebuggingWindow : Window, IDebugging, INotifyPropertyChanged
{
private static readonly Brush[] _brushes = new Brush[]
{
new SolidColorBrush(Color.FromRgb(220, 223, 228)),
new SolidColorBrush(Color.FromRgb(229, 192, 123)),
new SolidColorBrush(Color.FromRgb(224, 108, 117)),
};

public DebuggingWindow()
{
InitializeComponent();
DataContext = this;
}

public void ClearLogs()
{
LogPanel.Children.Clear();
}

public void HideDebugger()
{
Application.Current.Dispatcher.Invoke(Close);
}

public void Log(long ms, string tag, string message)
{
Application.Current.Dispatcher.Invoke(() =>
{
var str = $"[{(ms / 1000):D3}.{(ms % 1000):D3}] {tag} {message}";
var brush = tag switch
{
"INF" => _brushes[0],
"WRN" => _brushes[1],
"ERR" => _brushes[2],
_ => _brushes[0],
};
LogPanel.Children.Insert(0, new TextBlock
{
Text = str,
Foreground = brush
});
});
}

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public event PropertyChangedEventHandler PropertyChanged;
}
}

0 comments on commit 720d1c6

Please sign in to comment.