Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHDStudio.Tests/BugReportServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,28 @@ public async Task SendBugReportAsyncReturnsFalseOnBadRequest()
// A device that became unready mid-batch (removable card reader, network share).
[InlineData(" Cannot create the output folder: The device is not ready. : 'H:\\roms\\ps1'.")]
[InlineData(" Cannot convert 'game.iso': the source or output could not be read or written (The device is not ready. : 'F:\\CHDStudio_Temp\\x.iso').")]
// A .pbp whose header is not PBP magic and whose content is not a known image format.
[InlineData(
"Failed to extract PBP file: Bloody Roar.PBP (190,840,832 bytes) - Failed to open PBP file: InvalidHeader (code 1)"
)]
[InlineData(
" Bloody Roar.PBP is not a PBP (its header is missing) and its content is not a disc image the app recognises — skipping."
)]
// A genuinely damaged PBP block: the message already tells the user to re-download it.
[InlineData(
" Tekken.PBP: the PBP's disc data is damaged (a compressed block ends before a full 16-sector block) — skipping. Re-download the file."
)]
// No default browser / headless session: the app copies the URL instead.
[InlineData("Failed to open browser: An error occurred trying to start process 'https://example.com' with working directory 'C:\\app'. Class not registered")]
[InlineData("Error opening URL: https://example.com")]
// A release bundle missing the optional MDSSharp assembly.
[InlineData(
"Could not load file or assembly 'MDSSharp, Version=1.2.3.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified."
)]
// A Windows privilege failure while the encoder opens its output file.
[InlineData(
"Failed to convert 'Death Connection (Japan).iso': Error creating CHD file (I:\\Death Connection (Japan).6f9e52f6.chdtmp): A required privilege is not held by the client."
)]
public void IsExcludedFromBugReport_KnownPatterns_ReturnsTrue(string message)
{
Assert.True(BugReportService.IsExcludedFromBugReport(message));
Expand Down
17 changes: 17 additions & 0 deletions CHDStudio.Tests/ChdSharpLoggerFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,21 @@ public void LatestWarningReplacesEarlierOne()
Assert.NotNull(captured);
Assert.Contains("second", captured);
}

/// <summary>
/// Hunk-level failures in a user's CHD are diagnostics, not application errors. They are
/// captured for the caller's classified message but must not be forwarded to the
/// bug-report sink as Error events.
/// </summary>
[Theory]
[InlineData(LogLevel.Warning, Serilog.Events.LogEventLevel.Information)]
[InlineData(LogLevel.Error, Serilog.Events.LogEventLevel.Information)]
[InlineData(LogLevel.Critical, Serilog.Events.LogEventLevel.Fatal)]
public void LibraryFailuresDoNotBecomeBugReportLevels(
LogLevel input,
Serilog.Events.LogEventLevel expected
)
{
Assert.Equal(expected, ChdSharpLoggerFactory.MapLevel(input));
}
}
17 changes: 17 additions & 0 deletions CHDStudio.Tests/DiscImageSignatureTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@
Assert.Equal(DiscImageKind.Unknown, DiscImageSignature.Classify(header));
}

[Fact]
public void DetectRecognisesCookedIsoVolumeDescriptor()
{
// A plain 2048-byte-sector ISO has no signature in its first sector; the ISO9660 primary
// volume descriptor at sector 16 is what identifies it. This is the shape of the .pbp
// files that were really renamed ISOs and failed with InvalidHeader.
var path = Path.Combine(_tempDir, "game.pbp");
var data = new byte[16 * 2048 + 8];
data[16 * 2048] = 1;
"CD001"u8.CopyTo(data.AsSpan(16 * 2048 + 1));
data[16 * 2048 + 6] = 1;
File.WriteAllBytes(path, data);

Assert.Equal(DiscImageKind.Iso, DiscImageSignature.Detect(path));
Assert.Equal("an ISO9660 disc image", DiscImageSignature.Describe(DiscImageKind.Iso));
}

