Skip to content

Commit

Permalink
add logging, some settings, security fixes, bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuvix25 committed Jun 24, 2023
1 parent fd7ec48 commit 403d238
Show file tree
Hide file tree
Showing 17 changed files with 444 additions and 82 deletions.
11 changes: 5 additions & 6 deletions Pages/Index.cshtml
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
@page
@model IndexModel


@* he = hud-element *@
@{
Layout = "~/Pages/Shared/_Layout.cshtml";
}

<head>
<title>ReHUD</title>


<script src="https://www.unpkg.com/agnostic-draggable@1.4.5/dist/agnostic-draggable.min.js"></script>

<script src="~/js/utils.js" asp-append-version="true"></script>
<script src="~/lib/agnostic-draggable/dist/agnostic-draggable.min.js"></script>
<script src="~/js/index.js" asp-append-version="true"></script>
</head>

@* he = hud-element *@
<div id="main-container" class="col sb">
<div class="row sb" id="top-group">
<div class="row" id="top-left-group">
Expand Down
26 changes: 20 additions & 6 deletions Pages/Settings.cshtml
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
@page
@model SettingsModel

@{
Layout = "~/Pages/Shared/_Layout.cshtml";
}

<head>
<title>ReHUD | Settings</title>

<link rel="stylesheet" href="~/css/settings.css" asp-append-version="true" />

<script src="~/js/settings.js" asp-append-version="true"></script>
</head>

<div class="setting">
<div class="setting" id="layout-setting">
<label>HUD Layout</label>
<button id="edit-layout" onclick="lockOverlay(true)">Edit</button>
<button id="cancel-reset-layout" onclick="lockOverlay(false)">Reset</button>
<button id="edit-layout">Edit</button>
<button id="cancel-reset-layout">Reset</button>
</div>

<div class="setting">
<div class="setting" id="speed-units-setting">
<label>Speed Units</label>
<button id="speed-units-kmh" onclick="speedUnits('kmh')">km/h</button>
<button id="speed-units-mph" onclick="speedUnits('mph')">mp/h</button>
<button id="speed-units-kmh">km/h</button>
<button id="speed-units-mph">mp/h</button>
</div>

<div class="setting" id="radar-beep-setting">
<label>Radar Beep Volume</label>
<input type="range" min="0" max="3" value="1" step="0.01" class="slider" id="radar-beep-volume">
<input type="number" min="0" max="3" step="0.01" id="radar-beep-volume-text">
</div>


<button id="show-log-file">Show Log File</button>
5 changes: 4 additions & 1 deletion Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<!DOCTYPE html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; img-src 'self' https://game.raceroom.com/ https://prod.r3eassets.com/; connect-src https://raw.githubusercontent.com/; style-src-elem https://fonts.googleapis.com/ 'self'; font-src https://fonts.gstatic.com;">
<link rel="stylesheet" href="~/css/app.css" asp-append-version="true" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
Expand All @@ -15,6 +17,7 @@

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/utils.js" asp-append-version="true"></script>

@await RenderSectionAsync("Scripts", required: false)
</body>
Expand Down
20 changes: 9 additions & 11 deletions R3E.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ enum VersionMajor
enum VersionMinor
{
// Minor version number to test against
R3E_VERSION_MINOR = 13
R3E_VERSION_MINOR = 14
};

enum Session
Expand Down Expand Up @@ -554,9 +554,8 @@ internal struct DriverInfo
public Int32 ClassPerformanceIndex;
// Note: See the EngineType enum
public Int32 EngineType;

public Int32 Unused1;
public Int32 Unused2;
public Single CarWidth;
public Single CarLength;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
Expand Down Expand Up @@ -656,14 +655,13 @@ internal struct DriverData
// DisqualifyPenaltyIgnoredBlueFlag = 13,
// DisqualifyPenaltyMax = 14
public Int32 PenaltyReason;

// -1 unavailable, 0 = ignition off, 1 = ignition on but not running, 2 = ignition on and running
public Int32 EngineState;

// Reserved data
public Int32 Unused1;
public Single Unused2;
public Single Unused3;
// Car body orientation
// Unit: Euler angles
public Vector3<Single> Orientation;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
Expand Down Expand Up @@ -732,7 +730,7 @@ internal struct Shared

// If the session is time based, lap based or time based with an extra lap at the end
public Int32 SessionLengthFormat;

