Browse Source

Pushed SKCraft Launcher base

master
Brandon Pearce 3 years ago
parent
commit
f2a54f7d68
100 changed files with 7539 additions and 0 deletions
  1. 151
    0
      .gitignore
  2. 198
    0
      LICENSE.txt
  3. 125
    0
      README.md
  4. 3
    0
      build.bat
  5. 41
    0
      build.gradle
  6. 3
    0
      build.sh
  7. 33
    0
      creator-tools/build.gradle
  8. 90
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/Creator.java
  9. 218
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/GenerateListingController.java
  10. 55
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/ManifestEntryController.java
  11. 819
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/PackManagerController.java
  12. 171
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/VersionCheckController.java
  13. 212
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/WelcomeController.java
  14. 57
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/DirectoryDeleter.java
  15. 73
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/DirectoryWalker.java
  16. 66
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/ManifestInfoEnumerator.java
  17. 77
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/PackBuilder.java
  18. 57
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/PackLoader.java
  19. 95
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/ProblemChecker.java
  20. 69
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/ServerDeploy.java
  21. 81
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/controller/task/TestLauncher.java
  22. 77
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/AboutDialog.java
  23. 109
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/BuildDialog.java
  24. 231
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/BuilderConfigDialog.java
  25. 97
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/DeployServerDialog.java
  26. 148
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/FeaturePatternDialog.java
  27. 24
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/FeaturePatternTable.java
  28. 82
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/GenerateListingDialog.java
  29. 64
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/ManifestEntryDialog.java
  30. 204
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/PackManagerFrame.java
  31. 30
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/ProblemTable.java
  32. 76
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/ProblemViewer.java
  33. 76
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/VersionCheckDialog.java
  34. 70
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/dialog/WelcomeDialog.java
  35. 34
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/creator/CreatorConfig.java
  36. 27
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/creator/ManifestEntry.java
  37. 38
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/creator/ModFile.java
  38. 71
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/creator/Pack.java
  39. 27
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/creator/Problem.java
  40. 27
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/creator/RecentEntry.java
  41. 78
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/creator/Workspace.java
  42. 97
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/FeaturePatternTableModel.java
  43. 96
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/ListingType.java
  44. 35
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/ListingTypeComboBoxModel.java
  45. 122
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/ManifestEntryTableModel.java
  46. 101
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/ModFileTableModel.java
  47. 100
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/PackTableModel.java
  48. 90
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/ProblemTableModel.java
  49. 35
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/RecentListModel.java
  50. 40
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/model/swing/RecommendationComboBoxModel.java
  51. 41
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/server/LatestHandler.java
  52. 39
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/server/NewsHandler.java
  53. 66
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/server/PackagesHandler.java
  54. 32
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/server/TestServer.java
  55. 78
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/server/TestServerBuilder.java
  56. 28
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/swing/BorderCellRenderer.java
  57. 26
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/swing/PackDirectoryFilter.java
  58. 24
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/swing/WorkspaceDirectoryFilter.java
  59. 169
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/util/ModInfoReader.java
  60. 91
    0
      creator-tools/src/main/java/com/skcraft/launcher/creator/util/NemModList.java
  61. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/about_header.png
  62. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/build.png
  63. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/check.png
  64. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/clean.png
  65. 7
    0
      creator-tools/src/main/resources/com/skcraft/launcher/creator/creator.properties
  66. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/edit.png
  67. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/help.png
  68. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/icon.png
  69. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/import.png
  70. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/log.png
  71. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/new.png
  72. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/open_folder.png
  73. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/options.png
  74. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/pack.png
  75. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/pack_icon.png
  76. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/server.png
  77. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/test.png
  78. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/warning_icon.png
  79. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/welcome_logo.png
  80. BIN
      creator-tools/src/main/resources/com/skcraft/launcher/creator/www_icon.png
  81. BIN
      gradle/wrapper/gradle-wrapper.jar
  82. 6
    0
      gradle/wrapper/gradle-wrapper.properties
  83. 164
    0
      gradlew
  84. 90
    0
      gradlew.bat
  85. 28
    0
      launcher-bootstrap/build.gradle
  86. 207
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/Bootstrap.java
  87. 49
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/BootstrapUtils.java
  88. 149
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/DownloadFrame.java
  89. 143
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/Downloader.java
  90. 492
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/HttpRequest.java
  91. 108
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/LauncherBinary.java
  92. 52
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/LinedBoxPanel.java
  93. 23
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/ProgressObservable.java
  94. 106
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/SharedLocale.java
  95. 63
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/SimpleLogFormatter.java
  96. 227
    0
      launcher-bootstrap/src/main/java/com/skcraft/launcher/bootstrap/SwingHelper.java
  97. 10
    0
      launcher-bootstrap/src/main/resources/com/skcraft/launcher/bootstrap.properties
  98. BIN
      launcher-bootstrap/src/main/resources/com/skcraft/launcher/bootstrapper_icon.png
  99. 21
    0
      launcher-bootstrap/src/main/resources/com/skcraft/launcher/lang/Bootstrap.properties
  100. 0
    0
      launcher-builder/build.gradle

+ 151
- 0
.gitignore View File

@@ -0,0 +1,151 @@
/installer/

### Eclipse ###
*.pydevproject
.metadata
.gradle
bin/
tmp/
run/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath

# Eclipse Core
.project

# External tool builders
.externalToolBuilders/

# Locally stored "Eclipse launch configurations"
*.launch

# CDT-specific
.cproject

# JDT-specific (Eclipse Java Development Tools)
.classpath

# PDT-specific
.buildpath

# sbteclipse plugin
.target

# TeXlipse plugin
.texlipse


### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml
.nb-gradle/


### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm

*.iml

## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:

# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries

# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml

# Gradle:
# .idea/gradle.xml
# .idea/libraries

# Mongo Explorer plugin:
# .idea/mongoSettings.xml

## File-based project format:
*.ipr
*.iws

## Plugin-specific files:

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties


### Java ###
*.class

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*


### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties


### Gradle ###
.gradle
build/

# Ignore Gradle GUI config
gradle-app.setting

# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar


### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk

+ 198
- 0
LICENSE.txt View File

@@ -0,0 +1,198 @@

GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.


This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

0. Additional Definitions.

As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

1. Exception to Section 3 of the GNU GPL.

You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

2. Conveying Modified Versions.

If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or

b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.

3. Object Code Incorporating Material from Library Header Files.

The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.

b) Accompany the object code with a copy of the GNU GPL and this license
document.

4. Combined Works.

You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.

b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.

c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.

d) Do one of the following:

0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.

1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.

e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)

5. Combined Libraries.

You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.

b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.

6. Revised Versions of the GNU Lesser General Public License.

The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

-------------------------------------------------------------------------------

The following license also applies to contributions by third parties:

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior
written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


+ 125
- 0
README.md View File

@@ -0,0 +1,125 @@
SKCraft Launcher
================

SKCraft Launcher provides a platform for creating, testing, and distributing modpacks for groups of all sizes. It 100% open source and works on Windows, Mac OS X and Linux/BSD.

With this platform, you have **full control** of the modpacks that you choose to release.

Every other launcher platform either requires you to maintain cryptic JSON/XML files (error prone and a lot of extra work), requires distributing a .zip of your modpack (therefore not supporting delta downloads and wasting disk space), or requires a complicated server setup where you have to install certain software on your server. In our case, we **(1)** threw away any need for JSON/XML files when making modpacks, **(2)** don't require a .zip and yet still can support delta downloads and **(3)** require absolutely zero server setup (if you only know FTP, that's enough).