[Fact]
public void DetectReadsFromDiskAndSurvivesAMissingFile()
{
Expand Down
14 changes: 14 additions & 0 deletions CHDStudio.Tests/MainWindowHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,20 @@ public void IsChdWriteFailure_ClassifiesWriteErrors(string? message, bool expect
Assert.Equal(expected, MainWindow.IsChdWriteFailure(message));
}

[Theory]
[InlineData(
"Error creating CHD file (I:\\Game.chdtmp): A required privilege is not held by the client.",
true
)]
[InlineData("Error creating CHD file: Access denied", true)]
[InlineData("Error creating CHD file: Permission denied", true)]
[InlineData("Error creating CHD file: UnauthorizedAccessException", true)]
[InlineData("Error creating CHD file: The disk is full", false)]
public void IsPermissionError_ClassifiesWindowsPrivilegeFailure(string message, bool expected)
{
Assert.Equal(expected, MainWindow.IsPermissionError(message));
}

[Fact]
public void IsDamagedPbpBlock_ShortDeflateStream_ReturnsTrue()
{
Expand Down
4 changes: 2 additions & 2 deletions CHDStudio.Tests/MdsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ public async Task CookedMode2Form1CdIsCuedAsMode2At2048Bytes()
{
var mds = WriteMds("CookedMode2.mds", 0x00, new TrackSpec(0x04, 1, 2048, 0));
WriteMdf("CookedMode2.mdf", 2048, 4);
var workDir = Path.Combine(_tempDir, "workmode2");
var workDir = Path.Join(_tempDir, "workmode2");
Directory.CreateDirectory(workDir);

var disc = MdsParser.Parse(mds);
Expand All @@ -840,7 +840,7 @@ public async Task Mode2Form2CdIsCuedAsMode2At2324Bytes()
{
var mds = WriteMds("Form2.mds", 0x00, new TrackSpec(0x05, 1, 2324, 0));
WriteMdf("Form2.mdf", 2324, 4);
var workDir = Path.Combine(_tempDir, "workform2");
var workDir = Path.Join(_tempDir, "workform2");
Directory.CreateDirectory(workDir);

var disc = MdsParser.Parse(mds);
Expand Down
32 changes: 32 additions & 0 deletions CHDStudio.Tests/PbpFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,38 @@
}
}

[Fact]
public void ExtractToAcceptsAShortFinalBlock()
{
// A disc whose sector count is not a multiple of 16 can store its last index block with
// only the sectors the image actually contains. The block is complete at its own declared
// size, not at the padded 16-sector size, and must extract successfully.
var path = Path.Combine(_tempDir, $"shortfinal_{Guid.NewGuid():N}.pbp");
new PbpTestFileBuilder()
.WithBlockCount(3)
.WithFinalBlockSectors(7)
.BuildTo(path);

var error = PbpFile.Open(path, out var pbp);
Assert.Equal(PbpError.None, error);
Assert.NotNull(pbp);

using (pbp)
{
const uint expectedIsoSize = 39 * PbpDiscInfo.IsoBlockSize;
Assert.Equal(expectedIsoSize, pbp.Discs[0].IsoSize);

using var outputStream = new MemoryStream();
pbp.Discs[0].ExtractTo(outputStream);
Assert.Equal(expectedIsoSize, (uint)outputStream.Length);

var binPath = Path.Combine(_tempDir, $"{Guid.NewGuid():N}.bin");
var result = pbp.Discs[0].ExtractToBinCue(binPath);
Assert.Equal(PbpError.None, result);
Assert.Equal(expectedIsoSize, (uint)new FileInfo(binPath).Length);
}
}

[Fact]
public void ExtractToIgnoresIndexEntriesBeyondDeclaredIsoSize()
{
Expand Down
64 changes: 48 additions & 16 deletions CHDStudio.Tests/PbpTestFileBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ internal sealed class PbpTestFileBuilder
private int _trailingPaddingBytes;
private int _shortIndexBlockIndex = -1;
private int _shortIndexBytes;
private int _finalBlockSectors = -1;

private string _title = "Test Game";

Expand Down Expand Up @@ -220,6 +221,21 @@ public PbpTestFileBuilder WithShortIndexLength(int blockIndex, int count)
return this;
}

/// <summary>
/// Writes the final ISO index block with only <paramref name="sectors" /> sectors (1-16)
/// instead of a padded 16-sector block, and records the matching total sector count in the
/// ISO9660 volume descriptor. Several PBP authoring tools store the disc's partially filled
/// last block this way; extraction must accept the short final block.
/// </summary>
/// <param name="sectors">Number of sectors stored in the final block, 1-16.</param>
public PbpTestFileBuilder WithFinalBlockSectors(int sectors)
{
_finalBlockSectors = sectors is >= 1 and <= 16
? sectors
: throw new ArgumentOutOfRangeException(nameof(sectors));
return this;
}

/// <summary>
/// Builds the PBP file and writes it to the specified path.
/// </summary>
Expand Down Expand Up @@ -448,7 +464,7 @@ private List<uint> WriteIsoIndex(Stream stream, int blockCount)
continue;
}

var storedLength = _compressBlocks ? GetStoredBlock(blockData, i).Length : BlockSize;
var storedLength = _compressBlocks ? GetStoredBlock(blockData, i).Length : blockData.Length;
var entryLength = storedLength;
if (i == _shortIndexBlockIndex)
entryLength = Math.Max(0, entryLength - _shortIndexBytes);
Expand All @@ -462,7 +478,7 @@ private List<uint> WriteIsoIndex(Stream stream, int blockCount)
// uncompressed block, set by pop-fe with compression disabled), SHA-1 at 8.
BinaryPrimitives.WriteUInt16LittleEndian(
entry.Slice(4, 2),
(ushort)(_compressBlocks ? entryLength : BlockSize)
(ushort)(_compressBlocks ? entryLength : blockData.Length)
);
if (!_compressBlocks)
entry[6] = 0x01;
Expand All @@ -471,13 +487,13 @@ private List<uint> WriteIsoIndex(Stream stream, int blockCount)
{
BinaryPrimitives.WriteInt32LittleEndian(
entry[4..8],
_compressBlocks ? entryLength : BlockSize
_compressBlocks ? entryLength : blockData.Length
);
}

stream.Write(entry);

currentOffset += (uint)(_compressBlocks ? storedLength : BlockSize);
currentOffset += (uint)storedLength;
}