// Unit: Meter per second (m/s)
public Single SessionPitSpeedLimit;

Expand Down Expand Up @@ -1051,7 +1049,7 @@ internal struct Shared
public Int32 TireTypeRear;
// Which subtype of tires the car has
// Note: See the R3E.Constant.TireSubtype enum
public Int32 TireSubtypeFront;
public Int32 TireSubtypeFront;
public Int32 TireSubtypeRear;

// Current brake temperature (-1.0 = N/A)
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ I started this project following the recent increase in the number of bugs in Ra
- Fuel insights
- Input meter
- Damage viewer
- Radar
- Live on-track relative display*
- Radar* (waiting for some features to be implemented into the shared memory API)
- Session status*
- Settings window:
- Element scale and rearrangement*
Expand Down Expand Up @@ -55,6 +55,9 @@ To change the position and scale of hud elements, first click on the "Edit" butt

---

## Bug Reporting
Since [v0.3.1-beta](https://github.com/Yuvix25/ReHUD/releases/tag/v0.3.1-beta), the settings window contains a "Show Log File" button. If you encounter a bug/issue, create a [new issue](https://github.com/Yuvix25/ReHUD/issues/new?assignees=Yuvix25&labels=bug&projects=&template=bug_report.md&title=),

## Contribution
Any contribution to the project will be highly appreciated! Feel free to open a new [issue](https://github.com/Yuvix25/ReHUD/issues/new/choose) or [pull request](https://github.com/Yuvix25/ReHUD/compare), and I'll do my best to review them and provide my own feedback.

Expand Down
3 changes: 2 additions & 1 deletion ReHUD.csproj
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>ReHUD</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="ElectronNET.API" Version="23.6.1" />
<PackageReference Include="log4net" Version="2.0.15" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

Expand Down
6 changes: 3 additions & 3 deletions SharedMemory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public void Run(SharedMemoryCallback callback)
var timeReset = DateTime.UtcNow;
var timeLast = timeReset;

Console.WriteLine("Looking for RRRE.exe...");
ReHUD.Startup.logger.Info("Looking for RRRE.exe...");

while (true)
{
Expand All @@ -48,13 +48,13 @@ public void Run(SharedMemoryCallback callback)
if (Utilities.IsRrreRunning() && !Mapped)
{
if (!found)
Console.WriteLine("Found RRRE.exe, mapping shared memory...");
ReHUD.Startup.logger.Info("Found RRRE.exe, mapping shared memory...");

found = true;

if (Map())
{
Console.WriteLine("Memory mapped successfully");
ReHUD.Startup.logger.Info("Memory mapped successfully");
timeReset = DateTime.UtcNow;

_buffer = new Byte[Marshal.SizeOf(typeof(Shared))];
Expand Down
106 changes: 98 additions & 8 deletions Startup.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
using ElectronNET.API;
using ElectronNET.API.Entities;
using Newtonsoft.Json;
using log4net;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using log4net.Config;
using System.Reflection;

namespace ReHUD;

public class Startup
{
public static ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType);
FileAppender? rootAppender;
string? logFilePath;

public Startup(IConfiguration configuration)
{
Configuration = configuration;
Expand All @@ -22,6 +31,12 @@ public void ConfigureServices(IServiceCollection services)
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

rootAppender = ((Hierarchy)logRepository).Root.Appenders.OfType<FileAppender>().FirstOrDefault();
logFilePath = rootAppender != null ? rootAppender.File : string.Empty;

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand Down Expand Up @@ -57,6 +72,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
}
}

private const string anotherInstanceMessage = "Another instance of ReHUD is already running";
private const string logFilePathWarning = "Log file path could not be determined. Try searching for a file name 'ReHUD.log' in C:\\Users\\<username>\\AppData\\Local\\Programs\\rehud\\resources\\bin";

private const string userDataFile = "userData.json";
private const string settingsFile = "settings.json";
Expand All @@ -75,16 +92,18 @@ private async Task CreateMainWindow(IWebHostEnvironment env)
Transparent = true,
BackgroundColor = "#00000000",
Icon = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ReHUD.png"),
WebPreferences = new WebPreferences()
{
EnableRemoteModule = true,
NodeIntegration = true,
// ContextIsolation = true,
},
});

bool gotLock = await Electron.App.RequestSingleInstanceLockAsync((args, arg) => { });
if (!gotLock)
{
MessageBoxOptions options = new MessageBoxOptions("Another instance of ReHUD is already running.");
options.Type = MessageBoxType.error;
options.Title = "Error";

await Electron.Dialog.ShowMessageBoxAsync(window, options);
await ShowMessageBox(window, anotherInstanceMessage, "Error", MessageBoxType.error);
Electron.App.Quit();
return;
}
Expand All @@ -95,6 +114,28 @@ private async Task CreateMainWindow(IWebHostEnvironment env)
window.SetIgnoreMouseEvents(true);


await Electron.IpcMain.On("log", (args) =>
{
Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)args;
if (obj == null || obj["level"] == null)
return;
string message = ((string)(obj["message"] ?? "(unknown)")).Trim();
string level = ((string)obj["level"]).ToUpper();

switch (level) {
case "INFO":
logger.Debug(message);
break;
case "WARN":
logger.Info(message);
break;
case "ERROR":
logger.Error(message);
break;
}
});


await Electron.IpcMain.On("get-hud-layout", (args) => {
SendHudLayout(window);
});
Expand All @@ -107,7 +148,7 @@ await Electron.IpcMain.On("reset-hud-layout", (args) => {
try {
SendHudLayout(window, new Dictionary<String, Object>());
} catch (Exception e) {
Console.WriteLine(e);
logger.Error("Error resetting HUD layout", e);
}
});

Expand All @@ -134,6 +175,13 @@ private async Task CreateSettingsWindow(IWebHostEnvironment env)
Width = 800,
Height = 600,
Icon = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ReHUD.png"),
WebPreferences = new WebPreferences()
{
// ContextIsolation = true,
EnableRemoteModule = true,
NodeIntegration = true,
// Preload = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "js", "utils.js"),
},
});