What to be aware of? You'll probably need a few hours to get everything working. Fortunately, we have a [detailed wiki](https://github.com/SKCraft/Launcher/wiki) with screenshots for every step, intended for someone with minimal technical experience.

### Features

* No XML/JSON files involved to create or update a modpack
* Create a modpack by dragging and dropping mod .jars into a mods/ folder
* Support for LiteLoader, Forge, and JAR mods
* Support for resource packs
* Support for all and any modpack files
* Test modpacks without even needing a separate launcher
* Multiple modpacks in the launcher
* Deduplication of files (only upload a mod once for all modpacks)
* Delta downloads when updating (only changed files)
* Download resume
* No need to host old versions; users can update from any previous version
* No PHP or complex server setup necessary
* Compatible with all standard website hosting and CDNs
* Optional mods/files support
* Support for default configuration files
* Modpack-specific Java flags
* "Hidden" modpacks that require a special access key (this *does* require PHP support)

The wiki provides a detailed tutorial for configuring the launcher. You will need a website or an older Dropbox account to host your modpack's files, but there are several free website hosting options (with PHP support) listed on the wiki (with tutorials).

### Making Modpacks

Making modpacks is extremely easy: you can use our modpack creator tools:

![Modpack Creator](readme/pack_manager.png)

If installing mods for your own game only requires putting a .jar file into a mods folder, why should making a modpack be any harder?

To get started, you just make a folder that looks like your Minecraft installation folder:

* src/**config**/
* src/**mods**/
* src/**resourcepacks**/
* loaders/

Support for Minecraft Forge and LiteLoader merely involves putting their installer .jars into the loaders folder.

### Great Client

The launcher has a beautiful dark UI that's elegant and easy to use (although a native UI is also available). Display your own webpages so users always know what's up when they start the game.

![Skinned](readme/launcher_skinned.png)

When it comes to launching your modpacks, users can start, abort, and resume updates at any time. Files are downloaded in parallel, and the launcher knows how to handle the removal of files from the modpack.

Users can select those optional features that you have added:

![Optional Features](readme/features.png)

The launcher can **even update itself**.

...and you can use it in portable mode too.

### More Features

All of the modpack tools can be used to create a server modpack alongside the client modpack!

You can optionally use **command line tools** only, without the GUI entirely. Combine the launcher with Git and Jenkins (or whatever you prefer) to automatically build modpack releases when you push a new version.

### History

The launcher has been in development since the early days of Minecraft Alpha. It has powered and always has powered sk89q's own server, SKCraft.

