Compare commits

..

62 Commits

Author SHA1 Message Date
comp500
580408b92a Accept optional mods on the server rather than throwing an exception 2019-08-30 14:52:06 +01:00
comp500
dbdd1fb9f3 Ensure CLI is closed when update is done 2019-08-30 13:57:43 +01:00
comp500
79a983bc2f Don't invalidate files that aren't on the current side 2019-08-30 03:39:15 +01:00
comp500
0cba5ba17b Ensure index and pack files are rechecked after errors 2019-08-12 02:17:28 +01:00
comp500
ce60cdc385 Automagic github release creation 2019-08-12 02:06:49 +01:00
comp500
b314fc8e0b Fix case-sensitivity for standard hashes, add more hash support 2019-08-12 01:37:02 +01:00
comp500
ca4a13589d Fix crash on empty index file 2019-08-11 22:37:42 +01:00
comp500
d21668afa6 ALWAYS IMPLEMENT .hashCode() if its gonna be in a map 2019-08-11 18:08:40 +01:00
comp500
7946377159 Implement optional mods and cancel buttons 2019-08-11 17:49:56 +01:00
comp500
5a54a90f59 Create a wrapper around URIs to fix issues with spaces 2019-08-11 14:36:08 +01:00
comp500
465e4973ba Use ExceptionListWindow to present errors 2019-08-11 01:45:39 +01:00
comp500
ea60175514 Make handleExceptionAndExit better, fix some stuff 2019-08-11 01:14:39 +01:00
comp500
78f5d76fe9 Add showExceptions 2019-08-11 01:01:52 +01:00
comp500
452ab15cc7 Add new GUI code from windowbuilder, fix a thing 2019-08-11 00:53:29 +01:00
comp500
87b00f316a Fix ordering of locationing 2019-08-10 20:13:07 +01:00
comp500
1623c0f880 Correct dialog parentage 2019-08-10 20:08:02 +01:00
comp500
46bbc9b82e Enable text wrapping on the option description 2019-08-10 19:52:19 +01:00
comp500
02b50be782 Ensure files are removed when they need to be 2019-08-10 19:43:41 +01:00
comp500
e6637b9af8 Wrong use of boolean, should be different 2019-08-10 19:37:14 +01:00
comp500
5fc7d6382d Make intellij happy again 2019-08-10 19:31:20 +01:00
comp500
afd8e85754 Change text 2019-08-10 19:30:39 +01:00
comp500
ecbf0b9eba Clean up gitignore mess 2019-08-10 18:46:59 +01:00
comp500
37a1464e11 Make intellij happy 2019-08-10 18:31:12 +01:00
comp500
54fd84a6d8 Add proper options dialog (I do GUI in Windowbuilder usually) 2019-08-10 18:29:40 +01:00
comp500
dcf8d21aad Whoops, I am bad programmer 2019-08-10 02:18:02 +01:00
comp500
eaed3b2187 whoops i java 11'd again 2019-08-10 01:37:39 +01:00
comp500
b22edf920e whoops i java 11'd 2019-08-10 01:26:35 +01:00
comp500
4d8e695fc4 Add cancellation from options list 2019-08-09 20:17:01 +01:00
comp500
a9bd83e96b Implement some stuff, edge case checks, intellij optimisations 2019-08-09 18:15:47 +01:00
comp500
ae085743be Finally, there are no more errors in UpdateManager. Now to actually make it work 2019-08-09 18:03:34 +01:00
comp500
ad79cb3b21 Very fun indeed 2019-08-09 16:31:29 +01:00
comp500
320e56e74e Start rewrite of downloading system, THIS IS SCARY HELP 2019-08-09 15:40:18 +01:00
comp500
bd95bc15ad Thanks IntelliJ. ThintelliJ. 2019-08-07 13:21:15 +01:00
comp500
794b817eff Check for cachedFiles existing 2019-07-04 01:08:24 +01:00
comp500
a5ff63c587 Correctly handle file invalidation 2019-07-03 23:12:11 +01:00
comp500
34a86ffb7d Handle renamed files correctly, log invalidation 2019-07-03 22:49:08 +01:00
comp500
780efe2c9f Remove files correctly, redownload when deleted 2019-07-02 23:32:00 +01:00
comp500
d1647764c4 Implement preserve and alias in index 2019-06-24 17:47:17 +01:00
comp500
12bf090895 Fix hash serialisation in JSON, check index hash 2019-06-24 17:27:28 +01:00
comp500
533c7a3ed5 Gson isn't broken, I'm broken 2019-06-24 03:41:33 +01:00
comp500
d18e134140 Better error reporting, fix NPE (stupid Gson) 2019-06-24 03:38:19 +01:00
comp500
165c8cc172 Add murmur2 support 2019-06-24 03:23:26 +01:00
comp500
d986b39aa5 Fix URI parsing, hash checking, NPEs, create dirs 2019-06-24 02:09:19 +01:00
comp500
040bb955ec Download the right file 2019-06-21 16:36:39 +01:00
comp500
022af4b5c5 whoops, forgot to remove that one 2019-06-21 16:17:38 +01:00
comp500
442fb93ca8 Rewrite *everything* to use Okio 2019-06-21 16:14:25 +01:00
comp500
81c1ebaa15 Commit WIP downloading process 2019-06-21 14:28:41 +01:00
comp500
917d10c448 Add more deserialisation classes 2019-06-20 17:08:30 +01:00
comp500
26c3261848 uhhhhhhhhh Added IndexFile i guess 2019-06-20 14:22:15 +01:00
comp500
fbd54b4604 Redo hashing sytem, pack file reading, write json 2019-06-12 14:28:38 +01:00
comp500
8be5cb8e60 Null safety, better exception handling, check strm 2019-06-08 14:31:52 +01:00
comp500
c181a36edc Manifest file loading, hashing, pack file loading 2019-06-08 14:22:30 +01:00
comp500
e32d98fb98 Refactor handlers into ui package 2019-06-08 02:13:52 +01:00
comp500
e65d20be79 Add some command line params 2019-06-08 02:05:43 +01:00
comp500
3d28f0a674 Better exception handling, progress system 2019-06-06 23:25:22 +01:00
comp500
905630cb2a Revamp UI system, improve UpdateManager 2019-06-05 20:06:09 +01:00
comp500
fd87edd6ca Make github request handling work, fix some things 2019-06-01 16:26:15 +01:00
comp500
2118a8fda1 Notes 2019-06-01 12:41:33 +01:00
comp500
86c2349fd3 All cases mutate, so R/W lock is redundant and complicates things 2019-06-01 12:37:01 +01:00
comp500
f76a3d2d62 Implement Zip request handler 2019-06-01 12:33:28 +01:00
comp500
72d27715f8 Commit this WIP code because I might change my mind 2019-05-31 22:20:08 +01:00
comp500
26b8e1de86 Close input stream (ProgressMonitor) after copying 2019-05-21 01:19:39 +01:00
41 changed files with 3047 additions and 186 deletions

119
.gitignore vendored
View File

@@ -1,74 +1,87 @@
# Created by https://www.gitignore.io/api/java,gradle,eclipse
# Edit at https://www.gitignore.io/?templates=java,gradle,eclipse
### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Created by https://www.gitignore.io/api/java,gradle,intellij
# Edit at https://www.gitignore.io/?templates=java,gradle,intellij
# External tool builders
.externalToolBuilders/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# Locally stored "Eclipse launch configurations"
*.launch
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# Generated files
.idea/**/contentModel.xml
# CDT-specific (C/C++ Development Tooling)
.cproject
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# CDT- autotools
.autotools
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Java annotation processor (APT)
.factorypath
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# PDT-specific (PHP Development Tools)
.buildpath
# CMake
cmake-build-*/
# sbteclipse plugin
.target
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# Tern plugin
.tern-project
# File-based project format
*.iws
# TeXlipse plugin
.texlipse
# IntelliJ
out/
# STS (Spring Tool Suite)
.springBeans
# mpeltonen/sbt-idea plugin
.idea_modules/
# Code Recommenders
.recommenders/
# JIRA plugin
atlassian-ide-plugin.xml
# Annotation Processing
.apt_generated/
# Cursive Clojure plugin
.idea/replstate.xml
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Eclipse Patch ###
# Eclipse Core
.project
# Editor-based Rest Client
.idea/httpRequests
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# Annotation Processing
.apt_generated
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
.sts4-cache/
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Java ###
# Compiled class file
@@ -114,4 +127,4 @@ gradle-app.setting
### Gradle Patch ###
**/build/
# End of https://www.gitignore.io/api/java,gradle,eclipse
# End of https://www.gitignore.io/api/java,gradle,intellij

View File

@@ -0,0 +1,36 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true">
<option name="TOP_LEVEL_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="INNER_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="METHOD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
</value>
</option>
<option name="FIELD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="IGNORE_DEPRECATED" value="false" />
<option name="IGNORE_JAVADOC_PERIOD" value="true" />
<option name="IGNORE_DUPLICATED_THROWS" value="false" />
<option name="IGNORE_POINT_TO_ITSELF" value="false" />
<option name="myAdditionalJavadocTags" value="wbp.parser.entryPoint" />
</inspection_tool>
</profile>
</component>

10
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<list size="1">
<item index="0" class="java.lang.String" itemvalue="com.google.gson.annotations.SerializedName" />
</list>
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="11" project-jdk-type="JavaSDK" />
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -3,11 +3,18 @@ plugins {
id 'application'
id 'com.github.johnrengelman.shadow' version '5.0.0'
id 'com.palantir.git-version' version '0.11.0'
id 'com.github.breadmoirai.github-release' version '2.2.9'
}
sourceCompatibility = 1.8
dependencies {
implementation 'commons-cli:commons-cli:1.4'
implementation 'com.moandjiezana.toml:toml4j:0.7.2'
// TODO: Implement tests
//testImplementation 'junit:junit:4.12'
implementation 'com.google.code.gson:gson:2.8.1'
implementation 'com.squareup.okio:okio:2.2.2'
}
repositories {
@@ -26,9 +33,40 @@ jar {
}
}
// Commons CLI is already included in packwiz-installer-bootstrap
// Commons CLI and Minimal JSON are already included in packwiz-installer-bootstrap
shadowJar {
dependencies {
exclude(dependency('commons-cli:commons-cli:1.4'))
exclude(dependency('com.eclipsesource.minimal-json:minimal-json:0.9.5'))
}
}
// Used for vscode launch.json
task copyJar(type: Copy) {
from shadowJar
rename "packwiz-installer-(.*)\\.jar", "packwiz-installer.jar"
into "build/libs/"
}
build.dependsOn copyJar
if (project.hasProperty("github.token")) {
githubRelease {
// IntelliJ u ok?
//noinspection GroovyAssignabilityCheck
owner "comp500"
//noinspection GroovyAssignabilityCheck
repo "packwiz-installer"
//noinspection GroovyAssignabilityCheck
tagName "${project.version}"
//noinspection GroovyAssignabilityCheck
releaseName "Release ${project.version}"
//noinspection GroovyAssignabilityCheck
draft true
//noinspection GroovyAssignabilityCheck
token findProperty("github.token") ?: ""
releaseAssets = [jar.destinationDirectory.file("packwiz-installer.jar").get()]
}
tasks.githubRelease.dependsOn(build)
}

View File