if (!env.IsDevelopment())
Expand Down Expand Up @@ -172,12 +220,54 @@ await Electron.IpcMain.On("set-setting", (arg) =>
if (array.Count == 2 && array[0] != null && array[0].Type == Newtonsoft.Json.Linq.JTokenType.String)
SaveSetting(array[0].ToString(), array[1]);
else
Console.WriteLine("Invalid setting: " + arg);
logger.Error("Invalid setting when attempting 'set-setting': " + arg);
});


await Electron.IpcMain.On("show-log-file", async (arg) => {
if (logFilePath == null) {
await ShowMessageBox(window, logFilePathWarning, "Warning", MessageBoxType.warning);
} else {
await Electron.Shell.ShowItemInFolderAsync(Path.Combine(logFilePath));
}
});

window.OnClosed += () => Electron.App.Quit();
}

private async Task<MessageBoxResult> ShowMessageBox(BrowserWindow window, string message, string title = "Error", MessageBoxType type = MessageBoxType.error)
{
MessageBoxOptions options = PrepareMessageBox(message, title, type);
return await Electron.Dialog.ShowMessageBoxAsync(window, options);
}

private async Task<MessageBoxResult> ShowMessageBox(string message, string title = "Error", MessageBoxType type = MessageBoxType.error)
{
MessageBoxOptions options = PrepareMessageBox(message, title, type);
return await Electron.Dialog.ShowMessageBoxAsync(options);
}

private MessageBoxOptions PrepareMessageBox(string message, string title = "Error", MessageBoxType type = MessageBoxType.error)
{
MessageBoxOptions options = new MessageBoxOptions(message);
options.Type = type;
options.Title = title;

switch (type) {
case MessageBoxType.error:
logger.Error(message);
break;
case MessageBoxType.info:
logger.Info(message);
break;
case MessageBoxType.warning:
logger.Warn(message);
break;
}

return options;
}

Dictionary<String, Object> settings = GetSettings();

private void SaveSetting(String key, Object value)
Expand Down Expand Up @@ -287,7 +377,7 @@ private void RunLoop(BrowserWindow window, IWebHostEnvironment env)
}
catch (Exception e)
{
Console.WriteLine(e);
logger.Error("Error saving data", e);
}

lastLap = data.CompletedLaps;
Expand Down
2 changes: 1 addition & 1 deletion electron.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"appId": "com.yuvix.rehud",
"productName": "ReHUD",
"copyright": "Copyright © 2023",
"buildVersion": "0.3.0",
"buildVersion": "0.3.1",
"win": {
"icon": "../../../wwwroot/ReHUD.png"
},
Expand Down
Loading

0 comments on commit 403d238

Please sign in to comment.