[The older 3.x version was can be found elsewhere](https://github.com/sk89q/SKMCLauncher).

## Additional Screenshots

You can also use the "plain" version of the launcher:

![Main Launcher](readme/launcher.png)

![Options](readme/options.png)

![Console](readme/log.png)

More of the Modpack Creator:

![Modpack Creator](readme/modpack_creator.png)

![Build Modpacks](readme/packages_generator.png)

## Getting Started

* [Read the wiki](https://github.com/SKCraft/Launcher/wiki)
* [Forum to ask for help](http://forum.enginehub.org/forums/launcher.25/)
* [Join us on IRC: #sklauncher on EsperNet (irc.esper.net)](https://webchat.esper.net/?channels=sklauncher)

If you find the launcher useful, you can [support me on Patreon](https://www.patreon.com/sk89q).

[![Support Me on Patreon](https://i.imgur.com/Sg03Bzc.png)](https://www.patreon.com/sk89q)

## Compiling

In your command prompt or terminal, run:

./gradlew clean build

If you are on Windows:

gradlew clean build

If you wish to import the project into an IDE, you must add support for Project Lombok (IntelliJ IDEA users: also enable annotation processing in compiler settings).

## Contributing

Pull requests can be submitted on GitHub, but we will accept them at our discretion. Please note that your code must follow Oracle's Java Code Conventions.

Contributions by third parties must be dual licensed under the two licenses described within LICENSE.txt (GNU Lesser General Public License, version 3, and the 3-clause BSD license).

## License

The launcher is licensed under the GNU Lesser General Public License, version 3.

+ 3
- 0
build.bat View File

@@ -0,0 +1,3 @@
@echo off
call gradlew clean build
pause

+ 41
- 0
build.gradle View File

@@ -0,0 +1,41 @@
println """
*******************************************
You are building SKCraft Launcher!

Output files will be in [subproject]/build/libs
*******************************************
"""

buildscript {
repositories {
mavenCentral()
jcenter()
}

dependencies {
classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.0'
}
}

subprojects {
apply plugin: 'java'
apply plugin: 'maven'

group = 'com.skcraft'
version = '4.3-SNAPSHOT'

sourceCompatibility = 1.6
targetCompatibility = 1.6

repositories {
mavenCentral()
maven { url "http://repo.maven.apache.org/maven2" }
}

if (JavaVersion.current().isJava8Compatible()) {
// Java 8 turns on doclint which we fail
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
}

+ 3
- 0
build.sh View File

@@ -0,0 +1,3 @@
#!/bin/sh
./gradlew clean build
read -p "Press any key to continue..."

+ 33
- 0
creator-tools/build.gradle View File

@@ -0,0 +1,33 @@
apply plugin: 'com.github.johnrengelman.shadow'

version = "2.0.2-SNAPSHOT"
sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
compile project(':launcher-builder')
compile 'org.eclipse.jetty:jetty-server:9.3.1.v20150714'
compile 'com.jidesoft:jide-oss:3.6.10'
}

processResources {
filesMatching('**/*.properties') {
filter {
it.replace('${project.version}', project.version)
}
}
}

jar {
manifest {
attributes("Main-Class": "com.skcraft.launcher.creator.Creator")
}
}

shadowJar {
dependencies {
exclude(dependency('org.projectlombok:lombok'))
}
}

build.dependsOn(shadowJar)

+ 90
- 0
creator-tools/src/main/java/com/skcraft/launcher/creator/Creator.java View File

@@ -0,0 +1,90 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010-2014 Albert Pham <http://www.sk89q.com> and contributors
* Please see LICENSE.txt for license information.
*/

package com.skcraft.launcher.creator;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.skcraft.launcher.Launcher;
import com.skcraft.launcher.creator.controller.WelcomeController;
import com.skcraft.launcher.creator.dialog.WelcomeDialog;
import com.skcraft.launcher.creator.model.creator.CreatorConfig;
import com.skcraft.launcher.creator.model.creator.RecentEntry;
import com.skcraft.launcher.creator.model.creator.Workspace;
import com.skcraft.launcher.persistence.Persistence;
import com.skcraft.launcher.swing.SwingHelper;
import lombok.Getter;

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;

public class Creator {

@Getter private final File dataDir;
@Getter private final CreatorConfig config;
@Getter private final ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

public Creator() {
this.dataDir = getAppDataDir();
this.config = Persistence.load(new File(dataDir, "config.json"), CreatorConfig.class);

System.setProperty("com.skcraft.builder.ignoreURLOverrides", "true");

// Remove deleted workspaces
List<RecentEntry> recentEntries = config.getRecentEntries();
Iterator<RecentEntry> it = recentEntries.iterator();
while (it.hasNext()) {
RecentEntry workspace = it.next();
if (!Workspace.getWorkspaceFile(workspace.getPath()).exists()) {
it.remove();
}
}
}

public void showWelcome() {
WelcomeDialog dialog = new WelcomeDialog();
WelcomeController controller = new WelcomeController(dialog, this);
controller.show();
}

private static File getFileChooseDefaultDir() {
JFileChooser chooser = new JFileChooser();
FileSystemView fsv = chooser.getFileSystemView();
return fsv.getDefaultDirectory();
}

private static File getAppDataDir() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
return new File(getFileChooseDefaultDir(), "SKCraft Modpack Creator");
} else {
return new File(System.getProperty("user.home"), ".skcraftcreator");
}
}

public static void main(String[] args) throws Exception {
Launcher.setupLogger();
System.setProperty("skcraftLauncher.killWithoutConfirm", "true");

final Creator creator = new Creator();

SwingUtilities.invokeAndWait(() -> {
SwingHelper.setSwingProperties("Modpack Creator");
SwingHelper.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

try {
creator.showWelcome();
} catch (Exception e) {
SwingHelper.showErrorDialog(null, "Failed to start the modpack creator program.", "Start Error", e);
}
});
}

}

+ 218
- 0
creator-tools/src/main/java/com/skcraft/launcher/creator/controller/GenerateListingController.java View File

@@ -0,0 +1,218 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010-2014 Albert Pham <http://www.sk89q.com> and contributors
* Please see LICENSE.txt for license information.
*/

package com.skcraft.launcher.creator.controller;

import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.skcraft.concurrency.Deferred;
import com.skcraft.concurrency.Deferreds;
import com.skcraft.concurrency.SettableProgress;
import com.skcraft.launcher.creator.dialog.GenerateListingDialog;
import com.skcraft.launcher.creator.dialog.ManifestEntryDialog;
import com.skcraft.launcher.creator.model.creator.ManifestEntry;
import com.skcraft.launcher.creator.model.creator.Workspace;
import com.skcraft.launcher.creator.model.swing.ListingType;
import com.skcraft.launcher.creator.model.swing.ManifestEntryTableModel;
import com.skcraft.launcher.dialog.ProgressDialog;
import com.skcraft.launcher.persistence.Persistence;
import com.skcraft.launcher.swing.SwingHelper;
import com.skcraft.launcher.util.SwingExecutor;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;

public class GenerateListingController {

private final GenerateListingDialog dialog;
private final Workspace workspace;
private final List<ManifestEntry> manifestEntries;
private final ListeningExecutorService executor;
private final ManifestEntryTableModel manifestTableModel;

public GenerateListingController(GenerateListingDialog dialog, Workspace workspace, List<ManifestEntry> manifestEntries, ListeningExecutorService executor) {
this.dialog = dialog;
this.workspace = workspace;
this.manifestEntries = manifestEntries;
this.executor = executor;

this.manifestTableModel = new ManifestEntryTableModel(manifestEntries);
dialog.getManifestsTable().setModel(manifestTableModel);
dialog.getManifestsTableAdjuster().adjustColumns();

initListeners();

setListingType(workspace.getPackageListingType());
}

public void setOutputDir(File dir) {
dialog.getDestDirField().setPath(dir.getAbsolutePath());
}

public void setListingType(ListingType type) {
dialog.getListingTypeCombo().setSelectedItem(type);
}

public void show() {
dialog.setVisible(true);
}

public Optional<ManifestEntry> getManifestFromIndex(int selectedIndex) {
if (selectedIndex >= 0) {
ManifestEntry manifest = manifestEntries.get(selectedIndex);
if (manifest != null) {
return Optional.fromNullable(manifest);
}
}
return Optional.absent();
}

public Optional<ManifestEntry> getSelectedManifest() {
JTable table = dialog.getManifestsTable();
int selectedIndex = table.getSelectedRow();
if (selectedIndex >= 0) {
selectedIndex = table.convertRowIndexToModel(selectedIndex);
ManifestEntry manifest = manifestEntries.get(selectedIndex);
if (manifest != null) {
return Optional.fromNullable(manifest);
}
}

SwingHelper.showErrorDialog(dialog, "Please select a modpack from the list.", "Error");
return Optional.absent();
}

private void updateManifestEntryInTable(ManifestEntry manifestEntry) {
int index = manifestEntries.indexOf(manifestEntry);
if (index >= 0) {
manifestTableModel.fireTableRowsUpdated(index, index);
}
}

private void initListeners() {
dialog.getManifestsTable().addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
JTable table = (JTable) e.getSource();
Point point = e.getPoint();
int selectedIndex = table.rowAtPoint(point);
if (selectedIndex >= 0) {
selectedIndex = table.convertRowIndexToModel(selectedIndex);
Optional<ManifestEntry> optional = getManifestFromIndex(selectedIndex);
if (optional.isPresent()) {
if (showModifyDialog(optional.get())) {
updateManifestEntryInTable(optional.get());
}
}
}
}
}
});

dialog.getListingTypeCombo().addItemListener(e -> {
ListingType type = (ListingType) e.getItem();
dialog.getGameKeyWarning().setVisible(!type.isGameKeyCompatible());
});

dialog.getEditManifestButton().addActionListener(e -> {
Optional<ManifestEntry> optional = getSelectedManifest();
if (optional.isPresent()) {
if (showModifyDialog(optional.get())) {
updateManifestEntryInTable(optional.get());
}
}
});

dialog.getGenerateButton().addActionListener(e -> tryGenerate());

dialog.getCancelButton().addActionListener(e -> dialog.dispose());
}

private boolean showModifyDialog(ManifestEntry manifestEntry) {
ManifestEntryDialog modifyDialog = new ManifestEntryDialog(dialog);
modifyDialog.setTitle("Modify " + manifestEntry.getManifestInfo().getLocation());
ManifestEntryController controller = new ManifestEntryController(modifyDialog, manifestEntry);
return controller.show();
}

private boolean tryGenerate() {
String path = dialog.getDestDirField().getPath().trim();

if (path.isEmpty()) {
SwingHelper.showErrorDialog(dialog, "A directory must be entered.", "Error");
return false;
}

List<ManifestEntry> selected = manifestEntries.stream()
.filter(ManifestEntry::isSelected)
.sorted()
.collect(Collectors.toCollection(Lists::newArrayList));

if (selected.isEmpty()) {
SwingHelper.showErrorDialog(dialog, "At least one modpack must be selected to appear in the package list.", "Error");
return false;
}

ListingType listingType = (ListingType) dialog.getListingTypeCombo().getSelectedItem();
File destDir = new File(path);
destDir.mkdirs();
File file = new File(destDir, listingType.getFilename());

workspace.setPackageListingEntries(selected);
workspace.setPackageListingType(listingType);
Persistence.commitAndForget(workspace);

SettableProgress progress = new SettableProgress("Generating package listing...", -1);

Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(() -> listingType.generate(selected)))
.thenTap(() -> progress.set("Deleting older package listing files...", -1))
.thenApply(input -> {
for (ListingType otherListingType : ListingType.values()) {
File f = new File(destDir, otherListingType.getFilename());
if (f.exists()) {
f.delete();
}
}

return input;
})
.thenTap(() -> progress.set("Writing package listing to disk...", -1))
.thenApply(input -> {
try {
Files.write(input, file, Charset.forName("UTF-8"));
return file;
} catch (IOException e) {
throw new RuntimeException("Failed to write package listing file to disk", e);
}
})
.handleAsync(v -> {
if (listingType.isGameKeyCompatible()) {
SwingHelper.showMessageDialog(dialog, "Successfully generated package listing.", "Success", null, JOptionPane.INFORMATION_MESSAGE);
} else {
SwingHelper.showMessageDialog(dialog, "Successfully generated package listing.\n\n" +
"Note that any modpacks with game keys set were not added.",
"Success", null, JOptionPane.INFORMATION_MESSAGE);
}
dialog.dispose();
SwingHelper.browseDir(destDir, dialog);
}, ex -> {}, SwingExecutor.INSTANCE);

ProgressDialog.showProgress(dialog, deferred, progress, "Writing package listing...", "Writing package listing...");
SwingHelper.addErrorDialogCallback(dialog, deferred);

return true;
}

}