@@ -0,0 +1,245 @@
package link.infra.packwiz.installer;
import link.infra.packwiz.installer.metadata.IndexFile;
import link.infra.packwiz.installer.metadata.ManifestFile;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import link.infra.packwiz.installer.metadata.hash.GeneralHashingSource;
import link.infra.packwiz.installer.metadata.hash.Hash;
import link.infra.packwiz.installer.metadata.hash.HashUtils;
import link.infra.packwiz.installer.ui.IExceptionDetails;
import link.infra.packwiz.installer.ui.IOptionDetails;
import okio.Buffer;
import okio.Okio;
import okio.Source;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
class DownloadTask implements IOptionDetails, IExceptionDetails {
final IndexFile.File metadata;
ManifestFile.File cachedFile = null;
private Exception failure = null;
private boolean alreadyUpToDate = false;
private boolean metadataRequired = true;
private boolean invalidated = false;
// If file is new or isOptional changed to true, the option needs to be presented again
private boolean newOptional = true;
private final UpdateManager.Options.Side downloadSide;
private DownloadTask(IndexFile.File metadata, String defaultFormat, UpdateManager.Options.Side downloadSide) {
this.metadata = metadata;
if (metadata.hashFormat == null || metadata.hashFormat.length() == 0) {
metadata.hashFormat = defaultFormat;
}
this.downloadSide = downloadSide;
}
void invalidate() {
invalidated = true;
alreadyUpToDate = false;
}
void updateFromCache(ManifestFile.File cachedFile) {
if (failure != null) return;
if (cachedFile == null) {
this.cachedFile = new ManifestFile.File();
return;
}
this.cachedFile = cachedFile;
if (!invalidated) {
Hash currHash;
try {
currHash = HashUtils.getHash(metadata.hashFormat, metadata.hash);
} catch (Exception e) {
failure = e;
return;
}
if (currHash != null && currHash.equals(cachedFile.hash)) {
// Already up to date
alreadyUpToDate = true;
metadataRequired = false;
}
}
if (cachedFile.isOptional) {
// Because option selection dialog might set this task to true/false, metadata is always needed to download
// the file, and to show the description and name
metadataRequired = true;
}
}
void downloadMetadata(IndexFile parentIndexFile, SpaceSafeURI indexUri) {
if (failure != null) return;
if (metadataRequired) {
try {
metadata.downloadMeta(parentIndexFile, indexUri);
} catch (Exception e) {
failure = e;
return;
}
if (metadata.linkedFile != null) {
if (metadata.linkedFile.option != null) {
if (metadata.linkedFile.option.optional) {
if (cachedFile.isOptional) {
// isOptional didn't change
newOptional = false;
} else {
// isOptional false -> true, set option to it's default value
// TODO: preserve previous option value, somehow??
cachedFile.optionValue = this.metadata.linkedFile.option.defaultValue;
}
}
}
cachedFile.isOptional = isOptional();
cachedFile.onlyOtherSide = !correctSide();
}
}
}
void download(String packFolder, SpaceSafeURI indexUri) {
if (failure != null) return;
// Ensure it is removed
if (!cachedFile.optionValue || !correctSide()) {
if (cachedFile.cachedLocation == null) return;
try {
Files.deleteIfExists(Paths.get(packFolder, cachedFile.cachedLocation));
} catch (IOException e) {
// TODO: how much of a problem is this? use log4j/other log library to show warning?
e.printStackTrace();
}
cachedFile.cachedLocation = null;
return;
}
if (alreadyUpToDate) return;
Path destPath = Paths.get(packFolder, metadata.getDestURI().toString());
// Don't update files marked with preserve if they already exist on disk
if (metadata.preserve) {
if (Files.exists(destPath)) {
return;
}
}
try {
Hash hash;
String fileHashFormat;
if (metadata.linkedFile != null) {
hash = metadata.linkedFile.getHash();
fileHashFormat = metadata.linkedFile.download.hashFormat;
} else {
hash = metadata.getHash();
fileHashFormat = metadata.hashFormat;
}
Source src = metadata.getSource(indexUri);
GeneralHashingSource fileSource = HashUtils.getHasher(fileHashFormat).getHashingSource(src);
Buffer data = new Buffer();
Okio.buffer(fileSource).readAll(data);
if (fileSource.hashIsEqual(hash)) {
Files.createDirectories(destPath.getParent());
Files.copy(data.inputStream(), destPath, StandardCopyOption.REPLACE_EXISTING);
} else {
// TODO: no more SYSOUT!!!!!!!!!
System.out.println("Invalid hash for " + metadata.getDestURI().toString());
System.out.println("Calculated: " + fileSource.getHash());
System.out.println("Expected: " + hash);
failure = new Exception("Hash invalid!");
}
if (cachedFile.cachedLocation != null && !destPath.equals(Paths.get(packFolder, cachedFile.cachedLocation))) {
// Delete old file if location changes
Files.delete(Paths.get(packFolder, cachedFile.cachedLocation));
}
} catch (Exception e) {
failure = e;
}
if (failure == null) {
if (cachedFile == null) {
cachedFile = new ManifestFile.File();
}
// Update the manifest file
try {
cachedFile.hash = metadata.getHash();
} catch (Exception e) {
failure = e;
return;
}
cachedFile.isOptional = isOptional();
cachedFile.cachedLocation = metadata.getDestURI().toString();
if (metadata.linkedFile != null) {
try {
cachedFile.linkedFileHash = metadata.linkedFile.getHash();
} catch (Exception e) {
failure = e;
}
}
}
}
public Exception getException() {
return failure;
}
boolean isOptional() {
if (metadata.linkedFile != null) {
return metadata.linkedFile.isOptional();
}
return false;
}
boolean isNewOptional() {
return isOptional() && this.newOptional;
}
boolean correctSide() {
if (metadata.linkedFile != null) {
return metadata.linkedFile.side.hasSide(downloadSide);
}
return true;
}
public String getName() {
return metadata.getName();
}
@Override
public boolean getOptionValue() {
return cachedFile.optionValue;
}
@Override
public String getOptionDescription() {
if (metadata.linkedFile != null) {
return metadata.linkedFile.option.description;
}
return null;
}
public void setOptionValue(boolean value) {
if (value && !cachedFile.optionValue) {
// Ensure that an update is done if it changes from false to true, or from true to false
alreadyUpToDate = false;
}
cachedFile.optionValue = value;
}
static List<DownloadTask> createTasksFromIndex(IndexFile index, String defaultFormat, UpdateManager.Options.Side downloadSide) {
ArrayList<DownloadTask> tasks = new ArrayList<>();
for (IndexFile.File file : index.files) {
tasks.add(new DownloadTask(file, defaultFormat, downloadSide));
}
return tasks;
}
}

View File

@@ -1,99 +0,0 @@
package link.infra.packwiz.installer;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class InstallWindow {
// TODO: move to seperate file, make usable without GUI
private JFrame frmPackwizlauncher;
private UpdateManager updateManager = new UpdateManager();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
InstallWindow window = new InstallWindow();
window.frmPackwizlauncher.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public InstallWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPackwizlauncher = new JFrame();
frmPackwizlauncher.setTitle("Updating modpack...");
frmPackwizlauncher.setBounds(100, 100, 493, 95);
frmPackwizlauncher.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPackwizlauncher.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
frmPackwizlauncher.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(50);
panel.add(progressBar, BorderLayout.CENTER);
JLabel lblProgresslabel = new JLabel("Loading...");
panel.add(lblProgresslabel, BorderLayout.SOUTH);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new EmptyBorder(0, 5, 0, 5));
frmPackwizlauncher.getContentPane().add(panel_1, BorderLayout.EAST);
GridBagLayout gbl_panel_1 = new GridBagLayout();
panel_1.setLayout(gbl_panel_1);
JButton btnOptions = new JButton("Options...");
btnOptions.setAlignmentX(Component.CENTER_ALIGNMENT);
GridBagConstraints gbc_btnOptions = new GridBagConstraints();
gbc_btnOptions.gridx = 0;
gbc_btnOptions.gridy = 0;
panel_1.add(btnOptions, gbc_btnOptions);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
updateManager.cleanup();
frmPackwizlauncher.dispose();
}
});
btnCancel.setAlignmentX(Component.CENTER_ALIGNMENT);
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.gridx = 0;
gbc_btnCancel.gridy = 1;
panel_1.add(btnCancel, gbc_btnCancel);
}
}

View File

