mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-20 08:39:58 -04:00
Triforce v0.2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
425
builder/HookshotBuilder/App.xaml
Normal file
425
builder/HookshotBuilder/App.xaml
Normal file
@@ -0,0 +1,425 @@
|
||||
<Application x:Class="HookshotBuilder.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
<!-- Slate, frosted (the approved installer design: Desktop\loader\index.html, "Installer") -->
|
||||
<SolidColorBrush x:Key="Page" Color="#14161A"/>
|
||||
<SolidColorBrush x:Key="Raised" Color="#1C1F24"/>
|
||||
<SolidColorBrush x:Key="RaisedHover" Color="#23272D"/>
|
||||
<SolidColorBrush x:Key="Line" Color="#2C3037"/>
|
||||
<SolidColorBrush x:Key="LineStrong" Color="#3D434C"/>
|
||||
<SolidColorBrush x:Key="Ink" Color="#EDEFF2"/>
|
||||
<SolidColorBrush x:Key="InkSoft" Color="#A2A9B3"/>
|
||||
<SolidColorBrush x:Key="InkFaint" Color="#6E7681"/>
|
||||
<SolidColorBrush x:Key="Brand" Color="#3D63E6"/>
|
||||
<SolidColorBrush x:Key="BrandHover" Color="#4B70F0"/>
|
||||
<SolidColorBrush x:Key="BrandInk" Color="#DFE6FF"/>
|
||||
<SolidColorBrush x:Key="Go" Color="#5FB08A"/>
|
||||
<SolidColorBrush x:Key="GoHover" Color="#70C09A"/>
|
||||
<SolidColorBrush x:Key="GoInk" Color="#06150E"/>
|
||||
<SolidColorBrush x:Key="Warn" Color="#E2B86B"/>
|
||||
<SolidColorBrush x:Key="Bad" Color="#E2776B"/>
|
||||
<!-- (kept for the old names the code still uses) -->
|
||||
<SolidColorBrush x:Key="Accent" Color="#5FB08A"/>
|
||||
|
||||
<!-- glass: white at low alpha over the acrylic backdrop -->
|
||||
<SolidColorBrush x:Key="Glass" Color="#0DFFFFFF"/>
|
||||
<SolidColorBrush x:Key="GlassHover" Color="#17FFFFFF"/>
|
||||
<SolidColorBrush x:Key="GlassLine" Color="#17FFFFFF"/>
|
||||
<SolidColorBrush x:Key="GlassLineStrong" Color="#2AFFFFFF"/>
|
||||
<SolidColorBrush x:Key="GoSoft" Color="#265FB08A"/>
|
||||
<SolidColorBrush x:Key="BadSoft" Color="#26E2776B"/>
|
||||
<SolidColorBrush x:Key="WarnSoft" Color="#1FE2B86B"/>
|
||||
<SolidColorBrush x:Key="BrandSoft" Color="#333D63E6"/>
|
||||
|
||||
<FontFamily x:Key="Ui">pack://application:,,,/Fonts/#Inter</FontFamily>
|
||||
<FontFamily x:Key="Display">pack://application:,,,/Fonts/#Inter</FontFamily>
|
||||
<FontFamily x:Key="Mono">Cascadia Mono, Consolas</FontFamily>
|
||||
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Ui}"/>
|
||||
<Setter Property="FontSize" Value="14"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
|
||||
<Setter Property="TextOptions.TextFormattingMode" Value="Ideal"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Heading" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
|
||||
<Setter Property="FontSize" Value="24"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Sub" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
|
||||
<Setter Property="Foreground" Value="{StaticResource InkSoft}"/>
|
||||
<Setter Property="TextWrapping" Value="Wrap"/>
|
||||
<Setter Property="Margin" Value="0,6,0,0"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Note" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
|
||||
<Setter Property="Foreground" Value="{StaticResource InkSoft}"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="TextWrapping" Value="Wrap"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Faint" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
|
||||
<Setter Property="Foreground" Value="{StaticResource InkFaint}"/>
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
</Style>
|
||||
|
||||
<!-- section labels: FOUND ON THIS PC -->
|
||||
<Style x:Key="Label" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource InkSoft}"/>
|
||||
<Setter Property="Margin" Value="0,24,0,10"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Card" TargetType="Border">
|
||||
<Setter Property="Background" Value="{StaticResource Glass}"/>
|
||||
<Setter Property="BorderBrush" Value="{StaticResource GlassLine}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="CornerRadius" Value="10"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Chip" TargetType="Border">
|
||||
<Setter Property="Background" Value="#0DFFFFFF"/>
|
||||
<Setter Property="BorderBrush" Value="#14FFFFFF"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<!-- (a pill: the radius exactly half the height; WPF draws a larger one as a squashed ellipse) -->
|
||||
<Setter Property="Height" Value="26"/>
|
||||
<Setter Property="CornerRadius" Value="13"/>
|
||||
<Setter Property="Padding" Value="10,0"/>
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Quiet" TargetType="Button">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Ui}"/>
|
||||
<Setter Property="FontSize" Value="14"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
|
||||
<Setter Property="Background" Value="#08FFFFFF"/>
|
||||
<Setter Property="BorderBrush" Value="#1FFFFFFF"/>
|
||||
<Setter Property="Padding" Value="18,0"/>
|
||||
<Setter Property="Height" Value="40"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="Box" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="1" CornerRadius="8" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="{StaticResource GlassHover}"/>
|
||||
<Setter TargetName="Box" Property="BorderBrush" Value="{StaticResource GlassLineStrong}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsKeyboardFocused" Value="True">
|
||||
<Setter TargetName="Box" Property="BorderBrush" Value="{StaticResource BrandHover}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Foreground" Value="{StaticResource InkFaint}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- blue: the step's action -->
|
||||
<Style x:Key="Primary" TargetType="Button" BasedOn="{StaticResource Quiet}">
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
<Setter Property="Padding" Value="20,0"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="Box" Background="{StaticResource Brand}" BorderBrush="#33FFFFFF" BorderThickness="1" CornerRadius="8"
|
||||
Padding="{TemplateBinding Padding}">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect x:Name="Glow" Color="#3D63E6" BlurRadius="22" ShadowDepth="6" Direction="270" Opacity="0.55"/>
|
||||
</Border.Effect>
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="{StaticResource BrandHover}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsKeyboardFocused" Value="True">
|
||||
<Setter TargetName="Box" Property="BorderBrush" Value="#AAFFFFFF"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="Box" Property="Background" Value="#14FFFFFF"/>
|
||||
<Setter TargetName="Box" Property="Effect" Value="{x:Null}"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource InkFaint}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- green: Play only -->
|
||||
<Style x:Key="GoButton" TargetType="Button" BasedOn="{StaticResource Quiet}">
|
||||
<Setter Property="Foreground" Value="{StaticResource GoInk}"/>
|
||||
<Setter Property="FontSize" Value="16"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Height" Value="50"/>
|
||||
<Setter Property="Padding" Value="34,0"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="Box" Background="{StaticResource Go}" BorderBrush="#40FFFFFF" BorderThickness="1" CornerRadius="10"
|
||||
Padding="{TemplateBinding Padding}">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect Color="#5FB08A" BlurRadius="30" ShadowDepth="8" Direction="270" Opacity="0.5"/>
|
||||
</Border.Effect>
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="{StaticResource GoHover}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- a text link: Browse..., Show details -->
|
||||
<Style x:Key="LinkButton" TargetType="Button">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Ui}"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource BrandInk}"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="Transparent"><ContentPresenter/></Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Link" TargetType="ToggleButton">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Ui}"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource InkSoft}"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border Background="Transparent"><ContentPresenter/></Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Caption" TargetType="Button">
|
||||
<Setter Property="Width" Value="46"/>
|
||||
<Setter Property="Height" Value="36"/>
|
||||
<Setter Property="Foreground" Value="#80FFFFFF"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="Box" Background="Transparent" CornerRadius="8">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="{StaticResource GlassHover}"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- a found .nup: the whole row is the choice -->
|
||||
<Style x:Key="DumpRow" TargetType="RadioButton">
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="RadioButton">
|
||||
<Border x:Name="Box" Background="Transparent" Padding="16,13">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition/></Grid.ColumnDefinitions>
|
||||
<Grid Width="18" Height="18" VerticalAlignment="Center" Margin="0,0,14,0">
|
||||
<Ellipse x:Name="Ring" Stroke="{StaticResource InkFaint}" StrokeThickness="2"/>
|
||||
<Ellipse x:Name="Dot" Width="8" Height="8" Fill="{StaticResource Brand}" Visibility="Collapsed"/>
|
||||
</Grid>
|
||||
<ContentPresenter Grid.Column="1" VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="Ring" Property="Stroke" Value="{StaticResource Brand}"/>
|
||||
<Setter TargetName="Dot" Property="Visibility" Value="Visible"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="#08FFFFFF"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Tick" TargetType="CheckBox">
|
||||
<Setter Property="Foreground" Value="{StaticResource InkSoft}"/>
|
||||
<Setter Property="FontFamily" Value="{StaticResource Ui}"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="CheckBox">
|
||||
<StackPanel Orientation="Horizontal" Background="Transparent">
|
||||
<Border x:Name="Box" Width="18" Height="18" CornerRadius="5" BorderThickness="1.5" BorderBrush="#40FFFFFF" Margin="0,0,8,0">
|
||||
<Path x:Name="Mark" Data="M3,9 L7,13 L15,4" Stroke="White" StrokeThickness="2" Visibility="Collapsed" Margin="-1,-1,0,0"/>
|
||||
</Border>
|
||||
<ContentPresenter VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="{StaticResource Brand}"/>
|
||||
<Setter TargetName="Box" Property="BorderBrush" Value="{StaticResource Brand}"/>
|
||||
<Setter TargetName="Mark" Property="Visibility" Value="Visible"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ChoiceItem" TargetType="ComboBoxItem">
|
||||
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
|
||||
<Setter Property="FontFamily" Value="{StaticResource Ui}"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBoxItem">
|
||||
<Border x:Name="Box" Background="Transparent" CornerRadius="6" Padding="10,7">
|
||||
<ContentPresenter/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsHighlighted" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="{StaticResource RaisedHover}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter Property="Foreground" Value="{StaticResource BrandInk}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Choice" TargetType="ComboBox">
|
||||
<Setter Property="Height" Value="40"/>
|
||||
<Setter Property="FontFamily" Value="{StaticResource Ui}"/>
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource Ink}"/>
|
||||
<Setter Property="ItemContainerStyle" Value="{StaticResource ChoiceItem}"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBox">
|
||||
<Grid>
|
||||
<ToggleButton Focusable="False" ClickMode="Press"
|
||||
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
|
||||
<ToggleButton.Template>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border x:Name="Box" Background="#08FFFFFF" BorderBrush="#1FFFFFFF" BorderThickness="1" CornerRadius="8">
|
||||
<Path Data="M0,0 L4,4 L8,0" Stroke="{StaticResource InkSoft}" StrokeThickness="1.3" HorizontalAlignment="Right"
|
||||
VerticalAlignment="Center" Margin="0,0,12,0"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Box" Property="Background" Value="{StaticResource GlassHover}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</ToggleButton.Template>
|
||||
</ToggleButton>
|
||||
<ContentPresenter IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}" VerticalAlignment="Center" Margin="12,0,28,0"/>
|
||||
<Popup IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" AllowsTransparency="True" Focusable="False" PopupAnimation="None">
|
||||
<Border Background="{StaticResource Raised}" BorderBrush="{StaticResource LineStrong}" BorderThickness="1" CornerRadius="8" Padding="4"
|
||||
Margin="0,4,0,0" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="300">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<ItemsPresenter/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Popup>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Path" TargetType="TextBox">
|
||||
<Setter Property="FontFamily" Value="{StaticResource Mono}"/>
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource InkSoft}"/>
|
||||
<Setter Property="CaretBrush" Value="{StaticResource Ink}"/>
|
||||
<Setter Property="SelectionBrush" Value="{StaticResource Brand}"/>
|
||||
<Setter Property="Height" Value="40"/>
|
||||
<Setter Property="VerticalContentAlignment" Value="Center"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="TextBox">
|
||||
<Border x:Name="Box" Background="{StaticResource Glass}" BorderBrush="{StaticResource GlassLine}" BorderThickness="1"
|
||||
CornerRadius="8" Padding="12,0">
|
||||
<ScrollViewer x:Name="PART_ContentHost" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsKeyboardFocused" Value="True">
|
||||
<Setter TargetName="Box" Property="BorderBrush" Value="{StaticResource Brand}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- a bar: the free space (green), the update (blue) -->
|
||||
<Style x:Key="Bar" TargetType="ProgressBar">
|
||||
<Setter Property="Height" Value="6"/>
|
||||
<Setter Property="Minimum" Value="0"/>
|
||||
<Setter Property="Maximum" Value="1"/>
|
||||
<Setter Property="Foreground" Value="{StaticResource Brand}"/>
|
||||
<Setter Property="Background" Value="#12FFFFFF"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ProgressBar">
|
||||
<Grid>
|
||||
<Border x:Name="PART_Track" Background="{TemplateBinding Background}" CornerRadius="3"/>
|
||||
<Border x:Name="PART_Indicator" Background="{TemplateBinding Foreground}" CornerRadius="3" HorizontalAlignment="Left"/>
|
||||
</Grid>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
49
builder/HookshotBuilder/App.xaml.cs
Normal file
49
builder/HookshotBuilder/App.xaml.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Windows;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
// (RecompLauncher) --cli <make_game.py's options>: no window; its lines on stdout, and its result as the exit code.
|
||||
// Why it stopped is one "error <text>" line on stdout (the stream a launcher reads) and again on stderr
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
if (e.Args.Length > 0 && e.Args[0] == "--cli")
|
||||
{
|
||||
Environment.Exit(Cli(e.Args.Skip(1).ToList()));
|
||||
return;
|
||||
}
|
||||
base.OnStartup(e);
|
||||
}
|
||||
|
||||
static int Cli(List<string> args)
|
||||
{
|
||||
using var stdout = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false)) { AutoFlush = true };
|
||||
var tools = Tools.Find();
|
||||
if (tools == null)
|
||||
{
|
||||
const string missing = "error The build tools were not found next to this program.";
|
||||
stdout.WriteLine(missing);
|
||||
Console.Error.WriteLine(missing);
|
||||
return 1;
|
||||
}
|
||||
var done = new ManualResetEventSlim();
|
||||
string? failure = null, said = null; // (said: make_game's own "error" line in --prepare mode, already passed on to stdout)
|
||||
var runner = new Runner(tools, args);
|
||||
runner.Line += line =>
|
||||
{
|
||||
if (line.StartsWith("error ")) said = line[6..];
|
||||
lock (stdout) stdout.WriteLine(line);
|
||||
};
|
||||
runner.Finished += result => { failure = result; done.Set(); };
|
||||
runner.Start();
|
||||
done.Wait();
|
||||
if (failure == null) return 0;
|
||||
var reason = failure == "cancelled" ? failure : said ?? failure;
|
||||
if (said == null) lock (stdout) stdout.WriteLine("error " + reason);
|
||||
Console.Error.WriteLine("error " + reason);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
29
builder/HookshotBuilder/BuildWorkers.cs
Normal file
29
builder/HookshotBuilder/BuildWorkers.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// A choice for this window only. Automatic leaves the build tools' inherited override and memory policy alone.
|
||||
static class BuildWorkers
|
||||
{
|
||||
public const string Automatic = "Automatic";
|
||||
|
||||
public static IEnumerable<object> Choices(int processors)
|
||||
{
|
||||
yield return Automatic;
|
||||
for (var count = 1; count <= Math.Max(1, processors); count++) yield return count;
|
||||
}
|
||||
|
||||
public static int? Selected(object? value) => value switch
|
||||
{
|
||||
string text when text == Automatic => null,
|
||||
int count when count > 0 => count,
|
||||
_ => throw new ArgumentException("Choose Automatic or a positive number of build workers."),
|
||||
};
|
||||
|
||||
public static void Apply(ProcessStartInfo info, int? count)
|
||||
{
|
||||
if (count is <= 0) throw new ArgumentOutOfRangeException(nameof(count), "Build workers must be positive.");
|
||||
if (count is int selected) info.Environment["HOOKSHOT_JOBS"] = selected.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
23
builder/HookshotBuilder/BuilderSettings.cs
Normal file
23
builder/HookshotBuilder/BuilderSettings.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// What the player chose last time (the install folder, the game files, the shaders' tick): builder-settings.json beside the versions
|
||||
sealed class BuilderSettings
|
||||
{
|
||||
public string? Out { get; set; }
|
||||
public string? Nup { get; set; }
|
||||
public string? Romfs { get; set; }
|
||||
public string? Exefs { get; set; }
|
||||
public bool Dlss { get; set; } // (NVIDIA DLSS ticked: NVIDIA's license was accepted)
|
||||
public bool Fsr { get; set; } // (AMD FSR 4 ticked)
|
||||
public bool PrepareLater { get; set; } // ("Prepare shaders now" unticked)
|
||||
|
||||
public static BuilderSettings? Load(string path)
|
||||
{
|
||||
try { return System.Text.Json.JsonSerializer.Deserialize<BuilderSettings>(System.IO.File.ReadAllText(path)); }
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// (the updates, from the launcher's Update and from the --update start after a self-update, begin before ApplySettings sets
|
||||
/// the tick from these settings: they read the saved choice itself. None saved: prepared, as the tick's default)
|
||||
public static bool PrepareNow(string path) => Load(path)?.PrepareLater != true;
|
||||
}
|
||||
55
builder/HookshotBuilder/Disk.cs
Normal file
55
builder/HookshotBuilder/Disk.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// Whether a folder is on a hard drive (a spinning disk) or an SSD: a build reads and writes tens of gigabytes, and an SSD makes
|
||||
/// that much faster. The answer is a warning only (the player may have no other drive), never a stop.
|
||||
static class Disk
|
||||
{
|
||||
/// True on a hard drive, false on an SSD, null when the drive cannot be told (a network share, an unknown volume)
|
||||
public static bool? Spinning(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
var root = Path.GetPathRoot(Path.GetFullPath(path));
|
||||
if (string.IsNullOrEmpty(root)) return null;
|
||||
using var volume = CreateFile(@"\\.\" + root.TrimEnd('\\'), 0, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open,
|
||||
FileOptions.None, IntPtr.Zero);
|
||||
if (volume.IsInvalid) return null;
|
||||
var query = new StoragePropertyQuery { PropertyId = SeekPenalty, QueryType = 0 };
|
||||
var answer = new DeviceSeekPenaltyDescriptor();
|
||||
// (a spinning disk says it incurs a seek penalty; an SSD says it does not)
|
||||
if (!DeviceIoControl(volume, QueryProperty, ref query, Marshal.SizeOf<StoragePropertyQuery>(), ref answer,
|
||||
Marshal.SizeOf<DeviceSeekPenaltyDescriptor>(), out _, IntPtr.Zero))
|
||||
return null;
|
||||
return answer.IncursSeekPenalty;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException) { return null; }
|
||||
}
|
||||
|
||||
const uint QueryProperty = 0x002D1400; // (IOCTL_STORAGE_QUERY_PROPERTY)
|
||||
const uint SeekPenalty = 7; // (StorageDeviceSeekPenaltyProperty)
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct StoragePropertyQuery // (STORAGE_PROPERTY_QUERY: AdditionalParameters[1], padded to a DWORD)
|
||||
{
|
||||
public uint PropertyId, QueryType, Additional;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DeviceSeekPenaltyDescriptor
|
||||
{
|
||||
public uint Version, Size;
|
||||
[MarshalAs(UnmanagedType.U1)] public bool IncursSeekPenalty;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
static extern SafeFileHandle CreateFile(string name, uint access, FileShare share, IntPtr security, FileMode mode,
|
||||
FileOptions flags, IntPtr template);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
static extern bool DeviceIoControl(SafeFileHandle device, uint code, ref StoragePropertyQuery input, int inputSize,
|
||||
ref DeviceSeekPenaltyDescriptor output, int outputSize, out uint returned, IntPtr overlapped);
|
||||
}
|
||||
145
builder/HookshotBuilder/Finder.cs
Normal file
145
builder/HookshotBuilder/Finder.cs
Normal file
@@ -0,0 +1,145 @@
|
||||
using System.IO;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// A .nup found on this PC
|
||||
sealed record Dump(string Path, string Where, long Size, DateTime Modified);
|
||||
|
||||
/// The player's game files where people keep them, and the game's shortcuts.
|
||||
static class Finder
|
||||
{
|
||||
/// .nup files in Downloads, Desktop, Documents, the home folder and the top of each drive, one folder level down too,
|
||||
/// newest first. (Only names and sizes are read here: the version is checked one file at a time afterwards.)
|
||||
public static List<Dump> FindDumps()
|
||||
{
|
||||
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
var places = new List<(string Dir, string Name)>
|
||||
{
|
||||
(Path.Combine(home, "Downloads"), "Downloads"),
|
||||
(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Desktop"),
|
||||
(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Documents"),
|
||||
(home, "Home"),
|
||||
};
|
||||
foreach (var d in DriveInfo.GetDrives())
|
||||
{
|
||||
try
|
||||
{
|
||||
if (d.IsReady && d.DriveType is DriveType.Fixed or DriveType.Removable) places.Add((d.RootDirectory.FullName, d.Name.TrimEnd('\\')));
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var found = new List<Dump>();
|
||||
foreach (var (dir, name) in places)
|
||||
{
|
||||
if (!Directory.Exists(dir) || !seen.Add(Path.GetFullPath(dir))) continue;
|
||||
var dirs = new List<string> { dir };
|
||||
try
|
||||
{
|
||||
dirs.AddRange(Directory.EnumerateDirectories(dir)
|
||||
.Where(s => !Path.GetFileName(s).StartsWith('.') && !Path.GetFileName(s).StartsWith('$')
|
||||
&& !string.Equals(Path.GetFileName(s), "Windows", StringComparison.OrdinalIgnoreCase)
|
||||
&& !Path.GetFileName(s).StartsWith("Program", StringComparison.OrdinalIgnoreCase))
|
||||
.Take(200));
|
||||
}
|
||||
catch (Exception) { }
|
||||
foreach (var sub in dirs)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var f in Directory.EnumerateFiles(sub, "*.nup"))
|
||||
{
|
||||
var info = new FileInfo(f);
|
||||
if (seen.Add(info.FullName)) found.Add(new Dump(info.FullName, name, info.Length, info.LastWriteTime));
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
return found.OrderByDescending(d => d.Modified).ToList();
|
||||
}
|
||||
|
||||
public static string Ago(DateTime t)
|
||||
{
|
||||
var d = DateTime.Now - t;
|
||||
if (d.TotalDays < 1 && t.Date == DateTime.Today) return "modified today";
|
||||
if (d.TotalDays < 2) return "modified yesterday";
|
||||
if (d.TotalDays < 14) return $"{(int)d.TotalDays} days ago";
|
||||
if (d.TotalDays < 60) return $"{(int)(d.TotalDays / 7)} weeks ago";
|
||||
return t.ToString("d MMM yyyy");
|
||||
}
|
||||
|
||||
public static string Size(long bytes) => bytes >= 1L << 30 ? $"{bytes / (double)(1L << 30):0.0} GB" : $"{bytes >> 20} MB";
|
||||
|
||||
// ---- shortcuts to the built game ----
|
||||
|
||||
public static string DesktopLink => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Hookshot.lnk");
|
||||
public static string StartLink => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "Hookshot.lnk");
|
||||
|
||||
/// Made or removed as the two ticks say (Windows' own shell object writes the .lnk)
|
||||
/// The shortcuts the player has, made again (onto the folder's launcher now that it has one); none made where there was none
|
||||
public static void RefreshShortcuts(string gameFolder) => Shortcuts(gameFolder, File.Exists(DesktopLink), File.Exists(StartLink));
|
||||
|
||||
public static void Shortcuts(string gameFolder, bool desktop, bool start)
|
||||
{
|
||||
// (hookshot.exe: the game's launcher in a folder built since it came (Play, and Update when a newer release is out), else the
|
||||
// game. The icon is the game's own: bin\hookshot.exe when it is there)
|
||||
var exe = Path.Combine(gameFolder, "hookshot.exe");
|
||||
var icon = File.Exists(Path.Combine(gameFolder, "bin", "hookshot.exe")) ? Path.Combine(gameFolder, "bin", "hookshot.exe") : exe;
|
||||
foreach (var (link, want) in new[] { (DesktopLink, desktop), (StartLink, start) })
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!want)
|
||||
{
|
||||
if (File.Exists(link)) File.Delete(link);
|
||||
continue;
|
||||
}
|
||||
if (!File.Exists(exe)) continue;
|
||||
// (the shell's own shortcut object (IShellLinkW + IPersistFile): the scripting host's, late-bound through dynamic,
|
||||
// made none for players and said nothing)
|
||||
var sl = (IShellLinkW)new ShellLink();
|
||||
sl.SetPath(exe);
|
||||
sl.SetWorkingDirectory(gameFolder);
|
||||
sl.SetIconLocation(icon, 0);
|
||||
sl.SetDescription("The Legend of Zelda: Ocarina of Time, built by Hookshot");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(link)!);
|
||||
((System.Runtime.InteropServices.ComTypes.IPersistFile)sl).Save(link, true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ShortcutError = $"{Path.GetFileName(link)}: {e.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The last shortcut that could not be made, for the log
|
||||
public static string? ShortcutError;
|
||||
|
||||
[System.Runtime.InteropServices.ComImport, System.Runtime.InteropServices.Guid("00021401-0000-0000-C000-000000000046")]
|
||||
class ShellLink { }
|
||||
|
||||
[System.Runtime.InteropServices.ComImport, System.Runtime.InteropServices.Guid("000214F9-0000-0000-C000-000000000046"),
|
||||
System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
|
||||
interface IShellLinkW
|
||||
{
|
||||
void GetPath([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder file, int max, IntPtr fd, uint flags);
|
||||
void GetIDList(out IntPtr ppidl);
|
||||
void SetIDList(IntPtr pidl);
|
||||
void GetDescription([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder name, int max);
|
||||
void SetDescription([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string name);
|
||||
void GetWorkingDirectory([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder dir, int max);
|
||||
void SetWorkingDirectory([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string dir);
|
||||
void GetArguments([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder args, int max);
|
||||
void SetArguments([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string args);
|
||||
void GetHotkey(out short hotkey);
|
||||
void SetHotkey(short hotkey);
|
||||
void GetShowCmd(out int show);
|
||||
void SetShowCmd(int show);
|
||||
void GetIconLocation([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder path, int max, out int index);
|
||||
void SetIconLocation([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string path, int index);
|
||||
void SetRelativePath([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string path, uint reserved);
|
||||
void Resolve(IntPtr hwnd, uint flags);
|
||||
void SetPath([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string file);
|
||||
}
|
||||
}
|
||||
BIN
builder/HookshotBuilder/Fonts/Inter-Bold.ttf
Normal file
BIN
builder/HookshotBuilder/Fonts/Inter-Bold.ttf
Normal file
Binary file not shown.
92
builder/HookshotBuilder/Fonts/Inter-LICENSE.txt
Normal file
92
builder/HookshotBuilder/Fonts/Inter-LICENSE.txt
Normal file
@@ -0,0 +1,92 @@
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
builder/HookshotBuilder/Fonts/Inter-Medium.ttf
Normal file
BIN
builder/HookshotBuilder/Fonts/Inter-Medium.ttf
Normal file
Binary file not shown.
BIN
builder/HookshotBuilder/Fonts/Inter-Regular.ttf
Normal file
BIN
builder/HookshotBuilder/Fonts/Inter-Regular.ttf
Normal file
Binary file not shown.
BIN
builder/HookshotBuilder/Fonts/Inter-SemiBold.ttf
Normal file
BIN
builder/HookshotBuilder/Fonts/Inter-SemiBold.ttf
Normal file
Binary file not shown.
63
builder/HookshotBuilder/Glass.cs
Normal file
63
builder/HookshotBuilder/Glass.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// Windows 11's acrylic behind the window, dark title colours and round corners (DWM). Windows 10 has none of it, and
|
||||
/// neither does a light Windows: both get the plain Slate window, which the light palette is made for.
|
||||
static class Glass
|
||||
{
|
||||
[DllImport("dwmapi.dll")] static extern int DwmSetWindowAttribute(IntPtr hwnd, int attribute, ref int value, int size);
|
||||
[DllImport("dwmapi.dll")] static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins margins);
|
||||
[DllImport("user32.dll")] static extern IntPtr GetWindowLongPtrW(IntPtr hwnd, int index);
|
||||
[DllImport("user32.dll")] static extern IntPtr SetWindowLongPtrW(IntPtr hwnd, int index, IntPtr value);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct Margins { public int Left, Right, Top, Bottom; }
|
||||
|
||||
const int DarkMode = 20, CornerPreference = 33, SystemBackdrop = 38;
|
||||
const int Round = 2, Acrylic = 3;
|
||||
|
||||
/// Windows draws the acrylic in the system's Windows mode. Its light variant is brighter than anything the installer's
|
||||
/// tint can darken enough: the fixed Slate palette has light text and InkFaint (the inactive steps, the "Supported
|
||||
/// version" badge, the details) needs the dark page behind it. A light system gets that page, as Windows 10 does.
|
||||
static bool LightBackdrop()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");
|
||||
var value = key?.GetValue("SystemUsesLightTheme") ?? key?.GetValue("AppsUseLightTheme");
|
||||
return value is int on && on != 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// true: acrylic is on (the window's background must stay see-through)
|
||||
public static bool Apply(Window w)
|
||||
{
|
||||
var hwnd = new WindowInteropHelper(w).Handle;
|
||||
if (hwnd == IntPtr.Zero) return false;
|
||||
// (a framed window: Windows draws the backdrop only behind one. Without the system menu it draws no caption buttons of its
|
||||
// own behind the window's; WindowStyle None lost the acrylic, and the window was flat grey)
|
||||
const int GwlStyle = -16;
|
||||
const long SysMenu = 0x00080000;
|
||||
SetWindowLongPtrW(hwnd, GwlStyle, (IntPtr)((long)GetWindowLongPtrW(hwnd, GwlStyle) & ~SysMenu));
|
||||
var on = 1;
|
||||
DwmSetWindowAttribute(hwnd, DarkMode, ref on, sizeof(int));
|
||||
var corner = Round;
|
||||
DwmSetWindowAttribute(hwnd, CornerPreference, ref corner, sizeof(int));
|
||||
if (LightBackdrop()) return false; // (the plain Slate page: light acrylic cannot carry the palette)
|
||||
if (Environment.OSVersion.Version.Build < 22621 || SystemParameters.HighContrast) return false; // (22H2: the backdrop attribute)
|
||||
if (HwndSource.FromHwnd(hwnd) is { CompositionTarget: { } target }) target.BackgroundColor = Colors.Transparent;
|
||||
var all = new Margins { Left = -1, Right = -1, Top = -1, Bottom = -1 };
|
||||
DwmExtendFrameIntoClientArea(hwnd, ref all);
|
||||
var backdrop = Acrylic;
|
||||
return DwmSetWindowAttribute(hwnd, SystemBackdrop, ref backdrop, sizeof(int)) == 0;
|
||||
}
|
||||
}
|
||||
34
builder/HookshotBuilder/HookshotBuilder.csproj
Normal file
34
builder/HookshotBuilder/HookshotBuilder.csproj
Normal file
@@ -0,0 +1,34 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>HookshotBuilder</AssemblyName>
|
||||
<RootNamespace>HookshotBuilder</RootNamespace>
|
||||
<Version>0.1.0</Version>
|
||||
<Product>Hookshot Builder</Product>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<ApplicationIcon Condition="Exists('..\..\work\hookshot.ico')">..\..\work\hookshot.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Needs nothing installed: dotnet publish -c Release. A folder (the app and .NET's own signed files), not one compressed exe:
|
||||
antivirus programs took the self-extracting single file for a trojan and removed it -->
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
<DebugType>none</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Inter (SIL Open Font License, Fonts/Inter-LICENSE.txt) and the hookshot, inside the app -->
|
||||
<ItemGroup>
|
||||
<Resource Include="Fonts\*.ttf" />
|
||||
<Resource Include="Images\hookshot.png" />
|
||||
<None Include="Fonts\Inter-LICENSE.txt" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
BIN
builder/HookshotBuilder/Images/hookshot.png
Normal file
BIN
builder/HookshotBuilder/Images/hookshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 54 KiB |
360
builder/HookshotBuilder/MainWindow.xaml
Normal file
360
builder/HookshotBuilder/MainWindow.xaml
Normal file
@@ -0,0 +1,360 @@
|
||||
<Window x:Class="HookshotBuilder.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="Hookshot" Width="960" Height="600" ResizeMode="CanMinimize"
|
||||
WindowStartupLocation="CenterScreen" Background="Transparent" AllowDrop="True"
|
||||
UseLayoutRounding="True" SnapsToDevicePixels="True" FontFamily="{StaticResource Ui}">
|
||||
|
||||
<!-- One window, always 960x600: Windows 11's acrylic behind it (Glass.cs), Slate on Windows 10 -->
|
||||
<WindowChrome.WindowChrome>
|
||||
<WindowChrome CaptionHeight="64" ResizeBorderThickness="0" GlassFrameThickness="-1" CornerRadius="18" UseAeroCaptionButtons="False"/>
|
||||
</WindowChrome.WindowChrome>
|
||||
|
||||
<Grid x:Name="Root">
|
||||
<Grid.Background>
|
||||
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
|
||||
<GradientStop Color="#401A1D24" Offset="0"/>
|
||||
<GradientStop Color="#3312141A" Offset="1"/>
|
||||
</LinearGradientBrush>
|
||||
</Grid.Background>
|
||||
|
||||
<!-- ===================== the start: the hookshot in the middle ===================== -->
|
||||
<Grid x:Name="Splash" RenderTransformOrigin="0.5,0.5" Panel.ZIndex="4">
|
||||
<Grid.RenderTransform><ScaleTransform x:Name="SplashScale"/></Grid.RenderTransform>
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
<Grid Width="260" Height="260">
|
||||
<Ellipse Margin="24" RenderTransformOrigin="0.5,0.5" x:Name="Halo">
|
||||
<Ellipse.Fill>
|
||||
<RadialGradientBrush>
|
||||
<GradientStop Color="#663D63E6" Offset="0"/>
|
||||
<GradientStop Color="#003D63E6" Offset="0.68"/>
|
||||
</RadialGradientBrush>
|
||||
</Ellipse.Fill>
|
||||
<Ellipse.RenderTransform><ScaleTransform x:Name="HaloScale"/></Ellipse.RenderTransform>
|
||||
</Ellipse>
|
||||
<Image Source="pack://application:,,,/Images/hookshot.png" Width="178" RenderTransformOrigin="0.5,0.5" RenderOptions.BitmapScalingMode="HighQuality">
|
||||
<Image.RenderTransform>
|
||||
<TransformGroup>
|
||||
<RotateTransform x:Name="BobTurn"/>
|
||||
<TranslateTransform x:Name="BobLift"/>
|
||||
</TransformGroup>
|
||||
</Image.RenderTransform>
|
||||
<Image.Effect><DropShadowEffect BlurRadius="24" ShadowDepth="14" Direction="270" Opacity="0.6" Color="Black"/></Image.Effect>
|
||||
</Image>
|
||||
</Grid>
|
||||
<TextBlock Text="Hookshot" FontSize="22" FontWeight="SemiBold" HorizontalAlignment="Center" Margin="0,16,0,0"/>
|
||||
<TextBlock x:Name="SplashText" Text="Starting…" FontSize="13" Foreground="#A6FFFFFF" HorizontalAlignment="Center" Margin="0,6,0,0" MinHeight="20"/>
|
||||
<Border Width="200" Height="3" CornerRadius="1.5" Background="#14FFFFFF" Margin="0,16,0,0" ClipToBounds="True">
|
||||
<Border Width="80" HorizontalAlignment="Left" CornerRadius="1.5">
|
||||
<Border.Background>
|
||||
<LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
|
||||
<GradientStop Color="#007F9BFF" Offset="0"/>
|
||||
<GradientStop Color="#FF7F9BFF" Offset="0.5"/>
|
||||
<GradientStop Color="#007F9BFF" Offset="1"/>
|
||||
</LinearGradientBrush>
|
||||
</Border.Background>
|
||||
<Border.RenderTransform><TranslateTransform x:Name="Sweep"/></Border.RenderTransform>
|
||||
</Border>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- ===================== the installer ===================== -->
|
||||
<Grid x:Name="Main" Opacity="0" IsHitTestVisible="False">
|
||||
<Grid.RenderTransform><TranslateTransform x:Name="MainLift" Y="10"/></Grid.RenderTransform>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="64"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- the head: the hookshot, and the steps (or the update's versions) -->
|
||||
<StackPanel Orientation="Horizontal" Margin="28,0,0,0" VerticalAlignment="Center">
|
||||
<Image Source="pack://application:,,,/Images/hookshot.png" Width="28" RenderOptions.BitmapScalingMode="HighQuality">
|
||||
<Image.Effect><DropShadowEffect BlurRadius="6" ShadowDepth="2" Direction="270" Opacity="0.5" Color="Black"/></Image.Effect>
|
||||
</Image>
|
||||
<TextBlock Text="Hookshot" FontSize="15" FontWeight="Bold" Margin="10,0,0,0" VerticalAlignment="Center"/>
|
||||
<Border x:Name="VersionChip" Margin="12,0,0,0" VerticalAlignment="Center" Visibility="Collapsed">
|
||||
<TextBlock x:Name="VersionChipText" FontSize="12" Foreground="{StaticResource InkSoft}" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<Border x:Name="StepPill" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,12,0,0" Padding="4" Height="40" CornerRadius="20"
|
||||
Background="#0BFFFFFF" BorderBrush="#17FFFFFF" BorderThickness="1">
|
||||
<StackPanel x:Name="StepItems" Orientation="Horizontal"/>
|
||||
</Border>
|
||||
|
||||
<Grid Grid.Row="1" Margin="64,16,64,34">
|
||||
|
||||
<!-- ===== 1: game files ===== -->
|
||||
<Grid x:Name="FilesPage">
|
||||
<!-- (the content scrolls and the Build button row stays: on a small or scaled screen the rows above pushed the
|
||||
buttons out of the fixed-size window, 2026-11-08) -->
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Margin="0,0,0,12">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<StackPanel>
|
||||
<TextBlock x:Name="FilesTitle" Style="{StaticResource Heading}" Text="Build your game"/>
|
||||
<TextBlock x:Name="FilesSub" Style="{StaticResource Sub}" Text="Pick your game files and where the game goes. Hookshot does the rest, once."/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="1">
|
||||
<TextBlock x:Name="FoundLabel" Style="{StaticResource Label}" Text="FOUND ON THIS PC"/>
|
||||
<Border Style="{StaticResource Card}">
|
||||
<ScrollViewer MaxHeight="128" VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel x:Name="DumpList"/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<WrapPanel Grid.Row="2" Margin="0,10,0,0" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="NotListed" Style="{StaticResource Note}" Text="Not listed?" Margin="0,0,8,0"/>
|
||||
<Button x:Name="BrowseButton" Style="{StaticResource LinkButton}" Content="Browse…" Click="BrowseNup"/>
|
||||
<TextBlock x:Name="DropNote" Style="{StaticResource Faint}" FontSize="13" Text=" · or drop the file on this window · " VerticalAlignment="Center"/>
|
||||
<Button x:Name="OtherWays" Style="{StaticResource LinkButton}" Foreground="{StaticResource InkSoft}" Content="romfs and exefs folders" Click="BrowseFolders"/>
|
||||
</WrapPanel>
|
||||
|
||||
<Grid Grid.Row="3">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="20"/><ColumnDefinition Width="200"/></Grid.ColumnDefinitions>
|
||||
<StackPanel>
|
||||
<TextBlock x:Name="InstallLabel" Style="{StaticResource Label}" Text="INSTALL THE GAME TO"/>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<TextBox x:Name="OutPath" Style="{StaticResource Path}" TextChanged="PathsChanged"/>
|
||||
<Button x:Name="ChangeButton" Grid.Column="1" Style="{StaticResource Quiet}" Margin="10,0,0,0" Content="Change" Click="BrowseOut"/>
|
||||
</Grid>
|
||||
<!-- the build files: how much, where (Storage.cs), and choosing the place -->
|
||||
<Grid Margin="0,8,0,0">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<TextBlock x:Name="WorkNote" Style="{StaticResource Note}" FontSize="12" TextWrapping="Wrap" VerticalAlignment="Center"/>
|
||||
<Button x:Name="WorkChange" Grid.Column="1" Style="{StaticResource LinkButton}" FontSize="12" Margin="12,0,0,0" VerticalAlignment="Center"
|
||||
Content="Change" Click="BrowseWork"/>
|
||||
<Button x:Name="WorkReset" Grid.Column="2" Style="{StaticResource LinkButton}" FontSize="12" Margin="12,0,0,0" VerticalAlignment="Center"
|
||||
Content="Default" Click="ResetWork"/>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="2">
|
||||
<TextBlock x:Name="LanguageLabel" Style="{StaticResource Label}" Text="GAME LANGUAGE"/>
|
||||
<ComboBox x:Name="LanguageBox" Style="{StaticResource Choice}" AutomationProperties.Name="Language" SelectionChanged="LanguageChanged"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<Grid Grid.Row="4" Margin="0,12,0,0">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="20"/><ColumnDefinition Width="160"/></Grid.ColumnDefinitions>
|
||||
<Grid VerticalAlignment="Center">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition Width="16"/><ColumnDefinition/></Grid.ColumnDefinitions>
|
||||
<Border Width="16" Height="16" CornerRadius="8" Background="{StaticResource BrandSoft}" VerticalAlignment="Center">
|
||||
<TextBlock Text="i" FontSize="10" FontWeight="Bold" Foreground="#B9C8FF" HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
<TextBlock x:Name="ToolsNote" Grid.Column="1" Style="{StaticResource Note}" FontSize="12" Margin="8,0,0,0" VerticalAlignment="Center" TextWrapping="Wrap"/>
|
||||
</Grid>
|
||||
<StackPanel Grid.Column="2">
|
||||
<TextBlock x:Name="WorkerLabel" Style="{StaticResource Label}" Text="BUILD WORKERS"/>
|
||||
<ComboBox x:Name="WorkerBox" Style="{StaticResource Choice}" IsEditable="False"
|
||||
AutomationProperties.Name="Build workers" AutomationProperties.LabeledBy="{Binding ElementName=WorkerLabel}"
|
||||
ToolTip="Automatic uses available memory and any existing worker override. More workers need more memory and may not be faster.">
|
||||
<ComboBox.FocusVisualStyle>
|
||||
<Style TargetType="Control">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value><ControlTemplate><Border BorderBrush="{StaticResource Brand}" BorderThickness="2" CornerRadius="10" Margin="-2"/></ControlTemplate></Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ComboBox.FocusVisualStyle>
|
||||
</ComboBox>
|
||||
<!-- (make_game.py's last step, the game's prepare-shaders run: unticked, the game prepares them at its first start) -->
|
||||
<CheckBox x:Name="PrepareTick" Style="{StaticResource Tick}" Content="Prepare shaders now" IsChecked="True" Margin="0,12,0,0"
|
||||
ToolTip="Prepares the game's shaders at the end of the build, a few minutes (longer on some GPUs). Unticked, the game prepares them at its first start, behind a black window."/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- NVIDIA DLSS: off unless ticked. Ticking it shows NVIDIA's license; the build downloads NVIDIA's SDK under it
|
||||
(make_game.py, scripts/ngx_sdk.py). Nothing of NVIDIA's comes with the builder -->
|
||||
<StackPanel Grid.Row="5" Margin="0,14,0,0">
|
||||
<CheckBox x:Name="DlssTick" Style="{StaticResource Tick}" IsChecked="False" Click="DlssChanged"
|
||||
Content="NVIDIA DLSS (downloads NVIDIA's SDK under NVIDIA's license)"/>
|
||||
<TextBlock Style="{StaticResource Note}" FontSize="12" Margin="26,4,0,0" TextWrapping="Wrap"
|
||||
Text="For NVIDIA RTX graphics cards. NVIDIA's files stay on this PC: never share a game folder built with them."/>
|
||||
<!-- AMD FSR 4: off unless ticked. Nothing is downloaded: AMD's DLLs are put beside the game by hand (the readme) -->
|
||||
<CheckBox x:Name="FsrTick" Style="{StaticResource Tick}" IsChecked="False" Margin="0,10,0,0"
|
||||
Content="AMD FSR 4 (AMD's files are not included: see the readme)"/>
|
||||
<TextBlock Style="{StaticResource Note}" FontSize="12" Margin="26,4,0,0" TextWrapping="Wrap"
|
||||
Text="For AMD Radeon graphics cards. It is chosen in the game's Insert menu, as the Upscaler."/>
|
||||
</StackPanel>
|
||||
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
|
||||
<Grid Grid.Row="1">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<ProgressBar x:Name="SpaceBar" Style="{StaticResource Bar}" Foreground="{StaticResource Go}" Width="160" VerticalAlignment="Center"/>
|
||||
<TextBlock x:Name="SpaceText" Grid.Column="1" Style="{StaticResource Note}" FontSize="12" Margin="10,0,0,0" VerticalAlignment="Center"/>
|
||||
<TextBlock x:Name="AboutText" Grid.Column="2" Style="{StaticResource Faint}" Text="About 45 min" Margin="0,0,14,0" VerticalAlignment="Center"/>
|
||||
<Button x:Name="BuildButton" Grid.Column="3" Style="{StaticResource Primary}" Content="Build the game" IsEnabled="False" Click="StartBuild"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- ===== 2: building (and the update) ===== -->
|
||||
<Grid x:Name="BuildPage" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition/></Grid.ColumnDefinitions>
|
||||
<Grid x:Name="RingBox" Width="120" Height="120" Margin="0,0,28,0">
|
||||
<Ellipse Stroke="#14FFFFFF" StrokeThickness="10" Margin="0"/>
|
||||
<Path x:Name="RingArc" Stroke="{StaticResource Brand}" StrokeThickness="10" StrokeStartLineCap="Round" StrokeEndLineCap="Round"/>
|
||||
<TextBlock x:Name="RingText" Text="0%" FontSize="24" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
<StackPanel Grid.Column="1" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="BuildTitle" Style="{StaticResource Heading}" Text="Building your game"/>
|
||||
<TextBlock x:Name="BuildNote" Style="{StaticResource Sub}"/>
|
||||
<ProgressBar x:Name="UpdateBar" Style="{StaticResource Bar}" Margin="0,18,0,0" Visibility="Collapsed"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<Grid Grid.Row="1" Margin="0,22,0,14">
|
||||
<Border x:Name="StepCard" Style="{StaticResource Card}" Padding="18,6" VerticalAlignment="Top">
|
||||
<StackPanel x:Name="StageList"/>
|
||||
</Border>
|
||||
<TextBox x:Name="Log" Visibility="Collapsed" IsReadOnly="True" BorderThickness="1"
|
||||
BorderBrush="{StaticResource GlassLine}" Background="#33000000" Foreground="{StaticResource InkSoft}"
|
||||
FontFamily="{StaticResource Mono}" FontSize="11" Padding="10" VerticalScrollBarVisibility="Auto"
|
||||
HorizontalScrollBarVisibility="Auto" TextWrapping="NoWrap"/>
|
||||
</Grid>
|
||||
|
||||
<Grid Grid.Row="2">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<ToggleButton x:Name="ShowLog" Style="{StaticResource Link}" VerticalAlignment="Center" Content="Show details"
|
||||
Checked="LogToggled" Unchecked="LogToggled"/>
|
||||
<Button x:Name="CancelButton" Grid.Column="1" Style="{StaticResource Quiet}" Content="Cancel" Click="CancelBuild"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- ===== 3: ready ===== -->
|
||||
<StackPanel x:Name="ReadyPage" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
<Grid Width="84" Height="84" HorizontalAlignment="Center">
|
||||
<Ellipse Fill="{StaticResource GoSoft}">
|
||||
<Ellipse.Effect><DropShadowEffect Color="#5FB08A" BlurRadius="60" ShadowDepth="0" Opacity="0.55"/></Ellipse.Effect>
|
||||
</Ellipse>
|
||||
<Ellipse Margin="-10" Stroke="#125FB08A" StrokeThickness="10"/>
|
||||
<Path Data="M0,12 L10,22 L28,2" Stroke="{StaticResource Go}" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round"
|
||||
StrokeLineJoin="Round" HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
<TextBlock x:Name="ReadyTitle" Style="{StaticResource Heading}" Text="Your game is ready" HorizontalAlignment="Center" Margin="0,24,0,0"/>
|
||||
<TextBlock x:Name="ReadyNote" Style="{StaticResource Sub}" HorizontalAlignment="Center" TextAlignment="Center"/>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,28,0,0">
|
||||
<Button x:Name="PlayButton" Style="{StaticResource GoButton}" Click="Play">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Path Data="M0,0 L11,7 L0,14 Z" Fill="{StaticResource GoInk}" VerticalAlignment="Center" Margin="0,0,10,0"/>
|
||||
<TextBlock x:Name="PlayText" Text="Play" FontSize="16" FontWeight="Bold" Foreground="{StaticResource GoInk}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button x:Name="OpenButton" Style="{StaticResource Quiet}" Height="50" Margin="12,0,0,0" Content="Open folder" Click="OpenFolder"/>
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,22,0,0">
|
||||
<CheckBox x:Name="DesktopTick" Style="{StaticResource Tick}" Content="Desktop shortcut" IsChecked="True" Click="ShortcutsChanged"/>
|
||||
<CheckBox x:Name="StartTick" Style="{StaticResource Tick}" Content="Start menu entry" IsChecked="True" Margin="18,0,0,0" Click="ShortcutsChanged"/>
|
||||
</StackPanel>
|
||||
<!-- what the builder keeps on this PC for quick updates (Storage.cs), and letting it go -->
|
||||
<StackPanel x:Name="StorageRow" Visibility="Collapsed" HorizontalAlignment="Center" Margin="0,26,0,0" MaxWidth="560">
|
||||
<TextBlock x:Name="StorageNote" Style="{StaticResource Note}" TextAlignment="Center" TextWrapping="Wrap"/>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,8,0,0">
|
||||
<Button x:Name="FreeButton" Style="{StaticResource LinkButton}" Content="Free up space" Click="FreeSpace"/>
|
||||
<Button Style="{StaticResource LinkButton}" Content="Show folder" Margin="18,0,0,0" Click="ShowStorage"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ===== the launcher (Hookshot Launcher.exe in the game folder, started with launch and its folder) ===== -->
|
||||
<StackPanel x:Name="LaunchPage" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
<TextBlock Style="{StaticResource Label}" Text="THE LEGEND OF ZELDA" HorizontalAlignment="Center"/>
|
||||
<TextBlock Style="{StaticResource Heading}" Text="Ocarina of Time" HorizontalAlignment="Center" FontSize="34" Margin="0,4,0,0"/>
|
||||
<TextBlock x:Name="LaunchVersion" Style="{StaticResource Sub}" HorizontalAlignment="Center" TextAlignment="Center" Margin="0,8,0,0"/>
|
||||
<TextBlock x:Name="LaunchStatus" FontSize="13" Foreground="{StaticResource InkSoft}" Text="Checking for updates…"
|
||||
HorizontalAlignment="Center" Margin="0,16,0,0"/>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,28,0,0">
|
||||
<Button x:Name="LaunchUpdate" Style="{StaticResource Primary}" Height="50" Padding="26,0" Margin="0,0,12,0" Content="Update"
|
||||
Visibility="Collapsed" Click="LaunchUpdateClick"/>
|
||||
<Button x:Name="LaunchPlay" Style="{StaticResource GoButton}" Click="LaunchPlayClick">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Path Data="M0,0 L11,7 L0,14 Z" Fill="{StaticResource GoInk}" VerticalAlignment="Center" Margin="0,0,10,0"/>
|
||||
<TextBlock Text="Play" FontSize="16" FontWeight="Bold" Foreground="{StaticResource GoInk}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
<Button x:Name="LaunchFolder" Style="{StaticResource LinkButton}" Foreground="{StaticResource InkFaint}" HorizontalAlignment="Center"
|
||||
Margin="0,22,0,0" Content="Open the game folder" Click="LaunchFolderClick"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ===== when something goes wrong ===== -->
|
||||
<Grid x:Name="ProblemPage" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<StackPanel>
|
||||
<TextBlock x:Name="ProblemTitle" Style="{StaticResource Heading}" Text="The build stopped"/>
|
||||
<TextBlock x:Name="ProblemSub" Style="{StaticResource Sub}" Text="Nothing was changed in your game folder."/>
|
||||
</StackPanel>
|
||||
<Border Grid.Row="1" CornerRadius="10" BorderThickness="1" BorderBrush="#55E2776B" Padding="24,22" Margin="0,22,0,14" VerticalAlignment="Top">
|
||||
<Border.Background>
|
||||
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
|
||||
<GradientStop Color="#14E2776B" Offset="0"/>
|
||||
<GradientStop Color="#00E2776B" Offset="0.7"/>
|
||||
</LinearGradientBrush>
|
||||
</Border.Background>
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Grid Width="28" Height="28">
|
||||
<Ellipse Fill="{StaticResource BadSoft}"/>
|
||||
<TextBlock Text="!" FontWeight="Bold" Foreground="{StaticResource Bad}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
<TextBlock x:Name="ProblemHead" FontSize="16" FontWeight="SemiBold" Margin="12,0,0,0" VerticalAlignment="Center" TextWrapping="Wrap" MaxWidth="740"/>
|
||||
</StackPanel>
|
||||
<ScrollViewer MaxHeight="190" VerticalScrollBarVisibility="Auto" Margin="0,10,0,0">
|
||||
<StackPanel>
|
||||
<TextBlock x:Name="ProblemText" Style="{StaticResource Note}" FontSize="14"/>
|
||||
<StackPanel x:Name="ProblemSteps" Margin="0,8,0,0"/>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Grid Grid.Row="2">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Button x:Name="ProblemDetails" Style="{StaticResource LinkButton}" Foreground="{StaticResource InkSoft}" Content="Show details" Click="ProblemShowDetails"/>
|
||||
<TextBlock Style="{StaticResource Faint}" FontSize="13" Text=" · " VerticalAlignment="Center"/>
|
||||
<Button x:Name="CopyReport" Style="{StaticResource LinkButton}" Foreground="{StaticResource InkSoft}" Content="Copy for a bug report" Click="CopyForReport"/>
|
||||
</StackPanel>
|
||||
<Button x:Name="BackButton" Grid.Column="1" Style="{StaticResource Quiet}" Content="Back" Click="Back"/>
|
||||
<Button x:Name="RepairButton" Grid.Column="2" Style="{StaticResource Primary}" Content="Repair" Margin="10,0,0,0" Click="Repair"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- the window's own buttons, over everything -->
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,6,6,0" Panel.ZIndex="9"
|
||||
WindowChrome.IsHitTestVisibleInChrome="True">
|
||||
<Button Style="{StaticResource Caption}" Click="Minimize" ToolTip="Minimize">
|
||||
<Rectangle Width="10" Height="1" Fill="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
</Button>
|
||||
<Button Style="{StaticResource Caption}" Click="CloseWindow" ToolTip="Close">
|
||||
<Path Data="M0,0 L10,10 M10,0 L0,10" StrokeThickness="1.2" Stroke="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
1363
builder/HookshotBuilder/MainWindow.xaml.cs
Normal file
1363
builder/HookshotBuilder/MainWindow.xaml.cs
Normal file
File diff suppressed because it is too large
Load Diff
184
builder/HookshotBuilder/Runner.cs
Normal file
184
builder/HookshotBuilder/Runner.cs
Normal file
@@ -0,0 +1,184 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// Where nx2/make_game.py and its Python are: a "tools" folder beside the app when packaged, or the source tree it sits in.
|
||||
sealed record Tools(string Root, string Python, string[]? PythonArgs = null)
|
||||
{
|
||||
/// Which release these tools are (tools/version.txt, written when the release is packed); null from the source tree
|
||||
public string? Version => File.Exists(Path.Combine(Root, "version.txt")) ? File.ReadAllText(Path.Combine(Root, "version.txt")).Trim() : null;
|
||||
|
||||
public static Tools? Find()
|
||||
{
|
||||
var at = AppContext.BaseDirectory;
|
||||
var bundled = Path.Combine(at, "tools");
|
||||
if (File.Exists(Path.Combine(bundled, "nx2", "make_game.py")))
|
||||
{
|
||||
var py = Path.Combine(bundled, "python", "python.exe");
|
||||
return new Tools(bundled, File.Exists(py) ? py : "python");
|
||||
}
|
||||
// (the source tree the app was built in: its builder\ folder holds the app. Not any parent folder with an nx2\
|
||||
// folder, such as one another user of the PC made at the drive's root)
|
||||
for (var d = new DirectoryInfo(at); d != null; d = d.Parent)
|
||||
if (File.Exists(Path.Combine(d.FullName, "nx2", "make_game.py")) &&
|
||||
at.StartsWith(Path.Combine(d.FullName, "builder") + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var (exe, args) = PythonOnPath();
|
||||
return new Tools(d.FullName, exe, args);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The Python for a source tree: Windows' Store shortcut is not an interpreter (it only opens the Store), so the py
|
||||
/// launcher is tried when "python" is that. CONTRIBUTING: Python 3 from python.org, not the Microsoft Store build.
|
||||
static (string Exe, string[]? Args) PythonOnPath()
|
||||
{
|
||||
var python = FirstOnPath("python.exe");
|
||||
if (python != null && !IsStoreShortcut(python)) return (python, null);
|
||||
var py = FirstOnPath("py.exe");
|
||||
if (py != null) return (py, new[] { "-3" });
|
||||
var later = AllOnPath("python.exe").FirstOrDefault(p => !IsStoreShortcut(p));
|
||||
return (later ?? python ?? "python", null);
|
||||
}
|
||||
|
||||
static IEnumerable<string> AllOnPath(string name)
|
||||
{
|
||||
foreach (var dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator))
|
||||
if (!string.IsNullOrWhiteSpace(dir))
|
||||
{
|
||||
var path = Path.Combine(dir.Trim('"'), name);
|
||||
if (File.Exists(path)) yield return path;
|
||||
}
|
||||
}
|
||||
|
||||
static string? FirstOnPath(string name) => AllOnPath(name).FirstOrDefault();
|
||||
|
||||
static bool IsStoreShortcut(string path) => path.Contains(@"\Microsoft\WindowsApps\", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// nx2/make_game.py as a child process: its lines as they come, and how it ended.
|
||||
sealed class Runner
|
||||
{
|
||||
readonly Tools tools;
|
||||
readonly List<string> args;
|
||||
readonly int? workers;
|
||||
readonly string? ngxSdk;
|
||||
Process? process;
|
||||
string? error;
|
||||
bool cancelled;
|
||||
|
||||
public event Action<string>? Line;
|
||||
public event Action<string?>? Finished;
|
||||
|
||||
/// ngxSdk: NVIDIA DLSS (the builder's tick): the folder of NVIDIA's DLSS SDK, as HOOKSHOT_NGX_SDK; null builds without it
|
||||
public Runner(Tools tools, List<string> args, int? workers = null, string? ngxSdk = null)
|
||||
{
|
||||
this.tools = tools;
|
||||
this.args = args;
|
||||
if (workers is <= 0) throw new ArgumentOutOfRangeException(nameof(workers), "Build workers must be positive.");
|
||||
this.workers = workers;
|
||||
this.ngxSdk = ngxSdk;
|
||||
}
|
||||
|
||||
static ProcessStartInfo Info(Tools tools, IEnumerable<string> args, int? workers = null, string? ngxSdk = null)
|
||||
{
|
||||
var si = new ProcessStartInfo(tools.Python)
|
||||
{
|
||||
WorkingDirectory = tools.Root,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
si.Environment["PYTHONIOENCODING"] = "utf-8";
|
||||
BuildWorkers.Apply(si, workers);
|
||||
// (written into the game folder's hookshot_version.txt: the game starts this app again to update, host/hos_update.c)
|
||||
if (Environment.ProcessPath != null) si.Environment["HOOKSHOT_BUILDER_EXE"] = Environment.ProcessPath;
|
||||
// (NVIDIA DLSS: only when ticked. Without it, one set on the PC is not passed on either: a build is with DLSS only when asked)
|
||||
if (ngxSdk != null) si.Environment["HOOKSHOT_NGX_SDK"] = ngxSdk;
|
||||
else si.Environment.Remove("HOOKSHOT_NGX_SDK");
|
||||
// (the folder's own compiler, headers and libraries, when it has them: nothing of the PC's but Windows' own)
|
||||
var sets = new[] { ("EMSDK", "emsdk"), ("RX_CPM", "cpm"), ("WGPU_NATIVE", "wgpu-native") };
|
||||
foreach (var (name, folder) in sets)
|
||||
{
|
||||
var path = Path.Combine(tools.Root, folder);
|
||||
if (Directory.Exists(path)) si.Environment[name] = path;
|
||||
}
|
||||
foreach (var a in tools.PythonArgs ?? Array.Empty<string>()) si.ArgumentList.Add(a);
|
||||
si.ArgumentList.Add("-I");
|
||||
si.ArgumentList.Add(Path.Combine(tools.Root, "nx2", "make_game.py"));
|
||||
foreach (var a in args) si.ArgumentList.Add(a);
|
||||
return si;
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var p = Process.Start(Info(tools, args, workers, ngxSdk))!;
|
||||
process = p;
|
||||
p.ErrorDataReceived += (_, e) => { if (e.Data != null) Line?.Invoke(e.Data); };
|
||||
p.BeginErrorReadLine();
|
||||
try { p.PriorityClass = ProcessPriorityClass.BelowNormal; } catch (Exception) { }
|
||||
while (p.StandardOutput.ReadLine() is { } line)
|
||||
{
|
||||
if (line.StartsWith("@@error ")) error = line[8..];
|
||||
Line?.Invoke(line);
|
||||
}
|
||||
p.WaitForExit();
|
||||
Finished?.Invoke(cancelled ? "cancelled" : p.ExitCode == 0 ? null : error ?? "The build tools stopped without saying why. See the details.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Finished?.Invoke("The build tools could not start: " + e.Message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void Cancel()
|
||||
{
|
||||
cancelled = true;
|
||||
try { process?.Kill(entireProcessTree: true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// Is this the supported game and version? The answer in plain words.
|
||||
public static async Task<(bool Ok, string Text)> Check(Tools tools, IEnumerable<string> args)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var p = Process.Start(Info(tools, args))!;
|
||||
string? lastError = null;
|
||||
p.ErrorDataReceived += (_, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) lastError = e.Data; };
|
||||
p.BeginErrorReadLine();
|
||||
var result = (false, "The game files could not be read.");
|
||||
var answered = false;
|
||||
while (await p.StandardOutput.ReadLineAsync() is { } line)
|
||||
{
|
||||
if (line.StartsWith("@@check ok ")) { result = (true, line[11..]); answered = true; }
|
||||
else if (line.StartsWith("@@check bad ")) { result = (false, line[12..]); answered = true; }
|
||||
else if (line.StartsWith("@@error ")) { result = (false, line[8..]); answered = true; }
|
||||
}
|
||||
await p.WaitForExitAsync();
|
||||
// (a step that stopped before it could say why: the reason is on stderr, which used to be dropped here)
|
||||
if (!answered)
|
||||
{
|
||||
if (lastError != null && lastError.Contains("Microsoft Store", StringComparison.OrdinalIgnoreCase))
|
||||
return (false, "Python 3 was not found: the 'python' command on this PC is the Microsoft Store shortcut, which only opens " +
|
||||
"the Store. Install Python 3 from python.org (not the Store version), or use the full Hookshot Builder package.");
|
||||
return (false, lastError ?? "The game tools stopped without saying why (exit code " + p.ExitCode + ").");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// (the package's own Python missing: an antivirus took it, most often, after a false alarm on the download)
|
||||
if (tools.Python == "python" && Directory.Exists(Path.Combine(tools.Root, "python")))
|
||||
return (false, "The builder's own Python (tools/python/python.exe) is missing. Your antivirus probably removed it: restore it " +
|
||||
"from quarantine, or unpack the zip again into a folder your antivirus allows, then try again.");
|
||||
return (false, "Python 3 was not found. Install it from python.org (not the Microsoft Store build), or use the full Hookshot Builder package.");
|
||||
}
|
||||
}
|
||||
}
|
||||
30
builder/HookshotBuilder/ShaderStep.cs
Normal file
30
builder/HookshotBuilder/ShaderStep.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// The build's last step, the shaders' preparation (nx2/make_game.py prepare_shaders): the argument that leaves it to the game's
|
||||
/// first start, and what its row says once the build is done
|
||||
static class ShaderStep
|
||||
{
|
||||
public const string Id = "shaders";
|
||||
public const string Later = "--no-prepare-shaders";
|
||||
// (make_game.py NOT_PREPARED: a plain line, so a builder that does not know it only shows it)
|
||||
static readonly Regex NotPrepared = new(@"^the shaders were not prepared now \((.*)\): ");
|
||||
|
||||
/// make_game's arguments with the player's choice (unticked: the game prepares its shaders at its first start)
|
||||
public static List<string> Args(List<string> args, bool prepare)
|
||||
{
|
||||
if (!prepare) args.Add(Later);
|
||||
return args;
|
||||
}
|
||||
|
||||
/// Why make_game left the shaders to the first start, when this line says so; else null
|
||||
public static string? Reason(string line) => NotPrepared.Match(line) is { Success: true } m ? m.Groups[1].Value : null;
|
||||
|
||||
/// The line under the row of a finished build when the shaders were not prepared, or null when they were (a check mark).
|
||||
/// began: the game's @@stage shaders came; reason: make_game's not-prepared line
|
||||
public static string? Skipped(bool began, string? reason) =>
|
||||
reason != null ? $"Left to the game's first start: {reason}"
|
||||
: began ? null
|
||||
: "Left to the game's first start";
|
||||
}
|
||||
171
builder/HookshotBuilder/Storage.cs
Normal file
171
builder/HookshotBuilder/Storage.cs
Normal file
@@ -0,0 +1,171 @@
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// What the builder keeps on the PC, and letting it go. In %LOCALAPPDATA%\HookshotBuilder: the builder itself (versions\: the one
|
||||
/// installed last, and the one before it), the setup's downloaded parts (the next builder update downloads only those that changed).
|
||||
/// In the build files folder (that same folder, or one the player chose: make_game.py --work): the translated code and its compiled
|
||||
/// objects (sa\, objcache\: the next update compiles only what changed). None of it is needed to play: the game folder holds all the
|
||||
/// game uses, and its copy of the game files (.hookshot_exefs) is what updates build from
|
||||
static class Storage
|
||||
{
|
||||
public static string Base => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HookshotBuilder");
|
||||
|
||||
/// About what a build leaves in the build files folder (the translated code and its compiled objects): said before the build
|
||||
public const long BuildFilesBytes = 4L << 30;
|
||||
|
||||
/// HOOKSHOT_KEEP_BUILD_FILES=1: the build files stay after a build (quick updates); otherwise they go when the game is ready
|
||||
public static bool KeepBuildFiles => Environment.GetEnvironmentVariable("HOOKSHOT_KEEP_BUILD_FILES") is { Length: > 0 } v && v != "0";
|
||||
|
||||
/// Where builds keep their files: the folder the player chose (work.txt), else the builder's own
|
||||
public static string Work
|
||||
{
|
||||
get
|
||||
{
|
||||
try
|
||||
{
|
||||
var chosen = File.ReadAllText(Path.Combine(Base, "work.txt")).Trim();
|
||||
if (chosen.Length > 2 && Path.IsPathFullyQualified(chosen)) return chosen;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
|
||||
return Base;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool WorkChosen => !Same(Work, Base);
|
||||
|
||||
/// (NVIDIA DLSS, only when ticked) NVIDIA's DLSS SDK, downloaded under NVIDIA's license by the build (make_game.py
|
||||
/// --fetch-ngx-sdk, scripts/ngx_sdk.py): HOOKSHOT_NGX_SDK. NVIDIA's files, never part of the builder or its downloads
|
||||
public static string NgxSdk => Path.Combine(Base, "ngx-sdk");
|
||||
|
||||
/// The build files go to a folder of their own in the one the player picked (null: back to the builder's own). What the last
|
||||
/// builds left at the old place goes: the next build would not look for it there
|
||||
public static void MoveWork(string? picked)
|
||||
{
|
||||
var old = Work;
|
||||
var to = picked == null ? Base : Path.Combine(picked, "Hookshot build files");
|
||||
if (Same(old, to)) return;
|
||||
Directory.CreateDirectory(to);
|
||||
Directory.CreateDirectory(Base);
|
||||
if (picked == null) File.Delete(Path.Combine(Base, "work.txt"));
|
||||
else File.WriteAllText(Path.Combine(Base, "work.txt"), to);
|
||||
foreach (var d in WorkParts(old)) Delete(d);
|
||||
if (!Same(old, Base))
|
||||
try { Directory.Delete(old); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { } // (only when empty)
|
||||
}
|
||||
|
||||
/// What a build makes in its work folder (make_game.py, lift.py, build.py)
|
||||
static IEnumerable<string> WorkParts(string work) =>
|
||||
new[] { "objcache", "sa", "exefs", "probe", "image", "system_headers.txt", "hot_funcs.txt", "hot_order.txt", "hookshot_pieces.prof", "hookshot.res" }
|
||||
.Select(n => Path.Combine(work, n));
|
||||
|
||||
/// The builder versions that stay: the one installed last (current.txt) and the one running
|
||||
static bool Kept(string versionDir)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.ReadAllText(Path.Combine(Base, "versions", "current.txt")).Trim() == Path.GetFileName(versionDir)) return true;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
|
||||
var running = Path.GetFullPath(AppContext.BaseDirectory).TrimEnd('\\') + "\\";
|
||||
return running.StartsWith(Path.GetFullPath(versionDir).TrimEnd('\\') + "\\", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// What Free lets go. afterBuild: what goes once the game is ready, the compiled objects of the build (objcache, which make_game.py
|
||||
/// prunes to them) and their system headers' stamp kept, so that the next update compiles only what changed (issue 1287: every
|
||||
/// update compiled all ~600 files again, an hour and more). The Free up space button lets those go too
|
||||
static IEnumerable<string> Freeable(bool afterBuild = false)
|
||||
{
|
||||
foreach (var d in afterBuild ? new[] { "sa", "exefs", "probe" } : new[] { "objcache", "sa", "exefs", "probe" })
|
||||
yield return Path.Combine(Work, d);
|
||||
foreach (var d in new[] { "downloads", "update" })
|
||||
yield return Path.Combine(Base, d);
|
||||
var versions = Path.Combine(Base, "versions");
|
||||
if (Directory.Exists(versions))
|
||||
foreach (var v in Directory.EnumerateDirectories(versions))
|
||||
if (!Kept(v)) yield return v;
|
||||
}
|
||||
|
||||
/// Bytes in the builder's folder and the build files folder, and in what Free lets go (an object hard-linked in both sa\build and
|
||||
/// objcache counted once)
|
||||
public static (long total, long freeable) Measure()
|
||||
{
|
||||
var seen = new HashSet<(uint, ulong)>();
|
||||
long freeable = 0;
|
||||
foreach (var d in Freeable()) freeable += Size(d, seen);
|
||||
seen.Clear();
|
||||
var total = Size(Base, seen) + (WorkChosen ? Size(Work, seen) : 0);
|
||||
return (Math.Max(total, freeable), freeable);
|
||||
}
|
||||
|
||||
/// Lets go of what Measure counts as freeable; returns the bytes it could not delete (a file in use)
|
||||
public static long Free(bool afterBuild = false)
|
||||
{
|
||||
foreach (var d in Freeable(afterBuild)) Delete(d);
|
||||
if (!afterBuild) Delete(Path.Combine(Work, "system_headers.txt")); // (the stamp of the compiled objects' system headers goes with them)
|
||||
if (!afterBuild) return Measure().freeable;
|
||||
var seen = new HashSet<(uint, ulong)>(); // (what of the after-build set is still there: a file in use)
|
||||
long left = 0;
|
||||
foreach (var d in Freeable(afterBuild: true)) left += Size(d, seen);
|
||||
return left;
|
||||
}
|
||||
|
||||
public static string Gb(long bytes) => bytes >= 1L << 30 ? $"{bytes / (double)(1L << 30):0.0} GB" : $"{bytes >> 20} MB";
|
||||
|
||||
static bool Same(string a, string b) =>
|
||||
string.Equals(Path.GetFullPath(a).TrimEnd('\\'), Path.GetFullPath(b).TrimEnd('\\'), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
static void Delete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
|
||||
else if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
|
||||
}
|
||||
|
||||
static long Size(string dir, HashSet<(uint, ulong)> seen)
|
||||
{
|
||||
if (!Directory.Exists(dir)) return 0;
|
||||
long n = 0;
|
||||
IEnumerable<FileInfo> files;
|
||||
try
|
||||
{
|
||||
files = new DirectoryInfo(dir).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true });
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return 0; }
|
||||
foreach (var f in files)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (f.Length == 0) continue;
|
||||
if (Identity(f.FullName) is { } id && !seen.Add(id)) continue;
|
||||
n += f.Length;
|
||||
}
|
||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)] // (BY_HANDLE_FILE_INFORMATION: its FILETIMEs are two DWORDs, no padding)
|
||||
struct FileInfoByHandle
|
||||
{
|
||||
public uint Attributes;
|
||||
public long Created, Accessed, Written;
|
||||
public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
static extern bool GetFileInformationByHandle(SafeFileHandle h, out FileInfoByHandle info);
|
||||
|
||||
/// The file's volume and index (the same for each of its hard links); null for one with a single link, which needs no check
|
||||
static (uint, ulong)? Identity(string path)
|
||||
{
|
||||
using var h = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
if (!GetFileInformationByHandle(h, out var i) || i.Links < 2) return null;
|
||||
return (i.Volume, ((ulong)i.IndexHigh << 32) | i.IndexLow);
|
||||
}
|
||||
}
|
||||
174
builder/HookshotBuilder/Strings.cs
Normal file
174
builder/HookshotBuilder/Strings.cs
Normal file
@@ -0,0 +1,174 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// One of the game's languages: its code in language.txt, its own name, and the app's text in it.
|
||||
sealed record Language(string Code, string Name, string[] Text)
|
||||
{
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
enum S
|
||||
{
|
||||
Subtitle, GameFiles, Nup, Folders, DropHint, SaveTo, Build, Browse, Needs, Free, Checking, VersionOk, VersionBad, ToolsMissing, PythonMissing,
|
||||
Building, Patience, Elapsed, Read, Lift, Compile, Finish, ShowDetails, HideDetails, Cancel, Back, OpenFolder, Play, Ready, BuiltIn,
|
||||
Stopped, Cancelled, CancelledNote, CloseQuestion, LanguageLabel,
|
||||
// (the update, English only for now: Strings.Text falls back to it)
|
||||
Download, Updating, UpdateFailed,
|
||||
}
|
||||
|
||||
static class Strings
|
||||
{
|
||||
static readonly string[] En =
|
||||
{
|
||||
"Turns your own copy of Ocarina of Time into a game folder you can start on PC.", "Game files", ".nup file", "romfs and exefs",
|
||||
"You can also drop a file or folder onto this window.", "Save the game to", "Build", "Browse", "Takes about 45 minutes and needs 45 GB.",
|
||||
"{0} has {1} GB free.", "Checking the game version...", "This is the version Hookshot supports.", "This version isn't supported. Hookshot needs build e0f3ccfa.",
|
||||
"The Hookshot tools were not found next to this app.", "Python was not found.",
|
||||
"Building", "This takes a while, and your PC stays usable.", "Elapsed", "Reading your game files", "Translating the game to PC code", "Compiling",
|
||||
"Putting the game folder together", "Show details", "Hide details", "Cancel", "Back", "Open folder", "Play", "Your game is ready", "built in",
|
||||
"The build stopped", "Build cancelled", "You can start again from the same folder.", "Stop the build and close?", "Language",
|
||||
"Downloading the new version", "Updating your game", "The update could not be downloaded",
|
||||
};
|
||||
static readonly string[] Fr =
|
||||
{
|
||||
"Transforme votre copie d'Ocarina of Time en un dossier de jeu à lancer sur PC.", "Fichiers du jeu", "Fichier .nup", "romfs et exefs",
|
||||
"Vous pouvez aussi déposer un fichier ou un dossier sur cette fenêtre.", "Enregistrer le jeu dans", "Créer", "Parcourir", "Prend environ 45 minutes et nécessite 45 Go.",
|
||||
"{0} : {1} Go libres.", "Vérification de la version du jeu...", "Cette version est prise en charge par Hookshot.", "Cette version n'est pas prise en charge. Hookshot a besoin de la version e0f3ccfa.",
|
||||
"Les outils Hookshot sont introuvables à côté de cette application.", "Python est introuvable.",
|
||||
"Création en cours", "Cela prend du temps, et votre PC reste utilisable.", "Temps écoulé", "Lecture de vos fichiers de jeu", "Traduction du jeu en code PC", "Compilation",
|
||||
"Assemblage du dossier du jeu", "Afficher les détails", "Masquer les détails", "Annuler", "Retour", "Ouvrir le dossier", "Jouer", "Votre jeu est prêt", "créé en",
|
||||
"La création s'est arrêtée", "Création annulée", "Vous pouvez recommencer depuis le même dossier.", "Arrêter la création et fermer ?", "Langue",
|
||||
};
|
||||
static readonly string[] De =
|
||||
{
|
||||
"Macht aus deiner eigenen Kopie von Ocarina of Time einen Spielordner für den PC.", "Spieldateien", ".nup-Datei", "romfs und exefs",
|
||||
"Du kannst auch eine Datei oder einen Ordner auf dieses Fenster ziehen.", "Spiel speichern unter", "Erstellen", "Durchsuchen", "Dauert etwa 45 Minuten und benötigt 45 GB.",
|
||||
"{0} hat {1} GB frei.", "Spielversion wird geprüft...", "Diese Version wird von Hookshot unterstützt.", "Diese Version wird nicht unterstützt. Hookshot benötigt Build e0f3ccfa.",
|
||||
"Die Hookshot-Werkzeuge wurden neben dieser App nicht gefunden.", "Python wurde nicht gefunden.",
|
||||
"Wird erstellt", "Das dauert eine Weile, dein PC bleibt nutzbar.", "Vergangen", "Spieldateien werden gelesen", "Spiel wird in PC-Code übersetzt", "Kompilieren",
|
||||
"Spielordner wird zusammengestellt", "Details anzeigen", "Details ausblenden", "Abbrechen", "Zurück", "Ordner öffnen", "Spielen", "Dein Spiel ist fertig", "erstellt in",
|
||||
"Die Erstellung wurde angehalten", "Erstellung abgebrochen", "Du kannst im selben Ordner neu beginnen.", "Erstellung beenden und schließen?", "Sprache",
|
||||
};
|
||||
static readonly string[] It =
|
||||
{
|
||||
"Trasforma la tua copia di Ocarina of Time in una cartella di gioco da avviare su PC.", "File di gioco", "File .nup", "romfs ed exefs",
|
||||
"Puoi anche trascinare un file o una cartella su questa finestra.", "Salva il gioco in", "Crea", "Sfoglia", "Richiede circa 45 minuti e 45 GB.",
|
||||
"{0} ha {1} GB liberi.", "Controllo della versione del gioco...", "Questa versione è supportata da Hookshot.", "Questa versione non è supportata. Hookshot richiede la build e0f3ccfa.",
|
||||
"Gli strumenti di Hookshot non sono stati trovati accanto a questa app.", "Python non è stato trovato.",
|
||||
"Creazione in corso", "Ci vuole un po', e il PC resta utilizzabile.", "Trascorso", "Lettura dei file di gioco", "Traduzione del gioco in codice PC", "Compilazione",
|
||||
"Assemblaggio della cartella di gioco", "Mostra dettagli", "Nascondi dettagli", "Annulla", "Indietro", "Apri cartella", "Gioca", "Il tuo gioco è pronto", "creato in",
|
||||
"La creazione si è interrotta", "Creazione annullata", "Puoi ricominciare dalla stessa cartella.", "Interrompere la creazione e chiudere?", "Lingua",
|
||||
};
|
||||
static readonly string[] Es =
|
||||
{
|
||||
"Convierte tu copia de Ocarina of Time en una carpeta de juego para iniciar en PC.", "Archivos del juego", "Archivo .nup", "romfs y exefs",
|
||||
"También puedes soltar un archivo o una carpeta en esta ventana.", "Guardar el juego en", "Crear", "Examinar", "Tarda unos 45 minutos y necesita 45 GB.",
|
||||
"{0} tiene {1} GB libres.", "Comprobando la versión del juego...", "Hookshot admite esta versión.", "Esta versión no es compatible. Hookshot necesita la build e0f3ccfa.",
|
||||
"No se encontraron las herramientas de Hookshot junto a esta aplicación.", "No se encontró Python.",
|
||||
"Creando", "Tarda un rato, y tu PC sigue siendo utilizable.", "Transcurrido", "Leyendo tus archivos del juego", "Traduciendo el juego a código de PC", "Compilando",
|
||||
"Preparando la carpeta del juego", "Mostrar detalles", "Ocultar detalles", "Cancelar", "Atrás", "Abrir carpeta", "Jugar", "Tu juego está listo", "creado en",
|
||||
"La creación se detuvo", "Creación cancelada", "Puedes empezar de nuevo desde la misma carpeta.", "¿Detener la creación y cerrar?", "Idioma",
|
||||
};
|
||||
static readonly string[] Pt =
|
||||
{
|
||||
"Transforma sua cópia de Ocarina of Time em uma pasta de jogo para iniciar no PC.", "Arquivos do jogo", "Arquivo .nup", "romfs e exefs",
|
||||
"Você também pode soltar um arquivo ou uma pasta nesta janela.", "Salvar o jogo em", "Criar", "Procurar", "Leva cerca de 45 minutos e precisa de 45 GB.",
|
||||
"{0} tem {1} GB livres.", "Verificando a versão do jogo...", "Esta versão é compatível com o Hookshot.", "Esta versão não é compatível. O Hookshot precisa da build e0f3ccfa.",
|
||||
"As ferramentas do Hookshot não foram encontradas ao lado deste aplicativo.", "O Python não foi encontrado.",
|
||||
"Criando", "Isso leva um tempo, e seu PC continua utilizável.", "Decorrido", "Lendo seus arquivos do jogo", "Traduzindo o jogo para código de PC", "Compilando",
|
||||
"Montando a pasta do jogo", "Mostrar detalhes", "Ocultar detalhes", "Cancelar", "Voltar", "Abrir pasta", "Jogar", "Seu jogo está pronto", "criado em",
|
||||
"A criação parou", "Criação cancelada", "Você pode recomeçar a partir da mesma pasta.", "Parar a criação e fechar?", "Idioma",
|
||||
};
|
||||
static readonly string[] Nl =
|
||||
{
|
||||
"Maakt van je eigen exemplaar van Ocarina of Time een spelmap om op pc te starten.", "Spelbestanden", ".nup-bestand", "romfs en exefs",
|
||||
"Je kunt ook een bestand of map op dit venster slepen.", "Spel opslaan in", "Maken", "Bladeren", "Duurt ongeveer 45 minuten en vereist 45 GB.",
|
||||
"{0} heeft {1} GB vrij.", "Spelversie controleren...", "Deze versie wordt door Hookshot ondersteund.", "Deze versie wordt niet ondersteund. Hookshot heeft build e0f3ccfa nodig.",
|
||||
"De Hookshot-tools zijn niet naast deze app gevonden.", "Python is niet gevonden.",
|
||||
"Bezig met maken", "Dit duurt even, en je pc blijft bruikbaar.", "Verstreken", "Je spelbestanden lezen", "Spel vertalen naar pc-code", "Compileren",
|
||||
"Spelmap samenstellen", "Details tonen", "Details verbergen", "Annuleren", "Terug", "Map openen", "Spelen", "Je spel is klaar", "gemaakt in",
|
||||
"Het maken is gestopt", "Maken geannuleerd", "Je kunt opnieuw beginnen vanuit dezelfde map.", "Maken stoppen en sluiten?", "Taal",
|
||||
};
|
||||
static readonly string[] Pl =
|
||||
{
|
||||
"Zamienia Twoją kopię Ocarina of Time w folder gry, który uruchomisz na PC.", "Pliki gry", "Plik .nup", "romfs i exefs",
|
||||
"Możesz też upuścić plik lub folder na to okno.", "Zapisz grę w", "Utwórz", "Przeglądaj", "Trwa około 45 minut i wymaga 45 GB.",
|
||||
"{0}: wolne {1} GB.", "Sprawdzanie wersji gry...", "Ta wersja jest obsługiwana przez Hookshot.", "Ta wersja nie jest obsługiwana. Hookshot wymaga kompilacji e0f3ccfa.",
|
||||
"Nie znaleziono narzędzi Hookshot obok tej aplikacji.", "Nie znaleziono Pythona.",
|
||||
"Tworzenie", "To chwilę potrwa, a komputer pozostanie w użyciu.", "Upłynęło", "Odczytywanie plików gry", "Tłumaczenie gry na kod PC", "Kompilowanie",
|
||||
"Składanie folderu gry", "Pokaż szczegóły", "Ukryj szczegóły", "Anuluj", "Wstecz", "Otwórz folder", "Graj", "Twoja gra jest gotowa", "utworzono w",
|
||||
"Tworzenie zostało przerwane", "Anulowano tworzenie", "Możesz zacząć ponownie z tego samego folderu.", "Przerwać tworzenie i zamknąć?", "Język",
|
||||
};
|
||||
static readonly string[] Ru =
|
||||
{
|
||||
"Превращает вашу копию Ocarina of Time в папку с игрой для запуска на ПК.", "Файлы игры", "Файл .nup", "romfs и exefs",
|
||||
"Также можно перетащить файл или папку в это окно.", "Сохранить игру в", "Собрать", "Обзор", "Занимает около 45 минут и требует 45 ГБ.",
|
||||
"{0}: свободно {1} ГБ.", "Проверка версии игры...", "Эта версия поддерживается Hookshot.", "Эта версия не поддерживается. Hookshot нужна сборка e0f3ccfa.",
|
||||
"Инструменты Hookshot не найдены рядом с этим приложением.", "Python не найден.",
|
||||
"Сборка", "Это займёт время, а компьютером можно пользоваться.", "Прошло", "Чтение файлов игры", "Перевод игры в код для ПК", "Компиляция",
|
||||
"Подготовка папки с игрой", "Показать подробности", "Скрыть подробности", "Отмена", "Назад", "Открыть папку", "Играть", "Ваша игра готова", "собрано за",
|
||||
"Сборка остановлена", "Сборка отменена", "Можно начать заново из той же папки.", "Остановить сборку и закрыть?", "Язык",
|
||||
};
|
||||
static readonly string[] Ja =
|
||||
{
|
||||
"お持ちの Ocarina of Time を、PC で起動できるゲームフォルダーに変換します。", "ゲームファイル", ".nup ファイル", "romfs と exefs",
|
||||
"ファイルやフォルダーをこのウィンドウにドロップすることもできます。", "ゲームの保存先", "ビルド", "参照", "約 45 分かかり、45 GB 必要です。",
|
||||
"{0} の空き容量: {1} GB", "ゲームのバージョンを確認しています...", "このバージョンは Hookshot に対応しています。", "このバージョンには対応していません。Hookshot にはビルド e0f3ccfa が必要です。",
|
||||
"このアプリの横に Hookshot ツールが見つかりません。", "Python が見つかりません。",
|
||||
"ビルド中", "時間がかかりますが、PC はそのまま使えます。", "経過時間", "ゲームファイルを読み込んでいます", "ゲームを PC 用コードに変換しています", "コンパイル中",
|
||||
"ゲームフォルダーを作成しています", "詳細を表示", "詳細を隠す", "キャンセル", "戻る", "フォルダーを開く", "プレイ", "ゲームの準備ができました", "所要時間",
|
||||
"ビルドが停止しました", "ビルドをキャンセルしました", "同じフォルダーからやり直せます。", "ビルドを中止して閉じますか?", "言語",
|
||||
};
|
||||
static readonly string[] Ko =
|
||||
{
|
||||
"가지고 있는 Ocarina of Time을 PC에서 실행할 수 있는 게임 폴더로 만듭니다.", "게임 파일", ".nup 파일", "romfs 및 exefs",
|
||||
"파일이나 폴더를 이 창에 끌어다 놓을 수도 있습니다.", "게임 저장 위치", "빌드", "찾아보기", "약 45분이 걸리며 45GB가 필요합니다.",
|
||||
"{0} 여유 공간: {1}GB", "게임 버전을 확인하는 중...", "Hookshot이 지원하는 버전입니다.", "지원되지 않는 버전입니다. Hookshot에는 빌드 e0f3ccfa가 필요합니다.",
|
||||
"이 앱 옆에서 Hookshot 도구를 찾을 수 없습니다.", "Python을 찾을 수 없습니다.",
|
||||
"빌드 중", "시간이 걸리지만 PC는 계속 사용할 수 있습니다.", "경과 시간", "게임 파일을 읽는 중", "게임을 PC 코드로 변환하는 중", "컴파일 중",
|
||||
"게임 폴더를 만드는 중", "자세히 보기", "자세히 숨기기", "취소", "뒤로", "폴더 열기", "플레이", "게임이 준비되었습니다", "소요 시간",
|
||||
"빌드가 중단되었습니다", "빌드가 취소되었습니다", "같은 폴더에서 다시 시작할 수 있습니다.", "빌드를 중단하고 닫을까요?", "언어",
|
||||
};
|
||||
static readonly string[] ZhHans =
|
||||
{
|
||||
"将你自己的 Ocarina of Time 变成可在电脑上启动的游戏文件夹。", "游戏文件", ".nup 文件", "romfs 和 exefs",
|
||||
"也可以将文件或文件夹拖放到此窗口。", "游戏保存位置", "生成", "浏览", "大约需要 45 分钟和 45 GB 空间。",
|
||||
"{0} 可用空间 {1} GB。", "正在检查游戏版本...", "Hookshot 支持此版本。", "不支持此版本。Hookshot 需要构建版本 e0f3ccfa。",
|
||||
"在此应用旁边找不到 Hookshot 工具。", "找不到 Python。",
|
||||
"正在生成", "这需要一些时间,期间电脑仍可正常使用。", "已用时间", "正在读取游戏文件", "正在将游戏转换为电脑代码", "正在编译",
|
||||
"正在整理游戏文件夹", "显示详细信息", "隐藏详细信息", "取消", "返回", "打开文件夹", "开始游戏", "你的游戏已准备就绪", "用时",
|
||||
"生成已停止", "生成已取消", "你可以从同一文件夹重新开始。", "要停止生成并关闭吗?", "语言",
|
||||
};
|
||||
static readonly string[] ZhHant =
|
||||
{
|
||||
"將你自己的 Ocarina of Time 變成可在電腦上啟動的遊戲資料夾。", "遊戲檔案", ".nup 檔案", "romfs 和 exefs",
|
||||
"也可以將檔案或資料夾拖放到此視窗。", "遊戲儲存位置", "建置", "瀏覽", "大約需要 45 分鐘和 45 GB 空間。",
|
||||
"{0} 可用空間 {1} GB。", "正在檢查遊戲版本...", "Hookshot 支援此版本。", "不支援此版本。Hookshot 需要建置版本 e0f3ccfa。",
|
||||
"在此應用程式旁找不到 Hookshot 工具。", "找不到 Python。",
|
||||
"正在建置", "這需要一些時間,期間電腦仍可正常使用。", "已用時間", "正在讀取遊戲檔案", "正在將遊戲轉換為電腦程式碼", "正在編譯",
|
||||
"正在整理遊戲資料夾", "顯示詳細資訊", "隱藏詳細資訊", "取消", "返回", "開啟資料夾", "開始遊戲", "你的遊戲已準備就緒", "用時",
|
||||
"建置已停止", "建置已取消", "你可以從同一資料夾重新開始。", "要停止建置並關閉嗎?", "語言",
|
||||
};
|
||||
|
||||
public static readonly Language[] All =
|
||||
{
|
||||
new("en-US", "English (US)", En), new("en-GB", "English (UK)", En), new("fr", "Français", Fr), new("fr-CA", "Français (Canada)", Fr),
|
||||
new("de", "Deutsch", De), new("it", "Italiano", It), new("es", "Español (España)", Es), new("es-419", "Español (Latinoamérica)", Es),
|
||||
new("pt-BR", "Português (Brasil)", Pt), new("nl", "Nederlands", Nl), new("pl", "Polski", Pl), new("ru", "Русский", Ru),
|
||||
new("ja", "日本語", Ja), new("ko", "한국어", Ko), new("zh-Hans", "简体中文", ZhHans), new("zh-Hant", "繁體中文", ZhHant),
|
||||
};
|
||||
|
||||
/// The language closest to Windows' own: the exact one, then the same family, else English (US).
|
||||
public static Language Default()
|
||||
{
|
||||
var c = CultureInfo.CurrentUICulture;
|
||||
var name = c.Name;
|
||||
var pick = All.FirstOrDefault(l => l.Code.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
if (pick != null) return pick;
|
||||
if (name.StartsWith("zh")) return All.First(l => l.Code == (name.Contains("TW") || name.Contains("HK") || name.Contains("Hant") ? "zh-Hant" : "zh-Hans"));
|
||||
if (name.StartsWith("es-") && name != "es-ES") return All.First(l => l.Code == "es-419");
|
||||
if (name.StartsWith("pt")) return All.First(l => l.Code == "pt-BR");
|
||||
return All.FirstOrDefault(l => l.Code == c.TwoLetterISOLanguageName) ?? All[0];
|
||||
}
|
||||
}
|
||||
349
builder/HookshotBuilder/Updater.cs
Normal file
349
builder/HookshotBuilder/Updater.cs
Normal file
@@ -0,0 +1,349 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Windows;
|
||||
|
||||
namespace HookshotBuilder;
|
||||
|
||||
/// The game's update offer (host/hos_update.c) starts this app with --update <game folder> --tag <release>. When these tools are
|
||||
/// not that release, the release's HookshotBuilder.zip is downloaded and unpacked beside this app, and the new app is started with
|
||||
/// --fetched to build the folder; when they are, the folder is built again here (nx2/make_game.py --update: from the game files the
|
||||
/// folder keeps).
|
||||
static class Updater
|
||||
{
|
||||
const string Latest = "https://api.github.com/repos/NotRexed/Hookshot/releases/latest";
|
||||
const string Asset = "HookshotBuilder.zip";
|
||||
const string SetupAsset = "HookshotBuilder.exe"; // (the setup, builder/setup/setup.c: a release holds it and its list)
|
||||
const string SetupList = "hookshot-setup.txt"; // (scripts/make_setup_parts.py)
|
||||
static readonly TimeSpan[] RetryDelays = { TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(6), TimeSpan.FromSeconds(12), TimeSpan.FromSeconds(20) };
|
||||
|
||||
public static void FromCommandLine(MainWindow w)
|
||||
{
|
||||
var a = Environment.GetCommandLineArgs();
|
||||
string? folder = null, tag = null;
|
||||
var fetched = false;
|
||||
for (var i = 1; i < a.Length; i++)
|
||||
{
|
||||
if (a[i] == "--update" && i + 1 < a.Length) folder = a[++i];
|
||||
else if (a[i] == "--tag" && i + 1 < a.Length) tag = a[++i];
|
||||
else if (a[i] == "--fetched") fetched = true;
|
||||
}
|
||||
if (folder == null) return;
|
||||
UpdateFolder(w, folder, tag, fetched);
|
||||
}
|
||||
|
||||
/// The latest release's tag, quietly (null: GitHub did not answer); a few tries, 20 s at most
|
||||
public static async Task<string?> LatestTag()
|
||||
{
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(8) };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd("HookshotBuilder");
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, Latest);
|
||||
request.Headers.Accept.ParseAdd("application/vnd.github+json");
|
||||
using var response = await http.SendAsync(request);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
return doc.RootElement.GetProperty("tag_name").GetString();
|
||||
}
|
||||
if ((int)response.StatusCode < 500) break; // (the API's limit, 60 an hour a PC: the list below instead)
|
||||
}
|
||||
catch (Exception) { }
|
||||
await Task.Delay(TimeSpan.FromSeconds(2 << attempt));
|
||||
}
|
||||
// (v2.0.0: when the API did not answer, the builder said a game was up to date. The release's setup list names its tag in
|
||||
// its first line, from GitHub's download service, not the API)
|
||||
for (var attempt = 0; attempt < 2; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
var list = await http.GetStringAsync("https://github.com/NotRexed/Hookshot/releases/latest/download/" + SetupList);
|
||||
foreach (var line in list.Split('\n'))
|
||||
if (line.StartsWith("tag ")) return line[4..].Trim();
|
||||
}
|
||||
catch (Exception) { }
|
||||
await Task.Delay(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The latest release's setup (HookshotBuilder.exe) downloaded and started with args: it installs the new builder (only the
|
||||
/// parts that changed) and starts it with the same args; this one closes. (no args: the new builder opens as it does)
|
||||
public static async Task RunLatestSetup(MainWindow w, IEnumerable<string> args)
|
||||
{
|
||||
var token = w.DownloadToken;
|
||||
using var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd("HookshotBuilder");
|
||||
w.Note("Asking GitHub for the latest release");
|
||||
string? setupUrl = null, setupApiUrl = null;
|
||||
long setupSize = 0;
|
||||
using (var response = await GetWithRetries(w, http, Latest, token, "application/vnd.github+json", TimeSpan.FromSeconds(30)))
|
||||
using (var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token)))
|
||||
foreach (var asset in doc.RootElement.GetProperty("assets").EnumerateArray())
|
||||
if (asset.GetProperty("name").GetString() == SetupAsset)
|
||||
{
|
||||
setupUrl = asset.GetProperty("browser_download_url").GetString();
|
||||
setupApiUrl = asset.GetProperty("url").GetString();
|
||||
setupSize = asset.GetProperty("size").GetInt64();
|
||||
}
|
||||
if (setupUrl == null) throw new InvalidOperationException("The latest release has no " + SetupAsset + ".");
|
||||
var cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HookshotBuilder", "update");
|
||||
Directory.CreateDirectory(cache);
|
||||
var setup = Path.Combine(cache, SetupAsset);
|
||||
w.Note("Downloading the new Hookshot Builder");
|
||||
await DownloadWithRetries(w, http, setupUrl, setupApiUrl, setup, setupSize, token);
|
||||
var si = new ProcessStartInfo(setup) { UseShellExecute = false, WorkingDirectory = cache };
|
||||
foreach (var arg in args) si.ArgumentList.Add(arg);
|
||||
Process.Start(si);
|
||||
Application.Current.Shutdown();
|
||||
}
|
||||
|
||||
/// The game in folder built again with the latest release: here when these tools are it (or fetched), else after the setup
|
||||
/// installed it (it starts the new builder with --update folder --tag t --fetched)
|
||||
public static async void UpdateFolder(MainWindow w, string folder, string? tag, bool fetched)
|
||||
{
|
||||
w.BeginUpdate(folder, tag);
|
||||
var tools = Tools.Find();
|
||||
if (tools == null)
|
||||
{
|
||||
w.DownloadFailed("The Hookshot tools were not found next to this app.");
|
||||
return;
|
||||
}
|
||||
// (just downloaded, but another release than asked for: the setup installed the release before it (GitHub's latest link lags
|
||||
// right after a publish), and building here kept players on the old version while the builder said it updated)
|
||||
if (fetched && tag != null && tools.Version != null && tools.Version != tag)
|
||||
{
|
||||
w.DownloadFailed($"The update installed {tools.Version}, not {tag}: GitHub's download links can lag right after a release. Try Update again in a few minutes.");
|
||||
return;
|
||||
}
|
||||
// (already the new release, or just downloaded: no second download)
|
||||
if (fetched || (tag != null && tools.Version == tag))
|
||||
{
|
||||
w.UpdateBuild(tools, folder);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
var token = w.DownloadToken;
|
||||
using var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd("HookshotBuilder");
|
||||
w.Note("Asking GitHub for the latest release");
|
||||
string? newTag = null, url = null, setupUrl = null;
|
||||
string? apiUrl = null, setupApiUrl = null;
|
||||
long size = 0, setupSize = 0;
|
||||
var hasList = false;
|
||||
using (var response = await GetWithRetries(w, http, Latest, token, "application/vnd.github+json", TimeSpan.FromSeconds(30)))
|
||||
using (var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token)))
|
||||
{
|
||||
newTag = doc.RootElement.GetProperty("tag_name").GetString();
|
||||
foreach (var asset in doc.RootElement.GetProperty("assets").EnumerateArray())
|
||||
{
|
||||
var assetName = asset.GetProperty("name").GetString();
|
||||
if (assetName == Asset)
|
||||
{
|
||||
url = asset.GetProperty("browser_download_url").GetString();
|
||||
apiUrl = asset.GetProperty("url").GetString();
|
||||
size = asset.GetProperty("size").GetInt64();
|
||||
}
|
||||
else if (assetName == SetupAsset)
|
||||
{
|
||||
setupUrl = asset.GetProperty("browser_download_url").GetString();
|
||||
setupApiUrl = asset.GetProperty("url").GetString();
|
||||
setupSize = asset.GetProperty("size").GetInt64();
|
||||
}
|
||||
else if (assetName == SetupList) hasList = true;
|
||||
}
|
||||
}
|
||||
if (newTag == null || (url == null && setupUrl == null)) throw new InvalidOperationException("The latest release has no " + Asset + ".");
|
||||
if (newTag == tools.Version)
|
||||
{
|
||||
w.UpdateBuild(tools, folder);
|
||||
return;
|
||||
}
|
||||
var name = string.Concat(newTag.Where(c => char.IsLetterOrDigit(c) || c == '-' || c == '_' || c == '.'));
|
||||
// (hookshot) the name is a folder under builders\ that the update replaces: "..", "." or a name with a leading dot
|
||||
// would be the HookshotBuilder folder itself or not a version (the same rule as the setup's and Linux's lists)
|
||||
if (name.Length == 0 || name.Length > 128 || name[0] == '.')
|
||||
throw new InvalidOperationException("The latest release's tag is not a version name.");
|
||||
var cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HookshotBuilder", "update");
|
||||
Directory.CreateDirectory(cache);
|
||||
// (a release with the setup and its list: the setup downloads only the parts that changed since the version installed (a few MB
|
||||
// when only the builder's code did), checks them and starts the new builder with these arguments. The whole zip is the fallback)
|
||||
if (setupUrl != null && hasList)
|
||||
{
|
||||
w.Note($"Downloading the update for {newTag}");
|
||||
var setup = Path.Combine(cache, SetupAsset);
|
||||
await DownloadWithRetries(w, http, setupUrl, setupApiUrl, setup, setupSize, token);
|
||||
var ssi = new ProcessStartInfo(setup) { UseShellExecute = false, WorkingDirectory = cache };
|
||||
foreach (var arg in new[] { "--update", folder, "--tag", newTag, "--fetched" }) ssi.ArgumentList.Add(arg);
|
||||
Process.Start(ssi);
|
||||
Application.Current.Shutdown();
|
||||
return;
|
||||
}
|
||||
if (url == null) throw new InvalidOperationException("The latest release has no " + Asset + ".");
|
||||
var zip = Path.Combine(cache, "HookshotBuilder-" + name + ".zip");
|
||||
w.Note($"Downloading {Asset} of {newTag} ({size >> 20} MB)");
|
||||
await DownloadWithRetries(w, http, url, apiUrl, zip, size, token, w.DownloadProgress);
|
||||
w.Note("Unpacking the new version");
|
||||
// (beside this app when that folder takes writing, else in the app data folder)
|
||||
var parent = Directory.GetParent(AppContext.BaseDirectory.TrimEnd('\\', '/'))!.FullName;
|
||||
string target;
|
||||
try
|
||||
{
|
||||
target = await Unpack(zip, Path.Combine(parent, "HookshotBuilder " + name));
|
||||
}
|
||||
catch (Exception e) when (e is UnauthorizedAccessException or IOException)
|
||||
{
|
||||
target = await Unpack(zip, Path.Combine(Path.GetDirectoryName(cache)!, "builders", name));
|
||||
}
|
||||
try { File.Delete(zip); } catch (Exception) { }
|
||||
var exe = Path.Combine(target, "HookshotBuilder.exe");
|
||||
if (!File.Exists(exe)) throw new FileNotFoundException("The download has no HookshotBuilder.exe (your antivirus may have removed it).");
|
||||
var si = new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = target };
|
||||
foreach (var arg in new[] { "--update", folder, "--tag", newTag, "--fetched" }) si.ArgumentList.Add(arg);
|
||||
Process.Start(si);
|
||||
Application.Current.Shutdown();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
w.DownloadFailed("The download was cancelled. Your game folder is unchanged.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
w.DownloadFailed(e.Message + " Your game folder is unchanged; you can also download the new version from GitHub yourself.");
|
||||
}
|
||||
}
|
||||
|
||||
static async Task<HttpResponseMessage> GetWithRetries(MainWindow w, HttpClient http, string url, CancellationToken token,
|
||||
string? accept = null, TimeSpan? timeout = null)
|
||||
{
|
||||
Exception? last = null;
|
||||
for (var attempt = 0; attempt <= RetryDelays.Length; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (accept != null) request.Headers.Accept.ParseAdd(accept);
|
||||
using var ask = timeout is null ? null : new CancellationTokenSource(timeout.Value);
|
||||
using var both = ask is null ? null : CancellationTokenSource.CreateLinkedTokenSource(token, ask.Token);
|
||||
var response = await http.SendAsync(request, HttpCompletionOption.ResponseContentRead, both?.Token ?? token);
|
||||
if (response.IsSuccessStatusCode) return response;
|
||||
|
||||
var failure = HttpFailure(response);
|
||||
response.Dispose();
|
||||
if (!IsTransient(failure)) throw failure;
|
||||
last = failure;
|
||||
}
|
||||
catch (OperationCanceledException e) when (!token.IsCancellationRequested && timeout is not null)
|
||||
{
|
||||
last = e;
|
||||
}
|
||||
catch (HttpRequestException e) when (IsTransient(e))
|
||||
{
|
||||
last = e;
|
||||
}
|
||||
|
||||
if (attempt == RetryDelays.Length) break;
|
||||
w.Note($"GitHub did not answer{StatusDetail(last)}. Retrying in {(int)RetryDelays[attempt].TotalSeconds} s...");
|
||||
await Task.Delay(RetryDelays[attempt], token);
|
||||
}
|
||||
throw new HttpRequestException($"GitHub's release API did not respond after {RetryDelays.Length + 1} attempts: {last?.Message}",
|
||||
last, (last as HttpRequestException)?.StatusCode);
|
||||
}
|
||||
|
||||
static async Task DownloadWithRetries(MainWindow w, HttpClient http, string url, string? apiUrl, string path, long size,
|
||||
CancellationToken token, Action<double>? progress = null)
|
||||
{
|
||||
Exception? last = null;
|
||||
for (var attempt = 0; attempt <= RetryDelays.Length; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await DownloadOnce(http, url, path, size, token, progress, apiAsset: false);
|
||||
return;
|
||||
}
|
||||
catch (Exception e) when (IsTransient(e))
|
||||
{
|
||||
last = e;
|
||||
if (apiUrl != null) w.Note($"Release download failed{StatusDetail(e)}; trying GitHub's API asset URL.");
|
||||
}
|
||||
|
||||
if (apiUrl != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await DownloadOnce(http, apiUrl, path, size, token, progress, apiAsset: true);
|
||||
return;
|
||||
}
|
||||
catch (Exception e) when (IsTransient(e))
|
||||
{
|
||||
last = e;
|
||||
}
|
||||
}
|
||||
|
||||
if (attempt == RetryDelays.Length) break;
|
||||
w.Note($"GitHub's download servers did not answer{StatusDetail(last)}. Retrying in {(int)RetryDelays[attempt].TotalSeconds} s...");
|
||||
await Task.Delay(RetryDelays[attempt], token);
|
||||
}
|
||||
throw new HttpRequestException($"GitHub's asset download failed after {RetryDelays.Length + 1} attempts: {last?.Message}",
|
||||
last, (last as HttpRequestException)?.StatusCode);
|
||||
}
|
||||
|
||||
static async Task DownloadOnce(HttpClient http, string url, string path, long size, CancellationToken token,
|
||||
Action<double>? progress, bool apiAsset)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (apiAsset) request.Headers.Accept.ParseAdd("application/octet-stream");
|
||||
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
|
||||
if (!response.IsSuccessStatusCode) throw HttpFailure(response);
|
||||
|
||||
var total = response.Content.Headers.ContentLength ?? size;
|
||||
await using var from = await response.Content.ReadAsStreamAsync(token);
|
||||
await using var to = File.Create(path);
|
||||
var buffer = new byte[1 << 20];
|
||||
long have = 0;
|
||||
var shown = DateTime.MinValue;
|
||||
int n;
|
||||
while (true)
|
||||
{
|
||||
try { n = await from.ReadAsync(buffer, token); }
|
||||
catch (IOException e) { throw new HttpRequestException("The download connection ended unexpectedly.", e); }
|
||||
if (n == 0) break;
|
||||
await to.WriteAsync(buffer.AsMemory(0, n), token);
|
||||
have += n;
|
||||
if (progress != null && total > 0 && DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(200))
|
||||
{
|
||||
shown = DateTime.UtcNow;
|
||||
progress(Math.Min(1.0, (double)have / total));
|
||||
}
|
||||
}
|
||||
if (total > 0 && have != total) throw new HttpRequestException($"The download ended early ({have >> 20} of {total >> 20} MB).");
|
||||
}
|
||||
|
||||
static HttpRequestException HttpFailure(HttpResponseMessage response) =>
|
||||
new($"GitHub returned HTTP {(int)response.StatusCode} ({response.ReasonPhrase}).", null, response.StatusCode);
|
||||
|
||||
static bool IsTransient(Exception error) =>
|
||||
error is HttpRequestException request && (request.StatusCode is null || (int)request.StatusCode >= 500);
|
||||
|
||||
static string StatusDetail(Exception? error) =>
|
||||
error is HttpRequestException { StatusCode: { } status } ? $" (HTTP {(int)status})" : "";
|
||||
|
||||
/// The zip's HookshotBuilder folder, as target (an older one there replaced)
|
||||
static async Task<string> Unpack(string zip, string target)
|
||||
{
|
||||
var part = target + ".part";
|
||||
if (Directory.Exists(part)) Directory.Delete(part, true);
|
||||
await Task.Run(() => ZipFile.ExtractToDirectory(zip, part));
|
||||
var inner = Path.Combine(part, "HookshotBuilder");
|
||||
if (Directory.Exists(target)) Directory.Delete(target, true);
|
||||
Directory.Move(Directory.Exists(inner) ? inner : part, target);
|
||||
if (Directory.Exists(part)) Directory.Delete(part, true);
|
||||
return target;
|
||||
}
|
||||
}
|
||||
16
builder/HookshotBuilder/app.manifest
Normal file
16
builder/HookshotBuilder/app.manifest
Normal file
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="HookshotBuilder.app"/>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
Reference in New Issue
Block a user