+ 55
- 0
creator-tools/src/main/java/com/skcraft/launcher/creator/controller/ManifestEntryController.java View File

@@ -0,0 +1,55 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010-2014 Albert Pham <http://www.sk89q.com> and contributors
* Please see LICENSE.txt for license information.
*/

package com.skcraft.launcher.creator.controller;

import com.skcraft.launcher.creator.dialog.ManifestEntryDialog;
import com.skcraft.launcher.creator.model.creator.ManifestEntry;
import com.skcraft.launcher.swing.SwingHelper;

public class ManifestEntryController {

private final ManifestEntryDialog dialog;
private final ManifestEntry manifestEntry;

private boolean save;

public ManifestEntryController(ManifestEntryDialog dialog, ManifestEntry manifestEntry) {
this.dialog = dialog;
this.manifestEntry = manifestEntry;

initListeners();
copyFrom();
}

private void copyFrom() {
dialog.getIncludeCheck().setSelected(manifestEntry.isSelected());
dialog.getPrioritySpinner().setValue(manifestEntry.getManifestInfo().getPriority());
SwingHelper.setTextAndResetCaret(dialog.getGameKeysText(), SwingHelper.listToLines(manifestEntry.getGameKeys()));
}

private void copyTo() {
manifestEntry.setSelected(dialog.getIncludeCheck().isSelected());
manifestEntry.getManifestInfo().setPriority((Integer) dialog.getPrioritySpinner().getValue());
manifestEntry.setGameKeys(SwingHelper.linesToList(dialog.getGameKeysText().getText()));
}

public boolean show() {
dialog.setVisible(true);
return save;
}

private void initListeners() {
dialog.getOkButton().addActionListener(e -> {
copyTo();
save = true;
dialog.dispose();
});

dialog.getCancelButton().addActionListener(e -> dialog.dispose());
}

}

+ 819
- 0
creator-tools/src/main/java/com/skcraft/launcher/creator/controller/PackManagerController.java View File

@@ -0,0 +1,819 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010-2014 Albert Pham <http://www.sk89q.com> and contributors
* Please see LICENSE.txt for license information.
*/

package com.skcraft.launcher.creator.controller;

import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.skcraft.concurrency.Deferred;
import com.skcraft.concurrency.Deferreds;
import com.skcraft.concurrency.SettableProgress;
import com.skcraft.launcher.InstanceList;
import com.skcraft.launcher.Launcher;
import com.skcraft.launcher.auth.OfflineSession;
import com.skcraft.launcher.auth.Session;
import com.skcraft.launcher.builder.BuilderConfig;
import com.skcraft.launcher.builder.FnPatternList;
import com.skcraft.launcher.creator.Creator;
import com.skcraft.launcher.creator.model.creator.*;
import com.skcraft.launcher.creator.controller.task.*;
import com.skcraft.launcher.creator.dialog.*;
import com.skcraft.launcher.creator.dialog.BuildDialog.BuildOptions;
import com.skcraft.launcher.creator.dialog.DeployServerDialog.DeployOptions;
import com.skcraft.launcher.creator.model.swing.PackTableModel;
import com.skcraft.launcher.creator.server.TestServer;
import com.skcraft.launcher.creator.server.TestServerBuilder;
import com.skcraft.launcher.creator.swing.PackDirectoryFilter;
import com.skcraft.launcher.dialog.ConfigurationDialog;
import com.skcraft.launcher.dialog.ConsoleFrame;
import com.skcraft.launcher.dialog.LoginDialog;
import com.skcraft.launcher.dialog.ProgressDialog;
import com.skcraft.launcher.model.modpack.LaunchModifier;
import com.skcraft.launcher.persistence.Persistence;
import com.skcraft.launcher.swing.PopupMouseAdapter;
import com.skcraft.launcher.swing.SwingHelper;
import com.skcraft.launcher.util.MorePaths;
import com.skcraft.launcher.util.SwingExecutor;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

public class PackManagerController {

private static final DateFormat VERSION_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-z0-9_\\-\\.]+");

@Getter private final File workspaceDir;
@Getter private final Creator creator;
@Getter private final File workspaceFile;
@Getter private final File dataDir;
@Getter private final File distDir;
@Getter private final File launcherDir;
@Getter private File webRoot;
@Getter private Workspace workspace;
@Getter private final Launcher launcher;
@Getter private final ListeningExecutorService executor;
@Getter private final TestServer testServer;

private File lastServerDestDir;

private final PackManagerFrame frame;
private PackTableModel packTableModel;

public PackManagerController(PackManagerFrame frame, File workspaceDir, Creator creator) throws IOException {
this.workspaceDir = workspaceDir;
this.creator = creator;
this.dataDir = Workspace.getDataDir(workspaceDir);
workspaceFile = Workspace.getWorkspaceFile(workspaceDir);

this.distDir = new File(workspaceDir, "_upload");
launcherDir = new File(dataDir, "staging/launcher");
File launcherConfigDir = new File(creator.getDataDir(), "launcher");
this.webRoot = new File(dataDir, "staging/www");

launcherDir.mkdirs();
launcherConfigDir.mkdirs();
webRoot.mkdirs();

this.launcher = new Launcher(launcherDir, launcherConfigDir);
this.executor = launcher.getExecutor();
this.frame = frame;

TestServerBuilder builder = new TestServerBuilder();
builder.setBaseDir(webRoot);
builder.setPort(0);
testServer = builder.build();
}

public void show() {
frame.setVisible(true);
frame.setTitle("Modpack Creator - [" + workspaceDir.getAbsolutePath() + "]");

initListeners();
loadWorkspace();

Deferreds.makeDeferred(executor.submit(() -> {
startServer();
return null;
}))
.handle(
result -> {
},
(ex) -> SwingHelper.showErrorDialog(frame, "Failed to start a local web server. You will be unable to test modpacks.", "Error", ex)
);
}

private void startServer() throws Exception {
testServer.start();

launcher.getProperties().setProperty("newsUrl", "http://localhost:" + testServer.getLocalPort() + "/news.html");
launcher.getProperties().setProperty("packageListUrl", "http://localhost:" + testServer.getLocalPort() + "/packages.json");
launcher.getProperties().setProperty("selfUpdateUrl", "http://localhost:" + testServer.getLocalPort() + "/latest.json");
}

private void loadWorkspace() {
PackLoader loader = new PackLoader();

SettableProgress progress = new SettableProgress("Loading workspace...", -1);

Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(() -> {
Workspace workspace = Persistence.load(workspaceFile, Workspace.class);
workspace.setDirectory(workspaceDir);
workspace.load();
if (!workspaceFile.exists()) {
Persistence.commitAndForget(workspace);
}
this.workspace = workspace;
return workspace;
}))
.thenTap(() -> progress.observe(loader))
.thenApply(loader)
.thenApplyAsync(packs -> {
JTable table = frame.getPackTable();
packTableModel = new PackTableModel(packs);
table.setModel(packTableModel);
packTableModel.fireTableDataChanged();
table.getRowSorter().toggleSortOrder(1);
if (packTableModel.getRowCount() > 0) {
table.addRowSelectionInterval(0, 0);
}

return packs;
}, SwingExecutor.INSTANCE);