@@ -1,23 +1,49 @@
package link.infra.packwiz.installer;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import link.infra.packwiz.installer.ui.CLIHandler;
import link.infra.packwiz.installer.ui.IUserInterface;
import link.infra.packwiz.installer.ui.InputStateHandler;
import link.infra.packwiz.installer.ui.InstallWindow;
import org.apache.commons.cli.*;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import javax.swing.*;
import java.awt.*;
import java.net.URISyntaxException;
@SuppressWarnings("unused")
public class Main {
// Actual main() is in RequiresBootstrap!
@SuppressWarnings("unused")
public Main(String[] args) {
// Big overarching try/catch just in case everything breaks
try {
this.startup(args);
} catch (Exception e) {
e.printStackTrace();
EventQueue.invokeLater(() -> {
JOptionPane.showMessageDialog(null,
"A fatal error occurred: \n" + e.getClass().getCanonicalName() + ": " + e.getMessage(),
"packwiz-installer", JOptionPane.ERROR_MESSAGE);
System.exit(1);
});
// In case the eventqueue is broken, exit after 1 minute
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e1) {
// Good, it was already called?
return;
}
System.exit(1);
}
}
private void startup(String[] args) {
Options options = new Options();
addNonBootstrapOptions(options);
addBootstrapOptions(options);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = null;
try {
@@ -32,22 +58,91 @@ public class Main {
JOptionPane.showMessageDialog(null, e.getMessage(), "packwiz-installer", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
System.out.println("Hello World!");
IUserInterface ui;
// if "headless", GUI creation will fail anyway!
if (cmd.hasOption("no-gui") || GraphicsEnvironment.isHeadless()) {
ui = new CLIHandler();
} else {
ui = new InstallWindow();
}
String[] unparsedArgs = cmd.getArgs();
if (unparsedArgs.length > 1) {
ui.handleExceptionAndExit(new RuntimeException("Too many arguments specified!"));
return;
} else if (unparsedArgs.length < 1) {
ui.handleExceptionAndExit(new RuntimeException("URI to install from must be specified!"));
return;
}
String title = cmd.getOptionValue("title");
if (title != null) {
ui.setTitle(title);
}
InputStateHandler inputStateHandler = new InputStateHandler();
ui.show(inputStateHandler);
UpdateManager.Options uOptions = new UpdateManager.Options();
String side = cmd.getOptionValue("side");
if (side != null) {
uOptions.side = UpdateManager.Options.Side.from(side);
}
String packFolder = cmd.getOptionValue("pack-folder");
if (packFolder != null) {
uOptions.packFolder = packFolder;
}
String metaFile = cmd.getOptionValue("meta-file");
if (metaFile != null) {
uOptions.manifestFile = metaFile;
}
try {
uOptions.downloadURI = new SpaceSafeURI(unparsedArgs[0]);
} catch (URISyntaxException e) {
// TODO: better error message?
ui.handleExceptionAndExit(e);
return;
}
// Start update process!
// TODO: start in SwingWorker?
try {
ui.executeManager(() -> {
try {
new UpdateManager(uOptions, ui, inputStateHandler);
} catch (Exception e) {
// TODO: better error message?
ui.handleExceptionAndExit(e);
}
});
} catch (Exception e) {
// TODO: better error message?
ui.handleExceptionAndExit(e);
}
}
// Called by packwiz-installer-bootstrap to set up the help command
@SuppressWarnings("WeakerAccess")
public static void addNonBootstrapOptions(Options options) {
//options.addOption("w", "welp", false, "Testing options");
options.addOption("s", "side", true, "Side to install mods from (client/server, defaults to client)");
options.addOption(null, "title", true, "Title of the installer window");
options.addOption(null, "pack-folder", true, "Folder to install the pack to (defaults to the JAR directory)");
options.addOption(null, "meta-file", true, "JSON file to store pack metadata, relative to the pack folder (defaults to packwiz.json)");
}
// TODO: link these somehow so they're only defined once?
private static void addBootstrapOptions(Options options) {
options.addOption(null, "bootstrap-update-url", true, "Github API URL for checking for updates");
options.addOption(null, "bootstrap-update-token", true, "Github API Access Token, for private repositories");
options.addOption(null, "bootstrap-no-update", false, "Don't update packwiz-installer");
options.addOption(null, "bootstrap-main-jar", true, "Location of the packwiz-installer JAR file");
options.addOption("g", "no-gui", false, "Don't display a GUI to show update progress");
options.addOption("h", "help", false, "Display this message");
options.addOption("h", "help", false, "Display this message"); // Implemented in packwiz-installer-bootstrap!
}
}

View File

@@ -1,10 +1,8 @@
package link.infra.packwiz.installer;
import javax.swing.*;
import java.util.Arrays;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class RequiresBootstrap {
public static void main(String[] args) {
@@ -15,10 +13,10 @@ public class RequiresBootstrap {
if (Arrays.stream(args).map(str -> {
if (str == null) return "";
if (str.startsWith("--")) {
return str.substring(2, str.length());
return str.substring(2);
}
if (str.startsWith("-")) {
return str.substring(1, str.length());
return str.substring(1);
}
return "";
}).anyMatch(str -> str.equals("g") || str.equals("no-gui"))) {

View File

@@ -1,9 +1,500 @@
package link.infra.packwiz.installer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import com.moandjiezana.toml.Toml;
import link.infra.packwiz.installer.metadata.IndexFile;
import link.infra.packwiz.installer.metadata.ManifestFile;
import link.infra.packwiz.installer.metadata.PackFile;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import link.infra.packwiz.installer.metadata.hash.GeneralHashingSource;
import link.infra.packwiz.installer.metadata.hash.Hash;
import link.infra.packwiz.installer.metadata.hash.HashUtils;
import link.infra.packwiz.installer.request.HandlerManager;
import link.infra.packwiz.installer.ui.IExceptionDetails;
import link.infra.packwiz.installer.ui.IUserInterface;
import link.infra.packwiz.installer.ui.InputStateHandler;
import link.infra.packwiz.installer.ui.InstallProgress;
import okio.Okio;
import okio.Source;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
public class UpdateManager {
Thread updateThread = new Thread(new UpdateThread());
public void cleanup() {
private final Options opts;
public final IUserInterface ui;
private boolean cancelled;
private boolean cancelledStartGame = false;
private InputStateHandler stateHandler;
private boolean errorsOccurred = false;
public static class Options {
SpaceSafeURI downloadURI = null;
String manifestFile = "packwiz.json"; // TODO: make configurable
String packFolder = ".";
Side side = Side.CLIENT;
public enum Side {
@SerializedName("client")
CLIENT("client"),
@SerializedName("server")
SERVER("server"),
@SerializedName("both")
BOTH("both", new Side[] { CLIENT, SERVER });
private final String sideName;
private final Side[] depSides;
Side(String sideName) {
this.sideName = sideName.toLowerCase();
this.depSides = null;
}
Side(String sideName, Side[] depSides) {
this.sideName = sideName.toLowerCase();
this.depSides = depSides;
}
@Override
public String toString() {
return this.sideName;
}
public boolean hasSide(Side tSide) {
if (this.equals(tSide)) {
return true;
}
if (this.depSides != null) {
for (Side depSide : this.depSides) {
if (depSide.equals(tSide)) {
return true;
}
}
}
return false;
}
public static Side from(String name) {
String lowerName = name.toLowerCase();
for (Side side : Side.values()) {
if (side.sideName.equals(lowerName)) {
return side;
}
}
return null;
}
}
}
UpdateManager(Options opts, IUserInterface ui, InputStateHandler inputStateHandler) {
this.opts = opts;
this.ui = ui;
this.stateHandler = inputStateHandler;
this.start();
}
private void start() {
this.checkOptions();
ui.submitProgress(new InstallProgress("Loading manifest file..."));
Gson gson = new GsonBuilder().registerTypeAdapter(Hash.class, new Hash.TypeHandler()).create();
ManifestFile manifest;
try {
manifest = gson.fromJson(new FileReader(Paths.get(opts.packFolder, opts.manifestFile).toString()),
ManifestFile.class);
} catch (FileNotFoundException e) {
manifest = new ManifestFile();
} catch (JsonSyntaxException | JsonIOException e) {
ui.handleExceptionAndExit(e);
return;
}
if (stateHandler.getCancelButton()) {
showCancellationDialog();
handleCancellation();
}
ui.submitProgress(new InstallProgress("Loading pack file..."));
GeneralHashingSource packFileSource;
try {
Source src = HandlerManager.getFileSource(opts.downloadURI);
packFileSource = HashUtils.getHasher("sha256").getHashingSource(src);
} catch (Exception e) {
// TODO: still launch the game if updating doesn't work?
// TODO: ask user if they want to launch the game, exit(1) if they don't
ui.handleExceptionAndExit(e);
return;
}
PackFile pf;
try {
pf = new Toml().read(Okio.buffer(packFileSource).inputStream()).to(PackFile.class);
} catch (IllegalStateException e) {
ui.handleExceptionAndExit(e);
return;
}
if (stateHandler.getCancelButton()) {
showCancellationDialog();
handleCancellation();
}
ui.submitProgress(new InstallProgress("Checking local files..."));
// Invalidation checking must be done here, as it must happen before pack/index hashes are checked
List<SpaceSafeURI> invalidatedUris = new ArrayList<>();
if (manifest.cachedFiles != null) {
for (Map.Entry<SpaceSafeURI, ManifestFile.File> entry : manifest.cachedFiles.entrySet()) {
// ignore onlyOtherSide files
if (entry.getValue().onlyOtherSide) {
continue;
}
boolean invalid = false;
// if isn't optional, or is optional but optionValue == true
if (!entry.getValue().isOptional || entry.getValue().optionValue) {
if (entry.getValue().cachedLocation != null) {
if (!Files.exists(Paths.get(opts.packFolder, entry.getValue().cachedLocation))) {
invalid = true;
}
} else {
// if cachedLocation == null, should probably be installed!!
invalid = true;
}
}
if (invalid) {
SpaceSafeURI fileUri = entry.getKey();
System.out.println("File " + fileUri.toString() + " invalidated, marked for redownloading");
invalidatedUris.add(fileUri);
}
}
}
if (manifest.packFileHash != null && packFileSource.hashIsEqual(manifest.packFileHash) && invalidatedUris.isEmpty()) {
System.out.println("Modpack is already up to date!");
// todo: --force?
if (!stateHandler.getOptionsButton()) {
return;
}
}
System.out.println("Modpack name: " + pf.name);
if (stateHandler.getCancelButton()) {
showCancellationDialog();
handleCancellation();
}
try {
// This is badly written, I'll probably heavily refactor it at some point
processIndex(HandlerManager.getNewLoc(opts.downloadURI, pf.index.file),
HashUtils.getHash(pf.index.hashFormat, pf.index.hash), pf.index.hashFormat, manifest, invalidatedUris);
} catch (Exception e1) {
ui.handleExceptionAndExit(e1);
}
handleCancellation();
// TODO: update MMC params, java args etc
// If there were errors, don't write the manifest/index hashes, to ensure they are rechecked later
if (errorsOccurred) {
manifest.indexFileHash = null;
manifest.packFileHash = null;
} else {
manifest.packFileHash = packFileSource.getHash();
}
manifest.cachedSide = opts.side;
try (Writer writer = new FileWriter(Paths.get(opts.packFolder, opts.manifestFile).toString())) {
gson.toJson(manifest, writer);
} catch (IOException e) {
// TODO: add message?
ui.handleException(e);
}
}
private void checkOptions() {
// TODO: implement
}
private void processIndex(SpaceSafeURI indexUri, Hash indexHash, String hashFormat, ManifestFile manifest, List<SpaceSafeURI> invalidatedUris) {
if (manifest.indexFileHash != null && manifest.indexFileHash.equals(indexHash) && invalidatedUris.isEmpty()) {
System.out.println("Modpack files are already up to date!");
if (!stateHandler.getOptionsButton()) {
return;
}
}
manifest.indexFileHash = indexHash;
GeneralHashingSource indexFileSource;
try {
Source src = HandlerManager.getFileSource(indexUri);
indexFileSource = HashUtils.getHasher(hashFormat).getHashingSource(src);
} catch (Exception e) {
// TODO: still launch the game if updating doesn't work?
// TODO: ask user if they want to launch the game, exit(1) if they don't
ui.handleExceptionAndExit(e);
return;
}
IndexFile indexFile;
try {
indexFile = new Toml().read(Okio.buffer(indexFileSource).inputStream()).to(IndexFile.class);
} catch (IllegalStateException e) {
ui.handleExceptionAndExit(e);
return;
}
if (!indexFileSource.hashIsEqual(indexHash)) {
// TODO: throw exception
System.out.println("I was meant to put an error message here but I'll do that later");
return;
}
if (stateHandler.getCancelButton()) {
showCancellationDialog();
return;
}
if (manifest.cachedFiles == null) {
manifest.cachedFiles = new HashMap<>();
}
ui.submitProgress(new InstallProgress("Checking local files..."));
Iterator<Map.Entry<SpaceSafeURI, ManifestFile.File>> it = manifest.cachedFiles.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<SpaceSafeURI, ManifestFile.File> entry = it.next();
if (entry.getValue().cachedLocation != null) {
boolean alreadyDeleted = false;
// Delete if option value has been set to false
if (entry.getValue().isOptional && !entry.getValue().optionValue) {
try {
Files.deleteIfExists(Paths.get(opts.packFolder, entry.getValue().cachedLocation));
} catch (IOException e) {
// TODO: should this be shown to the user in some way?
e.printStackTrace();
}
// Set to null, as it doesn't exist anymore
entry.getValue().cachedLocation = null;
alreadyDeleted = true;
}
if (indexFile.files.stream().noneMatch(f -> f.file.equals(entry.getKey()))) {
// File has been removed from the index
if (!alreadyDeleted) {
try {
Files.deleteIfExists(Paths.get(opts.packFolder, entry.getValue().cachedLocation));
} catch (IOException e) {
// TODO: should this be shown to the user in some way?
e.printStackTrace();
}
}
it.remove();
}
}
}
if (stateHandler.getCancelButton()) {
showCancellationDialog();
return;
}
ui.submitProgress(new InstallProgress("Comparing new files..."));
// TODO: progress bar?
if (indexFile.files == null || indexFile.files.size() == 0) {
System.out.println("Warning: Index is empty!");
indexFile.files = new ArrayList<>();
}
List<DownloadTask> tasks = DownloadTask.createTasksFromIndex(indexFile, indexFile.hashFormat, opts.side);
// If the side changes, invalidate EVERYTHING just in case
// Might not be needed, but done just to be safe
boolean invalidateAll = !opts.side.equals(manifest.cachedSide);
if (invalidateAll) {
System.out.println("Side changed, invalidating all mods");
}
tasks.forEach(f -> {
// TODO: should linkedfile be checked as well? should this be done in the download section?
if (invalidateAll) {
f.invalidate();
} else if (invalidatedUris.contains(f.metadata.file)) {
f.invalidate();
}
ManifestFile.File file = manifest.cachedFiles.get(f.metadata.file);
if (file != null) {
// Ensure the file can be reverted later if necessary - the DownloadTask modifies the file so if it fails we need the old version back
file.backup();
}
// If it is null, the DownloadTask will make a new empty cachedFile
f.updateFromCache(file);
});
if (stateHandler.getCancelButton()) {
showCancellationDialog();
return;
}
// Let's hope downloadMetadata is a pure function!!!
tasks.parallelStream().forEach(f -> f.downloadMetadata(indexFile, indexUri));
List<IExceptionDetails> failedTasks = tasks.stream().filter(t -> t.getException() != null).collect(Collectors.toList());
if (!failedTasks.isEmpty()) {
errorsOccurred = true;
IExceptionDetails.ExceptionListResult exceptionListResult;
try {
exceptionListResult = ui.showExceptions(failedTasks, tasks.size(), true).get();
} catch (InterruptedException | ExecutionException e) {
// Interrupted means cancelled???
ui.handleExceptionAndExit(e);
return;
}
switch (exceptionListResult) {
case CONTINUE:
break;
case CANCEL:
cancelled = true;
return;
case IGNORE:
cancelledStartGame = true;
return;
}
}
if (stateHandler.getCancelButton()) {
showCancellationDialog();
return;
}
List<DownloadTask> nonFailedFirstTasks = tasks.stream().filter(t -> t.getException() == null).collect(Collectors.toList());
List<DownloadTask> optionTasks = nonFailedFirstTasks.stream().filter(DownloadTask::correctSide).filter(DownloadTask::isOptional).collect(Collectors.toList());
// If options changed, present all options again
if (stateHandler.getOptionsButton() || optionTasks.stream().anyMatch(DownloadTask::isNewOptional)) {
// new ArrayList is requires so it's an IOptionDetails rather than a DownloadTask list
Future<Boolean> cancelledResult = ui.showOptions(new ArrayList<>(optionTasks));
try {
if (cancelledResult.get()) {
cancelled = true;
// TODO: Should the UI be closed somehow??
return;
}
} catch (InterruptedException | ExecutionException e) {
// Interrupted means cancelled???
ui.handleExceptionAndExit(e);
}
}
ui.disableOptionsButton();
// TODO: different thread pool type?
ExecutorService threadPool = Executors.newFixedThreadPool(10);
CompletionService<DownloadTask> completionService = new ExecutorCompletionService<>(threadPool);
tasks.forEach(t -> completionService.submit(() -> {
t.download(opts.packFolder, indexUri);
return t;
}));
for (int i = 0; i < tasks.size(); i++) {
DownloadTask task;
try {
task = completionService.take().get();
} catch (InterruptedException | ExecutionException e) {
ui.handleException(e);
task = null;
}
// Update manifest - If there were no errors cachedFile has already been modified in place (good old pass by reference)
if (task != null) {
if (task.getException() != null) {
ManifestFile.File file = task.cachedFile.getRevert();
if (file != null) {
manifest.cachedFiles.putIfAbsent(task.metadata.file, file);
}
} else {
// idiot, if it wasn't there in the first place it won't magically appear there
manifest.cachedFiles.putIfAbsent(task.metadata.file, task.cachedFile);
}
}
String progress;
if (task != null) {
if (task.getException() != null) {
progress = "Failed to download " + task.metadata.getName() + ": " + task.getException().getMessage();
task.getException().printStackTrace();
} else {
// TODO: should this be revised for tasks that didn't actually download it?
progress = "Downloaded " + task.metadata.getName();
}
} else {
progress = "Failed to download, unknown reason";
}
ui.submitProgress(new InstallProgress(progress, i + 1, tasks.size()));
if (stateHandler.getCancelButton()) {
// Stop all tasks, don't launch the game (it's in an invalid state!)
threadPool.shutdown();
cancelled = true;
return;
}
}
// Shut down the thread pool when the update is done
threadPool.shutdown();
List<IExceptionDetails> failedTasks2ElectricBoogaloo = nonFailedFirstTasks.stream().filter(t -> t.getException() != null).collect(Collectors.toList());
if (!failedTasks2ElectricBoogaloo.isEmpty()) {
errorsOccurred = true;
IExceptionDetails.ExceptionListResult exceptionListResult;
try {
exceptionListResult = ui.showExceptions(failedTasks2ElectricBoogaloo, tasks.size(), false).get();
} catch (InterruptedException | ExecutionException e) {
// Interrupted means cancelled???
ui.handleExceptionAndExit(e);
return;
}
switch (exceptionListResult) {
case CONTINUE:
break;
case CANCEL:
cancelled = true;
return;
case IGNORE:
cancelledStartGame = true;
}
}
}
private void showCancellationDialog() {
IExceptionDetails.ExceptionListResult exceptionListResult;
try {
exceptionListResult = ui.showCancellationDialog().get();
} catch (InterruptedException | ExecutionException e) {
// Interrupted means cancelled???
ui.handleExceptionAndExit(e);
return;
}
switch (exceptionListResult) {
case CONTINUE:
throw new RuntimeException("Continuation not allowed here!");
case CANCEL:
cancelled = true;
return;
case IGNORE:
cancelledStartGame = true;
}
}
private void handleCancellation() {
if (cancelled) {
System.out.println("Update cancelled by user!");
System.exit(1);
} else if (cancelledStartGame) {
System.out.println("Update cancelled by user! Continuing to start game...");
System.exit(0);
}
}
}

View File

@@ -1,10 +0,0 @@
package link.infra.packwiz.installer;
public class UpdateThread implements Runnable {
@Override
public void run() {
}
}

View File

@@ -0,0 +1,29 @@
package link.infra.packwiz.installer.metadata;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
public class EfficientBooleanAdapter extends TypeAdapter<Boolean> {
@Override
public void write(JsonWriter out, Boolean value) throws IOException {
if (value == null || !value) {
out.nullValue();
return;
}
out.value(true);
}
@Override
public Boolean read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return false;
}
return in.nextBoolean();
}
}

View File

@@ -0,0 +1,105 @@
package link.infra.packwiz.installer.metadata;
import com.google.gson.annotations.SerializedName;
import com.moandjiezana.toml.Toml;
import link.infra.packwiz.installer.metadata.hash.GeneralHashingSource;
import link.infra.packwiz.installer.metadata.hash.Hash;
import link.infra.packwiz.installer.metadata.hash.HashUtils;
import link.infra.packwiz.installer.request.HandlerManager;
import okio.Okio;
import okio.Source;
import java.nio.file.Paths;
import java.util.List;
public class IndexFile {
@SerializedName("hash-format")
public String hashFormat;
public List<File> files;
public static class File {
public SpaceSafeURI file;
@SerializedName("hash-format")
public String hashFormat;
public String hash;
public SpaceSafeURI alias;
public boolean metafile;
public boolean preserve;
public transient ModFile linkedFile;
public transient SpaceSafeURI linkedFileURI;
public void downloadMeta(IndexFile parentIndexFile, SpaceSafeURI indexUri) throws Exception {
if (!metafile) {
return;
}
if (hashFormat == null || hashFormat.length() == 0) {
hashFormat = parentIndexFile.hashFormat;
}
Hash fileHash = HashUtils.getHash(hashFormat, hash);
linkedFileURI = HandlerManager.getNewLoc(indexUri, file);
Source src = HandlerManager.getFileSource(linkedFileURI);
GeneralHashingSource fileStream = HashUtils.getHasher(hashFormat).getHashingSource(src);
linkedFile = new Toml().read(Okio.buffer(fileStream).inputStream()).to(ModFile.class);
if (!fileStream.hashIsEqual(fileHash)) {
throw new Exception("Invalid mod file hash");
}
}
public Source getSource(SpaceSafeURI indexUri) throws Exception {
if (metafile) {
if (linkedFile == null) {
throw new Exception("Linked file doesn't exist!");
}
return linkedFile.getSource(linkedFileURI);
} else {
SpaceSafeURI newLoc = HandlerManager.getNewLoc(indexUri, file);
if (newLoc == null) {
throw new Exception("Index file URI is invalid");
}
return HandlerManager.getFileSource(newLoc);
}
}
public Hash getHash() throws Exception {
if (hash == null) {
// TODO: should these be more specific exceptions (e.g. IndexFileException?!)
throw new Exception("Index file doesn't have a hash");
}
if (hashFormat == null) {
throw new Exception("Index file doesn't have a hash format");
}
return HashUtils.getHash(hashFormat, hash);
}
public String getName() {
if (metafile) {
if (linkedFile != null) {
if (linkedFile.name != null) {
return linkedFile.name;
} else if (linkedFile.filename != null) {
return linkedFile.filename;
}
}
}
if (file != null) {
return Paths.get(file.getPath()).getFileName().toString();
}
// TODO: throw some kind of exception?
return "Invalid file";
}
public SpaceSafeURI getDestURI() {
if (alias != null) {
return alias;
}
if (metafile && linkedFile != null) {
// TODO: URIs are bad
return file.resolve(linkedFile.filename);
} else {
return file;
}
}
}
}

View File

@@ -0,0 +1,45 @@
package link.infra.packwiz.installer.metadata;
import com.google.gson.annotations.JsonAdapter;
import link.infra.packwiz.installer.UpdateManager;
import link.infra.packwiz.installer.metadata.hash.Hash;
import java.util.Map;
public class ManifestFile {
public Hash packFileHash = null;
public Hash indexFileHash = null;
public Map<SpaceSafeURI, File> cachedFiles;
// If the side changes, EVERYTHING invalidates. FUN!!!
public UpdateManager.Options.Side cachedSide = UpdateManager.Options.Side.CLIENT;
public static class File {
private transient File revert;
public Hash hash = null;
public Hash linkedFileHash = null;
public String cachedLocation = null;
@JsonAdapter(EfficientBooleanAdapter.class)
public boolean isOptional = false;
public boolean optionValue = true;
@JsonAdapter(EfficientBooleanAdapter.class)
public boolean onlyOtherSide = false;
// When an error occurs, the state needs to be reverted. To do this, I have a crude revert system.
public void backup() {
revert = new File();
revert.hash = hash;
revert.linkedFileHash = linkedFileHash;
revert.cachedLocation = cachedLocation;
revert.isOptional = isOptional;
revert.optionValue = optionValue;
revert.onlyOtherSide = onlyOtherSide;
}
public File getRevert() {
return revert;
}
}
}

View File

@@ -0,0 +1,70 @@
package link.infra.packwiz.installer.metadata;
import com.google.gson.annotations.SerializedName;
import link.infra.packwiz.installer.UpdateManager.Options.Side;
import link.infra.packwiz.installer.metadata.hash.Hash;
import link.infra.packwiz.installer.metadata.hash.HashUtils;
import link.infra.packwiz.installer.request.HandlerManager;
import okio.Source;
import java.util.Map;
public class ModFile {
public String name;
public String filename;
public Side side;
public Download download;
public static class Download {
public SpaceSafeURI url;
@SerializedName("hash-format")
public String hashFormat;
public String hash;
}
public Map<String, Object> update;
public Option option;
public static class Option {
public boolean optional;
public String description;
@SerializedName("default")
public boolean defaultValue;
}
public Source getSource(SpaceSafeURI baseLoc) throws Exception {
if (download == null) {
throw new Exception("Metadata file doesn't have download");
}
if (download.url == null) {
throw new Exception("Metadata file doesn't have a download URI");
}
SpaceSafeURI newLoc = HandlerManager.getNewLoc(baseLoc, download.url);
if (newLoc == null) {
throw new Exception("Metadata file URI is invalid");
}
return HandlerManager.getFileSource(newLoc);
}
public Hash getHash() throws Exception {
if (download == null) {
throw new Exception("Metadata file doesn't have download");
}
if (download.hash == null) {
throw new Exception("Metadata file doesn't have a hash");
}
if (download.hashFormat == null) {
throw new Exception("Metadata file doesn't have a hash format");
}
return HashUtils.getHash(download.hashFormat, download.hash);
}
public boolean isOptional() {
if (option != null) {
return option.optional;
}
return false;
}
}

View File

@@ -0,0 +1,21 @@
package link.infra.packwiz.installer.metadata;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
public class PackFile {
public String name;
public IndexFileLoc index;
public static class IndexFileLoc {
public SpaceSafeURI file;
@SerializedName("hash-format")
public String hashFormat;
public String hash;
}
public Map<String, String> versions;
public Map<String, Object> client;
public Map<String, Object> server;
}

View File

@@ -0,0 +1,88 @@
package link.infra.packwiz.installer.metadata;
import com.google.gson.annotations.JsonAdapter;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
// The world's worst URI wrapper
@JsonAdapter(SpaceSafeURIParser.class)
public class SpaceSafeURI implements Comparable<SpaceSafeURI>, Serializable {
private final URI u;
public SpaceSafeURI(String str) throws URISyntaxException {
u = new URI(str.replace(" ", "%20"));
}
public SpaceSafeURI(URI uri) {
this.u = uri;
}
public SpaceSafeURI(String scheme, String authority, String path, String query, String fragment) throws URISyntaxException {
// TODO: do all components need to be replaced?
scheme = scheme.replace(" ", "%20");
authority = authority.replace(" ", "%20");
path = path.replace(" ", "%20");
query = query.replace(" ", "%20");
fragment = fragment.replace(" ", "%20");
u = new URI(scheme, authority, path, query, fragment);
}
public String getPath() {
return u.getPath().replace("%20", " ");
}
public String toString() {
return u.toString().replace("%20", " ");
}
@SuppressWarnings("WeakerAccess")
public SpaceSafeURI resolve(String path) {
return new SpaceSafeURI(u.resolve(path.replace(" ", "%20")));
}
public SpaceSafeURI resolve(SpaceSafeURI loc) {
return new SpaceSafeURI(u.resolve(loc.u));
}
public SpaceSafeURI relativize(SpaceSafeURI loc) {
return new SpaceSafeURI(u.relativize(loc.u));
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SpaceSafeURI) {
return u.equals(((SpaceSafeURI) obj).u);
}
return false;
}
@Override
public int hashCode() {
return u.hashCode();
}
@Override
public int compareTo(SpaceSafeURI uri) {
return u.compareTo(uri.u);
}
public String getScheme() {
return u.getScheme();
}
public String getAuthority() {
return u.getAuthority();
}
public String getHost() {
return u.getHost();
}
public URL toURL() throws MalformedURLException {
return u.toURL();
}
}

View File

@@ -0,0 +1,29 @@
package link.infra.packwiz.installer.metadata;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
/**
* This class encodes spaces before parsing the URI, so the URI can actually be
* parsed.
*/
class SpaceSafeURIParser implements JsonDeserializer<SpaceSafeURI> {
@Override
public SpaceSafeURI deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return new SpaceSafeURI(json.getAsString());
} catch (URISyntaxException e) {
throw new JsonParseException("Failed to parse URI", e);
}
}
// TODO: replace this with a better solution?
}

View File

@@ -0,0 +1,18 @@
package link.infra.packwiz.installer.metadata.hash;
import okio.ForwardingSource;
import okio.Source;
public abstract class GeneralHashingSource extends ForwardingSource {
public GeneralHashingSource(Source delegate) {
super(delegate);
}
public abstract Hash getHash();
public boolean hashIsEqual(Object compareTo) {
return compareTo.equals(getHash());
}
}

View File

@@ -0,0 +1,48 @@
package link.infra.packwiz.installer.metadata.hash;
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public abstract class Hash {
protected abstract String getStringValue();
protected abstract String getType();
public static class TypeHandler implements JsonDeserializer<Hash>, JsonSerializer<Hash> {
@Override
public JsonElement serialize(Hash src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject out = new JsonObject();
out.add("type", new JsonPrimitive(src.getType()));
out.add("value", new JsonPrimitive(src.getStringValue()));
return out;
}
@Override
public Hash deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
String type, value;
try {
type = obj.get("type").getAsString();
value = obj.get("value").getAsString();
} catch (NullPointerException e) {
throw new JsonParseException("Invalid hash JSON data");
}
try {
return HashUtils.getHash(type, value);
} catch (Exception e) {
throw new JsonParseException("Failed to create hash object", e);
}
}
}
}