return offsets;
Expand Down Expand Up @@ -542,22 +558,23 @@ private byte[] GetStoredBlock(byte[] blockData, int blockIndex)

private byte[] GetBlockData(int blockIndex)
{
var length = GetBlockLength(blockIndex);

if (_incompressibleBlocks)
{
var randomBlock = new byte[BlockSize];
var randomBlock = new byte[length];
var seed = 0x2F6E2B1 ^ (blockIndex * 0x9E3779B1);
for (var i = 0; i < BlockSize; i++)
for (var i = 0; i < length; i++)
{
seed = seed * 1103515245 + 12345;
randomBlock[i] = (byte)((seed >> 16) & 0xFF);
}

if (blockIndex == 1)
{
var sectorCount = (uint)(_blockCount * 16);
BinaryPrimitives.WriteUInt32LittleEndian(
randomBlock.AsSpan(104, 4),
sectorCount
TotalSectorCount()
);
}

Expand All @@ -569,35 +586,50 @@ private byte[] GetBlockData(int blockIndex)
// Block index 1 (the second block) carries the ISO9660 volume information:
// PbpDiscInfo.ReadIsoSize reads the sector count from bytes 104..107 of this
// block, exactly like the reference implementation's GetIsoSize().
var data = new byte[BlockSize];
var data = new byte[length];

// Fill with a recognizable pattern
for (var i = 0; i < BlockSize; i++)
for (var i = 0; i < length; i++)
data[i] = (byte)((i + blockIndex) & 0xFF);

if (_customIsoBlock1Data?.Length <= BlockSize)
if (_customIsoBlock1Data?.Length <= length)
{
Buffer.BlockCopy(_customIsoBlock1Data, 0, data, 0, _customIsoBlock1Data.Length);
}
else
{
// ISO size in sectors at bytes 104-107 (little-endian uint32)
// Total ISO size = sectorCount * IsoBlockSize
// We want _blockCount blocks, each with 16 sectors
var sectorCount = (uint)(_blockCount * 16);
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(104, 4), sectorCount);
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(104, 4), TotalSectorCount());
}