ProgressDialog.showProgress(frame, deferred, progress, "Loading workspace...", "Loading workspace...");
SwingHelper.addErrorDialogCallback(frame, deferred);
}

private boolean checkPackLoaded(Pack pack) {
if (pack.isLoaded()) {
return true;
} else {
SwingHelper.showErrorDialog(frame, "The selected pack could not be loaded. You will have to remove it from the workspace or change its location.", "Error");
return false;
}
}

public Optional<Pack> getPackFromIndex(int selectedIndex, boolean requireLoaded) {
if (selectedIndex >= 0) {
Pack pack = workspace.getPacks().get(selectedIndex);
if (pack != null && (!requireLoaded || checkPackLoaded(pack))) {
return Optional.fromNullable(pack);
}
}
return Optional.absent();
}

public Optional<Pack> getSelectedPack(boolean requireLoaded) {
JTable table = frame.getPackTable();
int selectedIndex = table.getSelectedRow();
if (selectedIndex >= 0) {
selectedIndex = table.convertRowIndexToModel(selectedIndex);
Pack pack = workspace.getPacks().get(selectedIndex);
if (pack != null && (!requireLoaded || checkPackLoaded(pack))) {
return Optional.fromNullable(pack);
}
}

SwingHelper.showErrorDialog(frame, "Please select a modpack from the list.", "Error");
return Optional.absent();
}

public boolean writeWorkspace() {
try {
Persistence.commit(workspace);
return true;
} catch (IOException e) {
SwingHelper.showErrorDialog(frame, "Failed to write the current state of the workspace to disk. " +
"Any recent changes to the list of modpacks may not appear in the workspace on the next load.", "Error", e);
return false;
}
}

public boolean writeBuilderConfig(Pack pack, BuilderConfig config) {
try {
Persistence.write(pack.getConfigFile(), config, Persistence.L2F_LIST_PRETTY_PRINTER);
return true;
} catch (IOException e) {
SwingHelper.showErrorDialog(frame, "Failed to write modpack.json to disk. Aborting.", "Error", e);
return false;
}
}

private boolean isOfflineEnabled() {
CreatorConfig config = creator.getConfig();

if (config.isOfflineEnabled()) {
return true;
} else {
Session session = LoginDialog.showLoginRequest(frame, launcher);
if (session != null) {
config.setOfflineEnabled(true);
Persistence.commitAndForget(config);
return true;
} else {
return false;
}
}
}

public boolean canAddPackDir(File dir) {
try {
if (dir.exists() && !dir.isDirectory()) {
SwingHelper.showErrorDialog(frame, "The selected path is a file that already exists. It must be a directory.", "Error");
return false;
} else if (dir.getCanonicalPath().equals(workspaceDir.getCanonicalPath())) {
SwingHelper.showErrorDialog(frame, "You cannot choose the workspace directory.", "Error");
return false;
} else if (workspace.hasPack(dir)) {
SwingHelper.showErrorDialog(frame, "There is already a modpack in this workspace that uses that directory.", "Error");
return false;
} else {
return true;
}
} catch (IOException e) {
SwingHelper.showErrorDialog(frame, "An unexpected error occurred while checking if the modpack being added can be added.", "Error", e);
return false;
}
}

public boolean addPackToWorkspace(Pack pack) {
pack.load();

try {
File base = workspaceDir;
File child = pack.getDirectory();
if (MorePaths.isSubDirectory(base, child)) {
pack.setLocation(MorePaths.relativize(base, child));
}
} catch (IOException e) {
SwingHelper.showErrorDialog(frame, "An unexpected error occurred that could have been caused by the removal " +
"of the workspace or modpack directory.", "Error", e);
return false;
}

List<Pack> packs = workspace.getPacks();
pack.setWorkspace(workspace);
packs.add(pack);
packTableModel.fireTableRowsInserted(packs.size() - 1, packs.size() - 1);
writeWorkspace();

return true;
}

public void updatePackInWorkspace(Pack pack) {
List<Pack> packs = workspace.getPacks();
pack.load();
int index = packs.indexOf(pack);
if (index >= 0) {
packTableModel.fireTableRowsUpdated(index, index);
}
writeWorkspace();
}

public boolean removePackFromWorkspace(Pack pack) {
if (workspace.getPacks().remove(pack)) {
packTableModel.fireTableDataChanged();
writeWorkspace();
return true;
} else {
return false;
}
}

private void addDefaultConfig(BuilderConfig config) {
LaunchModifier launchModifier = new LaunchModifier();
launchModifier.setFlags(ImmutableList.of("-Dfml.ignoreInvalidMinecraftCertificates=true"));
config.setLaunchModifier(launchModifier);

FnPatternList userFiles = new FnPatternList();
userFiles.setInclude(Lists.newArrayList("options.txt", "optionsshaders.txt"));
userFiles.setExclude(Lists.<String>newArrayList());
config.setUserFiles(userFiles);
}

private void initListeners() {
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
try {
testServer.stop();
} catch (Exception ignored) {
}
System.exit(0); // TODO: Proper shutdown
}
});

frame.getPackTable().addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
JTable table = (JTable) e.getSource();
Point point = e.getPoint();
int selectedIndex = table.rowAtPoint(point);
if (selectedIndex >= 0) {
selectedIndex = table.convertRowIndexToModel(selectedIndex);
Optional<Pack> optional = getPackFromIndex(selectedIndex, true);
if (optional.isPresent()) {
if (e.isControlDown()) {
SwingHelper.browseDir(optional.get().getDirectory(), frame);
} else {
startTest(optional.get(), false);
}
}
}
}
}
});

frame.getPackTable().addMouseListener(new PopupMouseAdapter() {
@Override
protected void showPopup(MouseEvent e) {
JTable table = (JTable) e.getSource();
Point point = e.getPoint();
int selectedIndex = table.rowAtPoint(point);
if (selectedIndex >= 0) {
table.setRowSelectionInterval(selectedIndex, selectedIndex);
Optional<Pack> optional = getSelectedPack(false);
if (optional.isPresent()) {
popupPackMenu(e.getComponent(), e.getX(), e.getY(), optional.get());
}
}
}
});

frame.getNewPackMenuItem().addActionListener(event -> tryAddPackViaDialog());

frame.getNewPackAtLocationMenuItem().addActionListener(e -> tryAddPackViaDirectory(true));

frame.getImportPackMenuItem().addActionListener(event -> tryAddPackViaDirectory(false));

frame.getRemovePackItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(false);

if (optional.isPresent()) {
Pack pack = optional.get();

if (!pack.isLoaded() || SwingHelper.confirmDialog(frame, "Are you sure that you want to remove this modpack? No files will be deleted " +
"and you can later re-import the modpack using 'Add Existing'.", "Confirm")) {
removePackFromWorkspace(pack);
}
}
});

frame.getDeletePackItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(false);

if (optional.isPresent()) {
Pack pack = optional.get();

String input = JOptionPane.showInputDialog(
frame,
"Are you sure that you want to delete '" + pack.getDirectory().getAbsolutePath() + "'? " +
"If yes, type 'delete' below.",
"Confirm",
JOptionPane.WARNING_MESSAGE);

if (input != null && input.replaceAll("'", "").equalsIgnoreCase("delete")) {
removePackFromWorkspace(pack);

DirectoryDeleter deleter = new DirectoryDeleter(pack.getDirectory());
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(deleter), executor);
ProgressDialog.showProgress(frame, deferred, deleter, "Deleting modpack...", "Deleting modpack...");
SwingHelper.addErrorDialogCallback(frame, deferred);
} else if (input != null) {
SwingHelper.showMessageDialog(frame, "You did not enter the correct word. Nothing was deleted.", "Failure", null, JOptionPane.INFORMATION_MESSAGE);
}
}
});