View File

@@ -0,0 +1,29 @@
package link.infra.packwiz.installer.metadata.hash;
import java.util.HashMap;
import java.util.Map;
public class HashUtils {
private static final Map<String, IHasher> hashTypeConversion = new HashMap<String, IHasher>();
static {
hashTypeConversion.put("sha256", new HashingSourceHasher("sha256"));
hashTypeConversion.put("murmur2", new Murmur2Hasher());
}
public static IHasher getHasher(String type) throws Exception {
IHasher hasher = hashTypeConversion.get(type);
if (hasher == null) {
throw new Exception("Hash type not supported: " + type);
}
return hasher;
}
public static Hash getHash(String type, String value) throws Exception {
if (hashTypeConversion.containsKey(type)) {
return hashTypeConversion.get(type).getHash(value);
}
throw new Exception("Hash type not supported: " + type);
}
}

View File

@@ -0,0 +1,89 @@
package link.infra.packwiz.installer.metadata.hash;
import okio.HashingSource;
import okio.Source;
public class HashingSourceHasher implements IHasher {
private String type;
HashingSourceHasher(String type) {
this.type = type;
}
// i love naming things
private class HashingSourceGeneralHashingSource extends GeneralHashingSource {
HashingSource delegateHashing;
HashingSourceHash value;
HashingSourceGeneralHashingSource(HashingSource delegate) {
super(delegate);
delegateHashing = delegate;
}
@Override
public Hash getHash() {
if (value == null) {
value = new HashingSourceHash(delegateHashing.hash().hex());
}
return value;
}
}
// this some funky inner class stuff
// each of these classes is specific to the instance of the HasherHashingSource
// therefore HashingSourceHashes from different parent instances will be not instanceof each other
private class HashingSourceHash extends Hash {
String value;
private HashingSourceHash(String value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof HashingSourceHash)) {
return false;
}
HashingSourceHash objHash = (HashingSourceHash) obj;
if (value != null) {
return value.equalsIgnoreCase(objHash.value);
} else {
return objHash.value == null;
}
}
@Override
public String toString() {
return type + ": " + value;
}
@Override
protected String getStringValue() {
return value;
}
@Override
protected String getType() {
return type;
}
}
@Override
public GeneralHashingSource getHashingSource(Source delegate) {
switch (type) {
case "md5":
return new HashingSourceGeneralHashingSource(HashingSource.md5(delegate));
case "sha256":
return new HashingSourceGeneralHashingSource(HashingSource.sha256(delegate));
case "sha512":
return new HashingSourceGeneralHashingSource(HashingSource.sha512(delegate));
}
throw new RuntimeException("Invalid hash type provided");
}
@Override
public Hash getHash(String value) {
return new HashingSourceHash(value);
}
}

