mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-19 16:20:01 -04:00
Triforce v0.2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
4
builder/.gitignore
vendored
Normal file
4
builder/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
bin/
|
||||
obj/
|
||||
.vs/
|
||||
*.user
|
||||
22
builder/HookshotBuilder.sln
Normal file
22
builder/HookshotBuilder.sln
Normal file
@@ -0,0 +1,22 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.14.0.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HookshotBuilder", "HookshotBuilder\HookshotBuilder.csproj", "{6F1C2D94-7A3B-4E58-9C11-2D4B8E0A7F31}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{6F1C2D94-7A3B-4E58-9C11-2D4B8E0A7F31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{6F1C2D94-7A3B-4E58-9C11-2D4B8E0A7F31}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6F1C2D94-7A3B-4E58-9C11-2D4B8E0A7F31}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6F1C2D94-7A3B-4E58-9C11-2D4B8E0A7F31}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
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>
|
||||
38
builder/linux/AppRun
Executable file
38
builder/linux/AppRun
Executable file
@@ -0,0 +1,38 @@
|
||||
#!/bin/sh
|
||||
# The Hookshot AppImage: the builder window (builder/linux/hookshot_builder.py) with everything it builds the game with -
|
||||
# Python and the tools, clang and lld, a glibc 2.35 sysroot, FFmpeg, SDL2 and the Vulkan back end, built already.
|
||||
# Hookshot.AppImage the builder window (Play is in the window, once a game is built)
|
||||
# Hookshot.AppImage --play start the game the builder saved, without opening the window
|
||||
# Hookshot.AppImage --play <folder> start the game in that folder
|
||||
# Hookshot.AppImage <folder> the same
|
||||
# Hookshot.AppImage --cli <args> nx2/make_game.py itself, e.g. --cli --nup game.nup --out ~/Games/Hookshot
|
||||
# Hookshot.AppImage --launch <dir> the game folder's launcher: Play, and Update when a newer release is out
|
||||
# Hookshot.AppImage --update <dir> download the new release (only the parts that changed) and build that folder again
|
||||
HERE="$(dirname "$(readlink -f "$0")")"
|
||||
LIB="$HERE/usr/lib/hookshot"
|
||||
export HOOKSHOT_TOOLS="$HERE/usr/share/hookshot"
|
||||
export EMSDK="$LIB/emsdk"
|
||||
export HOOKSHOT_SYSROOT="$LIB/sysroot"
|
||||
export HOOKSHOT_FFMPEG="$LIB/ffmpeg"
|
||||
export HOOKSHOT_VK_PREBUILT="$LIB/hookshot_vk.so"
|
||||
export HOOKSHOT_SDL2="$LIB/libSDL2-2.0.so.0"
|
||||
# (written into the game folder's hookshot_version.txt, so its launcher finds this builder)
|
||||
if [ -n "${APPIMAGE:-}" ]; then
|
||||
export HOOKSHOT_BUILDER_EXE="$APPIMAGE"
|
||||
else
|
||||
export HOOKSHOT_BUILDER_EXE="$HERE/AppRun"
|
||||
fi
|
||||
PY="$HERE/usr/python/bin/python3"
|
||||
if [ "${1:-}" = "--cli" ]; then
|
||||
shift
|
||||
exec "$PY" -I "$HOOKSHOT_TOOLS/nx2/make_game.py" "$@"
|
||||
fi
|
||||
# Play is the same AppImage: the start script drops this image's libraries, then runs the built game.
|
||||
if [ "${1:-}" = "--play" ]; then
|
||||
shift
|
||||
exec "$HOOKSHOT_TOOLS/builder/linux/hookshot-launch" "$@"
|
||||
fi
|
||||
if [ -n "${1:-}" ] && [ -d "$1" ]; then
|
||||
exec "$HOOKSHOT_TOOLS/builder/linux/hookshot-launch" "$1"
|
||||
fi
|
||||
exec "$PY" -I "$HOOKSHOT_TOOLS/builder/linux/hookshot_builder.py" "$@"
|
||||
14
builder/linux/hookshot-builder.desktop
Normal file
14
builder/linux/hookshot-builder.desktop
Normal file
@@ -0,0 +1,14 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Hookshot Builder
|
||||
Comment=Builds Ocarina of Time for PC from your own copy of the game
|
||||
Exec=AppRun
|
||||
Icon=hookshot
|
||||
Categories=Game;
|
||||
Terminal=false
|
||||
Actions=Play;
|
||||
|
||||
[Desktop Action Play]
|
||||
Name=Play
|
||||
Exec=AppRun --play
|
||||
Icon=hookshot
|
||||
42
builder/linux/hookshot-folder
Executable file
42
builder/linux/hookshot-folder
Executable file
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# The game folder's launcher, what hookshot.exe is on Windows: Play, and Update when a newer release is out.
|
||||
# The game itself is bin/hookshot. This file is copied to hookshot in the folder (nx2/make_game.py).
|
||||
#
|
||||
# It starts the builder installed by an update ($XDG_DATA_HOME/hookshot/builder), or the builder= line in
|
||||
# hookshot_version.txt (the AppImage that built the folder). With neither, it starts the game.
|
||||
set -eu
|
||||
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
|
||||
installed() {
|
||||
root=${HOOKSHOT_BUILDER_HOME:-${XDG_DATA_HOME:-$HOME/.local/share}}/hookshot/builder
|
||||
[ -f "$root/current" ] || return 1
|
||||
tag=$(tr -d ' \r\n' < "$root/current")
|
||||
[ -n "$tag" ] && [ -x "$root/versions/$tag/AppRun" ] || return 1
|
||||
printf '%s\n' "$root/versions/$tag/AppRun"
|
||||
}
|
||||
|
||||
builder_line() {
|
||||
[ -f "$HERE/hookshot_version.txt" ] || return 1
|
||||
path=
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
case $line in
|
||||
builder=*) path=${line#builder=} ;;
|
||||
esac
|
||||
done < "$HERE/hookshot_version.txt"
|
||||
[ -n "$path" ] && [ -x "$path" ] || return 1
|
||||
printf '%s\n' "$path"
|
||||
}
|
||||
|
||||
run=$(installed || true)
|
||||
if [ -z "$run" ]; then
|
||||
run=$(builder_line || true)
|
||||
fi
|
||||
if [ -n "$run" ]; then
|
||||
exec "$run" --launch "$HERE"
|
||||
fi
|
||||
if [ -x "$HERE/bin/hookshot" ]; then
|
||||
cd "$HERE"
|
||||
exec ./bin/hookshot
|
||||
fi
|
||||
echo "Hookshot: the game (bin/hookshot) is missing from this folder. Build it again with Hookshot Builder." >&2
|
||||
exit 1
|
||||
68
builder/linux/hookshot-launch
Executable file
68
builder/linux/hookshot-launch
Executable file
@@ -0,0 +1,68 @@
|
||||
#!/bin/sh
|
||||
# Start the game Hookshot Builder wrote, from that folder, without the AppImage's libraries.
|
||||
# The builder AppImage calls this for --play. The window's Play button does the same thing.
|
||||
#
|
||||
# hookshot-launch the out= folder in ~/.config/hookshot/builder.ini
|
||||
# hookshot-launch /path/to/the/game that folder
|
||||
# HOOKSHOT_LAUNCH_CONFIG=<file> read that ini instead (a test)
|
||||
set -eu
|
||||
|
||||
ini_path() {
|
||||
if [ -n "${HOOKSHOT_LAUNCH_CONFIG:-}" ]; then
|
||||
printf '%s\n' "$HOOKSHOT_LAUNCH_CONFIG"
|
||||
else
|
||||
printf '%s\n' "${XDG_CONFIG_HOME:-$HOME/.config}/hookshot/builder.ini"
|
||||
fi
|
||||
}
|
||||
|
||||
# the last out= line, as the builder keeps the last value it wrote
|
||||
out_of() {
|
||||
out=
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
case $line in
|
||||
out=*) out=${line#out=} ;;
|
||||
esac
|
||||
done < "$1"
|
||||
[ -n "$out" ] || return 1
|
||||
printf '%s\n' "$out"
|
||||
}
|
||||
|
||||
ready() {
|
||||
[ -n "${1:-}" ] && [ -f "$1/image.bin" ] && { [ -x "$1/bin/hookshot" ] || [ -f "$1/hookshot" ]; }
|
||||
}
|
||||
|
||||
folder=${1:-}
|
||||
if [ -z "$folder" ]; then
|
||||
ini=$(ini_path)
|
||||
if [ -f "$ini" ]; then
|
||||
folder=$(out_of "$ini") || folder=
|
||||
fi
|
||||
fi
|
||||
|
||||
if ! ready "$folder"; then
|
||||
echo "Hookshot: no built game to start. Build one with Hookshot Builder, or pass its folder." >&2
|
||||
# (HOOKSHOT_LAUNCH_CONFIG is a test: it must not open a dialog)
|
||||
if [ -z "${HOOKSHOT_LAUNCH_CONFIG:-}" ]; then
|
||||
if command -v zenity >/dev/null 2>&1; then
|
||||
zenity --error --title=Hookshot --text="No built game to start. Build one with Hookshot Builder first." || true
|
||||
elif command -v kdialog >/dev/null 2>&1; then
|
||||
kdialog --error "No built game to start. Build one with Hookshot Builder first." || true
|
||||
fi
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The AppImage runtime and the builder put their own libraries on the search path. The game loads
|
||||
# SDL from beside itself, so those names go before it starts. Same set as the builder's Play button.
|
||||
names=$(env | awk -F= '$1 ~ /^(HOOKSHOT_|PYTHON|APPDIR|APPIMAGE|ARGV0|OWD)/ || $1 == "LD_LIBRARY_PATH" { print $1 }')
|
||||
for name in $names; do
|
||||
unset "$name"
|
||||
done
|
||||
|
||||
cd "$folder"
|
||||
# (--play already chose Play. The game's own update question stays for a bin/hookshot the player started themselves)
|
||||
export HOOKSHOT_NO_UPDATE_CHECK=1
|
||||
if [ -x ./bin/hookshot ]; then
|
||||
exec ./bin/hookshot
|
||||
fi
|
||||
exec ./hookshot
|
||||
1208
builder/linux/hookshot_builder.py
Normal file
1208
builder/linux/hookshot_builder.py
Normal file
File diff suppressed because it is too large
Load Diff
546
builder/linux/linux_update.py
Normal file
546
builder/linux/linux_update.py
Normal file
@@ -0,0 +1,546 @@
|
||||
"""Linux builder updates, the same way Windows installs (builder/setup/setup.c, scripts/make_setup_parts.py).
|
||||
|
||||
A release publishes hookshot-linux.txt. Each part is a zip named by its SHA-256 and kept on the linux-parts release, so a
|
||||
part whose files did not change is not downloaded again. The player's copy lives at
|
||||
$XDG_DATA_HOME/hookshot/builder/versions/<tag> (AppRun at its root, the same layout as the AppImage). An unchanged part
|
||||
is copied from the builder that is running now (the mounted AppImage, or the version installed last time).
|
||||
|
||||
tag <tag>
|
||||
part <sha256> <bytes> <dir under the install> <url>
|
||||
tree the whole directory
|
||||
file <name> one file in that directory (repeat; instead of tree)
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
from part_links import SYSROOT_PART, is_absolute_link, relative_sysroot_link
|
||||
|
||||
LIST_NAME = "hookshot-linux.txt"
|
||||
LATEST_LIST = "https://github.com/NotRexed/Hookshot/releases/latest/download/" + LIST_NAME
|
||||
LATEST_API = "https://api.github.com/repos/NotRexed/Hookshot/releases/latest"
|
||||
|
||||
|
||||
class Part(object):
|
||||
def __init__(self, sha, size, dest, url, files):
|
||||
self.sha, self.size, self.dest, self.url, self.files = sha, size, dest, url, files # files None: the whole directory
|
||||
|
||||
def same(self, other):
|
||||
return other is not None and other.sha == self.sha and other.dest == self.dest and other.files == self.files
|
||||
|
||||
|
||||
class Manifest(object):
|
||||
def __init__(self, tag, parts):
|
||||
self.tag, self.parts = tag, parts
|
||||
|
||||
def by_sha(self, sha):
|
||||
for part in self.parts:
|
||||
if part.sha == sha:
|
||||
return part
|
||||
return None
|
||||
|
||||
|
||||
def data_root():
|
||||
base = os.environ.get("HOOKSHOT_BUILDER_HOME") or os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
|
||||
return os.path.join(base, "hookshot", "builder")
|
||||
|
||||
|
||||
def parse_list(text, local=True):
|
||||
"""The setup list. A part owns the following tree line, or the file lines, until the next part. local: a list from
|
||||
this PC (the tools' own, HOOKSHOT_LINUX_LIST), whose parts may be file:// links; a downloaded one's are https"""
|
||||
tag, parts, cur = "", [], None
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if line.startswith("tag "):
|
||||
tag = line[4:].strip()
|
||||
elif line.startswith("part "):
|
||||
bits = line.split(" ")
|
||||
if len(bits) != 5:
|
||||
raise ValueError("a part line needs sha, size, directory and url")
|
||||
cur = Part(bits[1], int(bits[2]), bits[3], bits[4], [])
|
||||
parts.append(cur)
|
||||
elif line == "tree":
|
||||
if cur is None:
|
||||
raise ValueError("tree with no part")
|
||||
cur.files = None
|
||||
elif line.startswith("file "):
|
||||
if cur is None or cur.files is None:
|
||||
raise ValueError("file with no part")
|
||||
cur.files.append(line[5:].strip())
|
||||
else:
|
||||
raise ValueError("unknown list line")
|
||||
if not tag or not parts:
|
||||
raise ValueError("the setup list has no release")
|
||||
# (the tag names a folder under versions/ that an update removes and remakes, and a part's names are paths in it:
|
||||
# they stay inside it)
|
||||
if not re.fullmatch(r"[0-9A-Za-z._+-]{1,128}", tag) or tag in (".", ".."):
|
||||
raise ValueError("the setup list's tag is not a version name")
|
||||
for part in parts:
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", part.sha) or not part.url.startswith(("https://", "file://") if local else "https://"):
|
||||
raise ValueError("a part line has a bad checksum or link")
|
||||
if part.dest != ".":
|
||||
_safe_name(part.dest)
|
||||
for name in part.files or ():
|
||||
_safe_name(name)
|
||||
return Manifest(tag, parts)
|
||||
|
||||
|
||||
def release_key(tag):
|
||||
"""A version to compare: a release tag (v2.0.5, v2.1.0-rc.1) or git describe's v2.0.5-3-g1a2b3c4[-dirty] (a build from
|
||||
the Actions tab or a checkout: after v2.0.5, before any later release). None for a build that names no release: a bare
|
||||
commit (digits alone too: no v and no dot), dev, or no version at all."""
|
||||
m = re.match(r"^(?=v|\d+\.)v?(\d+(?:\.\d+)*)(?:-(?!\d+-g|dirty$)([0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*))?(-\d+-g[0-9a-f]+)?(-dirty)?$",
|
||||
(tag or "").strip())
|
||||
if not m:
|
||||
return None
|
||||
# (a prerelease before its release; commits after a tag, or changes to it, after that tag and before the next)
|
||||
return tuple(int(n) for n in m.group(1).split(".")), m.group(2) is None, bool(m.group(3) or m.group(4))
|
||||
|
||||
|
||||
def update_target(latest, tools):
|
||||
"""The newest version this builder knows of: the latest release when it is newer than these tools, else the tools'
|
||||
own. (issue 902) Any version other than the latest release was made to update before it could build, so a test
|
||||
build from the Actions tab, newer than the release, was taken back to it. One made after an older release is still
|
||||
offered the newer one."""
|
||||
if not latest or not tools:
|
||||
return latest or tools
|
||||
have, out = release_key(tools), release_key(latest)
|
||||
return latest if have and out and out > have else tools
|
||||
|
||||
|
||||
def choose_mode(game, tools, latest, source_picked, kept):
|
||||
"""What the builder's button does. The same order as the Windows builder (MainWindow.RefreshMode): an older game
|
||||
that still has its files is updated, a game at the newest known release is played, and an older builder updates
|
||||
itself before a new build. latest None: GitHub did not answer, so the builder's own version is the newest known.
|
||||
Newest is update_target's: a builder that is not an older release is not made to update."""
|
||||
target = update_target(latest, tools)
|
||||
if kept and game and target and game != target and not source_picked:
|
||||
return "update-game"
|
||||
if game and not source_picked:
|
||||
return "up-to-date"
|
||||
if latest and tools and target != tools:
|
||||
return "update-builder"
|
||||
return "build"
|
||||
|
||||
|
||||
def tools_tag(root):
|
||||
"""The release these tools are, from the file a package writes (VERSION, or version.txt). A source checkout has neither."""
|
||||
if not root:
|
||||
return ""
|
||||
for rel in ("usr/share/hookshot/VERSION", "usr/share/hookshot/version.txt", "VERSION", "version.txt"):
|
||||
path = os.path.join(root, rel)
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
line = f.readline().strip()
|
||||
except OSError:
|
||||
continue
|
||||
if line:
|
||||
return line
|
||||
return ""
|
||||
|
||||
|
||||
def running_root():
|
||||
"""The AppDir that is running: the AppImage's mount, or an installed version (its AppRun beside usr/)."""
|
||||
appdir = os.environ.get("APPDIR")
|
||||
if appdir and os.path.isfile(os.path.join(appdir, "AppRun")):
|
||||
return appdir
|
||||
tools = os.environ.get("HOOKSHOT_TOOLS")
|
||||
if tools:
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(tools)))) # (<root>/usr/share/hookshot)
|
||||
if os.path.isfile(os.path.join(root, "AppRun")):
|
||||
return root
|
||||
return None
|
||||
|
||||
|
||||
def read_manifest(root):
|
||||
path = os.path.join(root, LIST_NAME) if root else ""
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return parse_list(f.read())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def game_version(folder):
|
||||
"""The release a folder was built with, when it still has the game files an update builds from."""
|
||||
if not folder:
|
||||
return None, False
|
||||
kept = os.path.isdir(os.path.join(folder, ".hookshot_exefs")) and os.path.isdir(os.path.join(folder, "romfs"))
|
||||
version = None
|
||||
try:
|
||||
with open(os.path.join(folder, "hookshot_version.txt"), encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if line.startswith("version="):
|
||||
version = line[8:].strip() or None
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
return version, kept
|
||||
|
||||
|
||||
def game_exe(folder):
|
||||
"""bin/hookshot under the launcher, or hookshot in a folder built before the launcher."""
|
||||
if not folder:
|
||||
return None
|
||||
nested = os.path.join(folder, "bin", "hookshot")
|
||||
if os.path.isfile(nested) and os.path.isfile(os.path.join(folder, "image.bin")):
|
||||
return nested
|
||||
flat = os.path.join(folder, "hookshot")
|
||||
if os.path.isfile(flat) and os.path.isfile(os.path.join(folder, "image.bin")):
|
||||
return flat
|
||||
return None
|
||||
|
||||
|
||||
MAX_DOWNLOAD = 4 << 30 # (no part or list is this big: a download that is stops there)
|
||||
|
||||
|
||||
def _read_at_most(response, limit):
|
||||
data = response.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise RuntimeError("the download is larger than expected")
|
||||
return data
|
||||
|
||||
|
||||
def _https(url):
|
||||
"""Only https links are fetched (never file:, ftp: or a plain http: link from a release's answer)."""
|
||||
if not isinstance(url, str) or not url.startswith("https://"):
|
||||
raise ValueError("not an https link: %r" % (url,))
|
||||
return url
|
||||
|
||||
|
||||
def _request(url, timeout, limit=MAX_DOWNLOAD):
|
||||
# (no second argument: Request's second is the POST body, and a str body failed every download before connecting)
|
||||
req = urllib.request.Request(_https(url), headers={"User-Agent": "Hookshot", "Accept": "application/vnd.github+json"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
return _read_at_most(response, limit)
|
||||
|
||||
|
||||
def _api_download(url):
|
||||
"""A GitHub release link that failed: the same file through the API (scripts/linux/deps.sh does this for 504s)."""
|
||||
prefix = "https://github.com/"
|
||||
mark = "/releases/download/"
|
||||
if not url.startswith(prefix) or mark not in url:
|
||||
return None
|
||||
repo, _, rest = url[len(prefix):].partition(mark)
|
||||
tag, _, name = rest.partition("/")
|
||||
if not repo or not tag or not name or "/" in name:
|
||||
return None
|
||||
info = _request("https://api.github.com/repos/%s/releases/tags/%s" % (repo, tag), 30)
|
||||
import json
|
||||
for asset in json.loads(info.decode("utf-8")).get("assets", []):
|
||||
if asset.get("name") == name:
|
||||
req = urllib.request.Request(_https(asset.get("url")), headers={
|
||||
"User-Agent": "Hookshot", "Accept": "application/octet-stream"})
|
||||
with urllib.request.urlopen(req, timeout=120) as response:
|
||||
return _read_at_most(response, MAX_DOWNLOAD)
|
||||
return None
|
||||
|
||||
|
||||
def fetch_bytes(url, timeout=60):
|
||||
"""The url's bytes. A GitHub download that the server fails (5xx) is tried again, then through the API."""
|
||||
delay, last = 2, "the download failed"
|
||||
for attempt in range(4):
|
||||
try:
|
||||
return _request(url, timeout)
|
||||
except urllib.error.HTTPError as error:
|
||||
last = "GitHub answered %s" % error.code
|
||||
if error.code < 500 and error.code != 429:
|
||||
break
|
||||
except Exception as error:
|
||||
last = str(error) or error.__class__.__name__
|
||||
if attempt < 3:
|
||||
time.sleep(delay)
|
||||
delay = min(delay * 2, 20)
|
||||
try:
|
||||
got = _api_download(url)
|
||||
except Exception as error:
|
||||
got = None
|
||||
last = str(error) or last
|
||||
if got is not None:
|
||||
return got
|
||||
raise RuntimeError(last)
|
||||
|
||||
|
||||
def latest_tag(get=None):
|
||||
"""The latest release's tag, or None when GitHub did not answer. The API first (60 an hour); the setup list's tag
|
||||
otherwise, which is a file download and not that limit. Same fallback as the Windows builder."""
|
||||
get = get or (lambda url: fetch_bytes(url, 8))
|
||||
try:
|
||||
import json
|
||||
body = json.loads(get(LATEST_API).decode("utf-8"))
|
||||
tag = body.get("tag_name")
|
||||
if tag:
|
||||
return tag
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
text = get(LATEST_LIST).decode("utf-8")
|
||||
return parse_list(text, local=False).tag
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _sha256(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _clone(src, dst, root, rooted_links=None):
|
||||
"""A copy of src at dst. A hard link when the two are on one disk (the installed copy); a real copy from the
|
||||
AppImage's mount, which does not link."""
|
||||
if os.path.islink(src):
|
||||
link_to = os.readlink(src)
|
||||
if rooted_links is not None and is_absolute_link(link_to):
|
||||
rooted_links.append((dst, link_to))
|
||||
else:
|
||||
_symlink(root, link_to, dst)
|
||||
return
|
||||
try:
|
||||
os.link(src, dst)
|
||||
return
|
||||
except OSError:
|
||||
shutil.copy2(src, dst)
|
||||
|
||||
|
||||
def _clone_tree(src, dst, rebase_sysroot=False, root=None):
|
||||
root = dst if root is None else root
|
||||
rooted_links = [] if rebase_sysroot else None
|
||||
for dirpath, dirnames, filenames in os.walk(src, followlinks=False):
|
||||
rel = os.path.relpath(dirpath, src)
|
||||
out = dst if rel == os.curdir else os.path.join(dst, rel)
|
||||
os.makedirs(out, exist_ok=True)
|
||||
kept = []
|
||||
for name in dirnames:
|
||||
link = os.path.join(dirpath, name)
|
||||
if os.path.islink(link):
|
||||
_clone(link, os.path.join(out, name), root, rooted_links)
|
||||
else:
|
||||
kept.append(name)
|
||||
dirnames[:] = kept
|
||||
for name in filenames:
|
||||
_clone(os.path.join(dirpath, name), os.path.join(out, name), root, rooted_links)
|
||||
if rooted_links is not None:
|
||||
_finish_sysroot_links(dst, rooted_links)
|
||||
|
||||
|
||||
def _safe_name(name):
|
||||
if not name or name.startswith("/") or ".." in name.split("/"):
|
||||
raise ValueError("the zip has a path outside its folder")
|
||||
return name
|
||||
|
||||
|
||||
def _check_part_directory(path):
|
||||
if os.path.realpath(path) != os.path.abspath(path):
|
||||
raise ValueError("the update would write through a symbolic link: %s" % path)
|
||||
|
||||
|
||||
def _symlink(root, link_to, target):
|
||||
# The whole staging tree is the boundary: a valid toolchain link may name a different part or a later entry.
|
||||
root = os.path.abspath(root)
|
||||
# (".." only at the start: "x/../.." is checked as written, but the system resolves x first, and x may be a link the
|
||||
# same zip or a later part makes, so the check and the system would disagree)
|
||||
parts = link_to.split("/")
|
||||
ups = 0
|
||||
while ups < len(parts) and parts[ups] == "..":
|
||||
ups += 1
|
||||
if ".." in parts[ups:]:
|
||||
raise ValueError("an update symlink climbs after a name: %s -> %s" % (target, link_to))
|
||||
destination = os.path.abspath(os.path.join(os.path.dirname(target), link_to))
|
||||
real_root = os.path.realpath(root)
|
||||
if (is_absolute_link(link_to) or os.path.commonpath((root, destination)) != root or
|
||||
os.path.commonpath((real_root, os.path.realpath(destination))) != real_root):
|
||||
raise ValueError("an update symlink leaves its staging folder: %s -> %s" % (target, link_to))
|
||||
os.symlink(link_to, target)
|
||||
|
||||
|
||||
def _finish_sysroot_links(dest, rooted_links):
|
||||
while rooted_links:
|
||||
pending = []
|
||||
for target, link_to in rooted_links:
|
||||
try:
|
||||
relative = relative_sysroot_link(dest, target, link_to)
|
||||
except FileNotFoundError:
|
||||
pending.append((target, link_to))
|
||||
continue
|
||||
_check_part_directory(os.path.dirname(target))
|
||||
os.symlink(relative, target)
|
||||
if len(pending) == len(rooted_links):
|
||||
raise ValueError("sysroot links have missing or circular targets: %s" %
|
||||
", ".join("%s -> %s" % (target, link_to) for target, link_to in pending))
|
||||
rooted_links = pending
|
||||
|
||||
|
||||
def _unpack(data, dest, files, rebase_sysroot=False, root=None):
|
||||
root = dest if root is None else root
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
rooted_links = []
|
||||
with zipfile.ZipFile(__import__("io").BytesIO(data)) as zipped:
|
||||
for info in zipped.infolist():
|
||||
name = _safe_name(info.filename)
|
||||
if not name or name.endswith("/"):
|
||||
continue
|
||||
if files is not None and name not in files:
|
||||
raise ValueError("the zip has %s, which this part does not list" % name)
|
||||
target = os.path.join(dest, name)
|
||||
parent = os.path.dirname(target)
|
||||
_check_part_directory(parent)
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
mode = info.external_attr >> 16
|
||||
if stat.S_ISLNK(mode):
|
||||
link_to = zipped.read(info).decode("utf-8")
|
||||
# Released sysroots contain /lib links rooted inside the sysroot; other parts must reject absolute links.
|
||||
if is_absolute_link(link_to):
|
||||
if not rebase_sysroot:
|
||||
raise ValueError("a zip symlink has an absolute target: %s -> %s" % (name, link_to))
|
||||
rooted_links.append((target, link_to))
|
||||
else:
|
||||
_symlink(root, link_to, target)
|
||||
else:
|
||||
# A part can ship symlinks, but cannot overwrite one (or any earlier entry).
|
||||
with open(target, "xb") as out:
|
||||
out.write(zipped.read(info))
|
||||
if mode & 0o777:
|
||||
# (the modes the parts are made with: no group- or world-writable files from a zip)
|
||||
os.chmod(target, 0o755 if mode & 0o111 else 0o644)
|
||||
_finish_sysroot_links(dest, rooted_links)
|
||||
|
||||
|
||||
def _place(part, source_root, source, dest_root, get, note):
|
||||
# Resolve installation parent links without following the staging directory itself.
|
||||
parent, staging = os.path.split(os.path.abspath(dest_root))
|
||||
staging_root = os.path.join(os.path.realpath(parent), staging)
|
||||
dest = os.path.join(staging_root, _safe_name(part.dest))
|
||||
_check_part_directory(dest)
|
||||
old = source.by_sha(part.sha) if source else None
|
||||
src = os.path.join(source_root, part.dest) if old and old.same(part) and source_root else ""
|
||||
ready = src and os.path.isdir(src) and (part.files is None or all(
|
||||
os.path.lexists(os.path.join(src, name)) for name in part.files))
|
||||
rebase_sysroot = part.dest == SYSROOT_PART
|
||||
if ready:
|
||||
note("Keeping %s (unchanged)" % part.dest)
|
||||
if part.files is None:
|
||||
_clone_tree(src, dest, rebase_sysroot, staging_root)
|
||||
else:
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
rooted_links = [] if rebase_sysroot else None
|
||||
for name in part.files:
|
||||
_clone(os.path.join(src, name), os.path.join(dest, name), staging_root, rooted_links)
|
||||
if rooted_links is not None:
|
||||
_finish_sysroot_links(dest, rooted_links)
|
||||
return
|
||||
note("Downloading %s (%d MB)" % (part.dest, part.size >> 20))
|
||||
data = get(part.url)
|
||||
if len(data) != part.size or _sha256(data) != part.sha:
|
||||
raise RuntimeError("%s did not download correctly (its checksum differs)" % part.dest)
|
||||
_unpack(data, dest, part.files, rebase_sysroot, staging_root)
|
||||
|
||||
|
||||
def _check_links_inside(dest):
|
||||
"""Every link in the finished staging tree resolves inside it, whatever order the parts made them in."""
|
||||
real = os.path.realpath(dest)
|
||||
for dirpath, dirnames, filenames in os.walk(dest, followlinks=False):
|
||||
for name in dirnames + filenames:
|
||||
path = os.path.join(dirpath, name)
|
||||
if os.path.islink(path) and os.path.commonpath((real, os.path.realpath(path))) != real:
|
||||
raise ValueError("an update symlink leaves its staging folder: %s" % path)
|
||||
|
||||
|
||||
def _finish_tree(dest):
|
||||
"""AppRun at the root, from the tools just installed, so this folder starts the way the AppImage does."""
|
||||
_check_links_inside(dest)
|
||||
for name in ("AppRun", "hookshot.png", "hookshot-builder.desktop"):
|
||||
if os.path.islink(os.path.join(dest, name)): # (written below: never through a link a part made)
|
||||
raise ValueError("the update has a link where %s goes" % name)
|
||||
tools = os.path.join(dest, "usr", "share", "hookshot")
|
||||
apprun = os.path.join(dest, "AppRun")
|
||||
shutil.copyfile(os.path.join(tools, "builder", "linux", "AppRun"), apprun)
|
||||
os.chmod(apprun, 0o755) # (rwxr-xr-x: the launcher must run; only its owner may change it)
|
||||
icon = os.path.join(tools, "assets", "hookshot.png")
|
||||
if os.path.isfile(icon):
|
||||
shutil.copyfile(icon, os.path.join(dest, "hookshot.png"))
|
||||
desktop = os.path.join(tools, "builder", "linux", "hookshot-builder.desktop")
|
||||
if os.path.isfile(desktop):
|
||||
shutil.copyfile(desktop, os.path.join(dest, "hookshot-builder.desktop"))
|
||||
return apprun
|
||||
|
||||
|
||||
def install(manifest, source_root, source, note=None, get=None):
|
||||
"""versions/<tag> from the list. Unchanged parts come from source_root. The new folder replaces nothing until it
|
||||
is complete, and the version installed before stays until this one is."""
|
||||
note = note or (lambda message: None)
|
||||
get = get or fetch_bytes
|
||||
root = data_root()
|
||||
versions = os.path.join(root, "versions")
|
||||
dest = os.path.join(versions, manifest.tag)
|
||||
partial = dest + ".part"
|
||||
if os.path.islink(partial):
|
||||
raise ValueError("the update staging folder is a symbolic link: %s" % partial)
|
||||
if os.path.isdir(partial):
|
||||
shutil.rmtree(partial)
|
||||
os.makedirs(versions, exist_ok=True)
|
||||
try:
|
||||
for part in manifest.parts:
|
||||
_place(part, source_root, source, partial, get, note)
|
||||
# The publisher keeps the list outside all hashed parts. Never follow or overwrite a part-supplied leaf.
|
||||
with open(os.path.join(partial, LIST_NAME), "x", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write("tag %s\n" % manifest.tag)
|
||||
for part in manifest.parts:
|
||||
handle.write("part %s %d %s %s\n" % (part.sha, part.size, part.dest, part.url))
|
||||
handle.write("tree\n" if part.files is None else "".join("file %s\n" % name for name in part.files))
|
||||
apprun = _finish_tree(partial)
|
||||
except Exception:
|
||||
shutil.rmtree(partial, ignore_errors=True)
|
||||
raise
|
||||
if os.path.isdir(dest):
|
||||
shutil.rmtree(dest)
|
||||
os.rename(partial, dest)
|
||||
current = os.path.join(root, "current")
|
||||
tmp = current + ".new"
|
||||
with open(tmp, "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(manifest.tag + "\n")
|
||||
os.replace(tmp, current)
|
||||
for name in os.listdir(versions):
|
||||
if name != manifest.tag:
|
||||
shutil.rmtree(os.path.join(versions, name), ignore_errors=True)
|
||||
return os.path.join(dest, "AppRun") if os.path.isfile(os.path.join(dest, "AppRun")) else apprun
|
||||
|
||||
|
||||
def installed_apprun():
|
||||
root = data_root()
|
||||
try:
|
||||
with open(os.path.join(root, "current"), encoding="utf-8") as handle:
|
||||
tag = handle.read().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
path = os.path.join(root, "versions", tag, "AppRun")
|
||||
return path if tag and os.path.isfile(path) else ""
|
||||
|
||||
|
||||
def fetch_manifest(get=None):
|
||||
get = get or (lambda url: fetch_bytes(url, 30))
|
||||
override = os.environ.get("HOOKSHOT_LINUX_LIST")
|
||||
if override:
|
||||
with open(override, encoding="utf-8") as handle:
|
||||
return parse_list(handle.read())
|
||||
return parse_list(get(LATEST_LIST).decode("utf-8"), local=False)
|
||||
|
||||
|
||||
def startup_manifest(root, get=None):
|
||||
"""The list begin_update installs on launch: the latest release, except when these tools ship a list of their own
|
||||
that is that same release and no older than it (a self-contained -rc or Actions tab AppImage). Reinstalling an
|
||||
older release's parts over those tools replaces files the working tools had (issue 990: a -rc shipped
|
||||
gpu/vk/oot_cheat_items.h, the release's zip did not, and every launch lost it). The comparison is update_target's:
|
||||
a builder that is not an older release still updates. A HOOKSHOT_LINUX_LIST is a deliberate override: it wins."""
|
||||
latest = fetch_manifest(get)
|
||||
if not os.environ.get("HOOKSHOT_LINUX_LIST"):
|
||||
own = read_manifest(root)
|
||||
if own and own.tag == tools_tag(root) and update_target(latest.tag, own.tag) == own.tag:
|
||||
return own
|
||||
return latest
|
||||
26
builder/linux/part_links.py
Normal file
26
builder/linux/part_links.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""Safe handling of the rooted links in Linux sysroot update parts."""
|
||||
import os
|
||||
|
||||
|
||||
SYSROOT_PART = "usr/lib/hookshot/sysroot"
|
||||
|
||||
|
||||
def is_absolute_link(target):
|
||||
return target.startswith("/") or os.path.isabs(target)
|
||||
|
||||
|
||||
def relative_sysroot_link(root, link, target):
|
||||
"""Rebase a sysroot-absolute link onto an existing target within the same sysroot."""
|
||||
if not target.startswith("/") or target.startswith("//"):
|
||||
raise ValueError("not a rooted Linux sysroot link: %s -> %s" % (link, target))
|
||||
root = os.path.abspath(root)
|
||||
destination = os.path.abspath(os.path.join(root, target.lstrip("/")))
|
||||
if os.path.commonpath((root, destination)) != root:
|
||||
raise ValueError("a sysroot link leaves its root: %s -> %s" % (link, target))
|
||||
real_root = os.path.realpath(root)
|
||||
real_destination = os.path.realpath(destination)
|
||||
if os.path.commonpath((real_root, real_destination)) != real_root:
|
||||
raise ValueError("a sysroot link resolves outside its root: %s -> %s" % (link, target))
|
||||
if not os.path.exists(destination):
|
||||
raise FileNotFoundError("a sysroot link target is missing: %s -> %s" % (link, target))
|
||||
return os.path.relpath(destination, os.path.dirname(link))
|
||||
49
builder/msi/HookshotBuilder.wxs
Normal file
49
builder/msi/HookshotBuilder.wxs
Normal file
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The Windows installer (MSI) around HookshotBuilder.exe (builder/setup/setup.c), for players whose antivirus or SmartScreen
|
||||
treats a bare downloaded exe with more suspicion than an installer package. Per-user (no administrator rights): it puts the
|
||||
setup in %LOCALAPPDATA%\Programs\Hookshot Builder, adds a Start menu entry and starts the setup when it finishes, which installs
|
||||
or updates the builder as HookshotBuilder.exe does. Uninstalling removes the entry and the setup exe.
|
||||
Built with WiX 5 (MS-RL): wix build -arch x64 -d Version=<x.y.z> -d SetupExe=<path> HookshotBuilder.wxs -o HookshotBuilder.msi -->
|
||||
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs">
|
||||
<Package Name="Hookshot Builder" Manufacturer="Hookshot" Version="$(var.Version)" Scope="perUser"
|
||||
UpgradeCode="{6E1A0C2B-6B2F-4C8E-9D35-2F2B8F0D7A41}" Language="1033" Compressed="yes">
|
||||
<SummaryInformation Description="Hookshot Builder installer" />
|
||||
<MajorUpgrade DowngradeErrorMessage="A newer Hookshot Builder installer is already installed." />
|
||||
<MediaTemplate EmbedCab="yes" />
|
||||
<Icon Id="HookshotIcon" SourceFile="../setup/hookshot.ico" />
|
||||
<Property Id="ARPPRODUCTICON" Value="HookshotIcon" />
|
||||
<Property Id="ARPURLINFOABOUT" Value="https://github.com/NotRexed/Hookshot" />
|
||||
|
||||
<StandardDirectory Id="LocalAppDataFolder">
|
||||
<Directory Id="ProgramsDir" Name="Programs">
|
||||
<Directory Id="INSTALLFOLDER" Name="Hookshot Builder">
|
||||
<Component Id="SetupExe" Guid="{B4A7E0C9-3D61-4F0A-8C2E-5A9D17E3C6F2}">
|
||||
<File Id="SetupExeFile" Source="$(var.SetupExe)" Name="HookshotBuilder.exe" />
|
||||
<RegistryValue Root="HKCU" Key="Software\Hookshot\Builder" Name="Installer" Type="string" Value="[INSTALLFOLDER]" KeyPath="yes" />
|
||||
<RemoveFolder Id="RemoveInstallFolder" On="uninstall" />
|
||||
<RemoveFolder Id="RemoveProgramsDir" Directory="ProgramsDir" On="uninstall" />
|
||||
</Component>
|
||||
</Directory>
|
||||
</Directory>
|
||||
</StandardDirectory>
|
||||
|
||||
<StandardDirectory Id="ProgramMenuFolder">
|
||||
<Component Id="StartMenuEntry" Guid="{1F9C2D74-8E35-4B6A-A0D3-7C5E2B91F8A6}">
|
||||
<Shortcut Id="StartMenuShortcut" Name="Hookshot Builder" Description="Build and update Hookshot"
|
||||
Target="[INSTALLFOLDER]HookshotBuilder.exe" WorkingDirectory="INSTALLFOLDER" Icon="HookshotIcon" />
|
||||
<RegistryValue Root="HKCU" Key="Software\Hookshot\Builder" Name="StartMenu" Type="integer" Value="1" KeyPath="yes" />
|
||||
</Component>
|
||||
</StandardDirectory>
|
||||
|
||||
<Feature Id="Main" Title="Hookshot Builder">
|
||||
<ComponentRef Id="SetupExe" />
|
||||
<ComponentRef Id="StartMenuEntry" />
|
||||
</Feature>
|
||||
|
||||
<!-- (the setup starts once the install is done, as running HookshotBuilder.exe would) -->
|
||||
<CustomAction Id="StartSetup" FileRef="SetupExeFile" ExeCommand="" Return="asyncNoWait" Impersonate="yes" Execute="immediate" />
|
||||
<InstallExecuteSequence>
|
||||
<Custom Action="StartSetup" After="InstallFinalize" Condition="NOT Installed AND NOT REMOVE" />
|
||||
</InstallExecuteSequence>
|
||||
</Package>
|
||||
</Wix>
|
||||
57
builder/py/gen_strings.py
Normal file
57
builder/py/gen_strings.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""Writes hookshot_builder/strings.py from builder/HookshotBuilder/Strings.cs (the WPF builder's languages): the same text, the same
|
||||
order. Run again whenever Strings.cs changes: python -I builder/py/gen_strings.py"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
src = open(os.path.join(HERE, "..", "HookshotBuilder", "Strings.cs"), encoding="utf-8").read()
|
||||
enum = re.search(r"enum S\s*\{(.*?)\}", src, re.S).group(1)
|
||||
keys = [k.strip() for k in re.sub(r"//.*", "", enum).replace("\n", " ").split(",") if k.strip()]
|
||||
arrays = {}
|
||||
for m in re.finditer(r"static readonly string\[\] (\w+) =\s*\{(.*?)\n \};", src, re.S):
|
||||
arrays[m.group(1)] = [json.loads('"' + s + '"') for s in re.findall(r'"((?:[^"\\]|\\.)*)"', m.group(2))]
|
||||
langs = re.findall(r'new\("([^"]+)", "([^"]+)", (\w+)\)', src)
|
||||
|
||||
out = ['"""The builder\'s languages, generated by gen_strings.py from builder/HookshotBuilder/Strings.cs: one of the game\'s languages',
|
||||
'is its code in language.txt, its own name, and the app\'s text in it. Do not edit by hand."""',
|
||||
"", "KEYS = " + repr(keys), "", "TEXT = {"]
|
||||
for name, arr in arrays.items():
|
||||
out.append(" %r: %s," % (name, json.dumps(arr, ensure_ascii=False)))
|
||||
out += ["}", "", "LANGUAGES = [ # (code, its own name, the TEXT it uses)"]
|
||||
out += [" (%r, %r, %r)," % l for l in langs]
|
||||
out += ["]", ""]
|
||||
out.append('''
|
||||
|
||||
def text(lang, key):
|
||||
"""A string in the language (a LANGUAGES entry), English where it has none (the update's lines are English only)"""
|
||||
i = KEYS.index(key)
|
||||
arr = TEXT[lang[2]]
|
||||
return arr[i] if i < len(arr) else TEXT["En"][i]
|
||||
|
||||
|
||||
def default_language():
|
||||
"""The language closest to Windows' own: the exact one, then the same family, else English (US)"""
|
||||
name = ""
|
||||
try:
|
||||
import ctypes
|
||||
buf = ctypes.create_unicode_buffer(85)
|
||||
if ctypes.windll.kernel32.GetUserDefaultLocaleName(buf, 85):
|
||||
name = buf.value
|
||||
except Exception:
|
||||
pass
|
||||
for lang in LANGUAGES:
|
||||
if lang[0].lower() == name.lower():
|
||||
return lang
|
||||
if name.startswith("zh"):
|
||||
pick = "zh-Hant" if any(t in name for t in ("TW", "HK", "Hant")) else "zh-Hans"
|
||||
elif name.startswith("es-") and name != "es-ES":
|
||||
pick = "es-419"
|
||||
elif name.startswith("pt"):
|
||||
pick = "pt-BR"
|
||||
else:
|
||||
pick = name.split("-")[0]
|
||||
return next((lang for lang in LANGUAGES if lang[0] == pick), LANGUAGES[0])
|
||||
''')
|
||||
open(os.path.join(HERE, "hookshot_builder", "strings.py"), "w", encoding="utf-8", newline="\n").write("\n".join(out))
|
||||
print(len(keys), "keys;", {k: len(v) for k, v in arrays.items()}, len(langs), "languages")
|
||||
6
builder/py/hookshot_builder/__init__.py
Normal file
6
builder/py/hookshot_builder/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""Hookshot Builder, in Python: the same window as the WPF builder (builder/HookshotBuilder), run by python.org's own python.exe and
|
||||
Qt's DLLs (both signed by their makers), with no executable of Hookshot's own to download. It also does what the setup exe did
|
||||
(builder/setup/setup.c): it reads a release's hookshot-setup.txt, downloads the parts it names, checks each one's SHA-256 and
|
||||
unpacks them into %LOCALAPPDATA%\\HookshotBuilder\\versions\\<tag>."""
|
||||
APP_ID = "NotRexed.Hookshot.Builder" # (Windows' AppUserModelID: the taskbar groups and shows the window as Hookshot, not Python)
|
||||
REPO = "NotRexed/Hookshot"
|
||||
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Bold.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Bold.ttf
Normal file
Binary file not shown.
92
builder/py/hookshot_builder/assets/Fonts/Inter-LICENSE.txt
Normal file
92
builder/py/hookshot_builder/assets/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/py/hookshot_builder/assets/Fonts/Inter-Medium.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Medium.ttf
Normal file
Binary file not shown.
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Regular.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Regular.ttf
Normal file
Binary file not shown.
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-SemiBold.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-SemiBold.ttf
Normal file
Binary file not shown.
BIN
builder/py/hookshot_builder/assets/hookshot.ico
Normal file
BIN
builder/py/hookshot_builder/assets/hookshot.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 71 KiB |
BIN
builder/py/hookshot_builder/assets/hookshot.png
Normal file
BIN
builder/py/hookshot_builder/assets/hookshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 54 KiB |
557
builder/py/hookshot_builder/core.py
Normal file
557
builder/py/hookshot_builder/core.py
Normal file
@@ -0,0 +1,557 @@
|
||||
"""What the WPF builder's Runner.cs, Storage.cs, Finder.cs and BuildWorkers.cs do, the same rules: the build tools, nx2/make_game.py as a
|
||||
child process, what the builder keeps on the PC, the game files found on it, and the game's shortcuts."""
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import string
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
|
||||
from . import paths
|
||||
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
|
||||
|
||||
|
||||
# ---------------- the build tools (Runner.cs: Tools) ----------------
|
||||
|
||||
class Tools:
|
||||
"""Where nx2/make_game.py and its Python are: the installed version's tools, or the source tree this app sits in"""
|
||||
|
||||
def __init__(self, root, python, python_args=None):
|
||||
self.root, self.python, self.python_args = root, python, python_args or []
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
"""Which release these tools are (tools/version.txt, written when the release is packed); None from the source tree"""
|
||||
return paths.read_small(os.path.join(self.root, "version.txt")) or None
|
||||
|
||||
@staticmethod
|
||||
def find():
|
||||
from . import setup_parts
|
||||
env = os.environ.get("HOOKSHOT_TOOLS") # (development: these tools)
|
||||
cands = [env] if env else []
|
||||
cur = setup_parts.current()
|
||||
if cur:
|
||||
cands.append(os.path.join(cur, "HookshotBuilder", "tools"))
|
||||
for c in cands:
|
||||
if c and os.path.isfile(os.path.join(c, "nx2", "make_game.py")):
|
||||
py = os.path.join(c, "python", "python.exe")
|
||||
return Tools(c, py if os.path.isfile(py) else "python")
|
||||
d = paths.APP_DIR
|
||||
while True: # (a source checkout: builder/py/hookshot_builder in it)
|
||||
if os.path.isfile(os.path.join(d, "nx2", "make_game.py")):
|
||||
return Tools(d, sys.executable)
|
||||
up = os.path.dirname(d)
|
||||
if up == d:
|
||||
return None
|
||||
d = up
|
||||
|
||||
|
||||
def build_env(tools, workers=None, ngx_sdk=None):
|
||||
env = dict(os.environ)
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
if workers:
|
||||
env["HOOKSHOT_JOBS"] = str(int(workers))
|
||||
# (written into the game folder's hookshot_version.txt: the game starts this app again to update, host/hos_update.c)
|
||||
exe, args = paths.launcher_command()
|
||||
env["HOOKSHOT_BUILDER_EXE"] = exe
|
||||
env["HOOKSHOT_BUILDER_ARGS"] = subprocess.list2cmdline(args)
|
||||
# (NVIDIA DLSS: only when ticked. Without it, one set on the PC is not passed on either)
|
||||
if ngx_sdk:
|
||||
env["HOOKSHOT_NGX_SDK"] = ngx_sdk
|
||||
else:
|
||||
env.pop("HOOKSHOT_NGX_SDK", None)
|
||||
for name, folder in (("EMSDK", "emsdk"), ("RX_CPM", "cpm"), ("WGPU_NATIVE", "wgpu-native")):
|
||||
p = os.path.join(tools.root, folder)
|
||||
if os.path.isdir(p):
|
||||
env[name] = p
|
||||
return env
|
||||
|
||||
|
||||
def build_command(tools, args):
|
||||
return [tools.python, *tools.python_args, "-I", os.path.join(tools.root, "nx2", "make_game.py"), *args]
|
||||
|
||||
|
||||
class Runner:
|
||||
"""nx2/make_game.py as a child process: its lines as they come (on_line, from a worker thread), and how it ended (on_finished:
|
||||
None, "cancelled", or why it stopped)"""
|
||||
|
||||
def __init__(self, tools, args, workers=None, ngx_sdk=None, on_line=None, on_finished=None):
|
||||
if workers is not None and workers <= 0:
|
||||
raise ValueError("Build workers must be positive.")
|
||||
self.tools, self.args, self.workers, self.ngx_sdk = tools, args, workers, ngx_sdk
|
||||
self.on_line, self.on_finished = on_line or (lambda l: None), on_finished or (lambda f: None)
|
||||
self.process, self.error, self.cancelled = None, None, False
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._run, daemon=True).start()
|
||||
|
||||
def _run(self):
|
||||
try:
|
||||
p = subprocess.Popen(build_command(self.tools, self.args), cwd=self.tools.root,
|
||||
env=build_env(self.tools, self.workers, self.ngx_sdk), stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, stdin=subprocess.DEVNULL,
|
||||
creationflags=CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS)
|
||||
except OSError as e:
|
||||
self.on_finished("The build tools could not start: %s" % e)
|
||||
return
|
||||
self.process = p
|
||||
|
||||
def errs():
|
||||
for raw in p.stderr:
|
||||
self.on_line(raw.decode("utf-8", "replace").rstrip("\r\n"))
|
||||
threading.Thread(target=errs, daemon=True).start()
|
||||
for raw in p.stdout:
|
||||
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
||||
if line.startswith("@@error "):
|
||||
self.error = line[8:]
|
||||
self.on_line(line)
|
||||
p.wait()
|
||||
self.on_finished("cancelled" if self.cancelled else None if p.returncode == 0 else
|
||||
self.error or "The build tools stopped without saying why. See the details.")
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
p = self.process
|
||||
if p and p.poll() is None: # (the whole tree: the compilers it started too)
|
||||
subprocess.run(["taskkill", "/T", "/F", "/PID", str(p.pid)], capture_output=True, creationflags=CREATE_NO_WINDOW)
|
||||
|
||||
|
||||
def check(tools, args):
|
||||
"""Is this the supported game and version? (ok, the answer in plain words)"""
|
||||
try:
|
||||
p = subprocess.run(build_command(tools, args), cwd=tools.root, env=build_env(tools), capture_output=True,
|
||||
stdin=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
|
||||
except OSError:
|
||||
if tools.python == "python" and os.path.isdir(os.path.join(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, then try again.")
|
||||
return False, "Python 3 was not found. Install it from python.org (not the Microsoft Store build)."
|
||||
result, answered = (False, "The game files could not be read."), False
|
||||
for line in p.stdout.decode("utf-8", "replace").splitlines():
|
||||
if line.startswith("@@check ok "):
|
||||
result, answered = (True, line[11:]), True
|
||||
elif line.startswith("@@check bad "):
|
||||
result, answered = (False, line[12:]), True
|
||||
elif line.startswith("@@error "):
|
||||
result, answered = (False, line[8:]), True
|
||||
if not answered:
|
||||
errs = [l for l in p.stderr.decode("utf-8", "replace").splitlines() if l.strip()]
|
||||
last = errs[-1] if errs else None
|
||||
if last and "microsoft store" in last.lower():
|
||||
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).")
|
||||
return False, last or "The game tools stopped without saying why (exit code %d)." % p.returncode
|
||||
return result
|
||||
|
||||
|
||||
# ---------------- build workers (BuildWorkers.cs) ----------------
|
||||
|
||||
AUTOMATIC = "Automatic"
|
||||
|
||||
|
||||
def worker_choices():
|
||||
return [AUTOMATIC] + list(range(1, max(1, os.cpu_count() or 1) + 1))
|
||||
|
||||
|
||||
# ---------------- what the builder keeps on the PC (Storage.cs) ----------------
|
||||
|
||||
BUILD_FILES_BYTES = 4 << 30
|
||||
|
||||
|
||||
def keep_build_files():
|
||||
v = os.environ.get("HOOKSHOT_KEEP_BUILD_FILES", "")
|
||||
return bool(v) and v != "0"
|
||||
|
||||
|
||||
def _same(a, b):
|
||||
return os.path.normcase(os.path.abspath(a)).rstrip("\\/") == os.path.normcase(os.path.abspath(b)).rstrip("\\/")
|
||||
|
||||
|
||||
def work():
|
||||
"""Where builds keep their files: the folder the player chose (work.txt), else the builder's own"""
|
||||
chosen = paths.read_small(os.path.join(paths.base(), "work.txt"))
|
||||
return chosen if len(chosen) > 2 and os.path.isabs(chosen) else paths.base()
|
||||
|
||||
|
||||
def work_chosen():
|
||||
return not _same(work(), paths.base())
|
||||
|
||||
|
||||
def ngx_sdk():
|
||||
return os.path.join(paths.base(), "ngx-sdk")
|
||||
|
||||
|
||||
WORK_PARTS = ("objcache", "sa", "exefs", "probe", "image", "system_headers.txt", "hot_funcs.txt", "hot_order.txt",
|
||||
"hookshot_pieces.prof", "hookshot.res")
|
||||
|
||||
|
||||
def _delete(p):
|
||||
try:
|
||||
if os.path.isdir(p):
|
||||
shutil.rmtree(p)
|
||||
elif os.path.isfile(p):
|
||||
os.remove(p)
|
||||
except OSError:
|
||||
shutil.rmtree(p, ignore_errors=True) if os.path.isdir(p) else None
|
||||
|
||||
|
||||
def move_work(picked):
|
||||
"""The build files go to a folder of their own in the one the player picked (None: back to the builder's own); what the last
|
||||
builds left at the old place goes"""
|
||||
old = work()
|
||||
to = paths.base() if picked is None else os.path.join(picked, "Hookshot build files")
|
||||
if _same(old, to):
|
||||
return
|
||||
os.makedirs(to, exist_ok=True)
|
||||
os.makedirs(paths.base(), exist_ok=True)
|
||||
if picked is None:
|
||||
try:
|
||||
os.remove(os.path.join(paths.base(), "work.txt"))
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
paths.write_small(os.path.join(paths.base(), "work.txt"), to)
|
||||
for n in WORK_PARTS:
|
||||
_delete(os.path.join(old, n))
|
||||
if not _same(old, paths.base()):
|
||||
try:
|
||||
os.rmdir(old)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _kept_version(d):
|
||||
from . import setup_parts
|
||||
cur = setup_parts.current()
|
||||
return bool(cur) and _same(cur, d)
|
||||
|
||||
|
||||
def freeable(after_build=False):
|
||||
for d in (("sa", "exefs", "probe") if after_build else ("objcache", "sa", "exefs", "probe")):
|
||||
yield os.path.join(work(), d)
|
||||
for d in ("downloads", "update"):
|
||||
yield os.path.join(paths.base(), d)
|
||||
v = paths.versions()
|
||||
if os.path.isdir(v):
|
||||
for name in os.listdir(v):
|
||||
p = os.path.join(v, name)
|
||||
if os.path.isdir(p) and not _kept_version(p):
|
||||
yield p
|
||||
|
||||
|
||||
def _size(d, seen):
|
||||
n = 0
|
||||
for root, _dirs, files in os.walk(d):
|
||||
for f in files:
|
||||
try:
|
||||
st = os.stat(os.path.join(root, f))
|
||||
except OSError:
|
||||
continue
|
||||
if not st.st_size:
|
||||
continue
|
||||
if st.st_nlink > 1: # (an object hard-linked in both sa\build and objcache counted once)
|
||||
key = (st.st_dev, st.st_ino)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
n += st.st_size
|
||||
return n
|
||||
|
||||
|
||||
def measure():
|
||||
"""(bytes in the builder's folder and the build files folder, bytes Free lets go)"""
|
||||
seen = set()
|
||||
free = sum(_size(d, seen) for d in freeable())
|
||||
seen = set()
|
||||
total = _size(paths.base(), seen) + (_size(work(), seen) if work_chosen() else 0)
|
||||
return max(total, free), free
|
||||
|
||||
|
||||
def free(after_build=False):
|
||||
"""Lets go of what measure counts as freeable; returns the bytes it could not delete (a file in use)"""
|
||||
for d in list(freeable(after_build)):
|
||||
_delete(d)
|
||||
if not after_build:
|
||||
_delete(os.path.join(work(), "system_headers.txt"))
|
||||
return measure()[1]
|
||||
seen = set()
|
||||
return sum(_size(d, seen) for d in freeable(True))
|
||||
|
||||
|
||||
def gb(n):
|
||||
return "%.1f GB" % (n / (1 << 30)) if n >= 1 << 30 else "%d MB" % (n >> 20)
|
||||
|
||||
|
||||
def free_space(path):
|
||||
try:
|
||||
root = os.path.splitdrive(os.path.abspath(path))[0] + "\\"
|
||||
return root, shutil.disk_usage(root).free
|
||||
except OSError:
|
||||
return None, None
|
||||
|
||||
|
||||
def spinning(path):
|
||||
"""True on a hard drive, False on an SSD, None when the drive cannot be told (Disk.cs's IOCTL: the volume's seek penalty).
|
||||
A build reads and writes tens of gigabytes, and an SSD makes that much faster: a warning only, never a stop."""
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
root = os.path.splitdrive(os.path.abspath(os.path.expanduser(path)))[0]
|
||||
if not root:
|
||||
return None
|
||||
|
||||
class Query(ctypes.Structure):
|
||||
_fields_ = [("PropertyId", wintypes.DWORD), ("QueryType", wintypes.DWORD), ("Additional", wintypes.DWORD)]
|
||||
|
||||
class SeekPenalty(ctypes.Structure):
|
||||
_fields_ = [("Version", wintypes.DWORD), ("Size", wintypes.DWORD), ("IncursSeekPenalty", ctypes.c_ubyte)]
|
||||
|
||||
k = ctypes.windll.kernel32
|
||||
k.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p,
|
||||
wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
|
||||
k.CreateFileW.restype = wintypes.HANDLE
|
||||
k.DeviceIoControl.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD,
|
||||
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
|
||||
k.DeviceIoControl.restype = wintypes.BOOL
|
||||
k.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
handle = k.CreateFileW("\\\\.\\" + root, 0, 0x1 | 0x2, None, 3, 0, None) # (read + write share, OPEN_EXISTING)
|
||||
if not handle or handle == wintypes.HANDLE(-1).value:
|
||||
return None
|
||||
try:
|
||||
query, answer, returned = Query(7, 0, 0), SeekPenalty(), wintypes.DWORD()
|
||||
ok = k.DeviceIoControl(handle, 0x002D1400, ctypes.byref(query), ctypes.sizeof(query), ctypes.byref(answer),
|
||||
ctypes.sizeof(answer), ctypes.byref(returned), None)
|
||||
if not ok or returned.value < ctypes.sizeof(answer):
|
||||
return None
|
||||
return bool(answer.IncursSeekPenalty)
|
||||
finally:
|
||||
k.CloseHandle(handle)
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
# ---------------- the player's game files (Finder.cs) ----------------
|
||||
|
||||
class Dump:
|
||||
def __init__(self, path, where, size, modified):
|
||||
self.path, self.where, self.size, self.modified = path, where, size, modified
|
||||
|
||||
|
||||
def _known_folder(fid):
|
||||
buf = ctypes.c_wchar_p()
|
||||
guid = (ctypes.c_byte * 16).from_buffer_copy(fid)
|
||||
if ctypes.windll.shell32.SHGetKnownFolderPath(guid, 0, None, ctypes.byref(buf)) == 0:
|
||||
p = buf.value
|
||||
ctypes.windll.ole32.CoTaskMemFree(buf)
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _guid(s):
|
||||
import uuid
|
||||
return uuid.UUID(s).bytes_le
|
||||
|
||||
|
||||
FOLDER_DESKTOP = _guid("B4BFCC3A-DB2C-424C-B029-7FE99A87C641")
|
||||
FOLDER_DOCUMENTS = _guid("FDD39AD0-238F-46AF-ADB4-6C85480369C7")
|
||||
FOLDER_DOWNLOADS = _guid("374DE290-123F-4565-9164-39C4925E467B")
|
||||
FOLDER_PROGRAMS = _guid("A77F5D77-2E2B-44C3-A6A2-ABA601054A51")
|
||||
|
||||
|
||||
def find_dumps():
|
||||
""".nup files in Downloads, Desktop, Documents, the home folder and the top of each drive, one folder level down too, newest first"""
|
||||
home = os.path.expanduser("~")
|
||||
places = [(_known_folder(FOLDER_DOWNLOADS) or os.path.join(home, "Downloads"), "Downloads"),
|
||||
(_known_folder(FOLDER_DESKTOP) or os.path.join(home, "Desktop"), "Desktop"),
|
||||
(_known_folder(FOLDER_DOCUMENTS) or os.path.join(home, "Documents"), "Documents"), (home, "Home")]
|
||||
mask = ctypes.windll.kernel32.GetLogicalDrives()
|
||||
for i, letter in enumerate(string.ascii_uppercase):
|
||||
if mask >> i & 1:
|
||||
root = letter + ":\\"
|
||||
if ctypes.windll.kernel32.GetDriveTypeW(root) in (2, 3): # (removable, fixed)
|
||||
places.append((root, letter + ":"))
|
||||
seen, found = set(), []
|
||||
for d, name in places:
|
||||
if not d or not os.path.isdir(d) or os.path.normcase(os.path.abspath(d)) in seen:
|
||||
continue
|
||||
seen.add(os.path.normcase(os.path.abspath(d)))
|
||||
dirs = [d]
|
||||
try:
|
||||
subs = [e.path for e in os.scandir(d) if e.is_dir() and not e.name.startswith((".", "$"))
|
||||
and e.name.lower() != "windows" and not e.name.lower().startswith("program")]
|
||||
dirs += subs[:200]
|
||||
except OSError:
|
||||
pass
|
||||
for sub in dirs:
|
||||
try:
|
||||
for e in os.scandir(sub):
|
||||
if e.is_file() and e.name.lower().endswith(".nup"):
|
||||
full = os.path.abspath(e.path)
|
||||
if os.path.normcase(full) not in seen:
|
||||
seen.add(os.path.normcase(full))
|
||||
st = e.stat()
|
||||
found.append(Dump(full, name, st.st_size, st.st_mtime))
|
||||
except OSError:
|
||||
pass
|
||||
return sorted(found, key=lambda x: -x.modified)
|
||||
|
||||
|
||||
def ago(t):
|
||||
import datetime
|
||||
now, then = datetime.datetime.now(), datetime.datetime.fromtimestamp(t)
|
||||
days = (now - then).total_seconds() / 86400
|
||||
if days < 1 and then.date() == now.date():
|
||||
return "modified today"
|
||||
if days < 2:
|
||||
return "modified yesterday"
|
||||
if days < 14:
|
||||
return "%d days ago" % int(days)
|
||||
if days < 60:
|
||||
return "%d weeks ago" % int(days / 7)
|
||||
return "%d %s" % (then.day, then.strftime("%b %Y"))
|
||||
|
||||
|
||||
def size_text(n):
|
||||
return "%.1f GB" % (n / (1 << 30)) if n >= 1 << 30 else "%d MB" % (n >> 20)
|
||||
|
||||
|
||||
# ---------------- the game folder ----------------
|
||||
|
||||
def _version_line(folder):
|
||||
for line in paths.read_small(os.path.join(folder, "hookshot_version.txt")).splitlines():
|
||||
if line.startswith("version="):
|
||||
return line[8:].strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def game_version(folder):
|
||||
"""The release a game folder was built with, when it keeps its game files for updates"""
|
||||
if not os.path.isdir(os.path.join(folder, ".hookshot_exefs")) or not os.path.isdir(os.path.join(folder, "romfs")):
|
||||
return None
|
||||
return _version_line(folder)
|
||||
|
||||
|
||||
def read_version(folder):
|
||||
"""(a folder built before it kept its game files has a version too: only shown)"""
|
||||
return _version_line(folder)
|
||||
|
||||
|
||||
def game_exe(folder):
|
||||
g = os.path.join(folder, "bin", "hookshot.exe")
|
||||
return g if os.path.isfile(g) else os.path.join(folder, "hookshot.exe")
|
||||
|
||||
|
||||
def start_game(folder):
|
||||
"""(the launcher already checked for updates: the game does not ask again)"""
|
||||
env = dict(os.environ, HOOKSHOT_NO_UPDATE_CHECK="1")
|
||||
subprocess.Popen([game_exe(folder)], cwd=folder, env=env)
|
||||
|
||||
|
||||
def open_folder(folder):
|
||||
subprocess.Popen(["explorer.exe", folder])
|
||||
|
||||
|
||||
# ---------------- shortcuts (Finder.cs: IShellLinkW + IPersistFile, Windows' own shell object writes the .lnk) ----------------
|
||||
|
||||
def desktop_link():
|
||||
return os.path.join(_known_folder(FOLDER_DESKTOP) or os.path.join(os.path.expanduser("~"), "Desktop"), "Hookshot.lnk")
|
||||
|
||||
|
||||
def start_link():
|
||||
return os.path.join(_known_folder(FOLDER_PROGRAMS) or "", "Hookshot.lnk")
|
||||
|
||||
|
||||
def folder_link(game_folder):
|
||||
"""The game folder's own launcher: Play, and Update left of it when a newer release is out (the setup exe's launch mode)"""
|
||||
return os.path.join(game_folder, "Hookshot.lnk")
|
||||
|
||||
|
||||
shortcut_error = None
|
||||
|
||||
|
||||
def _com_call(obj, index, restype, *args):
|
||||
vtbl = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
|
||||
fn = ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *[type(a) for a in args])(vtbl[index])
|
||||
return fn(obj, *args)
|
||||
|
||||
|
||||
def make_link(link, target, args, workdir, icon, description):
|
||||
ole32 = ctypes.windll.ole32
|
||||
ole32.CoInitialize(None)
|
||||
clsid = (ctypes.c_byte * 16).from_buffer_copy(_guid("00021401-0000-0000-C000-000000000046"))
|
||||
iid_link = (ctypes.c_byte * 16).from_buffer_copy(_guid("000214F9-0000-0000-C000-000000000046"))
|
||||
iid_file = (ctypes.c_byte * 16).from_buffer_copy(_guid("0000010B-0000-0000-C000-000000000046"))
|
||||
sl = ctypes.c_void_p()
|
||||
hr = ole32.CoCreateInstance(clsid, None, 1, iid_link, ctypes.byref(sl))
|
||||
if hr != 0:
|
||||
raise OSError("CoCreateInstance(ShellLink) failed: 0x%08x" % (hr & 0xFFFFFFFF))
|
||||
try:
|
||||
W = ctypes.c_wchar_p
|
||||
_com_call(sl, 20, ctypes.HRESULT, W(target)) # SetPath
|
||||
_com_call(sl, 11, ctypes.HRESULT, W(args)) # SetArguments
|
||||
_com_call(sl, 9, ctypes.HRESULT, W(workdir)) # SetWorkingDirectory
|
||||
_com_call(sl, 17, ctypes.HRESULT, W(icon), ctypes.c_int(0)) # SetIconLocation
|
||||
_com_call(sl, 7, ctypes.HRESULT, W(description)) # SetDescription
|
||||
pf = ctypes.c_void_p()
|
||||
_com_call(sl, 0, ctypes.HRESULT, ctypes.cast(iid_file, ctypes.c_void_p), ctypes.byref(pf)) # QueryInterface
|
||||
try:
|
||||
os.makedirs(os.path.dirname(link), exist_ok=True)
|
||||
_com_call(pf, 6, ctypes.HRESULT, W(link), wintypes.BOOL(True)) # IPersistFile::Save
|
||||
finally:
|
||||
_com_call(pf, 2, ctypes.c_ulong)
|
||||
finally:
|
||||
_com_call(sl, 2, ctypes.c_ulong)
|
||||
|
||||
|
||||
def shortcuts(game_folder, desktop, start, folder=True):
|
||||
"""Made or removed as the ticks say: each starts this app's launcher for the folder (Play, and Update when a newer release is
|
||||
out), with the game's own icon"""
|
||||
global shortcut_error
|
||||
exe, args = paths.launcher_command()
|
||||
args = subprocess.list2cmdline(args + ["--launch", game_folder])
|
||||
icon = os.path.join(game_folder, "bin", "hookshot.exe")
|
||||
if not os.path.isfile(icon):
|
||||
icon = os.path.join(game_folder, "hookshot.exe")
|
||||
for link, want in ((desktop_link(), desktop), (start_link(), start), (folder_link(game_folder), folder)):
|
||||
try:
|
||||
if not want:
|
||||
if os.path.isfile(link):
|
||||
os.remove(link)
|
||||
continue
|
||||
if not os.path.isfile(icon):
|
||||
continue
|
||||
make_link(link, exe, args, game_folder, icon, "The Legend of Zelda: Ocarina of Time, built by Hookshot")
|
||||
except OSError as e:
|
||||
shortcut_error = "%s: %s" % (os.path.basename(link), e)
|
||||
|
||||
|
||||
def refresh_shortcuts(game_folder):
|
||||
shortcuts(game_folder, os.path.isfile(desktop_link()), os.path.isfile(start_link()))
|
||||
|
||||
|
||||
# ---------------- what the player chose last time (builder-settings.json, the WPF builder's) ----------------
|
||||
|
||||
def settings_path():
|
||||
return os.path.join(paths.base(), "builder-settings.json")
|
||||
|
||||
|
||||
def load_settings():
|
||||
try:
|
||||
with open(settings_path(), encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def save_settings(s):
|
||||
try:
|
||||
os.makedirs(paths.base(), exist_ok=True)
|
||||
with open(settings_path(), "w", encoding="utf-8") as f:
|
||||
json.dump(s, f)
|
||||
except OSError:
|
||||
pass
|
||||
45
builder/py/hookshot_builder/paths.py
Normal file
45
builder/py/hookshot_builder/paths.py
Normal file
@@ -0,0 +1,45 @@
|
||||
"""Where things are: the builder's own folder in %LOCALAPPDATA%, and this app's folder."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
APP_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
ASSETS = os.path.join(APP_DIR, "assets")
|
||||
|
||||
|
||||
def base():
|
||||
"""%LOCALAPPDATA%\\HookshotBuilder (HOOKSHOT_SETUP_BASE=<folder>: another, for testing installs and updates)"""
|
||||
b = os.environ.get("HOOKSHOT_SETUP_BASE")
|
||||
if b:
|
||||
return b
|
||||
return os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~"), "HookshotBuilder")
|
||||
|
||||
|
||||
def versions():
|
||||
return os.path.join(base(), "versions")
|
||||
|
||||
|
||||
def read_small(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def write_small(path, text):
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(text)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def launcher_command():
|
||||
"""How this app is started again (the game folder's launcher, the game's update offer, a shortcut): the Python that runs it
|
||||
(pythonw.exe beside python.exe when there is one: no console window) and the app's start script"""
|
||||
exe = sys.executable
|
||||
w = os.path.join(os.path.dirname(exe), "pythonw.exe")
|
||||
if os.path.isfile(w):
|
||||
exe = w
|
||||
return exe, ["-I", os.path.join(os.path.dirname(APP_DIR), "hookshot_builder_start.py")]
|
||||
337
builder/py/hookshot_builder/setup_parts.py
Normal file
337
builder/py/hookshot_builder/setup_parts.py
Normal file
@@ -0,0 +1,337 @@
|
||||
"""The setup's work (builder/setup/setup.c, the same rules): a release's hookshot-setup.txt names its tag and its parts (one zip each,
|
||||
with its SHA-256 and size); each part is downloaded (or moved over from the installed version when its checksum did not change),
|
||||
checked and unpacked into versions\\<tag>.part, which becomes versions\\<tag> once complete. The version installed stays, the others
|
||||
and the downloads go.
|
||||
|
||||
hookshot-setup.txt, one item a line:
|
||||
tag <tag>
|
||||
part <sha256> <bytes> <folder under the install> <top folder in the zip to rename, or -> <new name, or -> <url>
|
||||
run <the WPF builder, relative to the install> (not needed here: the tools are what this app uses)"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
from . import REPO, paths
|
||||
|
||||
UA = "HookshotBuilder-Setup/2.0"
|
||||
WAITS = (3, 6, 12, 20, 30, 45, 60) # (8 tries over ~3 minutes: GitHub's release downloads answered 504 for hours on 2026-11-08)
|
||||
OWN = ("python", "emsdk", "cpm", "third_party", "wgpu-native")
|
||||
|
||||
|
||||
class SetupError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Part:
|
||||
def __init__(self, sha, size, dest, frm, to, url):
|
||||
self.sha, self.size, self.dest, self.frm, self.to, self.url = sha, int(size), dest, frm, to, url
|
||||
|
||||
|
||||
def retryable(status):
|
||||
"""an answer worth trying again: none, a server error, a download cut off half way (200), a timeout or the API's rate limit"""
|
||||
return not status or status >= 500 or status in (200, 408, 429, 403)
|
||||
|
||||
|
||||
class Http:
|
||||
def __init__(self):
|
||||
self.status = 0
|
||||
|
||||
def get(self, url, sink=None, expect=0, accept=None, progress=None, cancel=None):
|
||||
"""GET following redirects (never to http); the bytes to sink, or returned. Sets self.status; raises on failure"""
|
||||
if not url.startswith("https://"):
|
||||
raise SetupError("Only https downloads are allowed: " + url)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": UA, **({"Accept": accept} if accept else {})})
|
||||
self.status = 0
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
if not r.geturl().startswith("https://"):
|
||||
raise SetupError("A download was redirected away from https")
|
||||
self.status = r.status
|
||||
got, out = 0, []
|
||||
while True:
|
||||
if cancel and cancel():
|
||||
raise SetupError("cancelled")
|
||||
b = r.read(1 << 16)
|
||||
if not b:
|
||||
break
|
||||
got += len(b)
|
||||
if sink:
|
||||
sink(b)
|
||||
else:
|
||||
out.append(b)
|
||||
if progress and expect:
|
||||
progress(min(1.0, got / expect))
|
||||
if expect and got != expect:
|
||||
self.status = 200 # (cut off half way: worth another try)
|
||||
raise SetupError("The download ended early (%d of %d MB)" % (got >> 20, expect >> 20))
|
||||
return None if sink else b"".join(out)
|
||||
except urllib.error.HTTPError as e:
|
||||
self.status = e.code
|
||||
raise SetupError("GitHub returned HTTP %d" % e.code) from None
|
||||
except (urllib.error.URLError, OSError, TimeoutError) as e:
|
||||
if not isinstance(e, SetupError):
|
||||
self.status = self.status if self.status and self.status != 200 else 0
|
||||
raise SetupError("Could not reach GitHub (%s)" % getattr(e, "reason", e)) from None
|
||||
raise
|
||||
|
||||
|
||||
def api_link_for(http, url):
|
||||
"""https://github.com/<owner>/<repo>/releases/download/<tag>/<name> (or .../latest/download/<name>) -> the API's own link to
|
||||
that file, which redirects to a fresh download (GitHub's cached release links answered 504 for hours while its API answered)"""
|
||||
m = re.match(r"https://github\.com/([^/]+/[^/]+)/releases/(?:download/([^/]+)|latest/download)/([^/?]+)$", url)
|
||||
if not m:
|
||||
return None
|
||||
repo, tag, name = m.groups()
|
||||
api = "https://api.github.com/repos/%s/releases/%s" % (repo, ("tags/" + tag) if tag else "latest")
|
||||
try:
|
||||
doc = json.loads(http.get(api, accept="application/vnd.github+json"))
|
||||
for a in doc.get("assets", []):
|
||||
if a.get("name") == name and str(a.get("url", "")).startswith("https://api.github.com/"):
|
||||
return a["url"]
|
||||
except (SetupError, ValueError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def manifest_url(tag=None):
|
||||
"""(an update to a named release reads THAT release's list: the latest/download link can answer with the release before it for
|
||||
a while after a publish. HOOKSHOT_SETUP_LIST=<url>: another list, for testing a release before it is the latest)"""
|
||||
e = os.environ.get("HOOKSHOT_SETUP_LIST")
|
||||
if e:
|
||||
return e
|
||||
if tag:
|
||||
return "https://github.com/%s/releases/download/%s/hookshot-setup.txt" % (REPO, tag)
|
||||
return "https://github.com/%s/releases/latest/download/hookshot-setup.txt" % REPO
|
||||
|
||||
|
||||
def read_manifest(status, tag=None, cancel=None):
|
||||
"""(tag, parts) of the release's list, tried again on a server error or no answer"""
|
||||
http, url = Http(), manifest_url(tag)
|
||||
text, last = None, ""
|
||||
for attempt in range(len(WAITS) + 1):
|
||||
if attempt:
|
||||
status("GitHub didn't answer (%s). Trying again in %d s..." % (http.status or "no answer", WAITS[attempt - 1]))
|
||||
time.sleep(WAITS[attempt - 1])
|
||||
status("Looking for the latest Hookshot Builder...")
|
||||
try:
|
||||
text = http.get(url, cancel=cancel).decode("utf-8", "replace")
|
||||
break
|
||||
except SetupError as e:
|
||||
last = str(e)
|
||||
first = http.status
|
||||
if not first or first >= 500: # (the API's link instead)
|
||||
api = api_link_for(http, url)
|
||||
if api:
|
||||
try:
|
||||
text = http.get(api, accept="application/octet-stream", cancel=cancel).decode("utf-8", "replace")
|
||||
break
|
||||
except SetupError:
|
||||
http.status = first
|
||||
if not retryable(http.status):
|
||||
break
|
||||
if text is None:
|
||||
if http.status == 404:
|
||||
raise SetupError("The latest Hookshot release has no setup files yet. Download it from the releases page for now: "
|
||||
"https://github.com/%s/releases/latest" % REPO)
|
||||
if http.status:
|
||||
raise SetupError("GitHub's download servers are failing right now (an error 500 or above, tried 8 times over 3 minutes). "
|
||||
"This is on GitHub's side: try again in a few minutes, or later today.")
|
||||
raise SetupError("Could not reach GitHub to get the Hookshot Builder (%s). Check your internet connection and try again." % last)
|
||||
got_tag, parts = "", []
|
||||
for line in text.splitlines():
|
||||
p = line.split()
|
||||
if len(p) >= 2 and p[0] == "tag":
|
||||
got_tag = p[1]
|
||||
elif len(p) == 7 and p[0] == "part":
|
||||
parts.append(Part(*p[1:]))
|
||||
if not got_tag or not parts:
|
||||
raise SetupError("The release's setup list could not be read. Try again later.")
|
||||
if tag and tag != got_tag:
|
||||
raise SetupError("GitHub answered with the setup list of %s, not %s (its download links can lag right after a release). "
|
||||
"Try the update again in a few minutes." % (got_tag, tag))
|
||||
return got_tag, parts
|
||||
|
||||
|
||||
def part_folder(p):
|
||||
"""The folder a part unpacks into, relative to a version's folder (None: the part has none of its own)"""
|
||||
if p.to != "-" and p.dest != ".":
|
||||
return os.path.join(p.dest, p.to).replace("/", os.sep)
|
||||
b = p.url.rsplit("/", 1)[-1]
|
||||
for own in OWN:
|
||||
if b.startswith("HookshotBuilder-%s-" % own):
|
||||
return os.path.join("HookshotBuilder", "tools", own)
|
||||
return None
|
||||
|
||||
|
||||
def reuse_part(tag, p, install):
|
||||
"""A part whose checksum the installed version lists in its parts.txt (and whose folder it has) is moved over from it instead of
|
||||
downloaded: that version is deleted after the install anyway"""
|
||||
rel = part_folder(p)
|
||||
was = paths.read_small(os.path.join(paths.versions(), "current.txt"))
|
||||
if not rel or not was or was == tag:
|
||||
return False
|
||||
if p.sha not in paths.read_small(os.path.join(paths.versions(), was, "parts.txt")):
|
||||
return False
|
||||
src, dst = os.path.join(paths.versions(), was, rel), os.path.join(install, rel)
|
||||
if not os.path.exists(src):
|
||||
return False
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
try:
|
||||
os.replace(src, dst)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def rmtree(p):
|
||||
shutil.rmtree(p, ignore_errors=True)
|
||||
|
||||
|
||||
def installed(tag):
|
||||
d = os.path.join(paths.versions(), tag)
|
||||
return d if os.path.isfile(os.path.join(d, "installed.txt")) and os.path.isfile(
|
||||
os.path.join(d, "HookshotBuilder", "tools", "nx2", "make_game.py")) else None
|
||||
|
||||
|
||||
def current():
|
||||
"""The version installed last, its folder (None: none yet)"""
|
||||
tag = paths.read_small(os.path.join(paths.versions(), "current.txt"))
|
||||
return installed(tag) if tag else None
|
||||
|
||||
|
||||
def install(status, progress=lambda f: None, tag=None, repair=False, cancel=None):
|
||||
"""Installs the release (the latest, or tag) unless it is there already; returns (tag, its folder)"""
|
||||
tag, parts = read_manifest(status, tag, cancel)
|
||||
versions, downloads = paths.versions(), os.path.join(paths.base(), "downloads")
|
||||
final = os.path.join(versions, tag)
|
||||
if repair or not installed(tag):
|
||||
work = final + ".part"
|
||||
rmtree(work)
|
||||
rmtree(final)
|
||||
os.makedirs(work, exist_ok=True)
|
||||
os.makedirs(downloads, exist_ok=True)
|
||||
n = len(parts)
|
||||
for i, p in enumerate(parts, 1):
|
||||
if cancel and cancel():
|
||||
raise SetupError("cancelled")
|
||||
if reuse_part(tag, p, work):
|
||||
status("Part %d of %d unchanged: kept from the installed version" % (i, n))
|
||||
continue
|
||||
zpath = os.path.join(downloads, p.sha + ".zip")
|
||||
if not (os.path.isfile(zpath) and sha256_file(zpath) == p.sha):
|
||||
download_part(status, progress, p, i, n, zpath, cancel)
|
||||
status("Unpacking part %d of %d..." % (i, n))
|
||||
progress(-1)
|
||||
dest = work if p.dest == "." else os.path.join(work, p.dest.replace("/", os.sep))
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
try:
|
||||
with zipfile.ZipFile(zpath) as z:
|
||||
z.extractall(dest)
|
||||
except (OSError, zipfile.BadZipFile) as e:
|
||||
raise SetupError("Unpacking part %d of %d failed: %s" % (i, n, e)) from None
|
||||
if p.frm != "-" and p.to != "-": # (llvm-mingw-<version>-ucrt-x86_64 -> llvm-mingw)
|
||||
src, dst = os.path.join(dest, p.frm), os.path.join(dest, p.to)
|
||||
if not os.path.exists(dst):
|
||||
try:
|
||||
os.replace(src, dst)
|
||||
except OSError:
|
||||
raise SetupError("Could not set up part %d of %d (renaming %s)." % (i, n, p.frm)) from None
|
||||
if not os.path.isfile(os.path.join(work, "HookshotBuilder", "tools", "nx2", "make_game.py")):
|
||||
raise SetupError("The build tools are missing after unpacking. Your antivirus may have removed them: allow the folder %s "
|
||||
"and try again." % paths.base())
|
||||
try:
|
||||
os.replace(work, final)
|
||||
except OSError:
|
||||
raise SetupError("Could not finish installing into %s." % final) from None
|
||||
paths.write_small(os.path.join(final, "installed.txt"), tag)
|
||||
write_parts(final, parts)
|
||||
elif not os.path.isfile(os.path.join(final, "parts.txt")):
|
||||
write_parts(final, parts)
|
||||
prune(tag, parts)
|
||||
rmtree(downloads) # (installed: its zips are not kept; an update moves unchanged folders over instead)
|
||||
return tag, final
|
||||
|
||||
|
||||
def download_part(status, progress, p, i, n, zpath, cancel):
|
||||
http, part = Http(), zpath + ".part"
|
||||
for attempt in range(len(WAITS) + 1):
|
||||
if attempt:
|
||||
status("Part %d of %d: GitHub didn't answer (%s). Trying again in %d s..." % (i, n, http.status or "no answer",
|
||||
WAITS[attempt - 1]))
|
||||
time.sleep(WAITS[attempt - 1])
|
||||
status("Downloading part %d of %d (%d MB)..." % (i, n, p.size >> 20))
|
||||
h = hashlib.sha256()
|
||||
try:
|
||||
with open(part, "wb") as f:
|
||||
def sink(b):
|
||||
f.write(b)
|
||||
h.update(b)
|
||||
url = api_link_for(http, p.url) if attempt % 2 == 1 else None # (the API's link, every other try)
|
||||
if url:
|
||||
http.get(url, sink, p.size, "application/octet-stream", progress, cancel)
|
||||
else:
|
||||
http.get(p.url, sink, p.size, None, progress, cancel)
|
||||
except SetupError as e:
|
||||
if str(e) == "cancelled":
|
||||
raise
|
||||
if not retryable(http.status):
|
||||
break
|
||||
continue
|
||||
except OSError:
|
||||
raise SetupError("Could not write to %s." % os.path.dirname(zpath)) from None
|
||||
progress(-1)
|
||||
if h.hexdigest() != p.sha:
|
||||
os.remove(part)
|
||||
raise SetupError("Part %d of %d did not download correctly (its checksum differs). Try again." % (i, n))
|
||||
os.replace(part, zpath)
|
||||
return
|
||||
try:
|
||||
os.remove(part)
|
||||
except OSError:
|
||||
pass
|
||||
raise SetupError(("Downloading part %d of %d failed: GitHub's download servers are failing right now (tried 8 times over 3 "
|
||||
"minutes). This is on GitHub's side. The parts already downloaded are kept: try again in a few minutes."
|
||||
if retryable(http.status) else
|
||||
"Downloading part %d of %d failed. Check your connection and free space, then try again.") % (i, n))
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for b in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(b)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def write_parts(install_dir, parts):
|
||||
"""The checksums of the parts this version holds in folders of their own (reuse_part reads them at the next update)"""
|
||||
paths.write_small(os.path.join(install_dir, "parts.txt"), "".join(p.sha + "\n" for p in parts if part_folder(p)))
|
||||
|
||||
|
||||
def prune(tag, parts):
|
||||
"""Only the version installed stays (a folder still in use cannot be renamed: it goes at a later run), and downloads the list
|
||||
no longer names go"""
|
||||
versions = paths.versions()
|
||||
was = paths.read_small(os.path.join(versions, "current.txt"))
|
||||
if was != tag:
|
||||
if was:
|
||||
paths.write_small(os.path.join(versions, "previous.txt"), was)
|
||||
paths.write_small(os.path.join(versions, "current.txt"), tag)
|
||||
for name in os.listdir(versions):
|
||||
p = os.path.join(versions, name)
|
||||
if not os.path.isdir(p) or name == tag:
|
||||
continue
|
||||
if name.endswith(".gone"):
|
||||
rmtree(p)
|
||||
continue
|
||||
try:
|
||||
os.replace(p, p + ".gone")
|
||||
rmtree(p + ".gone")
|
||||
except OSError:
|
||||
pass
|
||||
71
builder/py/hookshot_builder/strings.py
Normal file
71
builder/py/hookshot_builder/strings.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""The builder's languages, generated by gen_strings.py from builder/HookshotBuilder/Strings.cs: one of the game's languages
|
||||
is its code in language.txt, its own name, and the app's text in it. Do not edit by hand."""
|
||||
|
||||
KEYS = ['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', 'Download', 'Updating', 'UpdateFailed']
|
||||
|
||||
TEXT = {
|
||||
'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"],
|
||||
'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"],
|
||||
'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"],
|
||||
'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"],
|
||||
'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"],
|
||||
'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"],
|
||||
'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"],
|
||||
'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"],
|
||||
'Ru': ["Превращает вашу копию Ocarina of Time в папку с игрой для запуска на ПК.", "Файлы игры", "Файл .nup", "romfs и exefs", "Также можно перетащить файл или папку в это окно.", "Сохранить игру в", "Собрать", "Обзор", "Занимает около 45 минут и требует 45 ГБ.", "{0}: свободно {1} ГБ.", "Проверка версии игры...", "Эта версия поддерживается Hookshot.", "Эта версия не поддерживается. Hookshot нужна сборка e0f3ccfa.", "Инструменты Hookshot не найдены рядом с этим приложением.", "Python не найден.", "Сборка", "Это займёт время, а компьютером можно пользоваться.", "Прошло", "Чтение файлов игры", "Перевод игры в код для ПК", "Компиляция", "Подготовка папки с игрой", "Показать подробности", "Скрыть подробности", "Отмена", "Назад", "Открыть папку", "Играть", "Ваша игра готова", "собрано за", "Сборка остановлена", "Сборка отменена", "Можно начать заново из той же папки.", "Остановить сборку и закрыть?", "Язык"],
|
||||
'Ja': ["お持ちの Ocarina of Time を、PC で起動できるゲームフォルダーに変換します。", "ゲームファイル", ".nup ファイル", "romfs と exefs", "ファイルやフォルダーをこのウィンドウにドロップすることもできます。", "ゲームの保存先", "ビルド", "参照", "約 45 分かかり、45 GB 必要です。", "{0} の空き容量: {1} GB", "ゲームのバージョンを確認しています...", "このバージョンは Hookshot に対応しています。", "このバージョンには対応していません。Hookshot にはビルド e0f3ccfa が必要です。", "このアプリの横に Hookshot ツールが見つかりません。", "Python が見つかりません。", "ビルド中", "時間がかかりますが、PC はそのまま使えます。", "経過時間", "ゲームファイルを読み込んでいます", "ゲームを PC 用コードに変換しています", "コンパイル中", "ゲームフォルダーを作成しています", "詳細を表示", "詳細を隠す", "キャンセル", "戻る", "フォルダーを開く", "プレイ", "ゲームの準備ができました", "所要時間", "ビルドが停止しました", "ビルドをキャンセルしました", "同じフォルダーからやり直せます。", "ビルドを中止して閉じますか?", "言語"],
|
||||
'Ko': ["가지고 있는 Ocarina of Time을 PC에서 실행할 수 있는 게임 폴더로 만듭니다.", "게임 파일", ".nup 파일", "romfs 및 exefs", "파일이나 폴더를 이 창에 끌어다 놓을 수도 있습니다.", "게임 저장 위치", "빌드", "찾아보기", "약 45분이 걸리며 45GB가 필요합니다.", "{0} 여유 공간: {1}GB", "게임 버전을 확인하는 중...", "Hookshot이 지원하는 버전입니다.", "지원되지 않는 버전입니다. Hookshot에는 빌드 e0f3ccfa가 필요합니다.", "이 앱 옆에서 Hookshot 도구를 찾을 수 없습니다.", "Python을 찾을 수 없습니다.", "빌드 중", "시간이 걸리지만 PC는 계속 사용할 수 있습니다.", "경과 시간", "게임 파일을 읽는 중", "게임을 PC 코드로 변환하는 중", "컴파일 중", "게임 폴더를 만드는 중", "자세히 보기", "자세히 숨기기", "취소", "뒤로", "폴더 열기", "플레이", "게임이 준비되었습니다", "소요 시간", "빌드가 중단되었습니다", "빌드가 취소되었습니다", "같은 폴더에서 다시 시작할 수 있습니다.", "빌드를 중단하고 닫을까요?", "언어"],
|
||||
'ZhHans': ["将你自己的 Ocarina of Time 变成可在电脑上启动的游戏文件夹。", "游戏文件", ".nup 文件", "romfs 和 exefs", "也可以将文件或文件夹拖放到此窗口。", "游戏保存位置", "生成", "浏览", "大约需要 45 分钟和 45 GB 空间。", "{0} 可用空间 {1} GB。", "正在检查游戏版本...", "Hookshot 支持此版本。", "不支持此版本。Hookshot 需要构建版本 e0f3ccfa。", "在此应用旁边找不到 Hookshot 工具。", "找不到 Python。", "正在生成", "这需要一些时间,期间电脑仍可正常使用。", "已用时间", "正在读取游戏文件", "正在将游戏转换为电脑代码", "正在编译", "正在整理游戏文件夹", "显示详细信息", "隐藏详细信息", "取消", "返回", "打开文件夹", "开始游戏", "你的游戏已准备就绪", "用时", "生成已停止", "生成已取消", "你可以从同一文件夹重新开始。", "要停止生成并关闭吗?", "语言"],
|
||||
'ZhHant': ["將你自己的 Ocarina of Time 變成可在電腦上啟動的遊戲資料夾。", "遊戲檔案", ".nup 檔案", "romfs 和 exefs", "也可以將檔案或資料夾拖放到此視窗。", "遊戲儲存位置", "建置", "瀏覽", "大約需要 45 分鐘和 45 GB 空間。", "{0} 可用空間 {1} GB。", "正在檢查遊戲版本...", "Hookshot 支援此版本。", "不支援此版本。Hookshot 需要建置版本 e0f3ccfa。", "在此應用程式旁找不到 Hookshot 工具。", "找不到 Python。", "正在建置", "這需要一些時間,期間電腦仍可正常使用。", "已用時間", "正在讀取遊戲檔案", "正在將遊戲轉換為電腦程式碼", "正在編譯", "正在整理遊戲資料夾", "顯示詳細資訊", "隱藏詳細資訊", "取消", "返回", "開啟資料夾", "開始遊戲", "你的遊戲已準備就緒", "用時", "建置已停止", "建置已取消", "你可以從同一資料夾重新開始。", "要停止建置並關閉嗎?", "語言"],
|
||||
}
|
||||
|
||||
LANGUAGES = [ # (code, its own name, the TEXT it uses)
|
||||
('en-US', 'English (US)', 'En'),
|
||||
('en-GB', 'English (UK)', 'En'),
|
||||
('fr', 'Français', 'Fr'),
|
||||
('fr-CA', 'Français (Canada)', 'Fr'),
|
||||
('de', 'Deutsch', 'De'),
|
||||
('it', 'Italiano', 'It'),
|
||||
('es', 'Español (España)', 'Es'),
|
||||
('es-419', 'Español (Latinoamérica)', 'Es'),
|
||||
('pt-BR', 'Português (Brasil)', 'Pt'),
|
||||
('nl', 'Nederlands', 'Nl'),
|
||||
('pl', 'Polski', 'Pl'),
|
||||
('ru', 'Русский', 'Ru'),
|
||||
('ja', '日本語', 'Ja'),
|
||||
('ko', '한국어', 'Ko'),
|
||||
('zh-Hans', '简体中文', 'ZhHans'),
|
||||
('zh-Hant', '繁體中文', 'ZhHant'),
|
||||
]
|
||||
|
||||
|
||||
|
||||
def text(lang, key):
|
||||
"""A string in the language (a LANGUAGES entry), English where it has none (the update's lines are English only)"""
|
||||
i = KEYS.index(key)
|
||||
arr = TEXT[lang[2]]
|
||||
return arr[i] if i < len(arr) else TEXT["En"][i]
|
||||
|
||||
|
||||
def default_language():
|
||||
"""The language closest to Windows' own: the exact one, then the same family, else English (US)"""
|
||||
name = ""
|
||||
try:
|
||||
import ctypes
|
||||
buf = ctypes.create_unicode_buffer(85)
|
||||
if ctypes.windll.kernel32.GetUserDefaultLocaleName(buf, 85):
|
||||
name = buf.value
|
||||
except Exception:
|
||||
pass
|
||||
for lang in LANGUAGES:
|
||||
if lang[0].lower() == name.lower():
|
||||
return lang
|
||||
if name.startswith("zh"):
|
||||
pick = "zh-Hant" if any(t in name for t in ("TW", "HK", "Hant")) else "zh-Hans"
|
||||
elif name.startswith("es-") and name != "es-ES":
|
||||
pick = "es-419"
|
||||
elif name.startswith("pt"):
|
||||
pick = "pt-BR"
|
||||
else:
|
||||
pick = name.split("-")[0]
|
||||
return next((lang for lang in LANGUAGES if lang[0] == pick), LANGUAGES[0])
|
||||
461
builder/py/hookshot_builder/theme.py
Normal file
461
builder/py/hookshot_builder/theme.py
Normal file
@@ -0,0 +1,461 @@
|
||||
"""The WPF builder's App.xaml in Qt: the Slate palette, the Inter fonts, and the controls drawn as its templates draw them (the same
|
||||
sizes, radii, colours, glows and hover states)."""
|
||||
import math
|
||||
import os
|
||||
|
||||
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal
|
||||
from PySide6.QtGui import QBrush, QColor, QFont, QFontDatabase, QLinearGradient, QPainter, QPainterPath, QPen
|
||||
from PySide6.QtWidgets import (QAbstractButton, QComboBox, QFrame, QGraphicsDropShadowEffect, QLabel, QLineEdit, QListView,
|
||||
QSizePolicy, QStyledItemDelegate, QWidget)
|
||||
|
||||
from . import paths
|
||||
|
||||
|
||||
def argb(s):
|
||||
"""#AARRGGBB or #RRGGBB, as WPF writes them"""
|
||||
s = s.lstrip("#")
|
||||
if len(s) == 8:
|
||||
return QColor(int(s[2:4], 16), int(s[4:6], 16), int(s[6:8], 16), int(s[0:2], 16))
|
||||
return QColor(int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
|
||||
|
||||
|
||||
C = {k: argb(v) for k, v in {
|
||||
"Page": "#14161A", "Raised": "#1C1F24", "RaisedHover": "#23272D", "Line": "#2C3037", "LineStrong": "#3D434C",
|
||||
"Ink": "#EDEFF2", "InkSoft": "#A2A9B3", "InkFaint": "#6E7681", "Brand": "#3D63E6", "BrandHover": "#4B70F0",
|
||||
"BrandInk": "#DFE6FF", "Go": "#5FB08A", "GoHover": "#70C09A", "GoInk": "#06150E", "Warn": "#E2B86B", "Bad": "#E2776B",
|
||||
"Glass": "#0DFFFFFF", "GlassHover": "#17FFFFFF", "GlassLine": "#17FFFFFF", "GlassLineStrong": "#2AFFFFFF",
|
||||
"GoSoft": "#265FB08A", "BadSoft": "#26E2776B", "WarnSoft": "#1FE2B86B", "BrandSoft": "#333D63E6", "White": "#FFFFFF",
|
||||
}.items()}
|
||||
|
||||
UI = "Inter"
|
||||
MONO = "Cascadia Mono"
|
||||
W_MEDIUM, W_SEMIBOLD, W_BOLD = QFont.Weight.Medium, QFont.Weight.DemiBold, QFont.Weight.Bold
|
||||
|
||||
|
||||
def load_fonts():
|
||||
global MONO
|
||||
for f in ("Inter-Regular.ttf", "Inter-Medium.ttf", "Inter-SemiBold.ttf", "Inter-Bold.ttf"):
|
||||
QFontDatabase.addApplicationFont(os.path.join(paths.ASSETS, "Fonts", f))
|
||||
if MONO not in QFontDatabase.families():
|
||||
MONO = "Consolas"
|
||||
|
||||
|
||||
def font(size=14, weight=QFont.Weight.Normal, family=None):
|
||||
f = QFont(family or UI)
|
||||
f.setPixelSize(int(size))
|
||||
f.setWeight(weight)
|
||||
f.setHintingPreference(QFont.HintingPreference.PreferNoHinting) # (WPF's Ideal text formatting)
|
||||
f.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
|
||||
return f
|
||||
|
||||
|
||||
def css(c):
|
||||
return "rgba(%d,%d,%d,%d)" % (c.red(), c.green(), c.blue(), c.alpha())
|
||||
|
||||
|
||||
def label(text="", size=14, weight=QFont.Weight.Normal, color="Ink", wrap=False, mono=False):
|
||||
l = QLabel(text)
|
||||
l.setFont(font(size, weight, MONO if mono else None))
|
||||
set_color(l, color)
|
||||
l.setWordWrap(wrap)
|
||||
l.setTextInteractionFlags(Qt.TextInteractionFlag.NoTextInteraction)
|
||||
l.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
return l
|
||||
|
||||
|
||||
def set_color(l, color):
|
||||
c = C[color] if isinstance(color, str) else color
|
||||
l.setStyleSheet("color: %s; background: transparent;" % css(c))
|
||||
|
||||
|
||||
# the text styles of App.xaml
|
||||
def heading(text=""):
|
||||
return label(text, 24, W_BOLD)
|
||||
|
||||
|
||||
def sub(text=""):
|
||||
l = label(text, 14, color="InkSoft", wrap=True)
|
||||
l.setContentsMargins(0, 6, 0, 0)
|
||||
return l
|
||||
|
||||
|
||||
def note(text="", size=13):
|
||||
return label(text, size, color="InkSoft", wrap=True)
|
||||
|
||||
|
||||
def faint(text="", size=12):
|
||||
return label(text, size, color="InkFaint")
|
||||
|
||||
|
||||
def section(text):
|
||||
l = label(text, 12, W_SEMIBOLD, "InkSoft")
|
||||
l.setContentsMargins(0, 24, 0, 10)
|
||||
return l
|
||||
|
||||
|
||||
def glow(widget, color, blur, depth, opacity):
|
||||
"""WPF's DropShadowEffect (Direction 270: straight down)"""
|
||||
e = QGraphicsDropShadowEffect(widget)
|
||||
c = QColor(argb(color) if isinstance(color, str) else color)
|
||||
c.setAlphaF(opacity)
|
||||
e.setColor(c)
|
||||
e.setBlurRadius(blur * 1.2)
|
||||
e.setOffset(0, depth)
|
||||
widget.setGraphicsEffect(e)
|
||||
return e
|
||||
|
||||
|
||||
def rounded(rect, r):
|
||||
p = QPainterPath()
|
||||
p.addRoundedRect(rect, r, r)
|
||||
return p
|
||||
|
||||
|
||||
class Card(QFrame):
|
||||
"""Card: Glass background, GlassLine border, corner radius 10"""
|
||||
|
||||
def __init__(self, radius=10, bg="Glass", line="GlassLine"):
|
||||
super().__init__()
|
||||
self.radius, self.bg, self.line = radius, bg, line
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
p.fillPath(rounded(r, self.radius), C[self.bg] if isinstance(self.bg, str) else self.bg)
|
||||
p.setPen(QPen(C[self.line] if isinstance(self.line, str) else self.line, 1))
|
||||
p.drawPath(rounded(r, self.radius))
|
||||
|
||||
|
||||
class Button(QAbstractButton):
|
||||
"""Quiet / Primary / GoButton / LinkButton / Link / Caption, as App.xaml's templates"""
|
||||
KINDS = {
|
||||
# kind: (height, padding x, radius, font size, weight)
|
||||
"quiet": (40, 18, 8, 14, W_SEMIBOLD), "primary": (40, 20, 8, 14, W_SEMIBOLD), "go": (50, 34, 10, 16, W_BOLD),
|
||||
"link": (None, 0, 0, 13, W_SEMIBOLD), "toggle": (None, 0, 0, 13, QFont.Weight.Normal), "caption": (36, 0, 8, 12, QFont.Weight.Normal),
|
||||
}
|
||||
|
||||
def __init__(self, text="", kind="quiet", icon=None, color=None, size=None):
|
||||
super().__init__()
|
||||
self._glow = None
|
||||
self.kind, self.icon, self.hover, self._color = kind, icon, False, color
|
||||
h, self.padx, self.radius, fs, fw = self.KINDS[kind]
|
||||
self.setFont(font(size or fs, fw))
|
||||
self.setText(text)
|
||||
self.setCursor(Qt.CursorShape.PointingHandCursor if kind != "caption" else Qt.CursorShape.ArrowCursor)
|
||||
self.setFocusPolicy(Qt.FocusPolicy.TabFocus if kind in ("quiet", "primary", "go") else Qt.FocusPolicy.NoFocus)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
self.fixed_h = h
|
||||
if kind == "caption":
|
||||
self.setFixedSize(46, 36)
|
||||
self._glow = None
|
||||
if kind == "primary":
|
||||
self._glow = glow(self, "#3D63E6", 22, 6, 0.55)
|
||||
elif kind == "go":
|
||||
self._glow = glow(self, "#5FB08A", 30, 8, 0.5)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
||||
|
||||
def setText(self, t):
|
||||
super().setText(t)
|
||||
self.updateGeometry()
|
||||
self.update()
|
||||
|
||||
def set_color(self, color):
|
||||
self._color = color
|
||||
self.update()
|
||||
|
||||
def sizeHint(self):
|
||||
fm = self.fontMetrics()
|
||||
w = fm.horizontalAdvance(self.text())
|
||||
if self.icon == "play":
|
||||
w += 21
|
||||
if self.kind in ("link", "toggle"):
|
||||
return QSize(w + 1, fm.height() + 2)
|
||||
if self.kind == "caption":
|
||||
return QSize(46, 36)
|
||||
return QSize(w + 2 * self.padx + 2, self.fixed_h)
|
||||
|
||||
def enterEvent(self, e):
|
||||
self.hover = True
|
||||
self.update()
|
||||
|
||||
def leaveEvent(self, e):
|
||||
self.hover = False
|
||||
self.update()
|
||||
|
||||
def changeEvent(self, e):
|
||||
if self._glow is not None:
|
||||
self._glow.setEnabled(self.isEnabled())
|
||||
super().changeEvent(e)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
k, on, hov, focus = self.kind, self.isEnabled(), self.hover and self.isEnabled(), self.hasFocus()
|
||||
ink = C["Ink"]
|
||||
if k == "quiet":
|
||||
bg = C["GlassHover"] if hov else argb("#08FFFFFF")
|
||||
line = C["BrandHover"] if focus else C["GlassLineStrong"] if hov else argb("#1FFFFFFF")
|
||||
p.fillPath(rounded(r, 8), bg)
|
||||
p.setPen(QPen(line, 1))
|
||||
p.drawPath(rounded(r, 8))
|
||||
ink = C["Ink"] if on else C["InkFaint"]
|
||||
elif k == "primary":
|
||||
bg = (C["BrandHover"] if hov else C["Brand"]) if on else argb("#14FFFFFF")
|
||||
p.fillPath(rounded(r, 8), bg)
|
||||
p.setPen(QPen(argb("#AAFFFFFF") if focus else argb("#33FFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 8))
|
||||
ink = C["White"] if on else C["InkFaint"]
|
||||
elif k == "go":
|
||||
p.fillPath(rounded(r, 10), C["GoHover"] if hov else C["Go"])
|
||||
p.setPen(QPen(argb("#40FFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 10))
|
||||
ink = C["GoInk"]
|
||||
elif k == "link":
|
||||
ink = C["White"] if hov else (self._color or C["BrandInk"])
|
||||
elif k == "toggle":
|
||||
ink = C["Ink"] if hov else (self._color or C["InkSoft"])
|
||||
elif k == "caption":
|
||||
if self.hover:
|
||||
p.fillPath(rounded(r, 8), C["GlassHover"])
|
||||
ink = C["Ink"] if self.hover else argb("#80FFFFFF")
|
||||
p.setPen(QPen(ink, 1.2 if self.icon == "close" else 1))
|
||||
cx, cy = self.width() / 2, self.height() / 2
|
||||
if self.icon == "min":
|
||||
p.fillRect(QRectF(cx - 5, cy, 10, 1), ink)
|
||||
else:
|
||||
p.drawLine(QPointF(cx - 5, cy - 5), QPointF(cx + 5, cy + 5))
|
||||
p.drawLine(QPointF(cx + 5, cy - 5), QPointF(cx - 5, cy + 5))
|
||||
return
|
||||
p.setFont(self.font())
|
||||
p.setPen(ink)
|
||||
fm = self.fontMetrics()
|
||||
tw = fm.horizontalAdvance(self.text())
|
||||
if self.icon == "play": # (the triangle M0,0 L11,7 L0,14, 10 px before the text)
|
||||
total = 11 + 10 + tw
|
||||
x0 = (self.width() - total) / 2
|
||||
tri = QPainterPath()
|
||||
cy = self.height() / 2
|
||||
tri.moveTo(x0, cy - 7)
|
||||
tri.lineTo(x0 + 11, cy)
|
||||
tri.lineTo(x0, cy + 7)
|
||||
tri.closeSubpath()
|
||||
p.fillPath(tri, ink)
|
||||
p.drawText(QRectF(x0 + 21, 0, tw + 2, self.height()), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, self.text())
|
||||
return
|
||||
align = Qt.AlignmentFlag.AlignCenter if k in ("quiet", "primary", "go") else Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
p.drawText(QRectF(self.rect()), align, self.text())
|
||||
|
||||
|
||||
class Tick(QAbstractButton):
|
||||
"""CheckBox Tick: an 18x18 box, radius 5, its mark when checked, the text in InkSoft 13"""
|
||||
|
||||
def __init__(self, text, checked=False):
|
||||
super().__init__()
|
||||
self.setCheckable(True)
|
||||
self.setChecked(checked)
|
||||
self.setText(text)
|
||||
self.setFont(font(13))
|
||||
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
|
||||
def sizeHint(self):
|
||||
return QSize(26 + self.fontMetrics().horizontalAdvance(self.text()) + 2, max(18, self.fontMetrics().height()))
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
y = (self.height() - 18) / 2
|
||||
box = QRectF(0.75, y + 0.75, 16.5, 16.5)
|
||||
if self.isChecked():
|
||||
p.fillPath(rounded(box, 5), C["Brand"])
|
||||
p.setPen(QPen(C["Brand"], 1.5))
|
||||
p.drawPath(rounded(box, 5))
|
||||
p.setPen(QPen(C["White"], 2))
|
||||
path = QPainterPath(QPointF(2, y + 8))
|
||||
path.lineTo(6, y + 12)
|
||||
path.lineTo(14, y + 3)
|
||||
p.drawPath(path)
|
||||
else:
|
||||
p.setPen(QPen(argb("#40FFFFFF"), 1.5))
|
||||
p.drawPath(rounded(box, 5))
|
||||
p.setFont(self.font())
|
||||
p.setPen(C["InkSoft"])
|
||||
p.drawText(QRectF(26, 0, self.width() - 26, self.height()), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
self.text())
|
||||
|
||||
|
||||
class Bar(QWidget):
|
||||
"""ProgressBar Bar: 6 high, track #12FFFFFF, the indicator in Foreground, both radius 3"""
|
||||
|
||||
def __init__(self, color="Brand", width=None):
|
||||
super().__init__()
|
||||
self.value, self.color = 0.0, color
|
||||
self.setFixedHeight(6)
|
||||
if width:
|
||||
self.setFixedWidth(width)
|
||||
|
||||
def set(self, v, color=None):
|
||||
self.value = max(0.0, min(1.0, v))
|
||||
if color:
|
||||
self.color = color
|
||||
self.update()
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect())
|
||||
p.fillPath(rounded(r, 3), argb("#12FFFFFF"))
|
||||
if self.value > 0:
|
||||
p.fillPath(rounded(QRectF(0, 0, r.width() * self.value, r.height()), 3), C[self.color])
|
||||
|
||||
|
||||
class Chip(QLabel):
|
||||
"""Border Chip: 26 high, radius 13, #0DFFFFFF with #14FFFFFF, 10 px each side"""
|
||||
|
||||
def __init__(self, text, color, soft=None):
|
||||
super().__init__(text)
|
||||
self.setFont(font(12))
|
||||
self.soft = soft
|
||||
self.setStyleSheet("color: %s; background: transparent; padding: 0 10px;" % css(C[color]))
|
||||
self.setFixedHeight(26)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
p.fillPath(rounded(r, 13), C[self.soft] if self.soft else argb("#0DFFFFFF"))
|
||||
p.setPen(QPen(argb("#14FFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 13))
|
||||
p.end()
|
||||
super().paintEvent(e)
|
||||
|
||||
|
||||
class PathEdit(QLineEdit):
|
||||
"""TextBox Path: mono 12 in InkSoft, Glass with GlassLine (Brand when focused), radius 8, 40 high"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setFont(font(12, family=MONO))
|
||||
self.setFixedHeight(40)
|
||||
self.setStyleSheet(
|
||||
"QLineEdit { color: %s; background: %s; border: 1px solid %s; border-radius: 8px; padding: 0 11px;"
|
||||
" selection-background-color: %s; }"
|
||||
"QLineEdit:focus { border-color: %s; }" % (css(C["InkSoft"]), css(C["Glass"]), css(C["GlassLine"]), css(C["Brand"]),
|
||||
css(C["Brand"])))
|
||||
|
||||
|
||||
class _ItemDelegate(QStyledItemDelegate):
|
||||
"""ComboBoxItem ChoiceItem: radius 6, 10/7 padding, RaisedHover under the mouse, BrandInk when chosen"""
|
||||
|
||||
def __init__(self, combo):
|
||||
super().__init__(combo)
|
||||
self.combo = combo
|
||||
|
||||
def sizeHint(self, opt, idx):
|
||||
return QSize(opt.rect.width(), 7 + 7 + opt.fontMetrics.height())
|
||||
|
||||
def paint(self, p, opt, idx):
|
||||
from PySide6.QtWidgets import QStyle
|
||||
p.save()
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
if opt.state & QStyle.StateFlag.State_MouseOver or opt.state & QStyle.StateFlag.State_Selected:
|
||||
p.fillPath(rounded(QRectF(opt.rect), 6), C["RaisedHover"])
|
||||
p.setFont(font(13))
|
||||
p.setPen(C["BrandInk"] if idx.row() == self.combo.currentIndex() else C["Ink"])
|
||||
p.drawText(QRectF(opt.rect).adjusted(10, 0, -10, 0), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
idx.data())
|
||||
p.restore()
|
||||
|
||||
|
||||
class Choice(QComboBox):
|
||||
"""ComboBox Choice: 40 high, #08FFFFFF with #1FFFFFFF (GlassHover under the mouse), radius 8, its chevron; the list in Raised
|
||||
with LineStrong, radius 8, padding 4"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setFixedHeight(40)
|
||||
self.setFont(font(13))
|
||||
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.hover = False
|
||||
v = QListView()
|
||||
v.setItemDelegate(_ItemDelegate(self))
|
||||
v.setMouseTracking(True)
|
||||
self.setView(v)
|
||||
self.setStyleSheet(
|
||||
"QComboBox { background: transparent; border: none; color: %s; }"
|
||||
"QComboBox::drop-down { width: 0; border: none; } QComboBox::down-arrow { image: none; }"
|
||||
"QComboBox QAbstractItemView { background: %s; border: 1px solid %s; border-radius: 8px; padding: 4px; outline: none;"
|
||||
" color: %s; }" % (css(C["Ink"]), css(C["Raised"]), css(C["LineStrong"]), css(C["Ink"])))
|
||||
self.view().window().setWindowFlags(Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint |
|
||||
Qt.WindowType.NoDropShadowWindowHint)
|
||||
self.view().window().setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
|
||||
def enterEvent(self, e):
|
||||
self.hover = True
|
||||
self.update()
|
||||
|
||||
def leaveEvent(self, e):
|
||||
self.hover = False
|
||||
self.update()
|
||||
|
||||
def showPopup(self):
|
||||
super().showPopup()
|
||||
w = self.view().window() # (4 px below the box, as WPF's Popup margin)
|
||||
w.move(w.x(), self.mapToGlobal(self.rect().bottomLeft()).y() + 4)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
p.fillPath(rounded(r, 8), C["GlassHover"] if self.hover else argb("#08FFFFFF"))
|
||||
p.setPen(QPen(C["Brand"], 2) if self.hasFocus() and self.property("focus_ring") else QPen(argb("#1FFFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 8))
|
||||
p.setPen(QPen(C["InkSoft"], 1.3))
|
||||
x, y = self.width() - 12 - 8, self.height() / 2 - 2
|
||||
path = QPainterPath(QPointF(x, y))
|
||||
path.lineTo(x + 4, y + 4)
|
||||
path.lineTo(x + 8, y)
|
||||
p.drawPath(path)
|
||||
p.setFont(self.font())
|
||||
p.setPen(C["Ink"])
|
||||
p.drawText(QRectF(12, 0, self.width() - 40, self.height()), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
self.currentText())
|
||||
|
||||
|
||||
class Ring(QWidget):
|
||||
"""The build's ring: a #14FFFFFF circle of 10, the Brand arc over it (round caps), the percent in the middle"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setFixedSize(120, 120)
|
||||
self.f = 0.0
|
||||
|
||||
def set(self, f):
|
||||
self.f = max(0.0, min(1.0, f))
|
||||
self.update()
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
p.setPen(QPen(argb("#14FFFFFF"), 10))
|
||||
p.drawEllipse(QRectF(5, 5, 110, 110))
|
||||
if self.f >= 0.002:
|
||||
pen = QPen(C["Brand"], 10)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
p.setPen(pen)
|
||||
p.drawArc(QRectF(5, 5, 110, 110), 90 * 16, -int(self.f * 360 * 16))
|
||||
p.setPen(C["Ink"])
|
||||
p.setFont(font(24, W_BOLD))
|
||||
p.drawText(QRectF(self.rect()), Qt.AlignmentFlag.AlignCenter, "%d%%" % int(self.f * 100))
|
||||
|
||||
|
||||
def tick_path(cx, cy):
|
||||
"""M0,4 L3.5,7.5 L10,0, centred on (cx, cy)"""
|
||||
path = QPainterPath(QPointF(cx - 5, cy))
|
||||
path.lineTo(cx - 1.5, cy + 3.5)
|
||||
path.lineTo(cx + 5, cy - 4)
|
||||
return path
|
||||
111
builder/py/hookshot_builder/updater.py
Normal file
111
builder/py/hookshot_builder/updater.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""The game's update offer and the builder's own (Updater.cs, the same rules). The game (host/hos_update.c) starts this app with
|
||||
--update <game folder> --tag <release>. When these tools are not that release, the release is installed (setup_parts: only the
|
||||
parts that changed are downloaded) and this app starts again on it 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)."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
from . import REPO, paths, setup_parts
|
||||
from .core import Tools
|
||||
|
||||
LATEST = "https://api.github.com/repos/%s/releases/latest" % REPO
|
||||
|
||||
|
||||
def latest_tag():
|
||||
"""The latest release's tag, quietly (None: GitHub did not answer); a few tries, 20 s at most"""
|
||||
if os.environ.get("HOOKSHOT_LATEST_TAG"): # (development: a made-up latest release, "none" for no answer)
|
||||
t = os.environ["HOOKSHOT_LATEST_TAG"]
|
||||
return None if t == "none" else t
|
||||
for attempt in range(3):
|
||||
try:
|
||||
req = urllib.request.Request(LATEST, headers={"User-Agent": "HookshotBuilder", "Accept": "application/vnd.github+json"})
|
||||
with urllib.request.urlopen(req, timeout=8) as r:
|
||||
return json.loads(r.read()).get("tag_name")
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code < 500: # (the API's limit, 60 an hour a PC: the list below instead)
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(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 _ in range(2):
|
||||
try:
|
||||
req = urllib.request.Request(setup_parts.manifest_url(), headers={"User-Agent": "HookshotBuilder"})
|
||||
with urllib.request.urlopen(req, timeout=8) as r:
|
||||
for line in r.read().decode("utf-8", "replace").splitlines():
|
||||
if line.startswith("tag "):
|
||||
return line[4:].strip()
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(2)
|
||||
return None
|
||||
|
||||
|
||||
def restart(args):
|
||||
"""This app started again (on the version just installed: hookshot_builder_start.py picks it) with args, and this one closes"""
|
||||
exe, base_args = paths.launcher_command()
|
||||
subprocess.Popen([exe, *base_args, *args], cwd=os.path.dirname(exe))
|
||||
|
||||
|
||||
class Install:
|
||||
"""The release installed on a worker thread; ui is the window (note, download_progress, download_failed, and done(tag) called
|
||||
on the window's thread through ui.post)"""
|
||||
|
||||
def __init__(self, ui, tag=None, then=None):
|
||||
self.ui, self.tag, self.then, self.cancelled = ui, tag, then, False
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._run, daemon=True).start()
|
||||
return self
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
def _run(self):
|
||||
post = self.ui.post
|
||||
try:
|
||||
tag, _ = setup_parts.install(lambda s: post(self.ui.note, s), lambda f: post(self.ui.download_progress, f) if f >= 0 else None,
|
||||
tag=self.tag, cancel=lambda: self.cancelled)
|
||||
post(self.then, tag)
|
||||
except setup_parts.SetupError as e:
|
||||
msg = str(e)
|
||||
post(self.ui.download_failed, "The download was cancelled. Your game folder is unchanged." if msg == "cancelled" else
|
||||
msg + " Your game folder is unchanged.")
|
||||
except Exception as e: # (anything else: said, not a silent window)
|
||||
post(self.ui.download_failed, "%s. Your game folder is unchanged." % e)
|
||||
|
||||
|
||||
def update_folder(ui, folder, tag, fetched):
|
||||
"""The game in folder built again with the latest release: here when these tools are it (or fetched), else after installing it
|
||||
(this app then starts again on it with --update folder --tag t --fetched)"""
|
||||
ui.begin_update(folder, tag)
|
||||
tools = Tools.find()
|
||||
# (just installed, but another release than asked for: GitHub's latest link lags right after a publish)
|
||||
if fetched and tag and tools and tools.version and tools.version != tag:
|
||||
ui.download_failed("The update installed %s, not %s: GitHub's download links can lag right after a release. Try Update again "
|
||||
"in a few minutes." % (tools.version, tag))
|
||||
return
|
||||
if tools and (fetched or (tag and tools.version == tag)):
|
||||
ui.update_build(tools, folder)
|
||||
return
|
||||
ui.note("Asking GitHub for the latest release")
|
||||
|
||||
def installed(new_tag):
|
||||
restart(["--update", folder, "--tag", new_tag, "--fetched"])
|
||||
ui.quit_app()
|
||||
ui.download = Install(ui, tag, installed).start()
|
||||
|
||||
|
||||
def run_latest_setup(ui):
|
||||
"""The latest release installed, then this app started again on it (the builder's own update)"""
|
||||
ui.note("Asking GitHub for the latest release")
|
||||
|
||||
def installed(_tag):
|
||||
restart([])
|
||||
ui.quit_app()
|
||||
ui.download = Install(ui, None, installed).start()
|
||||
1812
builder/py/hookshot_builder/window.py
Normal file
1812
builder/py/hookshot_builder/window.py
Normal file
File diff suppressed because it is too large
Load Diff
103
builder/py/hookshot_builder_start.py
Normal file
103
builder/py/hookshot_builder_start.py
Normal file
@@ -0,0 +1,103 @@
|
||||
"""Starts Hookshot Builder: python.exe -I hookshot_builder_start.py [--update <game folder> --tag <release> [--fetched]] [--launch
|
||||
<game folder>] [--repair]. Qt for Python is the "qt" folder beside this file's (the package), or HOOKSHOT_QT (development)."""
|
||||
import argparse
|
||||
import ctypes
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def settle():
|
||||
"""The package (python, qt, app) copied once into %LOCALAPPDATA%\\HookshotBuilder\\app and started from there: the shortcuts, the
|
||||
game folder's launcher and the game's update offer point at that copy, which stays where it is whatever happens to the folder
|
||||
the download was unpacked into. True: the copy was started, this one ends"""
|
||||
import shutil
|
||||
import subprocess
|
||||
root = os.path.dirname(HERE)
|
||||
version = os.path.join(HERE, "VERSION")
|
||||
if not os.path.isfile(version) or not os.path.isdir(os.path.join(root, "python")) or os.environ.get("HOOKSHOT_NO_SETTLE"):
|
||||
return False # (a source checkout: run where it is)
|
||||
base = os.environ.get("HOOKSHOT_SETUP_BASE") or os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~"),
|
||||
"HookshotBuilder")
|
||||
home = os.path.join(base, "app")
|
||||
if os.path.normcase(os.path.abspath(root)) == os.path.normcase(os.path.abspath(home)):
|
||||
return False
|
||||
want = open(version, encoding="utf-8").read().strip()
|
||||
try:
|
||||
have = open(os.path.join(home, "app", "VERSION"), encoding="utf-8").read().strip()
|
||||
except OSError:
|
||||
have = ""
|
||||
if have != want:
|
||||
part = home + ".part"
|
||||
shutil.rmtree(part, ignore_errors=True)
|
||||
try:
|
||||
shutil.copytree(root, part, ignore=shutil.ignore_patterns("__pycache__"))
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
os.replace(part, home)
|
||||
except OSError:
|
||||
shutil.rmtree(part, ignore_errors=True)
|
||||
return False # (could not copy: run from here)
|
||||
exe = os.path.join(home, "python", "pythonw.exe")
|
||||
if not os.path.isfile(exe):
|
||||
exe = os.path.join(home, "python", "python.exe")
|
||||
subprocess.Popen([exe, "-I", os.path.join(home, "app", "hookshot_builder_start.py"), *sys.argv[1:]], cwd=home)
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(add_help=False)
|
||||
p.add_argument("--update")
|
||||
p.add_argument("--tag")
|
||||
p.add_argument("--fetched", action="store_true")
|
||||
p.add_argument("--launch")
|
||||
p.add_argument("--repair", action="store_true")
|
||||
args, _ = p.parse_known_args()
|
||||
if settle():
|
||||
return
|
||||
# (the app's code: the newest of this folder's and the installed release's, so a release's fixes reach the window without a new
|
||||
# download of the package; the package's own when the release has none)
|
||||
sys.path.insert(0, HERE)
|
||||
try:
|
||||
from hookshot_builder import setup_parts
|
||||
cur = setup_parts.current()
|
||||
newer = os.path.join(cur, "HookshotBuilder", "tools", "builder_py") if cur else None
|
||||
if newer and os.path.isfile(os.path.join(newer, "hookshot_builder", "window.py")) and not os.environ.get("HOOKSHOT_OWN_APP"):
|
||||
for m in [m for m in sys.modules if m == "hookshot_builder" or m.startswith("hookshot_builder.")]:
|
||||
del sys.modules[m]
|
||||
sys.path.insert(0, newer)
|
||||
except Exception:
|
||||
pass
|
||||
qt = os.environ.get("HOOKSHOT_QT") or os.path.join(os.path.dirname(HERE), "qt")
|
||||
if os.path.isdir(qt):
|
||||
sys.path.insert(0, qt)
|
||||
os.add_dll_directory(qt)
|
||||
# (the taskbar groups and shows the window by this id and its own icon, not as python.exe)
|
||||
from hookshot_builder import APP_ID
|
||||
try:
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_ID)
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
try: # (a console the start left, when started by python.exe rather than pythonw.exe: not shown)
|
||||
if ctypes.windll.kernel32.GetConsoleWindow() and not os.environ.get("HOOKSHOT_CONSOLE"):
|
||||
ctypes.windll.kernel32.FreeConsole()
|
||||
except OSError:
|
||||
pass
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QGuiApplication, QIcon
|
||||
from PySide6.QtWidgets import QApplication
|
||||
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
|
||||
app = QApplication(sys.argv[:1])
|
||||
app.setApplicationName("Hookshot")
|
||||
app.setApplicationDisplayName("Hookshot")
|
||||
from hookshot_builder import paths, theme
|
||||
from hookshot_builder.window import Window
|
||||
app.setWindowIcon(QIcon(os.path.join(paths.ASSETS, "hookshot.ico")))
|
||||
theme.load_fonts()
|
||||
w = Window(args)
|
||||
w.show()
|
||||
sys.exit(app.exec())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
58
builder/py/shots.py
Normal file
58
builder/py/shots.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""Renders the window's pages to PNGs without showing it (QT_QPA_PLATFORM=offscreen): python -I shots.py <out folder>. For comparing
|
||||
the layout with the WPF builder's screenshots."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
qt = os.environ.get("HOOKSHOT_QT")
|
||||
if qt:
|
||||
sys.path.insert(0, qt)
|
||||
os.add_dll_directory(os.path.join(qt, "PySide6"))
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
out = sys.argv[1]
|
||||
os.makedirs(out, exist_ok=True)
|
||||
|
||||
from PySide6.QtCore import QTimer # noqa: E402
|
||||
from PySide6.QtWidgets import QApplication # noqa: E402
|
||||
|
||||
app = QApplication(sys.argv[:1])
|
||||
from hookshot_builder import theme, window # noqa: E402
|
||||
|
||||
theme.load_fonts()
|
||||
|
||||
|
||||
class Args:
|
||||
update = tag = launch = None
|
||||
fetched = repair = False
|
||||
|
||||
|
||||
pages = ["files", "build", "ready", "problem", "update", "launch", "splash"]
|
||||
state = {"i": 0, "w": None}
|
||||
|
||||
|
||||
def next_page():
|
||||
if state["w"] is not None:
|
||||
state["w"].grab().save(os.path.join(out, pages[state["i"] - 1] + ".png"))
|
||||
state["w"].close()
|
||||
if state["i"] >= len(pages):
|
||||
app.quit()
|
||||
return
|
||||
name = pages[state["i"]]
|
||||
state["i"] += 1
|
||||
if name not in ("files", "splash"):
|
||||
os.environ["HOOKSHOT_UI_PREVIEW"] = name
|
||||
else:
|
||||
os.environ.pop("HOOKSHOT_UI_PREVIEW", None)
|
||||
w = window.Window(Args())
|
||||
if name == "splash":
|
||||
w.start = lambda: None
|
||||
w.splash.text = "Looking for your game files…"
|
||||
w.show()
|
||||
state["w"] = w
|
||||
QTimer.singleShot(2600 if name != "splash" else 600, next_page)
|
||||
|
||||
|
||||
QTimer.singleShot(0, next_page)
|
||||
app.exec()
|
||||
print("wrote", out)
|
||||
2
builder/setup/.gitignore
vendored
Normal file
2
builder/setup/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*.exe
|
||||
*.o
|
||||
BIN
builder/setup/hookshot.ico
Normal file
BIN
builder/setup/hookshot.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 71 KiB |
881
builder/setup/setup.c
Normal file
881
builder/setup/setup.c
Normal file
@@ -0,0 +1,881 @@
|
||||
/* HookshotBuilder-Setup.exe: the one file players download. It reads the latest release's hookshot-setup.txt, downloads
|
||||
the parts it names (the builder and its tools from this repository's release, llvm-mingw from its own official
|
||||
release), checks each one's SHA-256, unpacks them with Windows' own tar.exe into %LOCALAPPDATA%\HookshotBuilder\<tag>
|
||||
and starts the builder there. Parts already downloaded and checked are used again; a release already installed just
|
||||
starts. Files fetched by a program carry no "downloaded from the internet" mark, and the download itself holds no
|
||||
scripts, which is what antivirus programs' machine-learning guesses (Trojan:Script/...!ml) fired on.
|
||||
|
||||
hookshot-setup.txt, one item a line:
|
||||
tag <tag>
|
||||
part <sha256> <bytes> <folder under the install> <top folder in the zip to rename, or -> <new name, or -> <url>
|
||||
run <the builder, relative to the install>
|
||||
Build: clang -O2 -mwindows -municode setup.c setup_rc.o -lwinhttp -lbcrypt -lcomctl32 -lshell32 -lole32 -o HookshotBuilder-Setup.exe */
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#ifndef UNICODE
|
||||
#define UNICODE
|
||||
#endif
|
||||
#define _UNICODE
|
||||
#include <windows.h>
|
||||
#include <winhttp.h>
|
||||
#include <bcrypt.h>
|
||||
#include <commctrl.h>
|
||||
#include <shlobj.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#define WM_STATUS (WM_APP + 1)
|
||||
#define WM_DONE (WM_APP + 2)
|
||||
#define MAX_PARTS 16
|
||||
|
||||
static HWND g_win, g_text, g_bar;
|
||||
static wchar_t g_status[512];
|
||||
static volatile LONG g_percent = -1;
|
||||
static DWORD g_http_status; /* (the last answer: 0 when the server was not reached) */
|
||||
static wchar_t g_cmdline[2048];
|
||||
/* (RecompLauncher) --cli <make_game.py's options>: no window, the builder's lines on this process's stdout and stderr, its exit code
|
||||
as ours; --play <game folder>: the game itself, waited for. Neither is used by the builder's own start, which is unchanged. */
|
||||
static int g_headless;
|
||||
static DWORD g_exit;
|
||||
|
||||
static void say_error(const wchar_t *msg) {
|
||||
char u[2048];
|
||||
const int n = WideCharToMultiByte(CP_UTF8, 0, msg, -1, u, (int)sizeof u - 8, NULL, NULL);
|
||||
const HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
|
||||
DWORD wrote;
|
||||
if (n > 0 && h && h != INVALID_HANDLE_VALUE) WriteFile(h, "error ", 6, &wrote, NULL), WriteFile(h, u, n - 1, &wrote, NULL), WriteFile(h, "\n", 1, &wrote, NULL);
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
char sha[65];
|
||||
unsigned long long size;
|
||||
char dest[260], from[260], to[260], url[1024];
|
||||
} Part;
|
||||
/* the next non-empty line of a text, cut in place (its \r or \n made 0); *next moves past it. NULL at the end
|
||||
(strtok's work without its hidden state) */
|
||||
static char *next_line(char **next) {
|
||||
char *p = *next;
|
||||
while (*p == '\r' || *p == '\n') p++;
|
||||
if (!*p) return *next = p, (char *)NULL;
|
||||
char *line = p;
|
||||
while (*p && *p != '\r' && *p != '\n') p++;
|
||||
if (*p) *p++ = 0;
|
||||
*next = p;
|
||||
return line;
|
||||
}
|
||||
/* a name from the setup list (a tag, or with path set a relative path with / or \ between its parts): letters, digits
|
||||
and . _ + - only, no ".." part, no drive, no root */
|
||||
static int list_name_ok(const char *s, int path) {
|
||||
if (!*s || *s == '/' || *s == '\\') return 0;
|
||||
for (const char *q = s; *q; q++)
|
||||
if (!((*q >= 'a' && *q <= 'z') || (*q >= 'A' && *q <= 'Z') || (*q >= '0' && *q <= '9') || strchr("._+-", *q) ||
|
||||
(path && (*q == '/' || *q == '\\'))))
|
||||
return 0;
|
||||
for (const char *q = s; *q;) { /* (each part: not "." or "..") */
|
||||
const size_t n = path ? strcspn(q, "/\\") : strlen(q);
|
||||
if ((n == 1 && q[0] == '.') || (n == 2 && q[0] == '.' && q[1] == '.') || !n) return 0;
|
||||
q += n;
|
||||
if (*q) q++;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void status(const wchar_t *fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vswprintf(g_status, 512, fmt, ap);
|
||||
va_end(ap);
|
||||
PostMessageW(g_win, WM_STATUS, 0, 0);
|
||||
}
|
||||
|
||||
static void fail(const wchar_t *fmt, ...) {
|
||||
wchar_t msg[1024];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vswprintf(msg, 1024, fmt, ap);
|
||||
va_end(ap);
|
||||
if (g_headless) say_error(msg), ExitProcess(1);
|
||||
MessageBoxW(g_win, msg, L"Hookshot Builder setup", MB_OK | MB_ICONERROR);
|
||||
PostMessageW(g_win, WM_DONE, 1, 0);
|
||||
ExitThread(1);
|
||||
}
|
||||
|
||||
/* ---- HTTPS GET into a sink, following redirects (GitHub's release links go to its download host) ---- */
|
||||
typedef int (*Sink)(void *user, const void *data, DWORD n);
|
||||
|
||||
static int http_get(const char *url8, Sink sink, void *user, unsigned long long expect, const wchar_t *accept) {
|
||||
wchar_t url[1024];
|
||||
MultiByteToWideChar(CP_UTF8, 0, url8, -1, url, 1024);
|
||||
URL_COMPONENTS uc = {sizeof uc};
|
||||
wchar_t host[256], path[1024];
|
||||
uc.lpszHostName = host, uc.dwHostNameLength = 256;
|
||||
uc.lpszUrlPath = path, uc.dwUrlPathLength = 1024;
|
||||
if (!WinHttpCrackUrl(url, 0, 0, &uc)) return 0;
|
||||
HINTERNET s = WinHttpOpen(L"HookshotBuilder-Setup/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, NULL, NULL, 0);
|
||||
if (!s) s = WinHttpOpen(L"HookshotBuilder-Setup/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, 0);
|
||||
if (!s) return 0;
|
||||
/* (a stalled download fails after a minute without data, with the message, instead of waiting forever: a GitHub 504 hour) */
|
||||
WinHttpSetTimeouts(s, 30000, 30000, 30000, 60000);
|
||||
DWORD policy = WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP; /* (a redirect never drops to clear text) */
|
||||
WinHttpSetOption(s, WINHTTP_OPTION_REDIRECT_POLICY, &policy, sizeof policy);
|
||||
HINTERNET c = WinHttpConnect(s, host, uc.nPort, 0);
|
||||
LPCWSTR types[2] = {accept, NULL};
|
||||
HINTERNET r = c ? WinHttpOpenRequest(c, L"GET", path, NULL, WINHTTP_NO_REFERER, accept ? types : WINHTTP_DEFAULT_ACCEPT_TYPES,
|
||||
uc.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0)
|
||||
: NULL;
|
||||
int ok = 0;
|
||||
if (r && WinHttpSendRequest(r, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0) && WinHttpReceiveResponse(r, NULL)) {
|
||||
DWORD code = 0, len = sizeof code;
|
||||
WinHttpQueryHeaders(r, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &code, &len, NULL);
|
||||
g_http_status = code;
|
||||
if (code == 200) {
|
||||
static char buf[1 << 16];
|
||||
unsigned long long got = 0;
|
||||
ok = 1;
|
||||
for (;;) {
|
||||
DWORD n = 0;
|
||||
if (!WinHttpReadData(r, buf, sizeof buf, &n)) { ok = 0; break; }
|
||||
if (!n) break;
|
||||
if (!sink(user, buf, n)) { ok = 0; break; }
|
||||
got += n;
|
||||
if (expect) InterlockedExchange(&g_percent, (LONG)(got * 100 / expect)), PostMessageW(g_win, WM_STATUS, 0, 0);
|
||||
}
|
||||
if (expect && got != expect) ok = 0;
|
||||
}
|
||||
}
|
||||
if (r) WinHttpCloseHandle(r);
|
||||
if (c) WinHttpCloseHandle(c);
|
||||
WinHttpCloseHandle(s);
|
||||
return ok;
|
||||
}
|
||||
|
||||
typedef struct { char *p; size_t n, cap; } Mem;
|
||||
static int mem_sink(void *u, const void *d, DWORD n) {
|
||||
Mem *m = (Mem *)u;
|
||||
if (m->n + n + 1 > m->cap) {
|
||||
m->cap = (m->n + n + 1) * 2;
|
||||
m->p = (char *)realloc(m->p, m->cap);
|
||||
if (!m->p) return 0;
|
||||
}
|
||||
memcpy(m->p + m->n, d, n);
|
||||
m->n += n;
|
||||
m->p[m->n] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
typedef struct { HANDLE f; BCRYPT_HASH_HANDLE h; } FileSink;
|
||||
static int file_sink(void *u, const void *d, DWORD n) {
|
||||
FileSink *s = (FileSink *)u;
|
||||
DWORD w = 0;
|
||||
if (!WriteFile(s->f, d, n, &w, NULL) || w != n) return 0;
|
||||
return BCryptHashData(s->h, (PUCHAR)d, n, 0) == 0;
|
||||
}
|
||||
|
||||
static void hex(const unsigned char *d, int n, char *out) {
|
||||
for (int i = 0; i < n; i++) sprintf(out + 2 * i, "%02x", d[i]);
|
||||
}
|
||||
|
||||
/* the SHA-256 of a file already on disk (a part downloaded before) */
|
||||
static int file_sha256(const wchar_t *path, char out[65]) {
|
||||
BCRYPT_ALG_HANDLE a;
|
||||
BCRYPT_HASH_HANDLE h;
|
||||
if (BCryptOpenAlgorithmProvider(&a, BCRYPT_SHA256_ALGORITHM, NULL, 0)) return 0;
|
||||
BCryptCreateHash(a, &h, NULL, 0, NULL, 0, 0);
|
||||
HANDLE f = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
|
||||
int ok = f != INVALID_HANDLE_VALUE;
|
||||
static unsigned char buf[1 << 20];
|
||||
DWORD n;
|
||||
while (ok && ReadFile(f, buf, sizeof buf, &n, NULL) && n) BCryptHashData(h, buf, n, 0);
|
||||
if (f != INVALID_HANDLE_VALUE) CloseHandle(f);
|
||||
unsigned char d[32];
|
||||
BCryptFinishHash(h, d, 32, 0);
|
||||
BCryptDestroyHash(h);
|
||||
BCryptCloseAlgorithmProvider(a, 0);
|
||||
if (ok) hex(d, 32, out);
|
||||
return ok;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
DWORD code, start_error, status_error, capture_error;
|
||||
char error[512];
|
||||
} RunResult;
|
||||
|
||||
static RunResult run_wait(wchar_t *cmd, const wchar_t *dir) {
|
||||
RunResult result = {0};
|
||||
HANDLE rd = NULL, wr = NULL, null = INVALID_HANDLE_VALUE;
|
||||
SECURITY_ATTRIBUTES sa = {sizeof sa, NULL, TRUE};
|
||||
STARTUPINFOW si = {sizeof si};
|
||||
PROCESS_INFORMATION pi;
|
||||
si.dwFlags = STARTF_USESHOWWINDOW, si.wShowWindow = SW_HIDE;
|
||||
if (CreatePipe(&rd, &wr, &sa, 0)) {
|
||||
if (SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0))
|
||||
null = CreateFileW(L"NUL", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL);
|
||||
if (null != INVALID_HANDLE_VALUE) {
|
||||
si.dwFlags |= STARTF_USESTDHANDLES;
|
||||
si.hStdInput = si.hStdOutput = null; /* (setup has no console: supply valid inherited handles) */
|
||||
si.hStdError = wr;
|
||||
} else {
|
||||
result.capture_error = GetLastError();
|
||||
CloseHandle(rd), CloseHandle(wr);
|
||||
rd = wr = NULL;
|
||||
}
|
||||
} else result.capture_error = GetLastError();
|
||||
/* Capturing a diagnostic is optional: if pipe setup fails, keep the original child-process route. */
|
||||
if (!CreateProcessW(NULL, cmd, NULL, NULL, wr != NULL, CREATE_NO_WINDOW, NULL, dir, &si, &pi)) {
|
||||
result.start_error = GetLastError();
|
||||
if (rd) CloseHandle(rd);
|
||||
if (wr) CloseHandle(wr);
|
||||
if (null != INVALID_HANDLE_VALUE) CloseHandle(null);
|
||||
return result;
|
||||
}
|
||||
if (wr) CloseHandle(wr); /* (otherwise EOF never arrives on the parent's reader) */
|
||||
if (null != INVALID_HANDLE_VALUE) CloseHandle(null);
|
||||
if (rd) {
|
||||
char buf[512];
|
||||
DWORD n;
|
||||
size_t kept = 0;
|
||||
while (ReadFile(rd, buf, sizeof buf, &n, NULL) && n) {
|
||||
size_t copy = n < sizeof result.error - 1 - kept ? n : sizeof result.error - 1 - kept;
|
||||
memcpy(result.error + kept, buf, copy);
|
||||
kept += copy; /* (keep draining after this buffer fills, so a noisy child cannot block) */
|
||||
}
|
||||
CloseHandle(rd);
|
||||
}
|
||||
WaitForSingleObject(pi.hProcess, INFINITE);
|
||||
if (!GetExitCodeProcess(pi.hProcess, &result.code)) result.status_error = GetLastError();
|
||||
CloseHandle(pi.hThread), CloseHandle(pi.hProcess);
|
||||
return result;
|
||||
}
|
||||
|
||||
static void mkdirs(const wchar_t *path) {
|
||||
wchar_t p[MAX_PATH];
|
||||
wcsncpy(p, path, MAX_PATH - 1);
|
||||
p[MAX_PATH - 1] = 0;
|
||||
for (wchar_t *q = p + 3; *q; q++)
|
||||
if (*q == L'\\') *q = 0, CreateDirectoryW(p, NULL), *q = L'\\';
|
||||
CreateDirectoryW(p, NULL);
|
||||
}
|
||||
|
||||
/* a folder and everything in it (a version folder, a half-unpacked one) */
|
||||
static void rmtree(const wchar_t *dir) {
|
||||
wchar_t pat[MAX_PATH], p[MAX_PATH];
|
||||
WIN32_FIND_DATAW fd;
|
||||
swprintf(pat, MAX_PATH, L"%ls\\*", dir);
|
||||
HANDLE h = FindFirstFileW(pat, &fd);
|
||||
if (h != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
if (!wcscmp(fd.cFileName, L".") || !wcscmp(fd.cFileName, L"..")) continue;
|
||||
swprintf(p, MAX_PATH, L"%ls\\%ls", dir, fd.cFileName);
|
||||
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && !(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) rmtree(p);
|
||||
else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) RemoveDirectoryW(p); /* (a link: never what it points to) */
|
||||
else SetFileAttributesW(p, FILE_ATTRIBUTE_NORMAL), DeleteFileW(p);
|
||||
} while (FindNextFileW(h, &fd));
|
||||
FindClose(h);
|
||||
}
|
||||
RemoveDirectoryW(dir);
|
||||
}
|
||||
|
||||
static void read_small(const wchar_t *path, char *out, int n) {
|
||||
out[0] = 0;
|
||||
HANDLE f = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
|
||||
if (f == INVALID_HANDLE_VALUE) return;
|
||||
DWORD got = 0;
|
||||
ReadFile(f, out, (DWORD)n - 1, &got, NULL);
|
||||
CloseHandle(f);
|
||||
out[got] = 0;
|
||||
for (char *q = out; *q; q++)
|
||||
if (*q == '\r' || *q == '\n') { *q = 0; break; }
|
||||
}
|
||||
|
||||
static void write_small(const wchar_t *path, const char *text) {
|
||||
HANDLE f = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
|
||||
if (f == INVALID_HANDLE_VALUE) return;
|
||||
DWORD n;
|
||||
WriteFile(f, text, (DWORD)strlen(text), &n, NULL);
|
||||
CloseHandle(f);
|
||||
}
|
||||
|
||||
/* A part that unpacks into a folder of its own (the tools the builder ships: Python, emsdk, the CPM packages, third_party,
|
||||
wgpu-native, llvm-mingw): that folder, relative to a version's folder, in rel (0: the part has none, e.g. the builder's own code).
|
||||
Named from its download (HookshotBuilder-<name>-<sha>.zip) or, for llvm-mingw, from its dest and rename. */
|
||||
static int part_folder(const Part *p, wchar_t *rel, int n) {
|
||||
if (strcmp(p->to, "-") && strcmp(p->dest, ".")) { /* (llvm-mingw: dest HookshotBuilder/tools, renamed to llvm-mingw) */
|
||||
swprintf(rel, n, L"%hs\\%hs", p->dest, p->to);
|
||||
} else {
|
||||
const char *b = strrchr(p->url, '/');
|
||||
b = b ? b + 1 : p->url;
|
||||
static const char *const own[] = {"python", "emsdk", "cpm", "third_party", "wgpu-native"};
|
||||
int found = 0;
|
||||
for (int i = 0; i < 5 && !found; i++) {
|
||||
char want[64];
|
||||
snprintf(want, sizeof want, "HookshotBuilder-%s-", own[i]);
|
||||
if (!strncmp(b, want, strlen(want))) swprintf(rel, n, L"HookshotBuilder\\tools\\%hs", own[i]), found = 1;
|
||||
}
|
||||
if (!found) return 0;
|
||||
}
|
||||
for (wchar_t *q = rel; *q; q++) if (*q == L'/') *q = L'\\';
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* (players asked for less in %LOCALAPPDATA%: the downloaded zips are not kept beside the unpacked version any more. So that an update
|
||||
still downloads only what changed, a part whose checksum the installed version lists in its parts.txt (and whose folder it has)
|
||||
is moved over from it instead of downloaded: that version is deleted after the install anyway) */
|
||||
static int reuse_part(const wchar_t *versions, const char *tag, const Part *p, const wchar_t *install) {
|
||||
wchar_t rel[MAX_PATH], cur[MAX_PATH], list[MAX_PATH], from[MAX_PATH], to[MAX_PATH], parent[MAX_PATH];
|
||||
char was[128];
|
||||
if (!part_folder(p, rel, MAX_PATH)) return 0;
|
||||
swprintf(cur, MAX_PATH, L"%ls\\current.txt", versions);
|
||||
read_small(cur, was, sizeof was);
|
||||
if (!was[0] || !strcmp(was, tag)) return 0;
|
||||
swprintf(list, MAX_PATH, L"%ls\\%hs\\parts.txt", versions, was);
|
||||
HANDLE f = CreateFileW(list, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
|
||||
if (f == INVALID_HANDLE_VALUE) return 0;
|
||||
char buf[8192];
|
||||
DWORD got = 0;
|
||||
ReadFile(f, buf, sizeof buf - 1, &got, NULL);
|
||||
CloseHandle(f);
|
||||
buf[got] = 0;
|
||||
if (!strstr(buf, p->sha)) return 0;
|
||||
swprintf(from, MAX_PATH, L"%ls\\%hs\\%ls", versions, was, rel);
|
||||
swprintf(to, MAX_PATH, L"%ls\\%ls", install, rel);
|
||||
if (GetFileAttributesW(from) == INVALID_FILE_ATTRIBUTES) return 0;
|
||||
wcscpy(parent, to);
|
||||
wchar_t *slash = wcsrchr(parent, L'\\');
|
||||
if (slash) *slash = 0, mkdirs(parent);
|
||||
return MoveFileW(from, to) != 0;
|
||||
}
|
||||
|
||||
/* The checksums of the parts this version holds in folders of their own (reuse_part reads them at the next update) */
|
||||
static void write_parts(const wchar_t *install, const Part *parts, int nparts) {
|
||||
wchar_t list[MAX_PATH], rel[MAX_PATH];
|
||||
swprintf(list, MAX_PATH, L"%ls\\parts.txt", install);
|
||||
HANDLE f = CreateFileW(list, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
|
||||
if (f == INVALID_HANDLE_VALUE) return;
|
||||
for (int i = 0; i < nparts; i++) {
|
||||
if (!part_folder(&parts[i], rel, MAX_PATH)) continue;
|
||||
char line[128];
|
||||
const int n = snprintf(line, sizeof line, "%s\n", parts[i].sha);
|
||||
DWORD put;
|
||||
WriteFile(f, line, (DWORD)n, &put, NULL);
|
||||
}
|
||||
CloseHandle(f);
|
||||
}
|
||||
|
||||
/* (as NX2navi's launcher keeps them: the version just installed and the one before it stay, older versions go, and so do downloads
|
||||
the list no longer names; a part unchanged since the last release keeps its checksum and stays cached) */
|
||||
static void prune(const wchar_t *versions, const wchar_t *downloads, const char *tag, const Part *parts, int nparts) {
|
||||
wchar_t cur[MAX_PATH], prev[MAX_PATH], pat[MAX_PATH], p[MAX_PATH];
|
||||
char was[128], before[128];
|
||||
swprintf(cur, MAX_PATH, L"%ls\\current.txt", versions);
|
||||
swprintf(prev, MAX_PATH, L"%ls\\previous.txt", versions);
|
||||
read_small(cur, was, sizeof was);
|
||||
if (strcmp(was, tag)) {
|
||||
if (was[0]) write_small(prev, was);
|
||||
write_small(cur, tag);
|
||||
}
|
||||
read_small(prev, before, sizeof before);
|
||||
WIN32_FIND_DATAW fd;
|
||||
swprintf(pat, MAX_PATH, L"%ls\\*", versions);
|
||||
HANDLE h = FindFirstFileW(pat, &fd);
|
||||
if (h != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || !wcscmp(fd.cFileName, L".") || !wcscmp(fd.cFileName, L"..")) continue;
|
||||
char name[260];
|
||||
WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, name, sizeof name, NULL, NULL);
|
||||
/* (issue 611: only the version installed stays; the one before was 1.3 GB nobody rolled back to. A folder still in use
|
||||
(the builder that started this, closing; a build it left) cannot be renamed: it stays, and goes at a later run) */
|
||||
(void)before;
|
||||
if (!strcmp(name, tag)) continue;
|
||||
swprintf(p, MAX_PATH, L"%ls\\%ls", versions, fd.cFileName);
|
||||
wchar_t gone[MAX_PATH];
|
||||
swprintf(gone, MAX_PATH, L"%ls.gone", p);
|
||||
if (wcslen(fd.cFileName) > 5 && !wcscmp(fd.cFileName + wcslen(fd.cFileName) - 5, L".gone")) rmtree(p);
|
||||
else if (MoveFileW(p, gone)) rmtree(gone);
|
||||
} while (FindNextFileW(h, &fd));
|
||||
FindClose(h);
|
||||
}
|
||||
swprintf(pat, MAX_PATH, L"%ls\\*.zip", downloads);
|
||||
h = FindFirstFileW(pat, &fd);
|
||||
if (h != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
char name[260];
|
||||
WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, name, sizeof name, NULL, NULL);
|
||||
int keep = 0;
|
||||
for (int i = 0; i < nparts; i++)
|
||||
if (!strncmp(name, parts[i].sha, 64)) keep = 1;
|
||||
if (!keep) swprintf(p, MAX_PATH, L"%ls\\%ls", downloads, fd.cFileName), DeleteFileW(p);
|
||||
} while (FindNextFileW(h, &fd));
|
||||
FindClose(h);
|
||||
}
|
||||
}
|
||||
|
||||
static void w(const char *s8, wchar_t *out, int n) { MultiByteToWideChar(CP_UTF8, 0, s8, -1, out, n); }
|
||||
|
||||
/* (HOOKSHOT_SETUP_LIST=<url>: another list, for testing a release before it is the latest) */
|
||||
/* ---- The GitHub API's link for a release file (after PR 546 by nicholasgower, issue 544). GitHub answered the release
|
||||
page's cached link (releases/latest/download/...) with 504 for hours on 2026-11-08 while its API still answered: the API
|
||||
gives the file's own asset link, which redirects to a fresh download. Used when the release link fails. ---- */
|
||||
static int json_space(char c) { return c == 32 || c == 9 || c == 10 || c == 13; }
|
||||
|
||||
static int json_string_after(const char *p, const char *end, char *out, int n) {
|
||||
while (p < end && json_space(*p)) p++;
|
||||
if (p >= end || *p != ':') return 0;
|
||||
for (p++; p < end && json_space(*p); p++) {}
|
||||
if (p >= end || *p != '"') return 0;
|
||||
int i = 0;
|
||||
for (p++; p < end && *p != '"'; p++) {
|
||||
if (*p == '\\' && p + 1 < end) p++;
|
||||
if (i + 1 < n) out[i++] = *p;
|
||||
}
|
||||
if (p >= end) return 0;
|
||||
out[i] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* The API link of the asset called name in a release's JSON (in an asset object its own "url" comes before its "name") */
|
||||
static int asset_from_json(const char *json, size_t len, const char *name, char *out, int n) {
|
||||
const char *end = json + len, *at = NULL;
|
||||
char v[600];
|
||||
for (const char *p = json; (p = strstr(p, "\"name\"")) && p < end; p += 6)
|
||||
if (json_string_after(p + 6, end, v, sizeof v) && !strcmp(v, name)) { at = p; break; }
|
||||
if (!at) return 0;
|
||||
const char *url = NULL;
|
||||
for (const char *p = json; p + 5 <= at; p++)
|
||||
if (!strncmp(p, "\"url\"", 5)) url = p;
|
||||
return url && json_string_after(url + 5, end, out, n) && !strncmp(out, "https://api.github.com/", 23);
|
||||
}
|
||||
|
||||
/* repo "owner/name", tag NULL for the latest release */
|
||||
static int api_asset_url(const char *repo, const char *tag, const char *name, char *out, int n) {
|
||||
char api[1024];
|
||||
if (tag) snprintf(api, sizeof api, "https://api.github.com/repos/%s/releases/tags/%s", repo, tag);
|
||||
else snprintf(api, sizeof api, "https://api.github.com/repos/%s/releases/latest", repo);
|
||||
Mem m = {0};
|
||||
const int found = http_get(api, mem_sink, &m, 0, L"application/vnd.github+json") && m.p && asset_from_json(m.p, m.n, name, out, n);
|
||||
free(m.p);
|
||||
return found;
|
||||
}
|
||||
|
||||
/* https://github.com/<owner>/<repo>/releases/download/<tag>/<name> or .../releases/latest/download/<name> -> its API link */
|
||||
static int api_link_for(const char *url, char *out, int n) {
|
||||
static const char pre[] = "https://github.com/";
|
||||
char repo[256], tag[256], name[260];
|
||||
if (strncmp(url, pre, sizeof pre - 1)) return 0;
|
||||
const char *p = url + sizeof pre - 1, *slash = strchr(p, '/');
|
||||
if (!slash || !(slash = strchr(slash + 1, '/'))) return 0;
|
||||
if ((size_t)(slash - p) >= sizeof repo) return 0;
|
||||
memcpy(repo, p, slash - p), repo[slash - p] = 0;
|
||||
const char *t;
|
||||
int latest = 0;
|
||||
if (!strncmp(slash, "/releases/latest/download/", 26)) latest = 1, t = slash + 26;
|
||||
else if (!strncmp(slash, "/releases/download/", 19)) {
|
||||
t = slash + 19;
|
||||
const char *e = strchr(t, '/');
|
||||
if (!e || (size_t)(e - t) >= sizeof tag) return 0;
|
||||
memcpy(tag, t, e - t), tag[e - t] = 0;
|
||||
t = e + 1;
|
||||
} else return 0;
|
||||
if (!*t || strlen(t) >= sizeof name || strpbrk(t, "/?#")) return 0;
|
||||
strcpy(name, t);
|
||||
return api_asset_url(repo, latest ? NULL : tag, name, out, n);
|
||||
}
|
||||
|
||||
/* an answer worth trying again: none (no connection), a server error, a download cut off half way (200), a timeout, or the API's
|
||||
rate limit (403/429) */
|
||||
static int retryable(DWORD status) {
|
||||
return !status || status >= 500 || status == 200 || status == 408 || status == 429 || status == 403;
|
||||
}
|
||||
|
||||
/* (the release the builder asked for: --tag <t> in the arguments, "" when none) */
|
||||
static void wanted_tag(char *out, size_t n) {
|
||||
out[0] = 0;
|
||||
const wchar_t *t = wcsstr(g_cmdline, L"--tag ");
|
||||
if (!t) return;
|
||||
t += 6;
|
||||
while (*t == L' ' || *t == L'"') t++;
|
||||
size_t k = 0;
|
||||
while (*t && *t != L' ' && *t != L'"' && k + 1 < n) {
|
||||
const wchar_t c = *t++;
|
||||
if (!((c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'z') || (c >= L'A' && c <= L'Z') || c == L'.' || c == L'-' || c == L'_'))
|
||||
{ out[0] = 0; return; }
|
||||
out[k++] = (char)c;
|
||||
}
|
||||
out[k] = 0;
|
||||
}
|
||||
|
||||
/* (an update to a named release reads THAT release's list: the latest/download link can answer with the release before it for a
|
||||
while after a publish, and the setup then installed the old version again and started it with --fetched, which builds without
|
||||
checking: players pressed Update and stayed on v2.0.3, 2026-11-08) */
|
||||
static const char *manifest_url(void) {
|
||||
static char u[1024];
|
||||
const char *e = getenv("HOOKSHOT_SETUP_LIST");
|
||||
char tag[128];
|
||||
wanted_tag(tag, sizeof tag);
|
||||
if (e && *e) snprintf(u, sizeof u, "%s", e);
|
||||
else if (tag[0]) snprintf(u, sizeof u, "https://github.com/NotRexed/Hookshot/releases/download/%s/hookshot-setup.txt", tag);
|
||||
else snprintf(u, sizeof u, "%s", "https://github.com/NotRexed/Hookshot/releases/latest/download/hookshot-setup.txt");
|
||||
return u;
|
||||
}
|
||||
|
||||
static DWORD WINAPI work(LPVOID unused) {
|
||||
(void)unused;
|
||||
/* (--repair, from the builder's Repair button: every part checked again and the version unpacked anew, after the builder that
|
||||
started this has closed. It is not passed on) */
|
||||
int repair = 0;
|
||||
wchar_t *flag = wcsstr(g_cmdline, L"--repair");
|
||||
if (flag) {
|
||||
repair = 1;
|
||||
wmemmove(flag, flag + 8, wcslen(flag + 8) + 1);
|
||||
Sleep(2000);
|
||||
}
|
||||
wchar_t base[MAX_PATH], downloads[MAX_PATH];
|
||||
if (SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, base) != S_OK) fail(L"No local application data folder.");
|
||||
wcscat(base, L"\\HookshotBuilder");
|
||||
{ /* (HOOKSHOT_SETUP_BASE=<folder>: install there instead, for testing installs and updates without touching the real one) */
|
||||
const wchar_t *tb = _wgetenv(L"HOOKSHOT_SETUP_BASE");
|
||||
if (tb && *tb) wcsncpy(base, tb, MAX_PATH - 1), base[MAX_PATH - 1] = 0;
|
||||
}
|
||||
swprintf(downloads, MAX_PATH, L"%ls\\downloads", base);
|
||||
mkdirs(downloads);
|
||||
|
||||
status(L"Looking for the latest Hookshot Builder...");
|
||||
Mem man = {0};
|
||||
/* (tried again on a server error or no answer: GitHub's release downloads answered 504 for an hour, 2026-11-08, and every
|
||||
start failed at once) */
|
||||
/* (low-vram, issue 558: 5 tries in 41 s were not enough while GitHub's site and API both failed on and off for hours; 8 tries
|
||||
over ~3 minutes now, alternating the release link and the API's) */
|
||||
static const int waits[] = {3, 6, 12, 20, 30, 45, 60};
|
||||
enum { TRIES = 8 };
|
||||
int ok = 0;
|
||||
for (int attempt = 0; attempt < TRIES && !ok; attempt++) {
|
||||
if (attempt) {
|
||||
status(L"GitHub didn't answer (%lu). Trying again in %d s...", g_http_status, waits[attempt - 1]);
|
||||
Sleep(waits[attempt - 1] * 1000);
|
||||
status(L"Looking for the latest Hookshot Builder...");
|
||||
}
|
||||
free(man.p);
|
||||
man = (Mem){0};
|
||||
g_http_status = 0;
|
||||
ok = http_get(manifest_url(), mem_sink, &man, 0, NULL) && man.p;
|
||||
const DWORD first = g_http_status;
|
||||
char api[1024];
|
||||
if (!ok && (!first || first >= 500) && api_link_for(manifest_url(), api, sizeof api)) { /* (the API's link instead) */
|
||||
free(man.p);
|
||||
man = (Mem){0};
|
||||
ok = http_get(api, mem_sink, &man, 0, L"application/octet-stream") && man.p;
|
||||
if (!ok) g_http_status = first;
|
||||
}
|
||||
if (!ok && !retryable(g_http_status)) break; /* (404 and the like: trying again changes nothing) */
|
||||
}
|
||||
if (!ok)
|
||||
fail(g_http_status == 404
|
||||
? L"The latest Hookshot release has no setup files yet. Download HookshotBuilder.zip from the releases page for now: "
|
||||
L"https://github.com/NotRexed/Hookshot/releases/latest"
|
||||
: g_http_status ? L"GitHub's download servers are failing right now (an error 500 or above, tried 8 times over 3 minutes). "
|
||||
L"This is on GitHub's side: try again in a few minutes, or later today."
|
||||
: L"Could not reach GitHub to get the Hookshot Builder. Check your internet connection and try again.");
|
||||
|
||||
char tag[128] = "", run[260] = "";
|
||||
Part parts[MAX_PARTS];
|
||||
int nparts = 0;
|
||||
for (char *next = man.p, *line; (line = next_line(&next)) != NULL;) {
|
||||
if (!strncmp(line, "tag ", 4)) sscanf(line + 4, "%127s", tag);
|
||||
else if (!strncmp(line, "run ", 4)) sscanf(line + 4, "%259s", run);
|
||||
else if (!strncmp(line, "part ", 5) && nparts < MAX_PARTS) {
|
||||
Part *p = &parts[nparts];
|
||||
if (sscanf(line + 5, "%64s %llu %259s %259s %259s %1023s", p->sha, &p->size, p->dest, p->from, p->to, p->url) == 6) nparts++;
|
||||
}
|
||||
}
|
||||
if (!tag[0] || !run[0] || !nparts) fail(L"The release's setup list could not be read. Try again later.");
|
||||
{ /* (the list's names become paths under the install folder, a folder this removes and remakes: they stay inside it) */
|
||||
int bad = !list_name_ok(tag, 0) || !list_name_ok(run, 1);
|
||||
for (int i = 0; i < nparts && !bad; i++) {
|
||||
const Part *p = &parts[i];
|
||||
bad = strlen(p->sha) != 64 || strspn(p->sha, "0123456789abcdef") != 64 || _strnicmp(p->url, "https://", 8) ||
|
||||
(strcmp(p->dest, ".") && !list_name_ok(p->dest, 1)) || (strcmp(p->from, "-") && !list_name_ok(p->from, 0)) ||
|
||||
(strcmp(p->to, "-") && !list_name_ok(p->to, 0));
|
||||
}
|
||||
if (bad) fail(L"The release's setup list has a name this setup does not accept. Try again later.");
|
||||
}
|
||||
{
|
||||
char want[128];
|
||||
wanted_tag(want, sizeof want);
|
||||
if (want[0] && strcmp(want, tag)) {
|
||||
wchar_t ww[128], wt[128];
|
||||
MultiByteToWideChar(CP_UTF8, 0, want, -1, ww, 128), MultiByteToWideChar(CP_UTF8, 0, tag, -1, wt, 128);
|
||||
fail(L"GitHub answered with the setup list of %ls, not %ls (its download links can lag right after a release). Try the "
|
||||
L"update again in a few minutes.", wt, ww);
|
||||
}
|
||||
}
|
||||
|
||||
wchar_t install[MAX_PATH], marker[MAX_PATH], wtag[128], wrun[260], exe[MAX_PATH], versions[MAX_PATH], final_dir[MAX_PATH];
|
||||
w(tag, wtag, 128), w(run, wrun, 260);
|
||||
swprintf(versions, MAX_PATH, L"%ls\\versions", base);
|
||||
swprintf(final_dir, MAX_PATH, L"%ls\\%ls", versions, wtag);
|
||||
swprintf(install, MAX_PATH, L"%ls\\%ls", versions, wtag);
|
||||
swprintf(marker, MAX_PATH, L"%ls\\installed.txt", install);
|
||||
swprintf(exe, MAX_PATH, L"%ls\\%ls", install, wrun);
|
||||
for (wchar_t *q = exe; *q; q++) if (*q == L'/') *q = L'\\';
|
||||
|
||||
if (repair || GetFileAttributesW(marker) == INVALID_FILE_ATTRIBUTES || GetFileAttributesW(exe) == INVALID_FILE_ATTRIBUTES) {
|
||||
/* (unpacked into <tag>.part and renamed once complete: a setup stopped half way never leaves a version that looks installed) */
|
||||
swprintf(install, MAX_PATH, L"%ls\\%ls.part", versions, wtag);
|
||||
rmtree(install);
|
||||
rmtree(final_dir);
|
||||
mkdirs(install);
|
||||
for (int i = 0; i < nparts; i++) {
|
||||
Part *p = &parts[i];
|
||||
wchar_t zip[MAX_PATH], wsha[65];
|
||||
w(p->sha, wsha, 65);
|
||||
swprintf(zip, MAX_PATH, L"%ls\\%ls.zip", downloads, wsha);
|
||||
if (reuse_part(versions, tag, p, install)) { /* (unchanged since the installed version: its folder moved over) */
|
||||
status(L"Part %d of %d unchanged: kept from the installed version", i + 1, nparts);
|
||||
continue;
|
||||
}
|
||||
char have[65] = "";
|
||||
if (!(GetFileAttributesW(zip) != INVALID_FILE_ATTRIBUTES && file_sha256(zip, have) && !strcmp(have, p->sha))) {
|
||||
wchar_t part[MAX_PATH];
|
||||
swprintf(part, MAX_PATH, L"%ls.part", zip);
|
||||
int got = 0;
|
||||
for (int attempt = 0; attempt < TRIES && !got; attempt++) { /* (a server error or a dropped connection: again) */
|
||||
if (attempt) {
|
||||
status(L"Part %d of %d: GitHub didn't answer (%lu). Trying again in %d s...", i + 1, nparts, g_http_status,
|
||||
waits[attempt - 1]);
|
||||
Sleep(waits[attempt - 1] * 1000);
|
||||
}
|
||||
status(L"Downloading part %d of %d (%llu MB)...", i + 1, nparts, p->size >> 20);
|
||||
FileSink fs;
|
||||
BCRYPT_ALG_HANDLE a;
|
||||
fs.f = CreateFileW(part, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
|
||||
if (fs.f == INVALID_HANDLE_VALUE) fail(L"Could not write to %ls.", downloads);
|
||||
BCryptOpenAlgorithmProvider(&a, BCRYPT_SHA256_ALGORITHM, NULL, 0);
|
||||
BCryptCreateHash(a, &fs.h, NULL, 0, NULL, 0, 0);
|
||||
g_http_status = 0;
|
||||
/* (after a failed try the API's link to the same file, every other try) */
|
||||
char api[1024];
|
||||
if (attempt % 2 == 1 && api_link_for(p->url, api, sizeof api))
|
||||
got = http_get(api, file_sink, &fs, p->size, L"application/octet-stream");
|
||||
else
|
||||
got = http_get(p->url, file_sink, &fs, p->size, NULL);
|
||||
CloseHandle(fs.f);
|
||||
unsigned char d[32];
|
||||
BCryptFinishHash(fs.h, d, 32, 0);
|
||||
BCryptDestroyHash(fs.h);
|
||||
BCryptCloseAlgorithmProvider(a, 0);
|
||||
InterlockedExchange(&g_percent, -1);
|
||||
hex(d, 32, have);
|
||||
/* (a download cut off half way answered 200 and stopped the tries at once: only a definite no stops them) */
|
||||
if (!got && !retryable(g_http_status)) break;
|
||||
}
|
||||
if (!got) DeleteFileW(part), fail(retryable(g_http_status)
|
||||
? L"Downloading part %d of %d failed: GitHub's download servers are failing right now (tried 8 times over 3 "
|
||||
L"minutes). This is on GitHub's side. The parts already downloaded are kept: run HookshotBuilder.exe again in a "
|
||||
L"few minutes and it carries on from here."
|
||||
: L"Downloading part %d of %d failed. Check your connection and free space, then try again.", i + 1, nparts);
|
||||
if (strcmp(have, p->sha)) DeleteFileW(part), fail(L"Part %d of %d did not download correctly (its checksum differs). Try again.", i + 1, nparts);
|
||||
/* (the checked file or nothing: an old <sha>.zip that could not be removed is never unpacked instead) */
|
||||
if (!MoveFileExW(part, zip, MOVEFILE_REPLACE_EXISTING)) {
|
||||
const DWORD e = GetLastError();
|
||||
DeleteFileW(part);
|
||||
fail(L"Could not place part %d of %d in %ls (Windows error %lu).", i + 1, nparts, downloads, e);
|
||||
}
|
||||
}
|
||||
status(L"Unpacking part %d of %d...", i + 1, nparts);
|
||||
wchar_t dest[MAX_PATH], wdest[260], tarcmd[2 * MAX_PATH + 64], sys[MAX_PATH];
|
||||
w(p->dest, wdest, 260);
|
||||
if (!strcmp(p->dest, ".")) wcscpy(dest, install);
|
||||
else swprintf(dest, MAX_PATH, L"%ls\\%ls", install, wdest);
|
||||
for (wchar_t *q = dest; *q; q++) if (*q == L'/') *q = L'\\';
|
||||
mkdirs(dest);
|
||||
GetSystemDirectoryW(sys, MAX_PATH);
|
||||
swprintf(tarcmd, 2 * MAX_PATH + 64, L"\"%ls\\tar.exe\" -xf \"%ls\" -C \"%ls\"", sys, zip, dest);
|
||||
RunResult tar = run_wait(tarcmd, dest);
|
||||
if (tar.start_error) fail(L"Could not start Windows' tar.exe (Windows error %lu).\nArchive: %ls\nDestination: %ls", tar.start_error, zip, dest);
|
||||
if (tar.status_error) fail(L"Could not read Windows' tar.exe exit status (Windows error %lu).\nArchive: %ls\nDestination: %ls", tar.status_error, zip, dest);
|
||||
if (tar.code) {
|
||||
wchar_t detail[512] = L"";
|
||||
if (tar.capture_error) swprintf(detail, 512, L"Could not capture stderr (Windows error %lu).", tar.capture_error);
|
||||
/* Best-effort UTF-8: tar may use an ANSI/OEM code page, or the byte cap may split a sequence. */
|
||||
else MultiByteToWideChar(CP_UTF8, 0, tar.error, -1, detail, 512);
|
||||
wchar_t heading[1024] = L"";
|
||||
swprintf(heading, 1024, L"Unpacking part %d of %d failed: Windows' tar.exe exited with code %lu.\nArchive: %ls\nDestination: %ls\n%ls:\n",
|
||||
i + 1, nparts, tar.code, zip, dest,
|
||||
tar.capture_error ? L"Stderr unavailable" : L"Tar stderr excerpt (up to 511 bytes captured)");
|
||||
heading[1023] = 0;
|
||||
/* Keep both paths; the displayed excerpt uses only the space left in fail()'s 1024-wide message. */
|
||||
fail(L"%ls%.*ls", heading, (int)(1023 - wcslen(heading)), detail);
|
||||
}
|
||||
if (strcmp(p->from, "-") && strcmp(p->to, "-")) { /* (llvm-mingw-<version>-ucrt-x86_64 -> llvm-mingw) */
|
||||
wchar_t from[MAX_PATH], to[MAX_PATH], wf[260], wt[260];
|
||||
w(p->from, wf, 260), w(p->to, wt, 260);
|
||||
swprintf(from, MAX_PATH, L"%ls\\%ls", dest, wf);
|
||||
swprintf(to, MAX_PATH, L"%ls\\%ls", dest, wt);
|
||||
if (GetFileAttributesW(to) == INVALID_FILE_ATTRIBUTES && !MoveFileW(from, to))
|
||||
fail(L"Could not set up part %d of %d (renaming %ls).", i + 1, nparts, wf);
|
||||
}
|
||||
}
|
||||
wchar_t staged_exe[MAX_PATH];
|
||||
swprintf(staged_exe, MAX_PATH, L"%ls\\%ls", install, wrun);
|
||||
for (wchar_t *q = staged_exe; *q; q++) if (*q == L'/') *q = L'\\';
|
||||
if (GetFileAttributesW(staged_exe) == INVALID_FILE_ATTRIBUTES)
|
||||
fail(L"The builder is missing after unpacking (%ls). Your antivirus may have removed it: allow the folder %ls and run the setup again.", staged_exe, base);
|
||||
if (!MoveFileW(install, final_dir)) fail(L"Could not finish installing into %ls.", final_dir);
|
||||
wcscpy(install, final_dir);
|
||||
write_small(marker, tag);
|
||||
write_parts(install, parts, nparts);
|
||||
}
|
||||
{ /* (a version an older setup installed has no parts.txt: written now, so the next update can move its folders over) */
|
||||
wchar_t have_list[MAX_PATH];
|
||||
swprintf(have_list, MAX_PATH, L"%ls\\parts.txt", final_dir);
|
||||
if (GetFileAttributesW(have_list) == INVALID_FILE_ATTRIBUTES) write_parts(final_dir, parts, nparts);
|
||||
}
|
||||
prune(versions, downloads, tag, parts, nparts);
|
||||
rmtree(downloads); /* (installed: its zips are not kept; an update moves unchanged folders over instead, reuse_part) */
|
||||
|
||||
status(L"Starting the Hookshot Builder...");
|
||||
wchar_t cmd[4096], dir[MAX_PATH];
|
||||
wcscpy(dir, exe);
|
||||
wchar_t *slash = wcsrchr(dir, L'\\');
|
||||
if (slash) *slash = 0;
|
||||
swprintf(cmd, 4096, L"\"%ls\" %ls", exe, g_cmdline);
|
||||
STARTUPINFOW si = {sizeof si};
|
||||
PROCESS_INFORMATION pi;
|
||||
BOOL inherit = FALSE;
|
||||
if (g_headless) { /* (the builder writes to the same pipes we were given) */
|
||||
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE), si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE), si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
|
||||
if (si.hStdOutput && si.hStdOutput != INVALID_HANDLE_VALUE && si.hStdError && si.hStdError != INVALID_HANDLE_VALUE) {
|
||||
if (!si.hStdInput || si.hStdInput == INVALID_HANDLE_VALUE) si.hStdInput = NULL;
|
||||
SetHandleInformation(si.hStdOutput, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
|
||||
SetHandleInformation(si.hStdError, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
|
||||
si.dwFlags = STARTF_USESTDHANDLES, inherit = TRUE;
|
||||
}
|
||||
}
|
||||
if (!CreateProcessW(NULL, cmd, NULL, NULL, inherit, 0, NULL, dir, &si, &pi)) fail(L"Could not start %ls.", exe);
|
||||
if (g_headless) WaitForSingleObject(pi.hProcess, INFINITE), GetExitCodeProcess(pi.hProcess, &g_exit);
|
||||
CloseHandle(pi.hThread), CloseHandle(pi.hProcess);
|
||||
PostMessageW(g_win, WM_DONE, 0, 0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK wndproc(HWND h, UINT msg, WPARAM wp, LPARAM lp) {
|
||||
switch (msg) {
|
||||
case WM_STATUS: {
|
||||
SetWindowTextW(g_text, g_status);
|
||||
const LONG p = g_percent;
|
||||
if (p < 0) SendMessageW(g_bar, PBM_SETMARQUEE, TRUE, 30);
|
||||
else SendMessageW(g_bar, PBM_SETMARQUEE, FALSE, 0), SendMessageW(g_bar, PBM_SETPOS, (WPARAM)p, 0);
|
||||
return 0;
|
||||
}
|
||||
case WM_DONE: DestroyWindow(h); return 0;
|
||||
case WM_DESTROY: PostQuitMessage(0); return 0;
|
||||
}
|
||||
return DefWindowProcW(h, msg, wp, lp);
|
||||
}
|
||||
|
||||
/* (launch mode) "Hookshot Launcher.exe" in a game folder (nx2/make_game.py puts this file there under that name): the installed
|
||||
builder opened as the game's launcher (--launch <that folder>: Play, and Update when a newer release is out), at once, with no
|
||||
window, download or network of its own. With no builder installed yet, the setup runs as usual and then opens the launcher. */
|
||||
static int launch_installed(const wchar_t *args) {
|
||||
wchar_t base[MAX_PATH], cur[MAX_PATH], exe[MAX_PATH], dir[MAX_PATH], cmd[4096];
|
||||
if (SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, base) != S_OK) return 0;
|
||||
char tag[128] = "";
|
||||
swprintf(cur, MAX_PATH, L"%ls\\HookshotBuilder\\versions\\current.txt", base);
|
||||
read_small(cur, tag, sizeof tag);
|
||||
if (!tag[0]) return 0;
|
||||
wchar_t wtag[128];
|
||||
MultiByteToWideChar(CP_UTF8, 0, tag, -1, wtag, 128);
|
||||
swprintf(dir, MAX_PATH, L"%ls\\HookshotBuilder\\versions\\%ls\\HookshotBuilder", base, wtag);
|
||||
swprintf(exe, MAX_PATH, L"%ls\\HookshotBuilder.exe", dir);
|
||||
if (GetFileAttributesW(exe) == INVALID_FILE_ATTRIBUTES) return 0;
|
||||
swprintf(cmd, 4096, L"\"%ls\" %ls", exe, args);
|
||||
STARTUPINFOW si = {sizeof si};
|
||||
PROCESS_INFORMATION pi;
|
||||
if (!CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, dir, &si, &pi)) return 0;
|
||||
CloseHandle(pi.hThread), CloseHandle(pi.hProcess);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* (RecompLauncher's Play) --play <game folder>: bin\hookshot.exe there, started like the game folder's launcher starts it but without
|
||||
its update question, and waited for, so the launcher knows when the session ends. */
|
||||
static int play_folder(const wchar_t *args) {
|
||||
wchar_t folder[MAX_PATH], cmd[MAX_PATH + 32];
|
||||
while (*args == L' ') args++;
|
||||
const int quoted = *args == L'"';
|
||||
size_t k = 0;
|
||||
for (args += quoted; *args && !(quoted ? *args == L'"' : *args == L' ') && k + 1 < MAX_PATH; ) folder[k++] = *args++;
|
||||
folder[k] = 0;
|
||||
swprintf(cmd, MAX_PATH + 32, L"\"%ls\\bin\\hookshot.exe\"", folder);
|
||||
_wputenv_s(L"HOOKSHOT_NO_UPDATE_CHECK", L"1");
|
||||
STARTUPINFOW si = {sizeof si};
|
||||
PROCESS_INFORMATION pi;
|
||||
DWORD code = 1;
|
||||
if (!k || !CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, folder, &si, &pi)) {
|
||||
g_headless = 1;
|
||||
say_error(L"No built game to start. Build it first (the game folder needs bin\\hookshot.exe).");
|
||||
return 1;
|
||||
}
|
||||
WaitForSingleObject(pi.hProcess, INFINITE), GetExitCodeProcess(pi.hProcess, &code);
|
||||
CloseHandle(pi.hThread), CloseHandle(pi.hProcess);
|
||||
return (int)code;
|
||||
}
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE inst, HINSTANCE prev, LPWSTR cmdline, int show) {
|
||||
(void)prev;
|
||||
/* (libraries loaded from here on come from System32 only, never from the folder the setup was downloaded to) */
|
||||
SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
wcsncpy(g_cmdline, cmdline ? cmdline : L"", 2047);
|
||||
{
|
||||
const wchar_t *c = g_cmdline;
|
||||
while (*c == L' ') c++;
|
||||
if (!wcsncmp(c, L"--play", 6) && (c[6] == L' ' || !c[6])) return play_folder(c + 6);
|
||||
if (!wcsncmp(c, L"--cli", 5) && (c[5] == L' ' || !c[5])) g_headless = 1, show = SW_HIDE;
|
||||
}
|
||||
{
|
||||
wchar_t self[MAX_PATH];
|
||||
GetModuleFileNameW(NULL, self, MAX_PATH);
|
||||
const wchar_t *name = wcsrchr(self, L'\\');
|
||||
name = name ? name + 1 : self;
|
||||
if (!_wcsicmp(name, L"hookshot.exe") && !wcsstr(g_cmdline, L"--")) { /* (the game folder's launcher) */
|
||||
wchar_t *slash = wcsrchr(self, L'\\');
|
||||
if (slash) *slash = 0;
|
||||
swprintf(g_cmdline, 2047, L"--launch \"%ls\"", self);
|
||||
if (launch_installed(g_cmdline)) return 0;
|
||||
/* (no builder installed on this PC: the game itself, at once; nothing is downloaded to show a Play button) */
|
||||
wchar_t game[MAX_PATH], cmd[MAX_PATH + 4];
|
||||
swprintf(game, MAX_PATH, L"%ls\\bin\\hookshot.exe", self);
|
||||
swprintf(cmd, MAX_PATH + 4, L"\"%ls\"", game);
|
||||
STARTUPINFOW si = {sizeof si};
|
||||
PROCESS_INFORMATION pi;
|
||||
if (CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, self, &si, &pi)) {
|
||||
CloseHandle(pi.hThread), CloseHandle(pi.hProcess);
|
||||
return 0;
|
||||
}
|
||||
MessageBoxW(NULL, L"The game (bin\\hookshot.exe) is missing from this folder. Build it again with the Hookshot Builder.", L"Hookshot",
|
||||
MB_ICONERROR);
|
||||
return 1;
|
||||
}
|
||||
if (wcsstr(g_cmdline, L"--launch") && launch_installed(g_cmdline)) return 0;
|
||||
}
|
||||
INITCOMMONCONTROLSEX icc = {sizeof icc, ICC_PROGRESS_CLASS};
|
||||
InitCommonControlsEx(&icc);
|
||||
WNDCLASSW wc = {0};
|
||||
wc.lpfnWndProc = wndproc, wc.hInstance = inst, wc.lpszClassName = L"HookshotSetup";
|
||||
wc.hIcon = LoadIconW(inst, MAKEINTRESOURCEW(1));
|
||||
wc.hCursor = LoadCursorW(NULL, (LPCWSTR)IDC_ARROW);
|
||||
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
|
||||
RegisterClassW(&wc);
|
||||
const int ww = 460, wh = 140;
|
||||
g_win = CreateWindowW(L"HookshotSetup", L"Hookshot Builder setup", WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
|
||||
(GetSystemMetrics(SM_CXSCREEN) - ww) / 2, (GetSystemMetrics(SM_CYSCREEN) - wh) / 2, ww, wh, NULL, NULL, inst, NULL);
|
||||
g_text = CreateWindowW(L"STATIC", L"Starting...", WS_CHILD | WS_VISIBLE, 16, 16, ww - 48, 22, g_win, NULL, inst, NULL);
|
||||
g_bar = CreateWindowW(PROGRESS_CLASSW, NULL, WS_CHILD | WS_VISIBLE | PBS_MARQUEE, 16, 48, ww - 48, 20, g_win, NULL, inst, NULL);
|
||||
HFONT f = CreateFontW(-15, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, 0, 0, CLEARTYPE_QUALITY, 0, L"Segoe UI");
|
||||
SendMessageW(g_text, WM_SETFONT, (WPARAM)f, TRUE);
|
||||
SendMessageW(g_bar, PBM_SETMARQUEE, TRUE, 30);
|
||||
ShowWindow(g_win, show);
|
||||
CloseHandle(CreateThread(NULL, 0, work, NULL, 0, NULL));
|
||||
MSG m;
|
||||
while (GetMessageW(&m, NULL, 0, 0) > 0) TranslateMessage(&m), DispatchMessageW(&m);
|
||||
return (int)g_exit;
|
||||
}
|
||||
7
builder/setup/setup.manifest
Normal file
7
builder/setup/setup.manifest
Normal file
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<assemblyIdentity type="win32" name="Hookshot.BuilderSetup" version="1.0.0.0"/>
|
||||
<dependency><dependentAssembly><assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/></dependentAssembly></dependency>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings><dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware></windowsSettings></application>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security><requestedPrivileges><requestedExecutionLevel level="asInvoker" uiAccess="false"/></requestedPrivileges></security></trustInfo>
|
||||
</assembly>
|
||||
22
builder/setup/setup.rc
Normal file
22
builder/setup/setup.rc
Normal file
@@ -0,0 +1,22 @@
|
||||
1 ICON "hookshot.ico"
|
||||
1 24 "setup.manifest"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 1,0,0,0
|
||||
PRODUCTVERSION 1,0,0,0
|
||||
BEGIN
|
||||
BLOCK "StringFileInfo"
|
||||
BEGIN
|
||||
BLOCK "040904b0"
|
||||
BEGIN
|
||||
VALUE "CompanyName", "Hookshot"
|
||||
VALUE "FileDescription", "Hookshot Builder setup"
|
||||
VALUE "ProductName", "Hookshot Builder"
|
||||
VALUE "FileVersion", "1.0.0"
|
||||
VALUE "OriginalFilename", "HookshotBuilder-Setup.exe"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
BEGIN
|
||||
VALUE "Translation", 0x409, 1200
|
||||
END
|
||||
END
|
||||
Reference in New Issue
Block a user