frame.getChangePackLocationMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(false);

if (optional.isPresent()) {
Pack pack = optional.get();

JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose New Folder for Pack");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setFileFilter(new PackDirectoryFilter());

File dir = workspaceDir;

do {
chooser.setCurrentDirectory(dir);
int returnVal = chooser.showOpenDialog(frame);

if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = chooser.getSelectedFile();
} else {
return;
}
} while (!canAddPackDir(dir));

pack.setLocation(dir.getAbsolutePath());
updatePackInWorkspace(pack);
}
});

frame.getRefreshMenuItem().addActionListener(e -> loadWorkspace());

frame.getQuitMenuItem().addActionListener(e -> {
frame.dispose();
});

frame.getEditConfigMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
Pack pack = optional.get();
File file = pack.getConfigFile();
BuilderConfig config = Persistence.read(file, BuilderConfig.class);

if (BuilderConfigDialog.showEditor(frame, config)) {
writeBuilderConfig(pack, config);
updatePackInWorkspace(pack);
}
}
});

frame.getOpenFolderMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
SwingHelper.browseDir(optional.get().getDirectory(), frame);
}
});

frame.getCheckProblemsMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
ProblemChecker checker = new ProblemChecker(optional.get());
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(checker), executor)
.handleAsync(this::showProblems, (ex) -> {
}, SwingExecutor.INSTANCE);
SwingHelper.addErrorDialogCallback(frame, deferred);
}
});

frame.getTestMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
Pack pack = optional.get();
startTest(pack, false);
}
});

frame.getTestOnlineMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
Pack pack = optional.get();
startTest(pack, true);
}
});

frame.getOptionsMenuItem().addActionListener(e -> {
ConfigurationDialog configDialog = new ConfigurationDialog(frame, launcher);
configDialog.setVisible(true);
});

frame.getClearInstanceMenuItem().addActionListener(e -> {
DirectoryDeleter deleter = new DirectoryDeleter(launcher.getInstancesDir());
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(deleter), executor);
ProgressDialog.showProgress(frame, deferred, deleter, "Deleting test instances...", "Deleting test instances...");
SwingHelper.addErrorDialogCallback(frame, deferred);
});

frame.getClearWebRootMenuItem().addActionListener(e -> {
DirectoryDeleter deleter = new DirectoryDeleter(webRoot);
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(deleter), executor);
ProgressDialog.showProgress(frame, deferred, deleter, "Deleting web server files...", "Deleting web server files...");
SwingHelper.addErrorDialogCallback(frame, deferred);
});

frame.getBuildMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
Pack pack = optional.get();
buildPack(pack);
}
});

frame.getDeployServerMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
Pack pack = optional.get();
DeployOptions options = DeployServerDialog.showDeployDialog(frame, lastServerDestDir);

if (options != null) {
ConsoleFrame.showMessages();

File destDir = options.getDestDir();
destDir.mkdirs();
lastServerDestDir = destDir;

ServerDeploy deploy = new ServerDeploy(pack.getSourceDir(), options);
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(deploy), executor)
.handleAsync(r -> SwingHelper.showMessageDialog(frame, "Server deployment complete!", "Success", null, JOptionPane.INFORMATION_MESSAGE),
ex -> {
},
SwingExecutor.INSTANCE);
ProgressDialog.showProgress(frame, deferred, deploy, "Deploying files...", "Deploying server files...");
SwingHelper.addErrorDialogCallback(frame, deferred);
}
}
});

frame.getGeneratePackagesMenuItem().addActionListener(e -> {
List<ManifestEntry> entries = workspace.getPackageListingEntries();
ManifestInfoEnumerator enumerator = new ManifestInfoEnumerator(distDir);
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(() -> enumerator.apply(entries)))
.handleAsync(loaded -> {
GenerateListingDialog dialog = new GenerateListingDialog(frame);
GenerateListingController controller = new GenerateListingController(dialog, workspace, loaded, executor);
controller.setOutputDir(distDir);
controller.show();
}, ex -> {
}, SwingExecutor.INSTANCE);
ProgressDialog.showProgress(frame, deferred, new SettableProgress("Searching...", -1), "Searching for manifests...", "Searching for manifests...");
SwingHelper.addErrorDialogCallback(frame, deferred);
});

frame.getVersionCheckMenuItem().addActionListener(e -> {
Optional<Pack> optional = getSelectedPack(true);

if (optional.isPresent()) {
Pack pack = optional.get();

VersionCheckDialog dialog = new VersionCheckDialog(frame);
VersionCheckController controller = new VersionCheckController(dialog, executor);
controller.showUpdates(pack.getModsDir(), pack.getCachedConfig().getGameVersion(), frame);
}
});

frame.getOpenOutputFolderMenuItem().addActionListener(e -> SwingHelper.browseDir(distDir, frame));

frame.getOpenWorkspaceFolderMenuItem().addActionListener(e1 -> SwingHelper.browseDir(workspaceDir, frame));

frame.getOpenLauncherFolderMenuItem().addActionListener(e1 -> SwingHelper.browseDir(launcherDir, frame));

frame.getOpenWebRootMenuItem().addActionListener(e1 -> SwingHelper.browseDir(webRoot, frame));

frame.getOpenConsoleMenuItem().addActionListener(e -> {
ConsoleFrame.showMessages();
});

frame.getDocsMenuItem().addActionListener(e -> {
SwingHelper.openURL("https://github.com/SKCraft/Launcher/wiki", frame);
});

frame.getAboutMenuItem().addActionListener(e -> {
AboutDialog.showAboutDialog(frame);
});

SwingHelper.addActionListeners(frame.getNewPackButton(), frame.getNewPackMenuItem().getActionListeners());
SwingHelper.addActionListeners(frame.getImportButton(), frame.getImportPackMenuItem().getActionListeners());
SwingHelper.addActionListeners(frame.getEditConfigButton(), frame.getEditConfigMenuItem().getActionListeners());
SwingHelper.addActionListeners(frame.getOpenFolderButton(), frame.getOpenFolderMenuItem().getActionListeners());
SwingHelper.addActionListeners(frame.getCheckProblemsButton(), frame.getCheckProblemsMenuItem().getActionListeners());
SwingHelper.addActionListeners(frame.getTestButton(), frame.getTestMenuItem().getActionListeners());
SwingHelper.addActionListeners(frame.getBuildButton(), frame.getBuildMenuItem().getActionListeners());
}