View File

@@ -0,0 +1,8 @@
package link.infra.packwiz.installer.metadata.hash;
import okio.Source;
public interface IHasher {
public GeneralHashingSource getHashingSource(Source delegate);
public Hash getHash(String value);
}

View File

@@ -0,0 +1,103 @@
package link.infra.packwiz.installer.metadata.hash;
import okio.Buffer;
import okio.Source;
import java.io.IOException;
public class Murmur2Hasher implements IHasher {
private class Murmur2GeneralHashingSource extends GeneralHashingSource {
Murmur2Hash value;
Buffer internalBuffer = new Buffer();
Buffer tempBuffer = new Buffer();
Source delegate;
public Murmur2GeneralHashingSource(Source delegate) {
super(delegate);
this.delegate = delegate;
}
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long out = delegate.read(tempBuffer, byteCount);
if (out > -1) {
sink.write(tempBuffer.clone(), out);
internalBuffer.write(tempBuffer, out);
}
return out;
}
@Override
public Hash getHash() {
if (value == null) {
byte[] data = computeNormalizedArray(internalBuffer.readByteArray());
value = new Murmur2Hash(Murmur2Lib.hash32(data, data.length, 1));
}
return value;
}
// Credit to https://github.com/modmuss50/CAV2/blob/master/murmur.go
private byte[] computeNormalizedArray(byte[] input) {
byte[] output = new byte[input.length];
int num = 0;
for (byte b : input) {
if (!(b == 9 || b == 10 || b == 13 || b == 32)) {
output[num] = b;
num++;
}
}
byte[] outputTrimmed = new byte[num];
System.arraycopy(output, 0, outputTrimmed, 0, num);
return outputTrimmed;
}
}
private static class Murmur2Hash extends Hash {
int value;
private Murmur2Hash(String value) {
// Parsing as long then casting to int converts values gt int max value but lt uint max value
// into negatives. I presume this is how the murmur2 code handles this.
this.value = (int)Long.parseLong(value);
}
private Murmur2Hash(int value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Murmur2Hash)) {
return false;
}
Murmur2Hash objHash = (Murmur2Hash) obj;
return value == objHash.value;
}
@Override
public String toString() {
return "murmur2: " + value;
}
@Override
protected String getStringValue() {
return Integer.toString(value);
}
@Override
protected String getType() {
return "murmur2";
}
}
@Override
public GeneralHashingSource getHashingSource(Source delegate) {
return new Murmur2GeneralHashingSource(delegate);
}
@Override
public Hash getHash(String value) {
return new Murmur2Hash(value);
}
}

View File