return data;
}

// Other blocks: fill with pattern
var block = new byte[BlockSize];
for (var i = 0; i < BlockSize; i++)
var block = new byte[length];
for (var i = 0; i < length; i++)
block[i] = (byte)((i + blockIndex * 17) & 0xFF);
return block;
}

/// <summary>Returns the uncompressed byte length of one ISO block (the final one may be short).</summary>
/// <param name="blockIndex">Zero-based block index.</param>
private int GetBlockLength(int blockIndex)
{
return blockIndex == _blockCount - 1 && _finalBlockSectors > 0
? _finalBlockSectors * IsoBlockSize
: BlockSize;
}

/// <summary>Returns the total number of sectors the ISO9660 volume descriptor declares.</summary>
private uint TotalSectorCount()
{
return _finalBlockSectors > 0
? (uint)((_blockCount - 1) * 16 + _finalBlockSectors)
: (uint)(_blockCount * 16);
}

private byte[] CompressBlock(byte[] data)
{
byte[] raw;
Expand Down
30 changes: 9 additions & 21 deletions CHDStudio/AboutWindow.axaml.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using System.Diagnostics;
using System.Reflection;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using CHDStudio.Dialogs;
using CHDStudio.Models;
using CHDStudio.Services;
using CHDStudio.Utilities;

namespace CHDStudio;

Expand Down Expand Up @@ -55,27 +55,15 @@ private void OpenUrl_Click(object? sender, RoutedEventArgs e)
{
if (sender is not Button { Tag: string url } || string.IsNullOrWhiteSpace(url)) return;

try
{
using var process = Process.Start(
new ProcessStartInfo { FileName = url, UseShellExecute = true }
);
}
catch (Exception ex)
{
if (App.SharedBugReportService != null)
{
_ = App.SharedBugReportService.SendBugReportAsync($"Error opening URL: {url}", ex);
}
if (UrlLauncher.TryOpen(url, out var error)) return;

_ = MessageBox.ShowAsync(
this,
$"Unable to open link: {ex.Message}",
"Error",
MessageBoxButton.Ok,
MessageBoxImage.Error
);
}
_ = MessageBox.ShowAsync(
this,
$"Unable to open link: {error}",
"Error",
MessageBoxButton.Ok,
MessageBoxImage.Error
);
}

private static string GetApplicationVersion()
Expand Down
8 changes: 4 additions & 4 deletions CHDStudio/CHDStudio.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Avalonia" Version="12.1.6" />
<PackageReference Include="Avalonia.Desktop" Version="12.1.6" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="12.1.6" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="12.1.6" />
<PackageReference Include="Avalonia" Version="12.2.0" />
<PackageReference Include="Avalonia.Desktop" Version="12.2.0" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="12.2.0" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="12.2.0" />
<PackageReference Include="Avalonia.Controls.DataGrid" Version="12.1.2" />
<PackageReference Include="CHDSharp" Version="1.7.1" />
<PackageReference Include="Meziantou.Analyzer" Version="3.0.342">
Expand Down
Loading
Loading