private void popupPackMenu(Component component, int x, int y, Pack pack) {
JPopupMenu popup = new JPopupMenu();
JMenuItem menuItem;

menuItem = new JMenuItem("Edit modpack.json...");
menuItem.addActionListener(e -> frame.getEditConfigMenuItem().doClick());
popup.add(menuItem);

menuItem = new JMenuItem("Open Directory");
menuItem.addActionListener(e -> frame.getOpenFolderMenuItem().doClick());
popup.add(menuItem);

menuItem = new JMenuItem("Check for Problems");
menuItem.addActionListener(e -> frame.getCheckProblemsMenuItem().doClick());
popup.add(menuItem);

popup.addSeparator();

menuItem = new JMenuItem("Test");
menuItem.addActionListener(e -> frame.getTestMenuItem().doClick());
popup.add(menuItem);

menuItem = new JMenuItem("Test Online");
menuItem.addActionListener(e -> frame.getTestOnlineMenuItem().doClick());
popup.add(menuItem);

menuItem = new JMenuItem("Build...");
menuItem.addActionListener(e -> frame.getBuildMenuItem().doClick());
popup.add(menuItem);

menuItem = new JMenuItem("Deploy Server...");
menuItem.addActionListener(e -> frame.getDeployServerMenuItem().doClick());
popup.add(menuItem);

popup.addSeparator();

menuItem = new JMenuItem("Change Location...");
menuItem.addActionListener(e -> frame.getChangePackLocationMenuItem().doClick());
popup.add(menuItem);

menuItem = new JMenuItem("Remove...");
menuItem.addActionListener(e -> frame.getRemovePackItem().doClick());
popup.add(menuItem);

menuItem = new JMenuItem("Delete Forever...");
menuItem.addActionListener(e -> frame.getDeletePackItem().doClick());
popup.add(menuItem);

popup.show(component, x, y);
}

private void tryAddPackViaDialog() {
BuilderConfig config = new BuilderConfig();
addDefaultConfig(config);
Pack pack = new Pack();
File dir;

do {
if (BuilderConfigDialog.showEditor(frame, config)) {
dir = new File(workspaceDir, config.getName());
} else {
return;
}
} while (!canAddPackDir(dir));

pack.setLocation(dir.getAbsolutePath());

if (pack.getConfigFile().exists()) {
if (SwingHelper.confirmDialog(frame, "There's already an existing modpack with that name, though " +
"it is not imported into this workspace. Would you like to import it and ignore " +
"the new modpack that you just entered?", "Conflict")) {
addPackToWorkspace(pack);
}
} else {
if (writeBuilderConfig(pack, config)) {
pack.createGuideFolders();
addPackToWorkspace(pack);
}
}
}

private void tryAddPackViaDirectory(boolean createNew) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose Folder for Pack");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setFileFilter(new PackDirectoryFilter());

File dir = workspaceDir;

do {
chooser.setCurrentDirectory(dir);
int returnVal = chooser.showOpenDialog(frame);

if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = chooser.getSelectedFile();
} else {
return;
}
} while (!canAddPackDir(dir));

Pack pack = new Pack();
pack.setLocation(dir.getAbsolutePath());

if (pack.getConfigFile().exists()) {
if (createNew) {
if (SwingHelper.confirmDialog(frame, "There's already a modpack in that directory. Do you want to import it instead?", "Exists Already")) {
addPackToWorkspace(pack);
}
} else {
addPackToWorkspace(pack);
}
} else if (createNew || SwingHelper.confirmDialog(frame, "You've selected a directory that doesn't seem to be a modpack " +
"(at least with the directory structure this program expects). Would you like to create the files necessary to turn " +
"that folder into a modpack?", "Import Error")) {

BuilderConfig config = new BuilderConfig();
addDefaultConfig(config);

if (BuilderConfigDialog.showEditor(frame, config)) {
if (writeBuilderConfig(pack, config)) {
pack.createGuideFolders();
addPackToWorkspace(pack);
}
}
}
}

private void startTest(Pack pack, boolean online) {
Session session;

if (online) {
session = LoginDialog.showLoginRequest(frame, launcher);
if (session == null) {
return;
}
} else {
if (!isOfflineEnabled()) {
return;
}

session = new OfflineSession("Player");
}

String version = generateVersionFromDate();

PackBuilder builder = new PackBuilder(pack, webRoot, version, "staging.json", false);
InstanceList.Enumerator enumerator = launcher.getInstances().createEnumerator();
TestLauncher instanceLauncher = new TestLauncher(launcher, frame, pack.getCachedConfig().getName(), session);

SettableProgress progress = new SettableProgress(builder);

ConsoleFrame.showMessages();

Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(builder), executor)
.thenTap(() -> progress.set("Loading instance in test launcher...", -1))
.thenRun(enumerator)
.thenTap(() -> progress.set("Launching", -1))
.thenApply(instanceLauncher)
.handleAsync(result -> ConsoleFrame.hideMessages(), ex -> {}, SwingExecutor.INSTANCE);

ProgressDialog.showProgress(frame, deferred, progress, "Setting up test instance...", "Preparing files for launch...");
SwingHelper.addErrorDialogCallback(frame, deferred);
}

private void buildPack(Pack pack) {
String initialVersion = generateVersionFromDate();
BuildOptions options = BuildDialog.showBuildDialog(frame, initialVersion, generateManifestName(pack), distDir);

if (options != null) {
ConsoleFrame.showMessages();
PackBuilder builder = new PackBuilder(pack, options.getDestDir(), options.getVersion(), options.getManifestFilename(), false);
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(builder), executor)
.handleAsync(result -> {
ConsoleFrame.hideMessages();
SwingHelper.showMessageDialog(frame, "Successfully generated the package files.", "Success", null, JOptionPane.INFORMATION_MESSAGE);
}, ex -> {}, SwingExecutor.INSTANCE);
ProgressDialog.showProgress(frame, deferred, builder, "Building modpack...", "Building modpack...");
SwingHelper.addErrorDialogCallback(frame, deferred);
}
}

private void showProblems(List<Problem> problems) {
if (problems.isEmpty()) {
SwingHelper.showMessageDialog(frame, "No potential problems found!", "Success", null, JOptionPane.INFORMATION_MESSAGE);
} else {
ProblemViewer viewer = new ProblemViewer(frame, problems);
viewer.setVisible(true);
}
}

public String generateManifestName(Pack pack) {
File file = pack.getConfigFile();
if (file.exists()) {
BuilderConfig config = Persistence.read(file, BuilderConfig.class, true);
if (config != null) {
String name = Strings.nullToEmpty(config.getName());
name = name.toLowerCase();
name = FILENAME_SANITIZE.matcher(name).replaceAll("-");
name = name.trim();
if (!name.isEmpty()) {
return name + ".json";
}
}
}

return "my_modpack.json";
}

public static String generateVersionFromDate() {
Date today = Calendar.getInstance().getTime();
return VERSION_DATE_FORMAT.format(today);
}

}

+ 171
- 0
creator-tools/src/main/java/com/skcraft/launcher/creator/controller/VersionCheckController.java View File

@@ -0,0 +1,171 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010-2014 Albert Pham <http://www.sk89q.com> and contributors
* Please see LICENSE.txt for license information.
*/

package com.skcraft.launcher.creator.controller;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.skcraft.concurrency.Deferred;
import com.skcraft.concurrency.Deferreds;
import com.skcraft.concurrency.SettableProgress;
import com.skcraft.launcher.creator.controller.task.DirectoryWalker;
import com.skcraft.launcher.creator.dialog.VersionCheckDialog;
import com.skcraft.launcher.creator.model.creator.ModFile;
import com.skcraft.launcher.creator.model.swing.ModFileTableModel;
import com.skcraft.launcher.creator.util.ModInfoReader;
import com.skcraft.launcher.creator.util.ModInfoReader.ModInfo;
import com.skcraft.launcher.creator.util.NemModList;
import com.skcraft.launcher.creator.util.NemModList.ModEntry;
import com.skcraft.launcher.dialog.ProgressDialog;
import com.skcraft.launcher.swing.SwingHelper;
import com.skcraft.launcher.util.SwingExecutor;