@@ -0,0 +1,166 @@
// Obtained from https://github.com/prasanthj/hasher/blob/master/src/main/java/hasher/Murmur2.java
/**
* Copyright 2014 Prasanth Jayachandran
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package link.infra.packwiz.installer.metadata.hash;
/**
* Murmur2 32 and 64 bit variants.
* 32-bit Java port of https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash2.cpp#37
* 64-bit Java port of https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash2.cpp#96
*/
public class Murmur2Lib {
// Constants for 32-bit variant
private static final int M_32 = 0x5bd1e995;
private static final int R_32 = 24;
// Constants for 64-bit variant
private static final long M_64 = 0xc6a4a7935bd1e995L;
private static final int R_64 = 47;
private static final int DEFAULT_SEED = 0;
/**
* Murmur2 32-bit variant.
*
* @param data - input byte array
* @return - hashcode
*/
public static int hash32(byte[] data) {
return hash32(data, data.length, DEFAULT_SEED);
}
/**
* Murmur2 32-bit variant.
*
* @param data - input byte array
* @param length - length of array
* @param seed - seed. (default 0)
* @return - hashcode
*/
public static int hash32(byte[] data, int length, int seed) {
int h = seed ^ length;
int len_4 = length >> 2;
// body
for (int i = 0; i < len_4; i++) {
int i_4 = i << 2;
int k = (data[i_4] & 0xff)
| ((data[i_4 + 1] & 0xff) << 8)
| ((data[i_4 + 2] & 0xff) << 16)
| ((data[i_4 + 3] & 0xff) << 24);
// mix functions
k *= M_32;
k ^= k >>> R_32;
k *= M_32;
h *= M_32;
h ^= k;
}
// tail
int len_m = len_4 << 2;
int left = length - len_m;
if (left != 0) {
if (left >= 3) {
h ^= (int) data[length - 3] << 16;
}
if (left >= 2) {
h ^= (int) data[length - 2] << 8;
}
if (left >= 1) {
h ^= (int) data[length - 1];
}
h *= M_32;
}
// finalization
h ^= h >>> 13;
h *= M_32;
h ^= h >>> 15;
return h;
}
/**
* Murmur2 64-bit variant.
*
* @param data - input byte array
* @return - hashcode
*/
public static long hash64(final byte[] data) {
return hash64(data, data.length, DEFAULT_SEED);
}
/**
* Murmur2 64-bit variant.
*
* @param data - input byte array
* @param length - length of array
* @param seed - seed. (default 0)
* @return - hashcode
*/
public static long hash64(final byte[] data, int length, int seed) {
long h = (seed & 0xffffffffl) ^ (length * M_64);
int length8 = length >> 3;
// body
for (int i = 0; i < length8; i++) {
final int i8 = i << 3;
long k = ((long) data[i8] & 0xff)
| (((long) data[i8 + 1] & 0xff) << 8)
| (((long) data[i8 + 2] & 0xff) << 16)
| (((long) data[i8 + 3] & 0xff) << 24)
| (((long) data[i8 + 4] & 0xff) << 32)
| (((long) data[i8 + 5] & 0xff) << 40)
| (((long) data[i8 + 6] & 0xff) << 48)
| (((long) data[i8 + 7] & 0xff) << 56);
// mix functions
k *= M_64;
k ^= k >>> R_64;
k *= M_64;
h ^= k;
h *= M_64;
}
// tail
int tailStart = length8 << 3;
switch (length - tailStart) {
case 7:
h ^= (long) (data[tailStart + 6] & 0xff) << 48;
case 6:
h ^= (long) (data[tailStart + 5] & 0xff) << 40;
case 5:
h ^= (long) (data[tailStart + 4] & 0xff) << 32;
case 4:
h ^= (long) (data[tailStart + 3] & 0xff) << 24;
case 3:
h ^= (long) (data[tailStart + 2] & 0xff) << 16;
case 2:
h ^= (long) (data[tailStart + 1] & 0xff) << 8;
case 1:
h ^= (long) (data[tailStart] & 0xff);
h *= M_64;
}
// finalization
h ^= h >>> R_64;
h *= M_64;
h ^= h >>> R_64;
return h;
}
}

View File

@@ -0,0 +1,59 @@
package link.infra.packwiz.installer.request;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import link.infra.packwiz.installer.request.handlers.RequestHandlerGithub;
import link.infra.packwiz.installer.request.handlers.RequestHandlerHTTP;
import okio.Source;
import java.util.ArrayList;
import java.util.List;
public abstract class HandlerManager {
private static List<IRequestHandler> handlers = new ArrayList<>();
static {
handlers.add(new RequestHandlerGithub());
handlers.add(new RequestHandlerHTTP());
}
public static SpaceSafeURI getNewLoc(SpaceSafeURI base, SpaceSafeURI loc) {
if (loc == null) return null;
if (base != null) {
loc = base.resolve(loc);
}
for (IRequestHandler handler : handlers) {
if (handler.matchesHandler(loc)) {
return handler.getNewLoc(loc);
}
}
return loc;
}
// TODO: What if files are read multiple times??
// Zip handler discards once read, requesting multiple times on other handlers would cause multiple downloads
// Caching system? Copy from already downloaded files?
public static Source getFileSource(SpaceSafeURI loc) throws Exception {
for (IRequestHandler handler : handlers) {
if (handler.matchesHandler(loc)) {
Source src = handler.getFileSource(loc);
if (src == null) {
throw new Exception("Couldn't find URI: " + loc.toString());
} else {
return src;
}
}
}
// TODO: specialised exception classes??
throw new Exception("No handler available for URI: " + loc.toString());
}
// github toml resolution
// e.g. https://github.com/comp500/Demagnetize -> demagnetize.toml
// https://github.com/comp500/Demagnetize/blob/master/demagnetize.toml
// To handle "progress", just count tasks, rather than individual progress
// It'll look bad, especially for zip-based things, but it should work fine
}

View File

@@ -0,0 +1,26 @@
package link.infra.packwiz.installer.request;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import okio.Source;
/**
* IRequestHandler handles requests for locations specified in modpack metadata.
*/
public interface IRequestHandler {
boolean matchesHandler(SpaceSafeURI loc);
default SpaceSafeURI getNewLoc(SpaceSafeURI loc) {
return loc;
}
/**
* Gets the Source for a location. Must be threadsafe.
* It is assumed that each location is read only once for the duration of an IRequestHandler.
* @param loc The location to be read
* @return The Source containing the data of the file
* @throws Exception Exception if it failed to download a file!!!
*/
Source getFileSource(SpaceSafeURI loc) throws Exception;
}

View File

@@ -0,0 +1,90 @@
package link.infra.packwiz.installer.request.handlers;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequestHandlerGithub extends RequestHandlerZip {
public RequestHandlerGithub() {
super(true);
}
@Override
public SpaceSafeURI getNewLoc(SpaceSafeURI loc) {
return loc;
}
// TODO: is caching really needed, if HTTPURLConnection follows redirects correctly?
private Map<String, SpaceSafeURI> zipUriMap = new HashMap<>();
private final ReentrantReadWriteLock zipUriLock = new ReentrantReadWriteLock();
private static Pattern repoMatcherPattern = Pattern.compile("/([\\w.-]+/[\\w.-]+).*");
private String getRepoName(SpaceSafeURI loc) {
Matcher matcher = repoMatcherPattern.matcher(loc.getPath());
if (matcher.matches()) {
return matcher.group(1);
} else {
return null;
}
}
@Override
protected SpaceSafeURI getZipUri(SpaceSafeURI loc) throws Exception {
String repoName = getRepoName(loc);
String branchName = getBranch(loc);
zipUriLock.readLock().lock();
SpaceSafeURI zipUri = zipUriMap.get(repoName + "/" + branchName);
zipUriLock.readLock().unlock();
if (zipUri != null) {
return zipUri;
}
zipUri = new SpaceSafeURI("https://api.github.com/repos/" + repoName + "/zipball/" + branchName);
zipUriLock.writeLock().lock();
// If another thread sets the value concurrently, use the value of the
// thread that first acquired the lock.
SpaceSafeURI zipUriInserted = zipUriMap.putIfAbsent(repoName + "/" + branchName, zipUri);
if (zipUriInserted != null) {
zipUri = zipUriInserted;
}
zipUriLock.writeLock().unlock();
return zipUri;
}
private static Pattern branchMatcherPattern = Pattern.compile("/[\\w.-]+/[\\w.-]+/blob/([\\w.-]+).*");
private String getBranch(SpaceSafeURI loc) {
Matcher matcher = branchMatcherPattern.matcher(loc.getPath());
if (matcher.matches()) {
return matcher.group(1);
} else {
return null;
}
}
@Override
protected SpaceSafeURI getLocationInZip(SpaceSafeURI loc) throws Exception {
String path = "/" + getRepoName(loc) + "/blob/" + getBranch(loc);
return new SpaceSafeURI(loc.getScheme(), loc.getAuthority(), path, null, null).relativize(loc);
}
@Override
public boolean matchesHandler(SpaceSafeURI loc) {
String scheme = loc.getScheme();
if (!("http".equals(scheme) || "https".equals(scheme))) {
return false;
}
if (!"github.com".equals(loc.getHost())) {
return false;
}
// TODO: sanity checks, support for more github urls
return true;
}
}

View File

@@ -0,0 +1,29 @@
package link.infra.packwiz.installer.request.handlers;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import link.infra.packwiz.installer.request.IRequestHandler;
import okio.Okio;
import okio.Source;
import java.net.URLConnection;
public class RequestHandlerHTTP implements IRequestHandler {
@Override
public boolean matchesHandler(SpaceSafeURI loc) {
String scheme = loc.getScheme();
return "http".equals(scheme) || "https".equals(scheme);
}
@Override
public Source getFileSource(SpaceSafeURI loc) throws Exception {
URLConnection conn = loc.toURL().openConnection();
// TODO: when do we send specific headers??? should there be a way to signal this?
// github *sometimes* requires it, sometimes not!
//conn.addRequestProperty("Accept", "application/octet-stream");
// 30 second read timeout
conn.setReadTimeout(30 * 1000);
return Okio.source(conn.getInputStream());
}
}

View File

@@ -0,0 +1,169 @@
package link.infra.packwiz.installer.request.handlers;
import link.infra.packwiz.installer.metadata.SpaceSafeURI;
import okio.Buffer;
import okio.BufferedSource;
import okio.Okio;
import okio.Source;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public abstract class RequestHandlerZip extends RequestHandlerHTTP {
private final boolean modeHasFolder;
public RequestHandlerZip(boolean modeHasFolder) {
this.modeHasFolder = modeHasFolder;
}
private String removeFolder(String name) {
if (modeHasFolder) {
return name.substring(name.indexOf("/")+1);
} else {
return name;
}
}
private class ZipReader {
private final ZipInputStream zis;
private final Map<SpaceSafeURI, Buffer> readFiles = new HashMap<>();
// Write lock implies access to ZipInputStream - only 1 thread must read at a time!
final ReentrantLock filesLock = new ReentrantLock();
private ZipEntry entry;
private final BufferedSource zipSource;
ZipReader(Source zip) {
zis = new ZipInputStream(Okio.buffer(zip).inputStream());
zipSource = Okio.buffer(Okio.source(zis));
}
// File lock must be obtained before calling this function
private Buffer readCurrFile() throws IOException {
Buffer fileBuffer = new Buffer();
zipSource.readFully(fileBuffer, entry.getSize());
return fileBuffer;
}
// File lock must be obtained before calling this function
private Buffer findFile(SpaceSafeURI loc) throws IOException, URISyntaxException {
while (true) {
entry = zis.getNextEntry();
if (entry == null) {
return null;
}
Buffer data = readCurrFile();
SpaceSafeURI fileLoc = new SpaceSafeURI(removeFolder(entry.getName()));
if (loc.equals(fileLoc)) {
return data;
} else {
readFiles.put(fileLoc, data);
}
}
}
Source getFileSource(SpaceSafeURI loc) throws Exception {
filesLock.lock();
// Assume files are only read once, allow GC by removing
Buffer file = readFiles.remove(loc);
if (file != null) {
filesLock.unlock();
return file;
}
file = findFile(loc);
filesLock.unlock();
return file;
}
SpaceSafeURI findInZip(Predicate<SpaceSafeURI> matches) throws Exception {
filesLock.lock();
for (SpaceSafeURI file : readFiles.keySet()) {
if (matches.test(file)) {
filesLock.unlock();
return file;
}
}
while (true) {
entry = zis.getNextEntry();
if (entry == null) {
filesLock.unlock();
return null;
}
Buffer data = readCurrFile();
SpaceSafeURI fileLoc = new SpaceSafeURI(removeFolder(entry.getName()));
readFiles.put(fileLoc, data);
if (matches.test(fileLoc)) {
filesLock.unlock();
return fileLoc;
}
}
}
}
private final Map<SpaceSafeURI, ZipReader> cache = new HashMap<>();
private final ReentrantReadWriteLock cacheLock = new ReentrantReadWriteLock();
protected abstract SpaceSafeURI getZipUri(SpaceSafeURI loc) throws Exception;
protected abstract SpaceSafeURI getLocationInZip(SpaceSafeURI loc) throws Exception;
@Override
public abstract boolean matchesHandler(SpaceSafeURI loc);
@Override
public Source getFileSource(SpaceSafeURI loc) throws Exception {
SpaceSafeURI zipUri = getZipUri(loc);
cacheLock.readLock().lock();
ZipReader zr = cache.get(zipUri);
cacheLock.readLock().unlock();
if (zr == null) {
cacheLock.writeLock().lock();
// Recheck, because unlocking read lock allows another thread to modify it
zr = cache.get(zipUri);
if (zr == null) {
Source src = super.getFileSource(zipUri);
if (src == null) {
cacheLock.writeLock().unlock();
return null;
}
zr = new ZipReader(src);
cache.put(zipUri, zr);
}
cacheLock.writeLock().unlock();
}
return zr.getFileSource(getLocationInZip(loc));
}
protected SpaceSafeURI findInZip(SpaceSafeURI loc, Predicate<SpaceSafeURI> matches) throws Exception {
SpaceSafeURI zipUri = getZipUri(loc);
cacheLock.readLock().lock();
ZipReader zr = cache.get(zipUri);
cacheLock.readLock().unlock();
if (zr == null) {
cacheLock.writeLock().lock();
// Recheck, because unlocking read lock allows another thread to modify it
zr = cache.get(zipUri);
if (zr == null) {
zr = new ZipReader(super.getFileSource(zipUri));
cache.put(zipUri, zr);
}
cacheLock.writeLock().unlock();
}
return zr.findInZip(matches);
}
}

View File

@@ -0,0 +1,55 @@
package link.infra.packwiz.installer.ui;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
public class CLIHandler implements IUserInterface {
@Override
public void handleException(Exception e) {
e.printStackTrace();
}
@Override
public void show(InputStateHandler h) {}
@Override
public void submitProgress(InstallProgress progress) {
StringBuilder sb = new StringBuilder();
if (progress.hasProgress) {
sb.append('(');
sb.append(progress.progress);
sb.append('/');
sb.append(progress.progressTotal);
sb.append(") ");
}
sb.append(progress.message);
System.out.println(sb.toString());
}
@Override
public void executeManager(Runnable task) {
task.run();
System.out.println("Finished successfully!");
}
@Override
public Future<Boolean> showOptions(List<IOptionDetails> options) {
for (IOptionDetails opt : options) {
opt.setOptionValue(true);
System.out.println("Warning: accepting option " + opt.getName() + " as option choosing is not implemented in the CLI");
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
future.complete(false); // Can't be cancelled!
return future;
}
@Override
public Future<IExceptionDetails.ExceptionListResult> showExceptions(List<IExceptionDetails> opts, int numTotal, boolean allowsIgnore) {
CompletableFuture<IExceptionDetails.ExceptionListResult> future = new CompletableFuture<>();
future.complete(IExceptionDetails.ExceptionListResult.CANCEL);
return future;
}
}

View File

@@ -0,0 +1,183 @@
package link.infra.packwiz.installer.ui;
import link.infra.packwiz.installer.ui.IExceptionDetails.ExceptionListResult;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
class ExceptionListWindow extends JDialog {
private static final long serialVersionUID = 1L;
private final JTextArea lblExceptionStacktrace;
/**
* Create the dialog.
*/
ExceptionListWindow(List<IExceptionDetails> eList, CompletableFuture<ExceptionListResult> future, int numTotal, boolean allowsIgnore, JFrame parentWindow) {
super(parentWindow, "Failed file downloads", true);
setBounds(100, 100, 540, 340);
setLocationRelativeTo(parentWindow);
getContentPane().setLayout(new BorderLayout());
{
JPanel errorPanel = new JPanel();
getContentPane().add(errorPanel, BorderLayout.NORTH);
{
JLabel lblWarning = new JLabel("One or more errors were encountered while installing the modpack!");
lblWarning.setIcon(UIManager.getIcon("OptionPane.warningIcon"));
errorPanel.add(lblWarning);
}
}
JPanel contentPanel = new JPanel();
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.3);
contentPanel.add(splitPane);
{
lblExceptionStacktrace = new JTextArea("Select a file");
lblExceptionStacktrace.setBackground(UIManager.getColor("List.background"));
lblExceptionStacktrace.setOpaque(true);
lblExceptionStacktrace.setWrapStyleWord(true);
lblExceptionStacktrace.setLineWrap(true);
lblExceptionStacktrace.setEditable(false);
lblExceptionStacktrace.setFocusable(true);
lblExceptionStacktrace.setFont(UIManager.getFont("Label.font"));
lblExceptionStacktrace.setBorder(new EmptyBorder(5, 5, 5, 5));
JScrollPane scrollPane = new JScrollPane(lblExceptionStacktrace);
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
splitPane.setRightComponent(scrollPane);
}
{
JList<String> list = new JList<>();
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(new EmptyBorder(5, 5, 5, 5));
ExceptionListModel listModel = new ExceptionListModel(eList);
list.setModel(listModel);
list.addListSelectionListener(e -> {
int i = list.getSelectedIndex();
if (i > -1) {
StringWriter sw = new StringWriter();
listModel.getExceptionAt(i).printStackTrace(new PrintWriter(sw));
lblExceptionStacktrace.setText(sw.toString());
// Scroll to the top
lblExceptionStacktrace.setCaretPosition(0);
} else {
lblExceptionStacktrace.setText("Select a file");
}
});
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
splitPane.setLeftComponent(scrollPane);
}
}
{
JPanel buttonPane = new JPanel();
getContentPane().add(buttonPane, BorderLayout.SOUTH);
buttonPane.setLayout(new BorderLayout(0, 0));
{
JPanel rightButtons = new JPanel();
buttonPane.add(rightButtons, BorderLayout.EAST);
{
JButton btnContinue = new JButton("Continue");
btnContinue.setToolTipText("Attempt to continue installing, excluding the failed downloads");
btnContinue.addActionListener(e -> {
future.complete(ExceptionListResult.CONTINUE);
ExceptionListWindow.this.dispose();
});
rightButtons.add(btnContinue);
}
{
JButton btnCancelLaunch = new JButton("Cancel launch");
btnCancelLaunch.setToolTipText("Stop launching the game");
btnCancelLaunch.addActionListener(e -> {
future.complete(ExceptionListResult.CANCEL);
ExceptionListWindow.this.dispose();
});
rightButtons.add(btnCancelLaunch);
}
{
JButton btnIgnoreUpdate = new JButton("Ignore update");
btnIgnoreUpdate.setEnabled(allowsIgnore);
btnIgnoreUpdate.setToolTipText("Start the game without attempting to update");
btnIgnoreUpdate.addActionListener(e -> {
future.complete(ExceptionListResult.IGNORE);
ExceptionListWindow.this.dispose();
});
rightButtons.add(btnIgnoreUpdate);
{
JLabel lblErrored = new JLabel(eList.size() + "/" + numTotal + " errored");
lblErrored.setHorizontalAlignment(SwingConstants.CENTER);
buttonPane.add(lblErrored, BorderLayout.CENTER);
}
{
JPanel leftButtons = new JPanel();
buttonPane.add(leftButtons, BorderLayout.WEST);
{
JButton btnReportIssue = new JButton("Report issue");
boolean supported = Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
btnReportIssue.setEnabled(supported);
if (supported) {
btnReportIssue.addActionListener(e -> {
try {
Desktop.getDesktop().browse(new URI("https://github.com/comp500/packwiz-installer/issues/new"));
} catch (IOException | URISyntaxException e1) {
// lol the button just won't work i guess
}
});
}
leftButtons.add(btnReportIssue);
}
}
}
}
}
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
future.complete(ExceptionListResult.CANCEL);
}
@Override
public void windowClosed(WindowEvent e) {
// Just in case closing didn't get triggered - if something else called dispose() the
// future will have already completed
future.complete(ExceptionListResult.CANCEL);
}
});
}
private static class ExceptionListModel extends AbstractListModel<String> {
private static final long serialVersionUID = 1L;
private final List<IExceptionDetails> details;
ExceptionListModel(List<IExceptionDetails> details) {
this.details = details;
}
public int getSize() {
return details.size();
}
public String getElementAt(int index) {
return details.get(index).getName();
}
Exception getExceptionAt(int index) {
return details.get(index).getException();
}
}
}

View File

@@ -0,0 +1,10 @@
package link.infra.packwiz.installer.ui;
public interface IExceptionDetails {
Exception getException();
String getName();
enum ExceptionListResult {
CONTINUE, CANCEL, IGNORE
}
}

View File

@@ -0,0 +1,8 @@
package link.infra.packwiz.installer.ui;
public interface IOptionDetails {
String getName();
boolean getOptionValue();
String getOptionDescription();
void setOptionValue(boolean value);
}

View File

@@ -0,0 +1,38 @@
package link.infra.packwiz.installer.ui;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
public interface IUserInterface {
void show(InputStateHandler handler);
void handleException(Exception e);
default void handleExceptionAndExit(Exception e) {
handleException(e);
System.exit(1);
}
default void setTitle(String title) {}
void submitProgress(InstallProgress progress);
void executeManager(Runnable task);
// Return true if the installation was cancelled!
Future<Boolean> showOptions(List<IOptionDetails> option);
Future<IExceptionDetails.ExceptionListResult> showExceptions(List<IExceptionDetails> opts, int numTotal, boolean allowsIgnore);
default void disableOptionsButton() {}
// Should not return CONTINUE
default Future<IExceptionDetails.ExceptionListResult> showCancellationDialog() {
CompletableFuture<IExceptionDetails.ExceptionListResult> future = new CompletableFuture<>();
future.complete(IExceptionDetails.ExceptionListResult.CANCEL);
return future;
}
}

View File

@@ -0,0 +1,22 @@
package link.infra.packwiz.installer.ui;
public class InputStateHandler {
private boolean optionsButtonPressed = false;
private boolean cancelButtonPressed = false;
synchronized void pressCancelButton() {
this.cancelButtonPressed = true;
}
synchronized void pressOptionsButton() {
this.optionsButtonPressed = true;
}
public synchronized boolean getCancelButton() {
return cancelButtonPressed;
}
public synchronized boolean getOptionsButton() {
return optionsButtonPressed;
}
}

View File

@@ -0,0 +1,22 @@
package link.infra.packwiz.installer.ui;
public class InstallProgress {
public final String message;
public final boolean hasProgress;
public final int progress;
public final int progressTotal;
public InstallProgress(String message) {
this.message = message;
hasProgress = false;
progress = 0;
progressTotal = 0;
}
public InstallProgress(String message, int progress, int progressTotal) {
this.message = message;
hasProgress = true;
this.progress = progress;
this.progressTotal = progressTotal;
}
}