import javax.annotation.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class VersionCheckController {

private final VersionCheckDialog dialog;
private final ListeningExecutorService executor;

public VersionCheckController(VersionCheckDialog dialog, ListeningExecutorService executor) {
this.dialog = dialog;
this.executor = executor;
}

public void showUpdates(File dir, String gameVersion, Window parentWindow) {
initListeners();

DirectoryWalker walker = new DirectoryWalker(dir);
walker.setRecursive(false);
walker.setFileFilter(pathname -> pathname.getName().endsWith(".jar"));

ModInfoReader binaryInspector = new ModInfoReader();
NemModList nemModList = new NemModList();

SettableProgress progress = new SettableProgress("Retrieving mod information...", -1);

Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(walker), executor)
.thenTap(() -> progress.set("Querying NotEnoughMods for version data...", -1))
.thenTap(() -> {
try {
nemModList.load(gameVersion);
} catch (IOException | InterruptedException e) {
throw new RuntimeException("Failed to retrieve mod information from NotEnoughMods. Perhaps NEM doesn't support your pack's MC version.", e);
}
})
.thenTap(() -> progress.set("Scanning mod files for manifests...", -1))
.thenApply(files -> {
List<ModFile> mods = Lists.newArrayList();

for (File file : files) {
ModFile mod = new ModFile();
mod.setGameVersion(gameVersion);
mod.setFile(file);

List<? extends ModInfo> infoList = binaryInspector.detectMods(file);
if (!infoList.isEmpty()) {
ModInfo info = infoList.get(0);
mod.setModId(info.getModId());
mod.setName(info.getName());
mod.setVersion(info.getVersion());

if (info.getUrl() != null) {
mod.setUrl(getFirstUrl(info.getUrl(), "http://" + info.getUrl()));
}
}

if (mod.getModId() != null) {
ModEntry entry = nemModList.get(mod.getModId());

if (entry != null) {
mod.setLatestVersion(entry.getLatestVersion());
mod.setLatestDevVersion(entry.getLatestDevVersion());
if (entry.getUrl() != null) {
mod.setUrl(entry.getUrl());
}
}
}

mods.add(mod);
}

return mods;
})
.handleAsync(mods -> {
List<ModFile> known = Lists.newArrayList();
List<ModFile> unknown = Lists.newArrayList();

for (ModFile mod : mods) {
if (mod.getVersion() != null && mod.getLatestVersion() != null) {
if (!mod.getCleanVersion().equals(mod.getLatestVersion()) && !mod.getCleanVersion().equals(mod.getLatestDevVersion())) {
known.add(mod);
}
} else {
unknown.add(mod);
}
}

dialog.getKnownModsTable().setModel(new ModFileTableModel(known));
dialog.getUnknownModsTable().setModel(new ModFileTableModel(unknown));
dialog.getKnownModsTable().getRowSorter().toggleSortOrder(1);
dialog.getUnknownModsTable().getRowSorter().toggleSortOrder(1);
dialog.setVisible(true);
}, ex -> {
}, SwingExecutor.INSTANCE);

ProgressDialog.showProgress(parentWindow, deferred, progress, "Checking for mod updates...", "Checking for mod updates...");
SwingHelper.addErrorDialogCallback(parentWindow, deferred);
}

private void initListeners() {
dialog.getCloseButton().addActionListener(e -> dialog.dispose());

ModTableMouseListener mouseListener = new ModTableMouseListener();
dialog.getKnownModsTable().addMouseListener(mouseListener);
dialog.getUnknownModsTable().addMouseListener(mouseListener);
}

@Nullable
private static URL getFirstUrl(String... options) {
for (String option : options) {
try {
return new URL(option);
} catch (MalformedURLException ignored) {
}
}

return null;
}

private class ModTableMouseListener extends MouseAdapter {

public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
JTable table = (JTable) e.getSource();
Point point = e.getPoint();
int selectedIndex = table.rowAtPoint(point);
if (selectedIndex >= 0) {
selectedIndex = table.convertRowIndexToModel(selectedIndex);
ModFile mod = ((ModFileTableModel) table.getModel()).getMod(selectedIndex);
if (mod != null && mod.getUrl() != null) {
SwingHelper.openURL(mod.getUrl(), dialog);
}
}
}
}

}

}

+ 212
- 0
creator-tools/src/main/java/com/skcraft/launcher/creator/controller/WelcomeController.java View File

@@ -0,0 +1,212 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010-2014 Albert Pham <http://www.sk89q.com> and contributors
* Please see LICENSE.txt for license information.
*/

package com.skcraft.launcher.creator.controller;

import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.skcraft.concurrency.Deferred;
import com.skcraft.concurrency.Deferreds;
import com.skcraft.concurrency.SettableProgress;
import com.skcraft.launcher.creator.Creator;
import com.skcraft.launcher.creator.dialog.AboutDialog;
import com.skcraft.launcher.creator.dialog.PackManagerFrame;
import com.skcraft.launcher.creator.dialog.WelcomeDialog;
import com.skcraft.launcher.creator.model.creator.RecentEntry;
import com.skcraft.launcher.creator.model.creator.Workspace;
import com.skcraft.launcher.creator.model.swing.RecentListModel;
import com.skcraft.launcher.creator.swing.WorkspaceDirectoryFilter;
import com.skcraft.launcher.dialog.ProgressDialog;
import com.skcraft.launcher.persistence.Persistence;
import com.skcraft.launcher.swing.PopupMouseAdapter;
import com.skcraft.launcher.swing.SwingHelper;
import com.skcraft.launcher.util.MorePaths;
import com.skcraft.launcher.util.SwingExecutor;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class WelcomeController {

private final WelcomeDialog dialog;
private final Creator creator;
private final RecentListModel recentListModel;

public WelcomeController(WelcomeDialog dialog, Creator creator) {
this.dialog = dialog;
this.creator = creator;

initListeners();

recentListModel = new RecentListModel(creator.getConfig().getRecentEntries());
dialog.getRecentList().setModel(recentListModel);
}

public void show() {
dialog.setVisible(true);
}

private boolean openWorkspace(File dir) {
ListeningExecutorService executor = creator.getExecutor();
PackManagerFrame frame = new PackManagerFrame();
Deferred<?> deferred = Deferreds.makeDeferred(executor.submit(() -> {
PackManagerController controller = new PackManagerController(frame, dir, creator);
addRecentEntry(dir);
return controller;
}), executor)
.handleAsync(PackManagerController::show, ex -> {}, SwingExecutor.INSTANCE);
ProgressDialog.showProgress(frame, deferred, new SettableProgress("Loading...", -1), "Loading workspace...", "Loading workspace...");
SwingHelper.addErrorDialogCallback(frame, deferred);

return true;
}

private void addRecentEntry(File dir) {
List<RecentEntry> newEntries = creator.getConfig().getRecentEntries()
.stream()
.filter(entry -> {
try {
return !MorePaths.isSamePath(entry.getPath(), dir);
} catch (IOException ignored) {
return false;
}
})
.collect(Collectors.toCollection(Lists::newArrayList));

RecentEntry recent = new RecentEntry();
recent.setPath(dir);
newEntries.add(0, recent);

creator.getConfig().setRecentEntries(newEntries);

Persistence.commitAndForget(creator.getConfig());

recentListModel.fireUpdate();
}

private void removeRecentEntry(RecentEntry entry) {
creator.getConfig().getRecentEntries().remove(entry);
Persistence.commitAndForget(creator.getConfig());

recentListModel.fireUpdate();
}

private Optional<RecentEntry> getSelectedRecentEntry() {
int selectedIndex = dialog.getRecentList().getSelectedIndex();
if (selectedIndex >= 0) {
return Optional.fromNullable(creator.getConfig().getRecentEntries().get(selectedIndex));
} else {
return Optional.absent();