View File

@@ -0,0 +1,228 @@
package link.infra.packwiz.installer.ui;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
public class InstallWindow implements IUserInterface {
private JFrame frmPackwizlauncher;
private JLabel lblProgresslabel;
private JProgressBar progressBar;
private InputStateHandler inputStateHandler;
private String title = "Updating modpack...";
private SwingWorkerButWithPublicPublish<Void, InstallProgress> worker;
private AtomicBoolean aboutToCrash = new AtomicBoolean();
private JButton btnOptions;
@Override
public void show(InputStateHandler handler) {
this.inputStateHandler = handler;
EventQueue.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
initialize();
frmPackwizlauncher.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Initialize the contents of the frame.
* @wbp.parser.entryPoint
*/
private void initialize() {
frmPackwizlauncher = new JFrame();
frmPackwizlauncher.setTitle(title);
frmPackwizlauncher.setBounds(100, 100, 493, 95);
frmPackwizlauncher.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPackwizlauncher.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
frmPackwizlauncher.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
progressBar = new JProgressBar();
progressBar.setIndeterminate(true);
panel.add(progressBar, BorderLayout.CENTER);
lblProgresslabel = new JLabel("Loading...");
panel.add(lblProgresslabel, BorderLayout.SOUTH);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new EmptyBorder(0, 5, 0, 5));
frmPackwizlauncher.getContentPane().add(panel_1, BorderLayout.EAST);
GridBagLayout gbl_panel_1 = new GridBagLayout();
panel_1.setLayout(gbl_panel_1);
btnOptions = new JButton("Optional mods...");
btnOptions.addActionListener(e -> {
btnOptions.setText("Loading...");
btnOptions.setEnabled(false);
inputStateHandler.pressOptionsButton();
});
btnOptions.setAlignmentX(Component.CENTER_ALIGNMENT);
GridBagConstraints gbc_btnOptions = new GridBagConstraints();
gbc_btnOptions.gridx = 0;
gbc_btnOptions.gridy = 0;
panel_1.add(btnOptions, gbc_btnOptions);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(e -> {
btnCancel.setEnabled(false);
inputStateHandler.pressCancelButton();
});
btnCancel.setAlignmentX(Component.CENTER_ALIGNMENT);
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.gridx = 0;
gbc_btnCancel.gridy = 1;
panel_1.add(btnCancel, gbc_btnCancel);
}
@Override
public void handleException(Exception e) {
e.printStackTrace();
EventQueue.invokeLater(() -> {
JOptionPane.showMessageDialog(null, "An error occurred: \n" + e.getClass().getCanonicalName() + ": " + e.getMessage(), title, JOptionPane.ERROR_MESSAGE);
});
}
@Override
public void handleExceptionAndExit(Exception e) {
e.printStackTrace();
// Used to prevent the done() handler of SwingWorker executing if the invokeLater hasn't happened yet
aboutToCrash.set(true);
EventQueue.invokeLater(() -> {
JOptionPane.showMessageDialog(null, "A fatal error occurred: \n" + e.getClass().getCanonicalName() + ": " + e.getMessage(), title, JOptionPane.ERROR_MESSAGE);
System.exit(1);
});
// Pause forever, so it blocks while we wait for System.exit to take effect
try {
Thread.currentThread().join();
} catch (InterruptedException ex) {
// no u
}
}
@Override
public void setTitle(String title) {
this.title = title;
if (frmPackwizlauncher != null) {
EventQueue.invokeLater(() -> frmPackwizlauncher.setTitle(title));
}
}
@Override
public void submitProgress(InstallProgress progress) {
StringBuilder sb = new StringBuilder();
if (progress.hasProgress) {
sb.append('(');
sb.append(progress.progress);
sb.append('/');
sb.append(progress.progressTotal);
sb.append(") ");
}
sb.append(progress.message);
// TODO: better logging library?
System.out.println(sb.toString());
if (worker != null) {
worker.publishPublic(progress);
}
}
@Override
public void executeManager(Runnable task) {
EventQueue.invokeLater(() -> {
worker = new SwingWorkerButWithPublicPublish<Void, InstallProgress>() {
@Override
protected Void doInBackground() {
task.run();
return null;
}
@Override
protected void process(List<InstallProgress> chunks) {
// Only process last chunk
if (chunks.size() > 0) {
InstallProgress prog = chunks.get(chunks.size() - 1);
if (prog.hasProgress) {
progressBar.setIndeterminate(false);
progressBar.setValue(prog.progress);
progressBar.setMaximum(prog.progressTotal);
} else {
progressBar.setIndeterminate(true);
progressBar.setValue(0);
}
lblProgresslabel.setText(prog.message);
}
}
@Override
protected void done() {
if (aboutToCrash.get()) {
return;
}
// TODO: a better way to do this?
frmPackwizlauncher.dispose();
System.out.println("Finished successfully!");
System.exit(0);
}
};
worker.execute();
});
}
@Override
public Future<Boolean> showOptions(List<IOptionDetails> opts) {
CompletableFuture<Boolean> future = new CompletableFuture<>();
EventQueue.invokeLater(() -> {
OptionsSelectWindow dialog = new OptionsSelectWindow(opts, future, frmPackwizlauncher);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
});
return future;
}
@Override
public Future<IExceptionDetails.ExceptionListResult> showExceptions(List<IExceptionDetails> opts, int numTotal, boolean allowsIgnore) {
CompletableFuture<IExceptionDetails.ExceptionListResult> future = new CompletableFuture<>();
EventQueue.invokeLater(() -> {
ExceptionListWindow dialog = new ExceptionListWindow(opts, future, numTotal, allowsIgnore, frmPackwizlauncher);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
});
return future;
}
@Override
public void disableOptionsButton() {
if (btnOptions != null) {
btnOptions.setText("Optional mods...");
btnOptions.setEnabled(false);
}
}
@Override
public Future<IExceptionDetails.ExceptionListResult> showCancellationDialog() {
CompletableFuture<IExceptionDetails.ExceptionListResult> future = new CompletableFuture<>();
EventQueue.invokeLater(() -> {
Object[] buttons = {"Quit", "Ignore"};
int result = JOptionPane.showOptionDialog(frmPackwizlauncher,
"The installation was cancelled. Would you like to quit the game, or ignore the update and start the game?",
"Cancelled installation",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, buttons, buttons[0]);
future.complete(result == 0 ? IExceptionDetails.ExceptionListResult.CANCEL : IExceptionDetails.ExceptionListResult.IGNORE);
});
return future;
}
}

View File

@@ -0,0 +1,33 @@
package link.infra.packwiz.installer.ui;
// Serves as a proxy for IOptionDetails, so that setOptionValue isn't called until OK is clicked
class OptionTempHandler implements IOptionDetails {
private final IOptionDetails opt;
private boolean tempValue;
OptionTempHandler(IOptionDetails opt) {
this.opt = opt;
tempValue = opt.getOptionValue();
}
public String getName() {
return opt.getName();
}
public String getOptionDescription() {
return opt.getOptionDescription();
}
public boolean getOptionValue() {
return tempValue;
}
public void setOptionValue(boolean value) {
tempValue = value;
}
void finalise() {
opt.setOptionValue(tempValue);
}
}

View File

@@ -0,0 +1,205 @@
package link.infra.packwiz.installer.ui;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class OptionsSelectWindow extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
private final JTextArea lblOptionDescription;
private final OptionTableModel tableModel;
private final CompletableFuture<Boolean> future;
/**
* Create the dialog.
*/
OptionsSelectWindow(List<IOptionDetails> optList, CompletableFuture<Boolean> future, JFrame parentWindow) {
super(parentWindow, "Select optional mods...", true);
tableModel = new OptionTableModel(optList);
this.future = future;
setBounds(100, 100, 450, 300);
setLocationRelativeTo(parentWindow);
getContentPane().setLayout(new BorderLayout());
JPanel contentPanel = new JPanel();
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.5);
contentPanel.add(splitPane);
{
JTable table = new JTable();
table.setShowVerticalLines(false);
table.setShowHorizontalLines(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setShowGrid(false);
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(0).setPreferredWidth(15);
table.getColumnModel().getColumn(0).setMaxWidth(15);
table.getColumnModel().getColumn(1).setResizable(false);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int i = table.getSelectedRow();
if (i > -1) {
lblOptionDescription.setText(tableModel.getDescription(i));
} else {
lblOptionDescription.setText("Select an option...");
}
}
});
table.setTableHeader(null);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.getViewport().setBackground(UIManager.getColor("List.background"));
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
splitPane.setLeftComponent(scrollPane);
}
{
lblOptionDescription = new JTextArea("Select an option...");
lblOptionDescription.setBackground(UIManager.getColor("List.background"));
lblOptionDescription.setOpaque(true);
lblOptionDescription.setWrapStyleWord(true);
lblOptionDescription.setLineWrap(true);
lblOptionDescription.setEditable(false);
lblOptionDescription.setFocusable(false);
lblOptionDescription.setFont(UIManager.getFont("Label.font"));
lblOptionDescription.setBorder(new EmptyBorder(10, 10, 10, 10));
JScrollPane scrollPane = new JScrollPane(lblOptionDescription);
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
splitPane.setRightComponent(scrollPane);
}
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
okButton.addActionListener(this);
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
cancelButton.addActionListener(this);
buttonPane.add(cancelButton);
}
}
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
future.complete(true);
}
@Override
public void windowClosed(WindowEvent e) {
// Just in case closing didn't get triggered - if something else called dispose() the
// future will have already completed
future.complete(true);
}
});
}
private static class OptionTableModel implements TableModel {
private List<OptionTempHandler> opts = new ArrayList<>();
OptionTableModel(List<IOptionDetails> givenOpts) {
for (IOptionDetails opt : givenOpts) {
opts.add(new OptionTempHandler(opt));
}
}
@Override
public int getRowCount() {
return opts.size();
}
@Override
public int getColumnCount() {
return 2;
}
private final String[] columnNames = {"Enabled", "Mod name"};
private final Class<?>[] columnTypes = {Boolean.class, String.class};
private final boolean[] columnEditables = {true, false};
@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnEditables[columnIndex];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
OptionTempHandler opt = opts.get(rowIndex);
return columnIndex == 0 ? opt.getOptionValue() : opt.getName();
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 0) {
OptionTempHandler opt = opts.get(rowIndex);
opt.setOptionValue((boolean) aValue);
}
}
// Noop, the table model doesn't change!
@Override
public void addTableModelListener(TableModelListener l) {}
@Override
public void removeTableModelListener(TableModelListener l) {}
String getDescription(int rowIndex) {
return opts.get(rowIndex).getOptionDescription();
}
void finalise() {
for (OptionTempHandler opt : opts) {
opt.finalise();
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("OK")) {
tableModel.finalise();
future.complete(false);
dispose();
} else if (e.getActionCommand().equals("Cancel")) {
future.complete(true);
dispose();
}
}
}

View File

@@ -0,0 +1,13 @@
package link.infra.packwiz.installer.ui;
import javax.swing.SwingWorker;
// Q: AAA WHAT HAVE YOU DONE THIS IS DISGUSTING
// A: it just makes things easier, so i can easily have one interface for CLI/GUI
// if someone has a better way to do this please PR it
public abstract class SwingWorkerButWithPublicPublish<T,V> extends SwingWorker<T,V> {
@SafeVarargs
public final void publishPublic(V... chunks) {
publish(chunks);
}
}