CVE-2022-4494 (Java, published 2022-12-14T12:15Z)
Description: value: A vulnerability, which was classified as critical, has been found in bspkrs MCPMappingViewer. Affected by this issue is the function extractZip of the file src/main/java/bspkrs/mmv/RemoteZipHandler.java of the component ZIP File Handler. The manipulation leads to path traversal. The attack may be launched remotely. The name of the patch is 6e602746c96b4756c271d080dae7d22ad804a1bd. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-215804.
Severity: nan (CVSS v3 base score: 9.8)
Weakness: CWE-22 \u2014 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
Repository: https://github.com/bspkrs/MCPMappingViewer
Files changed:
.gitignore
BON_LICENSE.txt
GSON_LICENSE.txt
LICENSE
README.md
build.gradle
change.log
gradle/wrapper/gradle-wrapper.properties
gradlew
gradlew.bat
src/main/java/bspkrs/mmv/ClassSrgData.java
src/main/java/bspkrs/mmv/CsvData.java
src/main/java/bspkrs/mmv/CsvFile.java
src/main/java/bspkrs/mmv/ExcData.java
src/main/java/bspkrs/mmv/ExcFile.java
src/main/java/bspkrs/mmv/FieldSrgData.java
src/main/java/bspkrs/mmv/McpBotCommand.java
src/main/java/bspkrs/mmv/McpMappingLoader.java
src/main/java/bspkrs/mmv/MemberSrgData.java
src/main/java/bspkrs/mmv/MethodSrgData.java
src/main/java/bspkrs/mmv/ParamCsvData.java
src/main/java/bspkrs/mmv/ParamCsvFile.java
src/main/java/bspkrs/mmv/RemoteZipHandler.java
src/main/java/bspkrs/mmv/SplittedNaturalComparator.java
src/main/java/bspkrs/mmv/SrgFile.java
src/main/java/bspkrs/mmv/StaticMethodsFile.java
src/main/java/bspkrs/mmv/TSrgFile.java
src/main/java/bspkrs/mmv/VersionFetcher.java
src/main/java/bspkrs/mmv/gui/BrowseActionListener.java
src/main/java/bspkrs/mmv/gui/MappingGui.java
src/main/java/bspkrs/mmv/gui/TableColumnAdjuster.java
src/main/java/bspkrs/mmv/version/AppVersionChecker.java
src/main/java/bspkrs/mmv/version/NaturalOrderComparator.java
src/main/java/immibis/bon/IProgressListener.java
src/main/java/immibis/bon/NameSet.java
src/main/java/immibis/bon/gui/Reference.java
src/main/java/immibis/bon/gui/Side.java
Commit message: vuln-fix: Zip Slip Vulnerability

This fixes a Zip-Slip vulnerability.

This change does one of two things. This change either

1. Inserts a guard to protect against Zip Slip.
OR
2. Replaces `dir.getCanonicalPath().startsWith(parent.getCanonicalPath())`, which is vulnerable to partial path traversal attacks, with the more secure `dir.getCanonicalFile().toPath().startsWith(parent.getCanonicalFile().toPath())`.

For number 2, consider `"/usr/outnot".startsWith("/usr/out")`.
The check is bypassed although `/outnot` is not under the `/out` directory.
It's important to understand that the terminating slash may be removed when using various `String` representations of the `File` object.
For example, on Linux, `println(new File("/var"))` will print `/var`, but `println(new File("/var", "/")` will print `/var/`;
however, `println(new File("/var", "/").getCanonicalPath())` will print `/var`.

Weakness: CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Severity: High
CVSSS: 7.4
Detection: CodeQL (https://codeql.github.com/codeql-query-help/java/java-zipslip/) & OpenRewrite (https://public.moderne.io/recipes/org.openrewrite.java.security.ZipSlip)

Reported-by: Jonathan Leitschuh <Jonathan.Leitschuh@gmail.com>
Signed-off-by: Jonathan Leitschuh <Jonathan.Leitschuh@gmail.com>

Bug-tracker: https://github.com/JLLeitschuh/security-research/issues/16

Co-authored-by: Moderne <team@moderne.io>

Vulnerable code:

Fixed code:
# package
*.jar

# eclipse
.classpath
.project
.metadata/
.settings/
.recommenders/
bin/

# (no) idea
.idea
*.iml
*.ipr
*.iws
out/

# gradle
/.gradle/
/build/
!/gradle/wrapper/gradle-wrapper.jar

dist
Copyright (C) 2013 Alex "immibis" Campbell

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   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.
Copyright (C) 2014 bspkrs
Portions Copyright (C) 2014 Alex "immibis" Campbell

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*** This project is no longer maintained ***

MCP Mapping Viewer
=================
A small GUI for viewing the mappings from Minecraft obfuscated code names to MCP code names.

### Links of Interest
 - [Official Minecraft Forum Thread](http://www.minecraftforum.net/topic/2115030-)
 - [Binary Downloads](http://bspk.rs/MC/MCPMappingViewer/index.html)
 - [Issue Tracking System](https://github.com/bspkrs/MCPMappingViewer/issues)
 
* * *

#### How to build from the source code ####

Run `gradlew build` from your favorite command line facilities

* * *

Copyright (C) 2013-2022 bspkrs<br/>
Portions Copyright (C) 2013 Alex "immibis" Campbell (see BON_LICENSE.txt for details)
GSON is licensed under the Apache License 2.0 (see GSON_LICENSE.txt for details)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
plugins {
    id 'java'
    id 'java-library'
    id 'eclipse'
    id 'idea'
    id 'com.github.johnrengelman.shadow' version '7.0.0'
    id 'edu.sc.seis.launch4j' version '2.5.0'
}

version = '1.0.3'
ext.mainClassName = "bspkrs.mmv.gui.MappingGui"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(8)
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.google.code.gson:gson:2.8.6'
}

[compileJava, compileTestJava].each { cJava ->
    cJava.options.compilerArgs += ['-Xlint:unchecked']
    cJava.options.encoding = 'UTF-8'
    cJava.options.incremental = true
    cJava.options.fork = true
}

processResources {
    from 'LICENSE'
}

build.dependsOn(shadowJar)

jar {
    destinationDirectory = temporaryDir
}

shadowJar {
    archiveClassifier.set('')
}

wrapper {
    distributionType = Wrapper.DistributionType.ALL
}

jar.manifest {
    attributes 'Main-Class': mainClassName
}

createExe {
    dependsOn 'build'
    mainClassName = mainClassName
    copyConfigurable = project.tasks.shadowJar.outputs.files
    jar = "lib/${project.tasks.shadowJar.archiveFileName}"
    outputDir = 'libs'
    outfile = tasks.shadowJar.archiveName - '.jar' + '.exe'
    productName = 'MCP Mapping Viewer'
    icon = "${projectDir}/MCPMappingViewer.ico"
    supportUrl = 'https://www.minecraftforum.net/topic/2115030'
    copyright = 'Copyright 2013-2021 bspkrs, portions Copyright 2013-2014 Alex "Immibis" Campbell'
    version = "${project.version}"
}

task run(type: JavaExec) {
  classpath = sourceSets.main.runtimeClasspath

  main = mainClassName
}
0.7.3 - 30-Jun-2014
- fixed version checker derping due to dropbox server changes
0.7.2 - 18-Apr-2014
- fixed derp where column sort settings were reset on search
0.7.1 - 12-Apr-2014
- fixed compabibility with latest Forge releases
0.7.0 - 01-Apr-2014
- fixed a potential issue with not adding the header row when exporting CSV files
- added support for viewing and editing params.csv :D
0.6.1 - 24-Feb-2014
- added code to make SRG name searches actually highlight the item they are meant to find
0.6.0 - 22-Jan-2014
- saving of edits back to CSVs is now possible! careful if you are editing Forge CSVs!
- when using side Universal (Forge), edits will produce multiple bot commands unless the item is client only
- better handling of button states based on edits
0.5.3 - 05-Dec-2013
- added application icon and About image
- cleaned up some messy code
- filter is now clear on load
0.5.2 - 03-Dec-2013
- added search history
0.5.1 - 26-Nov-2013
- fixed derp in method to get the bot command
0.5.0 - 25-Nov-2013
- added basic support for generating MCPBot commands to execute in a DCC session with the bot
0.2.2 - 14-Nov-2013
- proper fixed CsvFile parser defect
0.2.1 - 14-Nov-2013
- fixed major logic flaw in CsvFile parser
0.2.0 - 14-Nov-2013
- many UI improvements and tweaks
- column sort is now remembered
- added global search functionality
- added option to force reload from mcp/conf files vs cached data
- added version notifications (non-naggy, you'll only be notified once per new version)
- improved exception handling
0.1.0a - 12-Nov-2013
- initial release!
- acts as an obfuscation map viewer
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/usr/bin/env sh

#
# Copyright 2015 the original author or authors.
#
# 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
#
#      https://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.
#

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
    echo "$*"
}

die () {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
  NONSTOP* )
    nonstop=true
    ;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar


# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`

    JAVACMD=`cygpath --unix "$JAVACMD"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=`expr $i + 1`
    done
    case $i in
        0) set -- ;;
        1) set -- "$args0" ;;
        2) set -- "$args0" "$args1" ;;
        3) set -- "$args0" "$args1" "$args2" ;;
        4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Escape application args
save () {
    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
    echo " "
}
APP_ARGS=`save "$@"`

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"

exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem      https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem

@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar


@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega
/*
 * Copyright (C) 2014 bspkrs
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

public class ClassSrgData implements Comparable<ClassSrgData>
{
    public static enum SortType
    {
        PKG,
        OBF
    }

    private final String   obfName;
    private final String   srgName;
    private String         srgPkgName;
    private final boolean  isClientOnly;

    public static SortType sortType = SortType.PKG;

    public ClassSrgData(String obfName, String srgName, String srgPkgName, boolean isClientOnly)
    {
        this.obfName = obfName;
        this.srgName = srgName;
        this.srgPkgName = srgPkgName;
        this.isClientOnly = isClientOnly;
    }

    public String getObfName()
    {
        return this.obfName;
    }

    public String getSrgName()
    {
        return this.srgName;
    }

    public String getSrgPkgName()
    {
        return this.srgPkgName;
    }

    public ClassSrgData setSrgPkgName(String pkg)
    {
        this.srgPkgName = pkg;
        return this;
    }

    public boolean isClientOnly()
    {
        return isClientOnly;
    }

    public String getFullyQualifiedSrgName()
    {
        return srgPkgName + "/" + srgName;
    }

    @Override
    public int compareTo(ClassSrgData o)
    {
        if (sortType == SortType.PKG)
            if (o != null)
                return getFullyQualifiedSrgName().compareTo(o.getFullyQualifiedSrgName());
            else
                return 1;
        else if (o != null)
            if (obfName.length() != o.obfName.length())
                return obfName.length() - o.obfName.length();
            else
                return obfName.compareTo(o.obfName);
        else
            return 1;

    }

    public boolean contains(String s)
    {
        return srgName.contains(s) || obfName.contains(s) || this.srgPkgName.contains(s);
    }
}
/*
 * Copyright (C) 2014 bspkrs
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

public class CsvData implements Comparable<CsvData>
{
    private final String srgName;
    private String       mcpName;
    private final int    side;
    private String       comment;
    private boolean      needsQuoted;

    public CsvData(String srgName, String mcpName, int side, String comment)
    {
        this.srgName = srgName;
        this.mcpName = mcpName;
        this.side = side;

        if (comment.contains(",") || (!comment.isEmpty() && comment.charAt(0) == '"' && comment.charAt(comment.length() - 1) == '"'))
        {
            needsQuoted = true;
            if (comment.charAt(0) == '"' && comment.charAt(comment.length() - 1) == '"')
                this.comment = comment.substring(1, comment.length() - 1);
            else
                this.comment = comment;
        }
        else
        {
            this.comment = comment;
            needsQuoted = false;
        }
    }

    public String toCsv()
    {
        return srgName + "," + mcpName + "," + side + "," + (needsQuoted ? "\"" + comment + "\"" : comment);
    }

    public String getSrgName()
    {
        return srgName;
    }

    public String getMcpName()
    {
        return mcpName;
    }

    public CsvData setMcpName(String mcpName)
    {
        this.mcpName = mcpName;
        return this;
    }

    public int getSide()
    {
        return side;
    }

    public String getComment()
    {
        return comment;
    }

    public CsvData setComment(String comment)
    {
        this.comment = comment;
        return this;
    }

    @Override
    public int compareTo(CsvData o)
    {
        if (o != null)
            return this.srgName.compareTo(o.srgName);

        return 1;
    }

    public boolean contains(String s)
    {
        return this.mcpName.contains(s) || this.comment.contains(s);
    }
}
/*
 * Copyright (C) 2014 bspkrs
 * Portions Copyright (C) 2014 Alex "immibis" Campbell
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class CsvFile
{
    private final File                 file;
    private final Map<String, CsvData> srgMemberName2CsvData;
    private boolean                    isDirty;
    private String                     headerLine;

    public CsvFile(File file) throws IOException
    {
        this.file = file;
        srgMemberName2CsvData = new TreeMap<String, CsvData>();
        readFromFile();
        isDirty = false;
    }

    public void readFromFile() throws IOException
    {
        Scanner in = new Scanner(new BufferedReader(new FileReader(file)));
        try
        {
            in.useDelimiter(",");
            headerLine = in.nextLine(); // Skip header row
            while (in.hasNextLine())
            {
                String srgName = in.next();
                String mcpName = in.next();
                String side = in.next();
                String comment = in.nextLine().substring(1);
                srgMemberName2CsvData.put(srgName, new CsvData(srgName, mcpName, Integer.valueOf(side), comment));
            }
        }
        finally
        {
            in.close();
        }
    }

    public void writeToFile() throws IOException
    {
        if (isDirty)
        {
            if (file.exists())
            {
                File fileBak = new File(file.getAbsolutePath() + "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".bak");
                file.renameTo(fileBak);
            }

            file.createNewFile();

            PrintWriter out = new PrintWriter(new FileWriter(file));
            out.println(headerLine);

            for (CsvData data : srgMemberName2CsvData.values())
                out.println(data.toCsv());

            out.close();

            isDirty = false;
        }
    }

    public boolean hasCsvDataForKey(String srgName)
    {
        return srgMemberName2CsvData.containsKey(srgName);
    }

    public CsvData getCsvDataForKey(String srgName)
    {
        return srgMemberName2CsvData.get(srgName);
    }

    public void updateCsvDataForKey(String srgName, CsvData csvData)
    {
        srgMemberName2CsvData.put(srgName, csvData);
        isDirty = true;
    }

    public boolean isDirty()
    {
        return isDirty;
    }

    public void setIsDirty(boolean bol)
    {
        isDirty = bol;
    }
}
/*
 * Copyright (C) 2014 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExcData implements Comparable<ExcData>
{
    private final String   srgOwner;
    private final String   srgName;
    private final String   descriptor;
    private final String[] exceptions;
    private final String[] parameters;
    private final String[] paramTypes;

    public ExcData(String srgOwner, String srgName, String descriptor, String[] exceptions, String[] parameters)
    {
        this.srgOwner = srgOwner;
        this.srgName = srgName;
        this.descriptor = descriptor;
        this.exceptions = exceptions;
        paramTypes = splitMethodDesc(descriptor);
        this.parameters = parameters;
    }

    public ExcData(String srgOwner, String srgName, String descriptor, String[] exceptions, boolean isStatic)
    {
        this.srgOwner = srgOwner;
        this.srgName = srgName;
        this.descriptor = descriptor;
        this.exceptions = exceptions;
        paramTypes = splitMethodDesc(descriptor);
        parameters = genParamNames(ExcData.getSrgId(srgName), paramTypes, isStatic);
    }

    public String getSrgClassOwner()
    {
        return srgOwner;
    }

    public String getSrgMethodName()
    {
        return srgName;
    }

    public String getDescriptor()
    {
        return descriptor;
    }

    public String[] getExceptions()
    {
        return exceptions;
    }

    public String[] getParameters()
    {
        return parameters;
    }

    public String[] getParamTypes()
    {
        return paramTypes;
    }

    public boolean contains(String s)
    {
        if (srgName.contains(s))
            return true;
        else
            for (String param : parameters)
                if (param.contains(s))
                    return true;

        return false;
    }

    @Override
    public int compareTo(ExcData o)
    {
        return srgName.compareTo(o.srgName);
    }

    public static String[] splitMethodDesc(String desc)
    {
        //\[*(?:L[^;]+;|[ZBCSIFDJ])
        int beginIndex = desc.indexOf('(');
        int endIndex = desc.lastIndexOf(')');
        if (((beginIndex == -1) && (endIndex != -1)) || ((beginIndex != -1) && (endIndex == -1)))
        {
            System.err.println(beginIndex);
            System.err.println(endIndex);
            throw new RuntimeException();
        }
        String x0;
        if ((beginIndex == -1) && (endIndex == -1))
        {
            x0 = desc;
        }
        else
        {
            x0 = desc.substring(beginIndex + 1, endIndex);
        }
        Pattern pattern = Pattern.compile("\\[*(?:L[^;]+;|[ZBCSIFDJ])");
        Matcher matcher = pattern.matcher(x0);

        ArrayList<String> listMatches = new ArrayList<String>();

        while (matcher.find())
        {
            listMatches.add(matcher.group());
        }

        return listMatches.toArray(new String[listMatches.size()]);
    }

    public static String[] genParamNames(String srgId, String[] paramTypes, boolean isStatic)
    {
        boolean skip2 = (paramTypes.length >= 4) && paramTypes[0].equals("Ljava/lang/String;") && paramTypes[1].equals('I')
                && paramTypes[0].equals(paramTypes[2]) && paramTypes[1].equals(paramTypes[3]);

        String[] ret = new String[paramTypes.length];
        int idOffset = isStatic ? 0 : 1;
        if (skip2)
            idOffset += 2;

        for (int i = 0; i < paramTypes.length; i++)
        {
            ret[i] = "p_" + srgId + "_" + (i + idOffset) + "_";
            if (paramTypes[i].equals("D") || paramTypes[i].equals("J"))
                idOffset++;
        }

        return ret;
    }

    public static String getSrgId(String srgName)
    {
        Pattern pattern = Pattern.compile("func_(i?[0-9]+)_");
        Matcher matcher = pattern.matcher(srgName);
        if (matcher.find())
            return matcher.group(1);
        return srgName;
    }

    @Override
    public String toString()
    {
        return String.format("  Owner: %s\n  SRG Name: %s\n  Descriptor: %s\n  Exceptions: %s\n  Parameters: %s\n  Param Types: %s", srgOwner, srgName, descriptor, Arrays.toString(exceptions), Arrays.toString(parameters), Arrays.toString(paramTypes));
    }
}
/*
 * Copyright (C) 2014 bspkrs
 * Portions Copyright (C) 2014 Alex "immibis" Campbell
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class ExcFile
{
    public final Map<String, ExcData> srgMethodName2ExcData;
    public final Map<String, ExcData> srgParamName2ExcData;

    public ExcFile(File f) throws IOException
    {
        srgMethodName2ExcData = new HashMap<String, ExcData>();
        srgParamName2ExcData = new HashMap<String, ExcData>();
        // example lines:
        // net/minecraft/util/ChunkCoordinates=CL_00001555
        // net/minecraft/world/chunk/storage/AnvilChunkLoader.func_75816_a(Lnet/minecraft/world/World;Lnet/minecraft/world/chunk/Chunk;)V=net/minecraft/world/MinecraftException,java/io/IOException|p_75816_1_,p_75816_2_
        // net/minecraft/world/biome/BiomeGenMutated.func_150571_c(III)I=|p_150571_1_,p_150571_2_,p_150571_3_
        // net/minecraft/world/chunk/storage/AnvilChunkLoader.func_75818_b()V=|
        // net/minecraft/server/MinecraftServer.func_145747_a(Lnet/minecraft/util/IChatComponent;)V=|p_145747_1_

        Scanner in = new Scanner(new FileReader(f));
        try
        {
            while (in.hasNextLine())
            {
                if (in.hasNext("#"))
                {
                    in.nextLine();
                    continue;
                }

                in.useDelimiter("\\.");
                String srgOwner = in.next();
                in.useDelimiter("\\(");

                if (!in.hasNext())
                    if (in.hasNextLine())
                        in.nextLine();
                    else
                        break;

                String srgName = in.next().substring(1);
                in.useDelimiter("=");
                String descriptor = in.next();
                in.useDelimiter("\\|");
                String excs = in.next().substring(1);
                String params = in.nextLine().substring(1);

                ExcData toAdd = new ExcData(srgOwner, srgName, descriptor,
                        (excs.length() > 0 ? excs.split(",") : new String[0]),
                        (params.length() > 0 ? params.split(",") : new String[0]));

                ExcData existing = srgMethodName2ExcData.get(srgName);

                if ((existing == null) || (existing.getParameters().length < toAdd.getParameters().length))
                {
                    srgMethodName2ExcData.put(srgName, toAdd);

                    for (String parameter : toAdd.getParameters())
                        srgParamName2ExcData.put(parameter, toAdd);
                }
            }
        }
        finally
        {
            in.close();
        }
    }
}
/*
 * Copyright (C) 2014 bspkrs
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

public class FieldSrgData extends MemberSrgData implements Comparable<FieldSrgData>
{
    public FieldSrgData(String obfOwner, String obfName, String srgOwner, String srgPkg, String srgName, boolean isClientOnly)
    {
        super(obfOwner, obfName, srgOwner, srgPkg, srgName, isClientOnly);
    }

    @Override
    public int compareTo(FieldSrgData o)
    {
        if (o != null)
            return this.getSrgName().compareTo(o.getSrgName());
        else
            return 1;
    }
}
package bspkrs.mmv;

public class McpBotCommand
{
    public enum BotCommand
    {
        SF,
        SM,
        SP,
        FSF,
        FSM,
        FSP;
    }

    public enum MemberType
    {
        FIELD,
        METHOD,
        PARAM;
    }

    public static BotCommand getCommand(MemberType type, boolean isForced)
    {
        switch (type)
        {
            case METHOD:
                return isForced ? BotCommand.FSM : BotCommand.SM;
            case PARAM:
                return isForced ? BotCommand.FSP : BotCommand.SP;
            default:
                return isForced ? BotCommand.FSF : BotCommand.SF;
        }
    }

    private final BotCommand command;
    private final String     srgName;
    private final String     newName;
    private final String     comment;

    public McpBotCommand(BotCommand command, String srgName, String newName, String comment)
    {
        this.command = command;
        this.srgName = srgName;
        this.newName = newName;
        this.comment = comment;
    }

    public McpBotCommand(BotCommand command, String srgName, String newName)
    {
        this(command, srgName, newName, "");
    }

    public static McpBotCommand getMcpBotCommand(MemberType type, boolean isForced, String srgName, String newName, String comment)
    {
        return new McpBotCommand(getCommand(type, isForced), srgName, newName, comment);
    }

    public BotCommand getCommand()
    {
        return command;
    }

    public String getNewName()
    {
        return newName;
    }

    @Override
    public String toString()
    {
        return String.format("!%s %s %s %s", command.toString().toLowerCase(), srgName, newName, comment);
    }
}
/*
 * Copyright (C) 2015 bspkrs
 * Portions Copyright (C) 2014 Alex "immibis" Campbell
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import immibis.bon.IProgressListener;

import java.io.File;
import java.io.IOException;
import java.security.DigestException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import bspkrs.mmv.McpBotCommand.MemberType;
import bspkrs.mmv.gui.MappingGui;

public class McpMappingLoader
{

    public static class CantLoadMCPMappingException extends Exception
    {
        private static final long serialVersionUID = 1;

        public CantLoadMCPMappingException(String reason)
        {
            super(reason);
        }
    }

    private final File                                   baseDir                 = new File(new File(System.getProperty("user.home")), ".cache/MCPMappingViewer");
    private final String                                 baseSrgDir              = "{mc_ver}";
    private final String                                 baseMappingDir          = "{mc_ver}/{channel}_{map_ver}";
    private final String                                 baseMappingUrl          = "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_{channel}/{map_ver}-{mc_ver}/mcp_{channel}-{map_ver}-{mc_ver}.zip";
    private final String                                 newBaseSrgUrl           = "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_config/{mc_ver}/mcp_config-{mc_ver}.zip";
    private final String                                 oldBaseSrgUrl           = "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp/{mc_ver}/mcp-{mc_ver}-srg.zip";

    private final File                                   srgDir;
    private final File                                   mappingDir;
    private final File                                   srgFile;
    private final File                                   excFile;
    private final File                                   staticMethodsFile;
    private SrgFile                                      srgFileData;
    private ExcFile                                      excFileData;
    private StaticMethodsFile                            staticMethods;
    private CsvFile                                      csvFieldData, csvMethodData;
    private ParamCsvFile                                 csvParamData;
    private final MappingGui                             parentGui;
    private final Map<String, McpBotCommand>             commandMap              = new TreeMap<String, McpBotCommand>();                                                                // srgName -> McpBotCommand
    public final Map<MethodSrgData, CsvData>             srgMethodData2CsvData   = new TreeMap<MethodSrgData, CsvData>();
    public final Map<FieldSrgData, CsvData>              srgFieldData2CsvData    = new TreeMap<FieldSrgData, CsvData>();
    public final Map<ExcData, Map<String, ParamCsvData>> excData2MapParamCsvData = new TreeMap<ExcData, Map<String, ParamCsvData>>();

    public McpMappingLoader(MappingGui parentGui, String mappingString, IProgressListener progress) throws IOException, CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException
    {
        progress.setMax(6);
        progress.set(0);
        this.parentGui = parentGui;

        // mappingString: <mc>_<channel>_<ver>, eg, 1.8_snapshot_20151118
        String[] tokens = mappingString.split("_");
        if (tokens.length < 3)
            throw new CantLoadMCPMappingException("Invalid mapping string specified.");

        boolean isNew = tokens[0].compareTo("1.13") >= 0;
        if (tokens[0].contains("1.9") || tokens[0].contains("1.8") || tokens[0].contains("1.7"))
            isNew = false;

        String baseSrgUrl = isNew ? newBaseSrgUrl : oldBaseSrgUrl;
        String srgFileName = isNew ? "config/joined.tsrg" : "joined.srg";
        String excFileName = isNew ? "config/exceptions.txt" : "joined.exc";
        String staticMethodsFileName = isNew ? "config/static_methods.txt" : "static_methods.txt";

        progress.set(0, "Fetching SRG data");
        srgDir = getSubDirForZip(tokens, baseSrgUrl, baseSrgDir);
        progress.set(1, "Fetching CSV data");
        mappingDir = getSubDirForZip(tokens, baseMappingUrl, baseMappingDir);

        srgFile = new File(srgDir, srgFileName);
        excFile = new File(srgDir, excFileName);
        staticMethodsFile = new File(srgDir, staticMethodsFileName);

        if (!srgFile.exists())
            throw new CantLoadMCPMappingException("Unable to find joined.srg. Your MCP conf folder may be corrupt.");

        if (!excFile.exists())
            throw new CantLoadMCPMappingException("Unable to find joined.exc. Your MCP conf folder may be corrupt.");

        if (!staticMethodsFile.exists())
            throw new CantLoadMCPMappingException("Unable to find static_methods.txt. Your MCP conf folder may be corrupt.");

        progress.set(2, "Loading CSV data");
        loadCsvMapping();
        progress.set(3, "Loading SRG data");
        loadSrgMapping(isNew);
        progress.set(4, "Linking SRG data with CSV data");
        linkSrgDataToCsvData();
        progress.set(5, "Linking EXC data with CSV data");
        linkExcDataToSetParamCsvData();
    }

    private File getSubDirForZip(String[] tokens, String baseZipUrl, String baseSubDir) throws CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException, IOException
    {
        if (!baseDir.exists() && !baseDir.mkdirs())
            throw new CantLoadMCPMappingException("Application data folder does not exist and cannot be created.");

        File subDir = new File(baseDir, replaceTokens(baseSubDir, tokens));
        if (!subDir.exists() && !subDir.mkdirs())
            throw new CantLoadMCPMappingException("Data folder does not exist and cannot be created.");

        RemoteZipHandler rzh = new RemoteZipHandler(replaceTokens(baseZipUrl, tokens), subDir, "SHA1");
        rzh.checkRemoteZip();

        return subDir;
    }

    private String replaceTokens(String s, String[] tokens)
    {
        return s.replace("{mc_ver}", tokens[0]).replace("{channel}", tokens[1]).replace("{map_ver}", tokens[2]);
    }

    private void loadSrgMapping(boolean newFormat) throws IOException
    {
        staticMethods = new StaticMethodsFile(staticMethodsFile);
        excFileData = new ExcFile(excFile);
        srgFileData = newFormat
                ? new TSrgFile(srgFile, excFileData, staticMethods)
                : new SrgFile(srgFile, excFileData, staticMethods);
    }

    private void loadCsvMapping() throws IOException
    {
        csvFieldData = new CsvFile(new File(mappingDir, "fields.csv"));
        csvMethodData = new CsvFile(new File(mappingDir, "methods.csv"));
        csvParamData = new ParamCsvFile(new File(mappingDir, "params.csv"));
    }

    private void linkSrgDataToCsvData()
    {
        for (Entry<String, MethodSrgData> methodData : srgFileData.srgMethodName2MethodData.entrySet())
        {
            if (!srgMethodData2CsvData.containsKey(methodData.getValue()) && csvMethodData.hasCsvDataForKey(methodData.getKey()))
            {
                srgMethodData2CsvData.put(methodData.getValue(), csvMethodData.getCsvDataForKey(methodData.getKey()));
            }
            else if (srgMethodData2CsvData.containsKey(methodData.getValue()))
                System.out.println("SRG method " + methodData.getKey() + " has multiple entries in CSV file!");
        }

        for (Entry<String, FieldSrgData> fieldData : srgFileData.srgFieldName2FieldData.entrySet())
        {
            if (!srgFieldData2CsvData.containsKey(fieldData.getValue()) && csvFieldData.hasCsvDataForKey(fieldData.getKey()))
            {
                srgFieldData2CsvData.put(fieldData.getValue(), csvFieldData.getCsvDataForKey(fieldData.getKey()));
            }
            else if (srgFieldData2CsvData.containsKey(fieldData.getValue()))
                System.out.println("SRG field " + fieldData.getKey() + " has multiple entries in CSV file!");
        }
    }

    private void linkExcDataToSetParamCsvData()
    {
        for (Entry<String, ExcData> excData : excFileData.srgMethodName2ExcData.entrySet())
        {
            if (!excData2MapParamCsvData.containsKey(excData.getValue()) && excData.getValue().getParameters().length > 0)
            {
                TreeMap<String, ParamCsvData> params = new TreeMap<String, ParamCsvData>();
                for (String srgName : excData.getValue().getParameters())
                    if (csvParamData.hasCsvDataForKey(srgName))
                        params.put(srgName, csvParamData.getCsvDataForKey(srgName));

                excData2MapParamCsvData.put(excData.getValue(), params);
            }
            else if (excData2MapParamCsvData.containsKey(excData.getValue()))
                System.out.println("EXC method param " + excData.getKey() + " has multiple entries in CSV file!");
        }
    }

    private CsvData processMemberDataEdit(MemberType type, Map<String, ? extends MemberSrgData> srg2MemberData,
            Map<? extends MemberSrgData, CsvData> memberData2CsvData,
            String srgName, String mcpName, String comment)
    {
        MemberSrgData memberData = srg2MemberData.get(srgName);
        CsvData csvData = null;

        if (memberData != null)
        {
            boolean isForced = memberData2CsvData.containsKey(memberData);
            if (isForced)
            {
                csvData = memberData2CsvData.get(memberData);
                if (!mcpName.trim().equals(csvData.getMcpName()) || !comment.trim().equals(csvData.getComment()))
                {
                    csvData.setMcpName(mcpName.trim());
                    csvData.setComment(comment.trim());
                }
                else
                    return null;
            }
            else
            {
                csvData = new CsvData(srgName, mcpName.trim(), 2, comment.trim());
            }

            commandMap.put(srgName, McpBotCommand.getMcpBotCommand(type, isForced, csvData.getSrgName(), csvData.getMcpName(), csvData.getComment()));
        }

        return csvData;
    }

    public String getBotCommands(boolean clear)
    {
        String r = "";

        for (McpBotCommand command : commandMap.values())
            r += command.toString() + "\n";

        if (clear)
            commandMap.clear();

        return r;
    }

    public boolean hasPendingCommands()
    {
        return !commandMap.isEmpty();
    }

    public TableModel getSearchResults(String input, IProgressListener progress)
    {
        if (input == null || input.trim().isEmpty())
            return getClassModel();

        if (progress != null)
        {
            progress.setMax(3);
            progress.set(0);
        }

        Set<ClassSrgData> results = new TreeSet<ClassSrgData>();

        // Search Class objects
        for (ClassSrgData classData : srgFileData.srgClassName2ClassData.values())
            if (classData.contains(input))
                results.add(classData);

        if (progress != null)
            progress.set(1);

        // Search Methods
        for (Entry<ClassSrgData, Set<MethodSrgData>> entry : srgFileData.class2MethodDataSet.entrySet())
        {
            if (!results.contains(entry.getKey()))
            {
                for (MethodSrgData methodData : entry.getValue())
                {
                    CsvData csv = srgMethodData2CsvData.get(methodData);
                    if (methodData.contains(input) || csv != null && csv.contains(input))
                    {
                        results.add(entry.getKey());
                        break;
                    }
                }
            }
        }

        if (progress != null)
            progress.set(2);

        // Search Fields
        for (Entry<ClassSrgData, Set<FieldSrgData>> entry : srgFileData.class2FieldDataSet.entrySet())
        {
            if (!results.contains(entry.getKey()))
            {
                for (FieldSrgData fieldData : entry.getValue())
                {
                    CsvData csv = srgFieldData2CsvData.get(fieldData);
                    if (fieldData.contains(input) || csv != null && csv.contains(input))
                    {
                        results.add(entry.getKey());
                        break;
                    }
                }
            }
        }

        return new ClassModel(results);
    }

    public TableModel getClassModel()
    {
        return new ClassModel(srgFileData.srgClassName2ClassData.values());
    }

    public TableModel getMethodModel(String srgPkgAndOwner)
    {
        ClassSrgData classData = srgFileData.srgClassName2ClassData.get(srgPkgAndOwner);
        return new MethodModel(srgFileData.class2MethodDataSet.get(classData));
    }

    public TableModel getParamModel(String srgMethodName)
    {
        if (excFileData.srgMethodName2ExcData.containsKey(srgMethodName))
            return new ParamModel(excFileData.srgMethodName2ExcData.get(srgMethodName));
        else
            return MappingGui.paramsDefaultModel;
    }

    public TableModel getFieldModel(String srgPkgAndOwner)
    {
        ClassSrgData classData = srgFileData.srgClassName2ClassData.get(srgPkgAndOwner);
        return new FieldModel(srgFileData.class2FieldDataSet.get(classData));
    }

    @SuppressWarnings("rawtypes")
    public class ClassModel extends AbstractTableModel
    {
        private static final long              serialVersionUID = 1L;
        public final String[]                  columnNames      = { "Pkg name", "SRG name", "Obf name" };
        private final Class[]                  columnTypes      = { String.class, String.class, String.class };
        private final boolean[]                isColumnEditable = { false, false, false };
        private final Object[][]               data;
        private final Collection<ClassSrgData> collectionRef;

        public ClassModel(Collection<ClassSrgData> map)
        {
            collectionRef = map;

            data = new Object[collectionRef.size()][columnNames.length];

            int i = 0;

            for (ClassSrgData classData : collectionRef)
            {
                data[i][0] = classData.getSrgPkgName();
                data[i][1] = classData.getSrgName();
                data[i][2] = classData.getObfName();
                i++;
            }
        }

        @Override
        public int getRowCount()
        {
            return data.length;
        }

        @Override
        public int getColumnCount()
        {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int columnIndex)
        {
            if (columnIndex < columnNames.length && columnIndex >= 0)
                return columnNames[columnIndex];

            return "";
        }

        @Override
        public Class<?> getColumnClass(int columnIndex)
        {
            if (columnIndex < columnTypes.length && columnIndex >= 0)
                return columnTypes[columnIndex];

            return String.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex)
        {
            if (columnIndex < isColumnEditable.length && columnIndex >= 0)
                return isColumnEditable[columnIndex];

            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex)
        {
            return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
        }
    }

    @SuppressWarnings("rawtypes")
    public class MethodModel extends AbstractTableModel
    {
        private static final long        serialVersionUID = 1L;
        private final String[]           columnNames      = { "MCP Name", "SRG Name", "Obf Name", "SRG Descriptor", "Comment" };
        private final Class[]            columnTypes      = { String.class, String.class, String.class, String.class, String.class };
        private final boolean[]          isColumnEditable = { true, false, false, false, true };
        private final Object[][]         data;
        private final Set<MethodSrgData> setRef;

        public MethodModel(Set<MethodSrgData> srgMethodSet)
        {
            setRef = srgMethodSet;

            data = new Object[setRef.size()][columnNames.length];

            int i = 0;

            for (MethodSrgData methodData : setRef)
            {
                CsvData csvData = srgMethodData2CsvData.get(methodData);
                if (csvData != null)
                {
                    data[i][0] = csvData.getMcpName();
                    data[i][4] = csvData.getComment();
                }
                else
                {
                    data[i][0] = "";
                    data[i][4] = "";
                }
                data[i][1] = methodData.getSrgName();
                data[i][2] = methodData.getObfName();
                data[i][3] = methodData.getSrgDescriptor();

                i++;
            }
        }

        @Override
        public int getRowCount()
        {
            return data.length;
        }

        @Override
        public int getColumnCount()
        {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int columnIndex)
        {
            if (columnIndex < columnNames.length && columnIndex >= 0)
                return columnNames[columnIndex];

            return "";
        }

        @Override
        public Class<?> getColumnClass(int columnIndex)
        {
            if (columnIndex < columnTypes.length && columnIndex >= 0)
                return columnTypes[columnIndex];

            return String.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex)
        {
            if (columnIndex < isColumnEditable.length && columnIndex >= 0)
                return isColumnEditable[columnIndex];

            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex)
        {
            return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)
        {
            data[rowIndex][columnIndex] = aValue;

            if (columnIndex == 4 && aValue != null && (data[rowIndex][0] == null || data[rowIndex][0].toString().trim().isEmpty()))
                return; // if only the comment has been set, don't bother adding a command

            String srgName = (String) data[rowIndex][1];
            String mcpName = (String) data[rowIndex][0];
            String comment = (String) data[rowIndex][4];

            if (mcpName.trim().isEmpty())
                return;

            CsvData result = processMemberDataEdit(MemberType.METHOD, srgFileData.srgMethodName2MethodData, srgMethodData2CsvData, srgName, mcpName, comment);

            if (result != null)
            {
                csvMethodData.updateCsvDataForKey(srgName, result);
                srgMethodData2CsvData.put(srgFileData.srgMethodName2MethodData.get(srgName), result);
                parentGui.setCsvFileEdited(true);
            }
        }
    }

    @SuppressWarnings("rawtypes")
    public class ParamModel extends AbstractTableModel
    {
        private static final long serialVersionUID = 1L;
        private final String[]    columnNames      = { "MCP Name", "SRG Name", "Type" };
        private final Class[]     columnTypes      = { String.class, String.class, String.class };
        private final boolean[]   isColumnEditable = { true, false, false };
        private final Object[][]  data;

        public ParamModel(ExcData excData)
        {
            data = new Object[excData.getParameters().length][columnNames.length];

            for (int i = 0; i < excData.getParameters().length; i++)
            {
                if (excData2MapParamCsvData.containsKey(excData) && excData2MapParamCsvData.get(excData).containsKey(excData.getParameters()[i]))
                    data[i][0] = excData2MapParamCsvData.get(excData).get(excData.getParameters()[i]).getMcpName();
                else
                    data[i][0] = "";

                data[i][1] = excData.getParameters()[i];
                data[i][2] = excData.getParamTypes()[i];
                //i++;
            }
        }

        @Override
        public int getRowCount()
        {
            return data.length;
        }

        @Override
        public int getColumnCount()
        {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int columnIndex)
        {
            if (columnIndex < columnNames.length && columnIndex >= 0)
                return columnNames[columnIndex];

            return "";
        }

        @Override
        public Class<?> getColumnClass(int columnIndex)
        {
            if (columnIndex < columnTypes.length && columnIndex >= 0)
                return columnTypes[columnIndex];

            return String.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex)
        {
            if (columnIndex < isColumnEditable.length && columnIndex >= 0)
                return isColumnEditable[columnIndex];

            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex)
        {
            return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)
        {
            data[rowIndex][columnIndex] = aValue;

            String srgName = (String) data[rowIndex][1];
            String mcpName = (String) data[rowIndex][0];

            if (mcpName.trim().isEmpty())
                return;

            ExcData excData = excFileData.srgParamName2ExcData.get(srgName);
            ParamCsvData csvData = null;
            boolean isForced = csvParamData.hasCsvDataForKey(srgName);

            if (isForced)
            {
                csvData = csvParamData.getCsvDataForKey(srgName);
                if (!mcpName.trim().equals(csvData.getMcpName()))
                    csvData.setMcpName(mcpName.trim());
                else
                    return;
            }
            else
            {
                csvData = new ParamCsvData(srgName, mcpName, 2);
                excData2MapParamCsvData.get(excData).put(srgName, csvData);
            }

            commandMap.put(srgName, McpBotCommand.getMcpBotCommand(MemberType.PARAM, isForced, csvData.getSrgName(), csvData.getMcpName(), ""));

            csvParamData.updateCsvDataForKey(srgName, csvData);
            parentGui.setCsvFileEdited(true);
        }
    }

    @SuppressWarnings("rawtypes")
    public class FieldModel extends AbstractTableModel
    {
        private static final long       serialVersionUID = 1L;
        private final String[]          columnNames      = { "MCP Name", "SRG Name", "Obf Name", "Comment" };
        private final Class[]           columnTypes      = { String.class, String.class, String.class, String.class };
        private final boolean[]         isColumnEditable = { true, false, false, true };
        private final Object[][]        data;
        private final Set<FieldSrgData> setRef;

        public FieldModel(Set<FieldSrgData> srgFieldSet)
        {
            setRef = srgFieldSet;

            data = new Object[setRef.size()][columnNames.length];

            int i = 0;

            for (FieldSrgData fieldData : setRef)
            {
                CsvData csvData = srgFieldData2CsvData.get(fieldData);
                if (csvData != null)
                {
                    data[i][0] = csvData.getMcpName();
                    data[i][3] = csvData.getComment();
                }
                else
                {
                    data[i][0] = "";
                    data[i][3] = "";
                }
                data[i][1] = fieldData.getSrgName();
                data[i][2] = fieldData.getObfName();

                i++;
            }
        }

        @Override
        public int getRowCount()
        {
            return data.length;
        }

        @Override
        public int getColumnCount()
        {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int columnIndex)
        {
            if (columnIndex < columnNames.length && columnIndex >= 0)
                return columnNames[columnIndex];

            return "";
        }

        @Override
        public Class<?> getColumnClass(int columnIndex)
        {
            if (columnIndex < columnTypes.length && columnIndex >= 0)
                return columnTypes[columnIndex];

            return String.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex)
        {
            if (columnIndex < isColumnEditable.length && columnIndex >= 0)
                return isColumnEditable[columnIndex];

            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex)
        {
            return data[rowIndex][Math.min(columnIndex, data[rowIndex].length - 1)];
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)
        {
            data[rowIndex][columnIndex] = aValue;

            if (columnIndex == 3 && aValue != null && (data[rowIndex][0] == null || data[rowIndex][0].toString().trim().isEmpty()))
                return; // if only the comment has been set, don't bother adding a command

            String srgName = (String) data[rowIndex][1];
            String mcpName = (String) data[rowIndex][0];
            String comment = (String) data[rowIndex][3];

            if (mcpName.trim().isEmpty())
                return;

            CsvData result = processMemberDataEdit(MemberType.FIELD, srgFileData.srgFieldName2FieldData, srgFieldData2CsvData, srgName, mcpName, comment);

            if (result != null)
            {
                csvFieldData.updateCsvDataForKey(srgName, result);
                srgFieldData2CsvData.put(srgFileData.srgFieldName2FieldData.get(srgName), result);
                parentGui.setCsvFileEdited(true);
            }
        }
    }
}
/*
 * Copyright (C) 2014 bspkrs
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

public class MemberSrgData
{
    private final String  obfOwner;
    private final String  obfName;
    private final String  srgOwner;
    private final String  srgPkg;
    private final String  srgName;
    private final boolean isClientOnly;

    public MemberSrgData(String obfOwner, String obfName, String srgOwner, String srgPkg, String srgName, boolean isClientOnly)
    {
        this.obfOwner = obfOwner;
        this.obfName = obfName;
        this.srgOwner = srgOwner;
        this.srgPkg = srgPkg;
        this.srgName = srgName;
        this.isClientOnly = isClientOnly;
    }

    public String getObfOwner()
    {
        return obfOwner;
    }

    public String getObfName()
    {
        return obfName;
    }

    public String getSrgOwner()
    {
        return srgOwner;
    }

    public String getSrgName()
    {
        return srgName;
    }

    public boolean isClientOnly()
    {
        return isClientOnly;
    }

    public String getSrgPkg()
    {
        return srgPkg;
    }

    public boolean contains(String s)
    {
        return srgName.contains(s) || obfName.contains(s);
    }
}
/*
 * Copyright (C) 2014 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;


public class MethodSrgData extends MemberSrgData implements Comparable<MethodSrgData>
{
    private final String obfDescriptor;
    private final String srgDescriptor;

    public MethodSrgData(String obfOwner, String obfName, String obfDescriptor, String srgOwner, String srgPkg, String srgName, String srgDescriptor, boolean isClientOnly)
    {
        super(obfOwner, obfName, srgOwner, srgPkg, srgName, isClientOnly);
        this.obfDescriptor = obfDescriptor;
        this.srgDescriptor = srgDescriptor;
    }

    public String getObfDescriptor()
    {
        return obfDescriptor;
    }

    public String getSrgDescriptor()
    {
        return srgDescriptor;
    }

    @Override
    public int compareTo(MethodSrgData o)
    {
        if (o != null)
            return getSrgName().compareTo(o.getSrgName());
        else
            return 1;
    }
}
/*
 * Copyright (C) 2014 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

public class ParamCsvData implements Comparable<ParamCsvData>
{
    private final String srgName;
    private String       mcpName;
    private final int    side;

    public ParamCsvData(String srgName, String mcpName, int side)
    {
        this.srgName = srgName;
        this.mcpName = mcpName;
        this.side = side;
    }

    public String toCsv()
    {
        return srgName + "," + mcpName + "," + side;
    }

    public String getSrgName()
    {
        return srgName;
    }

    public String getMcpName()
    {
        return mcpName;
    }

    public ParamCsvData setMcpName(String mcpName)
    {
        this.mcpName = mcpName;
        return this;
    }

    public int getSide()
    {
        return side;
    }

    @Override
    public int compareTo(ParamCsvData o)
    {
        if (o != null)
            return srgName.compareTo(o.srgName);

        return 1;
    }

    public boolean contains(String s)
    {
        return mcpName.contains(s);
    }
}
/*
 * Copyright (C) 2014 bspkrs
 * Portions Copyright (C) 2014 Alex "immibis" Campbell
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class ParamCsvFile
{
    private final File                      file;
    private final Map<String, ParamCsvData> srgParamName2ParamCsvData;
    private boolean                         isDirty;
    private String                          headerLine;

    public ParamCsvFile(File file) throws IOException
    {
        this.file = file;
        srgParamName2ParamCsvData = new TreeMap<String, ParamCsvData>();
        readFromFile();
        isDirty = false;
    }

    public void readFromFile() throws IOException
    {
        Scanner in = new Scanner(new BufferedReader(new FileReader(file)));
        try
        {
            in.useDelimiter(",");
            headerLine = in.nextLine(); // Skip header row
            while (in.hasNextLine())
            {
                String srgName = in.next();
                String mcpName = in.next();
                String side = in.nextLine().substring(1);
                srgParamName2ParamCsvData.put(srgName, new ParamCsvData(srgName, mcpName, Integer.valueOf(side)));
            }
        }
        finally
        {
            in.close();
        }
    }

    public void writeToFile() throws IOException
    {
        if (isDirty)
        {
            if (file.exists())
            {
                File fileBak = new File(file.getAbsolutePath() + "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".bak");
                file.renameTo(fileBak);
            }

            file.createNewFile();

            PrintWriter out = new PrintWriter(new FileWriter(file));
            out.println(headerLine);

            for (ParamCsvData data : srgParamName2ParamCsvData.values())
                out.println(data.toCsv());

            out.close();

            isDirty = false;
        }
    }

    public boolean hasCsvDataForKey(String srgName)
    {
        return srgParamName2ParamCsvData.containsKey(srgName);
    }

    public ParamCsvData getCsvDataForKey(String srgName)
    {
        return srgParamName2ParamCsvData.get(srgName);
    }

    public void updateCsvDataForKey(String srgName, ParamCsvData csvData)
    {
        srgParamName2ParamCsvData.put(srgName, csvData);
        isDirty = true;
    }

    public boolean isDirty()
    {
        return isDirty;
    }

    public void setIsDirty(boolean bol)
    {
        isDirty = bol;
    }
}
/*
 * Copyright (C) 2015 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import bspkrs.mmv.gui.MappingGui;

public class RemoteZipHandler
{
    private final URL    zipUrl;
    private final URL    digestUrl;
    private final File   localDir;
    private final String digestType;
    private final String zipFileName;

    public RemoteZipHandler(String urlString, File dir, String digestType) throws MalformedURLException
    {
        zipUrl = new URL(urlString);
        if (digestType != null)
            digestUrl = new URL(urlString + "." + digestType.toLowerCase());
        else
            digestUrl = null;
        String[] tokens = urlString.split("/");
        zipFileName = tokens[tokens.length - 1];
        localDir = dir;
        this.digestType = digestType;
    }

    public void checkRemoteZip() throws IOException, NoSuchAlgorithmException, DigestException
    {
        // fetch zip file sha1
        boolean fetchZip = true;
        String remoteHash = null;
        File digestFile = null;
        if (digestType != null)
        {
            // check hash against local hash if exists
            remoteHash = loadTextFromURL(digestUrl, new String[] { "" })[0];
            if (!remoteHash.isEmpty())
            {
                digestFile = new File(localDir, zipFileName + "." + digestType.toLowerCase());

                // if local digest exists and hashes match skip getting the zip file
                if (digestFile.exists())
                {
                    String existingHash = loadTextFromFile(digestFile, new String[] { "" })[0];
                    if (!existingHash.isEmpty() && remoteHash.equals(existingHash))
                        fetchZip = false;
                }
            }
        }

        if (fetchZip)
        {
            // download zip
            File localZip = new File(localDir, zipFileName);
            if (localZip.exists())
                localZip.delete();
            OutputStream output = new FileOutputStream(localZip);
            try
            {
                URLConnection uc = zipUrl.openConnection();
                uc.addRequestProperty("User-Agent", "MMV/" + MappingGui.VERSION_NUMBER);
                byte[] buffer = new byte[1024]; // Or whatever
                int bytesRead;
                try (InputStream is = uc.getInputStream())
                {
                    while ((bytesRead = is.read(buffer)) > 0)
                        output.write(buffer, 0, bytesRead);
                }
            }
            finally
            {
                output.close();
            }

            // Check hash of downloaded file to ensure we received it correctly
            if (digestType != null && !remoteHash.isEmpty())
            {
                String downloadHash = getFileDigest(new FileInputStream(localZip), digestType);
                if (!remoteHash.equals(downloadHash))
                    throw new java.security.DigestException("Remote digest does not match digest of downloaded file!");
            }

            // extract zip file
            extractZip(localZip, localDir);
            if (localZip.exists())
                localZip.delete();

            // save new hash after successful extract
            if (digestType != null && !remoteHash.isEmpty())
            {
                if (digestFile.exists())
                    digestFile.delete();
                digestFile.createNewFile();
                PrintWriter out = new PrintWriter(new FileWriter(digestFile));
                out.print(remoteHash);
                out.close();
            }
        }
    }

    public static String[] loadTextFromURL(URL url, String[] defaultValue)
    {
        List<String> arraylist = new ArrayList<String>();
        Scanner scanner = null;
        try
        {
            URLConnection uc = url.openConnection();
            uc.addRequestProperty("User-Agent", "MMV/" + MappingGui.VERSION_NUMBER);
            InputStream is = uc.getInputStream();
            scanner = new Scanner(is, "UTF-8");

            while (scanner.hasNextLine())
            {
                arraylist.add(scanner.nextLine());
            }
        }
        catch (Throwable e)
        {
            return defaultValue;
        }
        finally
        {
            if (scanner != null)
                scanner.close();
        }
        return arraylist.toArray(new String[arraylist.size()]);
    }

    public static String[] loadTextFromFile(File file, String[] defaultValue)
    {
        ArrayList<String> lines = new ArrayList<String>();

        Scanner scanner = null;
        try
        {
            scanner = new Scanner(file);
            while (scanner.hasNextLine())
                lines.add(scanner.nextLine());
        }
        catch (FileNotFoundException e)
        {
            return defaultValue;
        }
        finally
        {
            if (scanner != null)
                scanner.close();
        }

        return lines.toArray(new String[lines.size()]);
    }

    public static String getFileDigest(InputStream is, String digestType) throws NoSuchAlgorithmException, IOException
    {
        MessageDigest md = MessageDigest.getInstance(digestType);
        byte[] dataBytes = new byte[1024];

        int nread = 0;

        while ((nread = is.read(dataBytes)) != -1)
            md.update(dataBytes, 0, nread);

        is.close();

        byte[] mdbytes = md.digest();

        //convert the byte to hex format
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mdbytes.length; i++)
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        return sb.toString();
    }

    public static void extractZip(File zipFile, File destDir) throws IOException
    {
        byte[] buffer = new byte[1024];
        if (!destDir.exists())
            destDir.mkdirs();

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();
        try
        {
            while (ze != null)
            {
                String fileName = ze.getName();
                File newFile = new File(destDir, fileName);
                if (!newFile.toPath().normalize().startsWith(destDir.toPath().normalize())) {
                    throw new IOException("Bad zip entry");
                }
                if (ze.isDirectory())
                {
                    if (newFile.exists())
                        deleteDirAndContents(newFile);
                    newFile.mkdirs();
                }
                else
                {
                    if (newFile.exists())
                        newFile.delete();
                    if (newFile.getParentFile() != null && !newFile.getParentFile().exists())
                        newFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0)
                        fos.write(buffer, 0, len);

                    fos.close();
                }
                ze = zis.getNextEntry();
            }
        }
        finally
        {
            zis.closeEntry();
            zis.close();
        }
    }

    public static boolean deleteDirAndContents(File dir)
    {
        if (dir.isDirectory())
        {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++)
            {
                boolean success = deleteDirAndContents(new File(dir, children[i]));
                if (!success)
                    return false;
            }
        }
        return dir.delete();
    }
}
/*
 * Copyright (C) 2015 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.util.Comparator;

import bspkrs.mmv.version.NaturalOrderComparator;

public class SplittedNaturalComparator implements Comparator<Object>
{
    private final String splitter;

    public SplittedNaturalComparator(String splitter)
    {
        this.splitter = splitter;
    }

    @Override
    public int compare(Object o1, Object o2)
    {
        String[] a = o1.toString().split(splitter);
        String[] b = o2.toString().split(splitter);

        if (a.length != b.length)
            return b.length - a.length;

        NaturalOrderComparator comp = new NaturalOrderComparator();
        for (int i = 0; i < a.length; i++)
        {
            int comparison = comp.compare(a[i], b[i]);
            if (comparison != 0)
                return comparison;
        }
        return 0;
    }
}
/*
 * Copyright (C) 2014 Alex "immibis" Campbell, bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Modified version of SrgFile.java from BON
 */
package bspkrs.mmv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class SrgFile
{
    // All maps should be inter-connected to reference a single set of objects
    public final Map<String, ClassSrgData>             srgClassName2ClassData   = new TreeMap<String, ClassSrgData>();            // full/pkg/ClassSrgName -> ClassSrgData
    public final Map<String, Set<ClassSrgData>>        srgPkg2ClassDataSet      = new TreeMap<String, Set<ClassSrgData>>();       // full/pkg -> Set<ClassSrgData>
    public final Map<String, FieldSrgData>             srgFieldName2FieldData   = new TreeMap<String, FieldSrgData>();            // field_12345_a -> FieldSrgData
    public final Map<String, MethodSrgData>            srgMethodName2MethodData = new TreeMap<String, MethodSrgData>();           // func_12345_a -> MethodSrgData
    public final Map<ClassSrgData, Set<MethodSrgData>> class2MethodDataSet      = new TreeMap<ClassSrgData, Set<MethodSrgData>>();
    public final Map<ClassSrgData, Set<FieldSrgData>>  class2FieldDataSet       = new TreeMap<ClassSrgData, Set<FieldSrgData>>();
    public final Map<String, ClassSrgData>             srgMethodName2ClassData  = new TreeMap<String, ClassSrgData>();            // func_12345_a -> ClassSrgData
    public final Map<String, ClassSrgData>             srgFieldName2ClassData   = new TreeMap<String, ClassSrgData>();            // field_12345_a -> ClassSrgData

    SrgFile() {} // FIXME Needed so that TSrgFile can extend SrgFile. A shared interface/abstract probably makes more sense

    public static String getLastComponent(String s)
    {
        String[] parts = s.split("/");
        return parts[parts.length - 1];
    }

    public SrgFile(File f, ExcFile excFile, StaticMethodsFile staticMethods) throws IOException
    {
        Scanner in = new Scanner(new BufferedReader(new FileReader(f)));
        try
        {
            while (in.hasNextLine())
            {
                if (in.hasNext("CL:"))
                {
                    // CL: a net/minecraft/util/EnumChatFormatting
                    in.next(); // skip CL:
                    String obf = in.next();
                    String deobf = in.next();
                    String srgName = getLastComponent(deobf);
                    String pkgName = deobf.substring(0, deobf.lastIndexOf('/'));

                    ClassSrgData classData = new ClassSrgData(obf, srgName, pkgName, in.hasNext("#C"));

                    if (!srgPkg2ClassDataSet.containsKey(pkgName))
                        srgPkg2ClassDataSet.put(pkgName, new TreeSet<ClassSrgData>());
                    srgPkg2ClassDataSet.get(pkgName).add(classData);

                    srgClassName2ClassData.put(pkgName + "/" + srgName, classData);

                    if (!class2MethodDataSet.containsKey(classData))
                        class2MethodDataSet.put(classData, new TreeSet<MethodSrgData>());

                    if (!class2FieldDataSet.containsKey(classData))
                        class2FieldDataSet.put(classData, new TreeSet<FieldSrgData>());
                }
                else if (in.hasNext("FD:"))
                {
                    // FD: aql/c net/minecraft/block/BlockStoneBrick/field_94408_c #C
                    in.next(); // skip FD:
                    String[] obf = in.next().split("/");
                    String obfOwner = obf[0];
                    String obfName = obf[1];
                    String deobf = in.next();
                    String srgName = getLastComponent(deobf);
                    String srgPkg = deobf.substring(0, deobf.lastIndexOf('/'));
                    String srgOwner = getLastComponent(srgPkg);
                    srgPkg = srgPkg.substring(0, srgPkg.lastIndexOf('/'));

                    FieldSrgData fieldData = new FieldSrgData(obfOwner, obfName, srgOwner, srgPkg, srgName, in.hasNext("#C"));

                    srgFieldName2FieldData.put(srgName, fieldData);
                    class2FieldDataSet.get(srgClassName2ClassData.get(srgPkg + "/" + srgOwner)).add(fieldData);
                    srgFieldName2ClassData.put(srgName, srgClassName2ClassData.get(srgPkg + "/" + srgOwner));
                }
                else if (in.hasNext("MD:"))
                {
                    // MD: aor/a (Lmt;)V net/minecraft/block/BlockHay/func_94332_a (Lnet/minecraft/client/renderer/texture/IconRegister;)V #C
                    in.next(); // skip MD:
                    String[] obf = in.next().split("/");
                    String obfOwner = obf[0];
                    String obfName = obf[1];
                    String obfDescriptor = in.next();
                    String deobf = in.next();
                    String srgName = getLastComponent(deobf);
                    String srgPkg = deobf.substring(0, deobf.lastIndexOf('/'));
                    String srgOwner = getLastComponent(srgPkg);
                    srgPkg = srgPkg.substring(0, srgPkg.lastIndexOf('/'));
                    String srgDescriptor = in.next();

                    MethodSrgData methodData = new MethodSrgData(obfOwner, obfName, obfDescriptor, srgOwner, srgPkg, srgName, srgDescriptor, in.hasNext("#C"));

                    srgMethodName2MethodData.put(srgName, methodData);
                    class2MethodDataSet.get(srgClassName2ClassData.get(srgPkg + "/" + srgOwner)).add(methodData);
                    srgMethodName2ClassData.put(srgName, srgClassName2ClassData.get(srgPkg + "/" + srgOwner));

                    // Hack in the missing parameter data
                    ExcData toAdd = new ExcData(srgOwner, srgName, srgDescriptor, new String[0], staticMethods.contains(srgName));
                    ExcData existing = excFile.srgMethodName2ExcData.get(srgName);

                    if ((existing == null) || (existing.getParameters().length < toAdd.getParameters().length))
                    {
                        excFile.srgMethodName2ExcData.put(srgName, toAdd);
                        for (String parameter : toAdd.getParameters())
                            excFile.srgParamName2ExcData.put(parameter, toAdd);
                    }
                }
                else
                    in.nextLine();
            }
        }
        finally
        {
            in.close();
        }
    }
}
/*
 * Copyright (C) 2015 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class StaticMethodsFile
{
    private final File  file;
    public List<String> staticMethods;

    public StaticMethodsFile(File file) throws IOException
    {
        this.file = file;
        staticMethods = new ArrayList<String>();
        readFromFile();
    }

    public void readFromFile() throws IOException
    {
        Scanner in = new Scanner(new BufferedReader(new FileReader(file)));
        try
        {
            while (in.hasNextLine())
            {
                staticMethods.add(in.nextLine());
            }
        }
        finally
        {
            in.close();
        }
    }

    public boolean contains(String srgName)
    {
        return staticMethods.contains(srgName);
    }
}
package bspkrs.mmv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.*;

public class TSrgFile extends SrgFile
{

    public TSrgFile(File f, ExcFile excFile, StaticMethodsFile staticMethods) throws FileNotFoundException
    {
        Scanner in = new Scanner(new BufferedReader(new FileReader(f)));
        try
        {
            String currentPackage = null;
            String currentClass = null;
            String currentObfClass = null;
            while (in.hasNextLine())
            {
                String[] line = in.nextLine().split(" ");

                if (line[0].indexOf("\t") == 0) // Member
                {
                    line[0] = line[0].substring(1); // ignore the leading tab

                    if (line.length == 2) // Field
                    {
                        //	a field_192300_a
                        String obf = line[0];
                        String srgName = line[1];
                        String obfOwner = currentObfClass;
                        String srgPkg = currentPackage;
                        String srgOwner = currentClass;

                        FieldSrgData fieldData = new FieldSrgData(obfOwner, obf, srgOwner, srgPkg, srgName, false);

                        srgFieldName2FieldData.put(srgName, fieldData);
                        class2FieldDataSet.get(srgClassName2ClassData.get(srgPkg + "/" + srgOwner)).add(fieldData);
                        srgFieldName2ClassData.put(srgName, srgClassName2ClassData.get(srgPkg + "/" + srgOwner));
                    }
                    else if (line.length == 3) // Method
                    {
                        //	b (Lhy;)Lu; func_192295_b
                        String obf = line[0];
                        String descriptor = line[1];
                        String srgName = line[2];
                        String obfOwner = currentObfClass;
                        String srgPkg = currentPackage;
                        String srgOwner = currentClass;

                        MethodSrgData methodData = new MethodSrgData(obfOwner, obf, descriptor, srgOwner, srgPkg, srgName, descriptor/*FIXME*/, false);

                        srgMethodName2MethodData.put(srgName, methodData);
                        class2MethodDataSet.get(srgClassName2ClassData.get(srgPkg + "/" + srgOwner)).add(methodData);
                        srgMethodName2ClassData.put(srgName, srgClassName2ClassData.get(srgPkg + "/" + srgOwner));

                        // Hack in the missing parameter data
                        ExcData toAdd = new ExcData(srgOwner, srgName, descriptor/*FIXME*/, new String[0], staticMethods.contains(srgName));
                        ExcData existing = excFile.srgMethodName2ExcData.get(srgName);

                        if ((existing == null) || (existing.getParameters().length < toAdd.getParameters().length))
                        {
                            excFile.srgMethodName2ExcData.put(srgName, toAdd);
                            for (String parameter : toAdd.getParameters())
                                excFile.srgParamName2ExcData.put(parameter, toAdd);
                        }
                    }
                }
                else // Class
                {
                    // u net/minecraft/advancements/DisplayInfo
                    currentObfClass = line[0];
                    currentPackage = line[1].substring(0, line[1].lastIndexOf('/'));
                    currentClass = line[1].substring(line[1].lastIndexOf('/') + 1);

                    ClassSrgData classData = new ClassSrgData(currentObfClass, currentClass, currentPackage, false);

                    if (!srgPkg2ClassDataSet.containsKey(currentPackage))
                        srgPkg2ClassDataSet.put(currentPackage, new TreeSet<ClassSrgData>());
                    srgPkg2ClassDataSet.get(currentPackage).add(classData);

                    srgClassName2ClassData.put(currentPackage + "/" + currentClass, classData);

                    if (!class2MethodDataSet.containsKey(classData))
                        class2MethodDataSet.put(classData, new TreeSet<MethodSrgData>());

                    if (!class2FieldDataSet.containsKey(classData))
                        class2FieldDataSet.put(classData, new TreeSet<FieldSrgData>());
                }
            }
        }
        finally
        {
            in.close();
        }
    }
}
/*
 * Copyright (C) 2015 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;

public class VersionFetcher
{
    private final String jsonUrl = "https://maven.minecraftforge.net/de/oceanlabs/mcp/versions.json";
    private List<String> versions;

    @SuppressWarnings("unchecked")
    public List<String> getVersions(boolean force) throws IOException
    {
        if ((versions == null) || force)
        {
            final URL url = new URL(jsonUrl);
            final URLConnection connection = url.openConnection();
            connection.addRequestProperty("User-Agent", "MMV/1.0.0");
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            Map<String, Object> json = new Gson().fromJson(br, Map.class);

            versions = new ArrayList<String>();
            for (String mcVer : json.keySet())
                for (String channel : ((Map<String, ArrayList<Double>[]>) json.get(mcVer)).keySet())
                    for (Double ver : ((Map<String, ArrayList<Double>>) json.get(mcVer)).get(channel))
                        versions.add(mcVer + "_" + channel + "_" + String.format("%.0f", ver));
            Collections.sort(versions, Collections.reverseOrder(new SplittedNaturalComparator("_")));
            return versions;
        }
        else
            return versions;
    }
}
/*
 * Copyright (C) 2014 Alex "immibis" Campbell, bspkrs
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv.gui;

import immibis.bon.gui.Reference;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class BrowseActionListener implements ActionListener
{

    private JComboBox<String> comboBox;
    private boolean           isOpen;
    private Component         parent;
    private JFileChooser      jfc;
    private Reference<File>   defaultDir;

    public BrowseActionListener(JComboBox<String> inputField, boolean isOpen, Component parent, boolean dirOnly, Reference<File> defaultDir)
    {

        this.defaultDir = defaultDir;
        this.comboBox = inputField;
        this.isOpen = isOpen;
        this.parent = parent;

        jfc = new JFileChooser();
        jfc.setFileSelectionMode(dirOnly ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY);

        if (!dirOnly)
            jfc.addChoosableFileFilter(new FileFilter()
            {
                @Override
                public String getDescription()
                {
                    return "Jars and zips only";
                }

                @Override
                public boolean accept(File arg0)
                {
                    String fn = arg0.getName();
                    return arg0.isDirectory() || fn.endsWith(".jar") || fn.endsWith(".zip");
                }
            });
    }

    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        int rv;
        jfc.setCurrentDirectory(defaultDir.val);
        if (isOpen)
            rv = jfc.showOpenDialog(parent);
        else
            rv = jfc.showSaveDialog(parent);

        if (rv == JFileChooser.APPROVE_OPTION)
        {
            File f = jfc.getSelectedFile();

            String path;
            try
            {
                path = f.getCanonicalPath();

            }
            catch (IOException e)
            {
                path = f.getAbsolutePath();
            }

            DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) comboBox.getModel();

            if (model.getIndexOf(path) != -1)
                model.removeElement(path);

            comboBox.insertItemAt(path, 0);
            comboBox.setSelectedItem(path);
        }

        defaultDir.val = new File((String) comboBox.getSelectedItem());
    }
}
/*
 * Copyright (C) 2015 bspkrs
 * Portions Copyright (C) 2014 Alex "immibis" Campbell
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.prefs.Preferences;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SortOrder;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import bspkrs.mmv.McpMappingLoader;
import bspkrs.mmv.McpMappingLoader.CantLoadMCPMappingException;
import bspkrs.mmv.VersionFetcher;
import bspkrs.mmv.version.AppVersionChecker;
import immibis.bon.IProgressListener;

public class MappingGui extends JFrame
{
    public static final String                  VERSION_NUMBER        = "1.0.1";
    private static final long                   serialVersionUID      = 1L;
    private final Preferences                   prefs                 = Preferences.userNodeForPackage(MappingGui.class);
    private JFrame                              frmMcpMappingViewer;
    private JButton                             btnRefreshTables;
    private JComboBox<String>                   cmbMappingVersion;
    private JCheckBox                           chkForceRefresh;
    private JPanel                              pnlProgress;
    private JProgressBar                        progressBar;
    private JPanel                              pnlFilter;
    private JComboBox<String>                   cmbFilter;
    private JButton                             btnSearch;
    private JButton                             btnGetBotCommands;
    private JCheckBox                           chkClearOnCopy;
    private final static String                 PREFS_KEY_FILTER      = "filter";
    private final static String                 PREFS_KEY_CLASS_SORT  = "classSort";
    private final static String                 PREFS_KEY_METHOD_SORT = "methodSort";
    private final static String                 PREFS_KEY_PARAM_SORT  = "paramSort";
    private final static String                 PREFS_KEY_FIELD_SORT  = "fieldSort";
    private final List<RowSorter.SortKey>       classSort             = new ArrayList<RowSorter.SortKey>();
    private final List<RowSorter.SortKey>       methodSort            = new ArrayList<RowSorter.SortKey>();
    private final List<RowSorter.SortKey>       paramSort             = new ArrayList<RowSorter.SortKey>();
    private final List<RowSorter.SortKey>       fieldSort             = new ArrayList<RowSorter.SortKey>();
    private JTable                              tblClasses;
    private JTable                              tblMethods;
    private JTable                              tblFields;
    private JTable                              tblParams;
    private Thread                              curTask               = null;
    private final Map<String, McpMappingLoader> mcpInstances          = new HashMap<>();
    private final VersionFetcher                versionFetcher        = new VersionFetcher();
    private McpMappingLoader                    currentLoader;
    private AppVersionChecker                   versionChecker;
    private final String                        versionURL            = "http://bspk.rs/Minecraft/MMV/MMV.version";
    private final String                        mcfTopic              = "http://www.minecraftforum.net/topic/2115030-";

    // @formatter:off
    public static DefaultTableModel classesDefaultModel = new DefaultTableModel(new Object[][] { {}, }, new String[] { "Pkg name", "SRG name", "Obf name" })
    {
        private static final long serialVersionUID = 1L;
        boolean[]                 columnEditables  = new boolean[] { false, false, false };
        @SuppressWarnings("rawtypes")
        Class[]                   columnTypes      = new Class[] { String.class, String.class, String.class };

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; }

        @Override
        public boolean isCellEditable(int row, int column) { return columnEditables[column]; }
    };

    public static DefaultTableModel methodsDefaultModel = new DefaultTableModel( new Object[][] { {}, }, new String[] { "MCP Name", "SRG Name", "Obf Name", "SRG Descriptor", "Comment" })
    {
        private static final long serialVersionUID = 1L;
        boolean[]                 columnEditables  = new boolean[] { false, false, false, false, false };
        @SuppressWarnings("rawtypes")
        Class[]                   columnTypes      = new Class[] { String.class, String.class, String.class, String.class, String.class };

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; }

        @Override
        public boolean isCellEditable(int row, int column) { return columnEditables[column]; }
    };

    public static DefaultTableModel paramsDefaultModel = new DefaultTableModel( new Object[][] { {}, }, new String[] { "MCP Name", "SRG Name", "Type" })
    {
        private static final long serialVersionUID = 1L;
        boolean[]                 columnEditables  = new boolean[] { false, false, false };
        @SuppressWarnings("rawtypes")
        Class[]                   columnTypes      = new Class[] { String.class, String.class, String.class };

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; }

        @Override
        public boolean isCellEditable(int row, int column) { return columnEditables[column]; }
    };

    public static DefaultTableModel fieldsDefaultModel = new DefaultTableModel( new Object[][] { {}, }, new String[] { "MCP Name", "SRG Name", "Obf Name", "Comment" } )
    {
        private static final long serialVersionUID = 1L;
        boolean[]                 columnEditables  = new boolean[] { false, false, false, false };
        @SuppressWarnings("rawtypes")
        Class[]                   columnTypes      = new Class[] { String.class, String.class, String.class, String.class };

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; }

        @Override
        public boolean isCellEditable(int row, int column) { return columnEditables[column]; }
    };
    private JSplitPane splitMethods;
    private JButton btnGetVersions;
    // @formatter:on

    private void savePrefs()
    {
        for (int i = 0; i < Math.min(cmbFilter.getItemCount(), 20); i++)
            prefs.put(PREFS_KEY_FILTER + i, cmbFilter.getItemAt(i));

        if (tblClasses.getRowSorter().getSortKeys().size() > 0)
        {
            int i = tblClasses.getRowSorter().getSortKeys().get(0).getColumn() + 1;
            SortOrder order = tblClasses.getRowSorter().getSortKeys().get(0).getSortOrder();
            prefs.putInt(PREFS_KEY_CLASS_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
        }
        else
            prefs.putInt(PREFS_KEY_CLASS_SORT, 1);

        if (tblMethods.getRowSorter().getSortKeys().size() > 0)
        {
            int i = tblMethods.getRowSorter().getSortKeys().get(0).getColumn() + 1;
            SortOrder order = tblMethods.getRowSorter().getSortKeys().get(0).getSortOrder();
            prefs.putInt(PREFS_KEY_METHOD_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
        }
        else
            prefs.putInt(PREFS_KEY_METHOD_SORT, 1);

        if (tblParams.getRowSorter().getSortKeys().size() > 0)
        {
            int i = tblParams.getRowSorter().getSortKeys().get(0).getColumn() + 1;
            SortOrder order = tblParams.getRowSorter().getSortKeys().get(0).getSortOrder();
            prefs.putInt(PREFS_KEY_PARAM_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
        }
        else
            prefs.putInt(PREFS_KEY_PARAM_SORT, 1);

        if (tblFields.getRowSorter().getSortKeys().size() > 0)
        {
            int i = tblFields.getRowSorter().getSortKeys().get(0).getColumn() + 1;
            SortOrder order = tblFields.getRowSorter().getSortKeys().get(0).getSortOrder();
            prefs.putInt(PREFS_KEY_FIELD_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
        }
        else
            prefs.putInt(PREFS_KEY_FIELD_SORT, 1);
    }

    private void loadPrefs(boolean sortOnly)
    {
        if (!sortOnly)
        {
            DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) cmbFilter.getModel();
            for (int i = 0; i < 20; i++)
            {
                String item = prefs.get(PREFS_KEY_FILTER + i, " ");
                if (!item.equals(" "))
                {
                    if (model.getIndexOf(item) == -1)
                        cmbFilter.addItem(item);
                }
            }

            cmbFilter.setSelectedIndex(-1);

            if (cmbMappingVersion.getItemCount() > 0)
            {
                btnRefreshTables.setEnabled(true);
                cmbMappingVersion.setSelectedIndex(0);
            }
            else
                btnRefreshTables.setEnabled(false);
        }

        classSort.clear();
        methodSort.clear();
        paramSort.clear();
        fieldSort.clear();

        int i = prefs.getInt(PREFS_KEY_CLASS_SORT, 1);
        classSort.add(new RowSorter.SortKey(Math.abs(i) - 1, i > 0 ? SortOrder.ASCENDING : SortOrder.DESCENDING));
        tblClasses.getRowSorter().setSortKeys(classSort);

        i = prefs.getInt(PREFS_KEY_METHOD_SORT, 1);
        methodSort.add(new RowSorter.SortKey(Math.abs(i) - 1, i > 0 ? SortOrder.ASCENDING : SortOrder.DESCENDING));
        tblMethods.getRowSorter().setSortKeys(methodSort);

        i = prefs.getInt(PREFS_KEY_PARAM_SORT, 1);
        paramSort.add(new RowSorter.SortKey(Math.abs(i) - 1, i > 0 ? SortOrder.ASCENDING : SortOrder.DESCENDING));
        tblParams.getRowSorter().setSortKeys(paramSort);

        i = prefs.getInt(PREFS_KEY_FIELD_SORT, 1);
        fieldSort.add(new RowSorter.SortKey(Math.abs(i) - 1, i > 0 ? SortOrder.ASCENDING : SortOrder.DESCENDING));
        tblFields.getRowSorter().setSortKeys(fieldSort);
    }

    private void checkForUpdates()
    {
        versionChecker = new AppVersionChecker("MCP Mapping Viewer", VERSION_NUMBER, versionURL, mcfTopic,
                new String[] { "{appName} {oldVer} is out of date! Visit {updateURL} to download the latest release ({newVer})." },
                new String[] {
                        "{appName} {oldVer} is out of date! <br/><br/>Download the latest release ({newVer}) from <a href=\"{updateURL}\">{updateURL}</a>." },
                5000);
        if (!versionChecker.isCurrentVersion())
        {
            showHTMLDialog(MappingGui.this, versionChecker.getDialogMessage()[0], "An update is available", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args)
    {
        try
        {
            // Set System L&F
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Throwable e)
        {}
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    MappingGui window = new MappingGui();
                    window.frmMcpMappingViewer.setVisible(true);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    private static String getPrintableStackTrace(Throwable e, Set<StackTraceElement> stopAt)
    {
        String s = e.toString();
        int numPrinted = 0;
        for (StackTraceElement ste : e.getStackTrace())
        {
            boolean stopHere = false;
            if (stopAt.contains(ste) && numPrinted > 0)
                stopHere = true;
            else
            {
                s += "\n    at " + ste.toString();
                numPrinted++;
                if (ste.getClassName().startsWith("javax.swing."))
                    stopHere = true;
            }

            if (stopHere)
            {
                int numHidden = e.getStackTrace().length - numPrinted;
                s += "\n    ... " + numHidden + " more";
                break;
            }
        }
        return s;
    }

    private static String getStackTraceMessage(String prefix, Throwable e)
    {
        String s = prefix;

        s += "\n" + getPrintableStackTrace(e, Collections.<StackTraceElement> emptySet());
        while (e.getCause() != null)
        {
            Set<StackTraceElement> stopAt = new HashSet<StackTraceElement>(Arrays.asList(e.getStackTrace()));
            e = e.getCause();
            s += "\nCaused by: " + getPrintableStackTrace(e, stopAt);
        }
        return s;
    }

    /**
     * Create the application.
     */
    public MappingGui()
    {
        initialize();
        checkForUpdates();
    }

    public void setCsvFileEdited(boolean bol)
    {
        btnGetBotCommands.setEnabled(bol);
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize()
    {
        frmMcpMappingViewer = new JFrame();
        frmMcpMappingViewer.setIconImage(new ImageIcon(MappingGui.class.getResource("/bspkrs/mmv/gui/icon/bspkrs32.png")).getImage());
        frmMcpMappingViewer.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent arg0)
            {
                savePrefs();
            }
        });
        frmMcpMappingViewer.setTitle("MCP Mapping Viewer");
        frmMcpMappingViewer.setBounds(100, 100, 925, 621);
        frmMcpMappingViewer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmMcpMappingViewer.getContentPane().setLayout(new BorderLayout(0, 0));

        JSplitPane splitMain = new JSplitPane();
        splitMain.setBorder(null);
        splitMain.setDividerSize(3);
        splitMain.setResizeWeight(0.5);
        splitMain.setContinuousLayout(true);
        splitMain.setMinimumSize(new Dimension(179, 80));
        splitMain.setPreferredSize(new Dimension(179, 80));
        splitMain.setOrientation(JSplitPane.VERTICAL_SPLIT);

        JScrollPane scrlpnClasses = new JScrollPane();
        scrlpnClasses.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        splitMain.setLeftComponent(scrlpnClasses);

        tblClasses = new JTable();
        tblClasses.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrlpnClasses.setViewportView(tblClasses);
        tblClasses.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tblClasses.getSelectionModel().addListSelectionListener(new ClassTableSelectionListener(tblClasses));
        tblClasses.setAutoCreateRowSorter(true);
        tblClasses.setEnabled(false);
        tblClasses.setModel(classesDefaultModel);
        tblClasses.setFillsViewportHeight(true);
        tblClasses.setCellSelectionEnabled(true);
        frmMcpMappingViewer.getContentPane().add(splitMain, BorderLayout.CENTER);

        JSplitPane splitMembers = new JSplitPane();
        splitMembers.setBorder(null);
        splitMembers.setDividerSize(3);
        splitMembers.setResizeWeight(0.5);
        splitMembers.setOrientation(JSplitPane.VERTICAL_SPLIT);
        splitMain.setRightComponent(splitMembers);

        splitMethods = new JSplitPane();
        splitMethods.setBorder(null);
        splitMethods.setDividerSize(3);
        splitMethods.setResizeWeight(0.5);
        splitMembers.setLeftComponent(splitMethods);

        JScrollPane scrlpnMethods = new JScrollPane();
        scrlpnMethods.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        splitMethods.setLeftComponent(scrlpnMethods);

        tblMethods = new JTable();
        tblMethods.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblMethods.getSelectionModel().addListSelectionListener(new MethodTableSelectionListener(tblMethods));
        tblMethods.setCellSelectionEnabled(true);
        tblMethods.setFillsViewportHeight(true);
        tblMethods.setAutoCreateRowSorter(true);
        tblMethods.setEnabled(false);
        tblMethods.setModel(methodsDefaultModel);
        scrlpnMethods.setViewportView(tblMethods);

        JScrollPane scrlpnParams = new JScrollPane();
        scrlpnParams.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        splitMethods.setRightComponent(scrlpnParams);

        tblParams = new JTable();
        tblParams.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblParams.setCellSelectionEnabled(true);
        tblParams.setFillsViewportHeight(true);
        tblParams.setAutoCreateRowSorter(true);
        tblParams.setEnabled(false);
        tblParams.setModel(paramsDefaultModel);
        scrlpnParams.setViewportView(tblParams);

        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                splitMethods.setDividerLocation(0.8);
            }
        });

        JScrollPane scrlpnFields = new JScrollPane();
        scrlpnFields.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        splitMembers.setRightComponent(scrlpnFields);

        tblFields = new JTable();
        tblFields.setCellSelectionEnabled(true);
        tblFields.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblFields.setAutoCreateRowSorter(true);
        tblFields.setEnabled(false);
        tblFields.setModel(fieldsDefaultModel);
        tblFields.setFillsViewportHeight(true);
        scrlpnFields.setViewportView(tblFields);

        JPanel pnlHeader = new JPanel();
        frmMcpMappingViewer.getContentPane().add(pnlHeader, BorderLayout.NORTH);
        pnlHeader.setLayout(new BorderLayout(0, 0));

        JPanel pnlControls = new JPanel();
        pnlHeader.add(pnlControls, BorderLayout.NORTH);
        pnlControls.setSize(new Dimension(0, 40));
        pnlControls.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 2));

        cmbMappingVersion = new JComboBox<String>(new DefaultComboBoxModel<String>());
        cmbMappingVersion.setEditable(false);
        cmbMappingVersion.setPreferredSize(new Dimension(320, 20));
        cmbMappingVersion.addItemListener(new MappingVersionsComboItemChanged());

        JLabel lblMappingVersion = new JLabel("Mapping Version");
        pnlControls.add(lblMappingVersion);
        pnlControls.add(cmbMappingVersion);

        btnGetVersions = new JButton("Get Versions");
        btnGetVersions.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    cmbMappingVersion.removeAllItems();
                    for (String s : versionFetcher.getVersions(chkForceRefresh.isSelected()))
                    {
                        cmbMappingVersion.addItem(s);
                    }
                }
                catch (IOException exc)
                {}
            }
        });
        pnlControls.add(btnGetVersions);

        btnRefreshTables = new JButton("Load Mappings");
        btnRefreshTables.setEnabled(false);
        btnRefreshTables.addActionListener(new RefreshActionListener());
        pnlControls.add(btnRefreshTables);

        chkForceRefresh = new JCheckBox("Force reload");
        chkForceRefresh.setToolTipText("Force a reload from the MCP conf folder files instead of the session cache.");
        pnlControls.add(chkForceRefresh);

        pnlProgress = new JPanel();
        pnlProgress.setVisible(false);
        pnlHeader.add(pnlProgress, BorderLayout.SOUTH);
        pnlProgress.setLayout(new BorderLayout(0, 0));

        progressBar = new JProgressBar();
        progressBar.setStringPainted(true);
        progressBar.setString("");
        progressBar.setForeground(UIManager.getColor("ProgressBar.foreground"));
        pnlProgress.add(progressBar);

        pnlFilter = new JPanel();
        FlowLayout flowLayout = (FlowLayout) pnlFilter.getLayout();
        flowLayout.setVgap(2);
        flowLayout.setAlignment(FlowLayout.LEFT);
        pnlFilter.setVisible(true);
        pnlHeader.add(pnlFilter, BorderLayout.CENTER);

        JLabel lblFilter = new JLabel("Search");
        pnlFilter.add(lblFilter);

        cmbFilter = new JComboBox<String>();
        cmbFilter.setEditable(true);
        cmbFilter.setPreferredSize(new Dimension(300, 20));
        cmbFilter.setMaximumRowCount(10);
        pnlFilter.add(cmbFilter);

        btnSearch = new JButton("Go");
        btnSearch.setToolTipText("");
        btnSearch.addActionListener(new SearchActionListener());
        pnlFilter.add(btnSearch);
        cmbFilter.setEnabled(false);
        cmbFilter.addActionListener(new FilterComboTextEdited());
        cmbFilter.getEditor().getEditorComponent().addFocusListener(new FocusAdapter()
        {
            @Override
            public void focusGained(FocusEvent e)
            {
                cmbFilter.getEditor().selectAll();
            }
        });
        cmbFilter.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                if (e.getKeyCode() == KeyEvent.VK_ENTER)
                    btnSearch.doClick();
            }
        });
        btnSearch.setEnabled(false);

        JLabel lblSearchInfo = new JLabel("A note on search");
        lblSearchInfo.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                String message = "Search is global and returns a set of classes that contain a match for the input. \n" +
                        "Search is case sensitive!\n\nData elements searched on:\n" +
                        "Classes:\n    ~ Pkg Name\n    ~ SRG Name\n    ~ Obf Name\n" +
                        "Methods/Fields:\n    ~ SRG Name\n    ~ Obf Name\n    ~ MCP Name\n    ~ Comment\n\n" +
                        "Parameters are not currently searchable.";
                JOptionPane.showMessageDialog(MappingGui.this, message, "Search Info", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        lblSearchInfo.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        lblSearchInfo.setForeground(Color.BLUE);
        pnlFilter.add(lblSearchInfo);

        JSeparator separator = new JSeparator();
        separator.setPreferredSize(new Dimension(1, 12));
        separator.setOrientation(SwingConstants.VERTICAL);
        pnlFilter.add(separator);

        JLabel lblAbout = new JLabel("About");
        pnlFilter.add(lblAbout);
        lblAbout.setForeground(Color.BLUE);
        lblAbout.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        JSeparator separator_1 = new JSeparator();
        separator_1.setPreferredSize(new Dimension(1, 12));
        separator_1.setOrientation(SwingConstants.VERTICAL);
        pnlFilter.add(separator_1);

        btnGetBotCommands = new JButton("Get Command List");
        btnGetBotCommands.setToolTipText("Exports to the system clipboard a listing of MCPBot commands for any edits you have made in the GUI.");
        btnGetBotCommands.setEnabled(false);
        btnGetBotCommands.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                String commands = currentLoader.getBotCommands(chkClearOnCopy.isSelected());
                if (commands != null && !commands.isEmpty())
                {
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(commands), null);
                    JOptionPane.showMessageDialog(MappingGui.this, "Commands copied to clipboard: \n" + commands, "MMV - MCPBot Commands",
                            JOptionPane.INFORMATION_MESSAGE);

                    if (chkClearOnCopy.isSelected())
                        btnGetBotCommands.setEnabled(false);
                }
                else
                    JOptionPane.showMessageDialog(MappingGui.this, "No commands to copy.", "MMV - MCPBot Commands", JOptionPane.INFORMATION_MESSAGE);

                chkClearOnCopy.setSelected(false);
            }
        });
        pnlFilter.add(btnGetBotCommands);

        chkClearOnCopy = new JCheckBox("Clear");
        chkClearOnCopy.setToolTipText("Whether or not to clear the MCPBot command list when the button is clicked.");
        pnlFilter.add(chkClearOnCopy);

        lblAbout.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                MappingGui.class.getClassLoader();
                String imgsrc = MappingGui.class.getResource("/bspkrs/mmv/gui/icon/bspkrs.png").toString();
                String year = new SimpleDateFormat("yyyy").format(new Date());
                String message = "<center><img src=\"" + imgsrc + "\"/><br/>" +
                        "MCP Mapping Viewer v" + VERSION_NUMBER + "<br/>" +
                        "Copyright (C) 2013-" + year + " bspkrs<br/>" +
                        "Portions Copyright (C) 2013 Alex \"immibis\" Campbell<br/><br/>" +
                        "Author: bspkrs<br/>" +
                        "Credits: immibis (for <a href=\"https://github.com/immibis/bearded-octo-nemesis\">BON</a> code), " +
                        "Searge et al (for <a href=\"http://mcp.ocean-labs.de\">MCP</a>)<br/><br/>" +
                        "<a href=\"" + mcfTopic + "\">MCF Thread</a><br/>" +
                        "<a href=\"https://github.com/bspkrs/MCPMappingViewer\">Github Repo</a><br/>" +
                        "<a href=\"https://github.com/bspkrs/MCPMappingViewer/blob/master/change.log\">Change Log</a><br/>" +
                        "<a href=\"http://bspk.rs/MC/MCPMappingViewer/index.html\">Binary Downloads</a><br/>" +
                        "<a href=\"https://raw.githubusercontent.com/bspkrs/MCPMappingViewer/master/LICENSE\">License</a><br/>" +
                        "<a href=\"https://raw.githubusercontent.com/google/gson/master/LICENSE\">GSON License</a><br/>" +
                        "<a href=\"https://twitter.com/bspkrs\">bspkrs on Twitter</a></center>";
                showHTMLDialog(MappingGui.this, message, "About MCP Mapping Viewer", JOptionPane.PLAIN_MESSAGE);
            }
        });

        addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                savePrefs();
            }
        });

        try
        {
            loadPrefs(false);
        }
        catch (Throwable e)
        {
            String s = getStackTraceMessage(
                    "An error has occurred - give bspkrs this stack trace (which has been copied to the clipboard) if the error continues to occur on launch.\n",
                    e);

            System.err.println(s);

            final String errMsg = s;
            SwingUtilities.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    progressBar.setString(" ");
                    progressBar.setValue(0);

                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(errMsg), null);
                    JOptionPane.showMessageDialog(MappingGui.this, errMsg, "MMV - Error", JOptionPane.ERROR_MESSAGE);
                }
            });
        }
    }

    class MappingVersionsComboItemChanged implements ItemListener
    {
        @Override
        public void itemStateChanged(ItemEvent e)
        {
            if (e.getStateChange() == ItemEvent.SELECTED)
            {
                @SuppressWarnings("unchecked")
                JComboBox<String> cmb = (JComboBox<String>) e.getSource();
                btnRefreshTables.setEnabled(cmb.getItemCount() > 0);
            }
        }
    }

    class FilterComboTextEdited implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if (e.getActionCommand().equals("comboBoxEdited"))
            {
                String filterText = cmbFilter.getSelectedItem().toString();

                if (filterText == null || filterText.trim().isEmpty())
                    return;

                DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) cmbFilter.getModel();

                if (model.getIndexOf(filterText) != -1)
                    model.removeElement(filterText);

                cmbFilter.insertItemAt(filterText, 0);
                cmbFilter.setSelectedItem(filterText);
            }
        }
    }

    class ClassTableSelectionListener implements ListSelectionListener
    {
        private final JTable table;

        public ClassTableSelectionListener(JTable table)
        {
            this.table = table;
        }

        @Override
        public void valueChanged(ListSelectionEvent e)
        {
            if (!e.getValueIsAdjusting() && !table.getModel().equals(classesDefaultModel))
            {
                int i = table.getSelectedRow();
                if (i > -1)
                {
                    savePrefs();
                    String pkg = (String) table.getModel().getValueAt(table.convertRowIndexToModel(i), 0);
                    String name = (String) table.getModel().getValueAt(table.convertRowIndexToModel(i), 1);
                    tblMethods.setModel(currentLoader.getMethodModel(pkg + "/" + name));
                    tblMethods.setEnabled(true);
                    tblFields.setModel(currentLoader.getFieldModel(pkg + "/" + name));
                    tblFields.setEnabled(true);
                    tblParams.setModel(paramsDefaultModel);
                    tblParams.setEnabled(true);
                    new TableColumnAdjuster(tblMethods).adjustColumns();
                    new TableColumnAdjuster(tblFields).adjustColumns();
                    loadPrefs(true);
                }
                else
                {
                    tblMethods.setModel(methodsDefaultModel);
                    tblMethods.setEnabled(false);
                    tblFields.setModel(fieldsDefaultModel);
                    tblFields.setEnabled(false);
                    tblParams.setModel(paramsDefaultModel);
                    tblParams.setEnabled(false);
                }
            }
        }
    }

    class MethodTableSelectionListener implements ListSelectionListener
    {
        private final JTable table;

        public MethodTableSelectionListener(JTable table)
        {
            this.table = table;
        }

        @Override
        public void valueChanged(ListSelectionEvent e)
        {
            if (!e.getValueIsAdjusting() && !table.getModel().equals(methodsDefaultModel))
            {
                int i = table.getSelectedRow();
                if (i > -1)
                {
                    savePrefs();
                    String name = (String) table.getModel().getValueAt(table.convertRowIndexToModel(i), 1);
                    tblParams.setModel(currentLoader.getParamModel(name));
                    tblParams.setEnabled(true);
                    new TableColumnAdjuster(tblParams).adjustColumns();
                    loadPrefs(true);
                }
                else
                {
                    tblParams.setModel(paramsDefaultModel);
                    tblParams.setEnabled(false);
                }
            }
        }
    }

    class SearchActionListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if (curTask != null && curTask.isAlive() || cmbFilter.getItemCount() == 0)
                return;

            String filterText = cmbFilter.getSelectedItem().toString();

            if (filterText != null && !filterText.trim().isEmpty())
            {
                DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) cmbFilter.getModel();

                if (model.getIndexOf(filterText) != -1)
                    model.removeElement(filterText);

                cmbFilter.insertItemAt(filterText, 0);
                cmbFilter.setSelectedItem(filterText);
            }

            savePrefs();

            cmbFilter.setEnabled(false);
            btnSearch.setEnabled(false);
            pnlProgress.setVisible(true);
            tblClasses.setModel(classesDefaultModel);
            tblClasses.setEnabled(false);
            tblMethods.setModel(methodsDefaultModel);
            tblMethods.setEnabled(false);
            tblParams.setModel(paramsDefaultModel);
            tblParams.setEnabled(false);
            tblFields.setModel(fieldsDefaultModel);
            tblFields.setEnabled(false);

            loadPrefs(true);

            curTask = new Thread()
            {
                @Override
                public void run()
                {
                    boolean crashed = false;

                    try
                    {
                        IProgressListener progress = new IProgressListener()
                        {
                            private String currentText;

                            @Override
                            public void start(final int max, final String text)
                            {
                                currentText = text.equals("") ? " " : text;
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setString(currentText);
                                        if (max >= 0)
                                            progressBar.setMaximum(max);
                                        progressBar.setValue(0);
                                    }
                                });
                            }

                            @Override
                            public void set(final int value)
                            {
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setValue(value);
                                    }
                                });
                            }

                            @Override
                            public void set(final int value, final String text)
                            {
                                currentText = text.equals("") ? " " : text;
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setValue(value);
                                        progressBar.setString(currentText);
                                    }
                                });
                            }

                            @Override
                            public void setMax(final int max)
                            {
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setMaximum(max);
                                    }
                                });
                            }
                        };

                        progress.start(0, "Searching MCP objects for input");
                        tblClasses.setModel(currentLoader.getSearchResults(cmbFilter.getSelectedItem().toString(), progress));
                        tblClasses.setEnabled(true);
                        new TableColumnAdjuster(tblClasses).adjustColumns();
                        loadPrefs(true);

                        if (tblClasses.getRowCount() > 0)
                        {
                            String pkg = (String) tblClasses.getModel().getValueAt(0, 0);
                            String name = (String) tblClasses.getModel().getValueAt(0, 1);
                            tblMethods.setModel(currentLoader.getMethodModel(pkg + "/" + name));
                            tblMethods.setEnabled(true);
                            tblFields.setModel(currentLoader.getFieldModel(pkg + "/" + name));
                            tblFields.setEnabled(true);
                            tblParams.setModel(paramsDefaultModel);
                            tblParams.setEnabled(true);
                            new TableColumnAdjuster(tblMethods).adjustColumns();
                            new TableColumnAdjuster(tblFields).adjustColumns();
                            loadPrefs(true);

                            if (cmbFilter.getSelectedItem().toString().trim().startsWith("field") && tblFields.getRowCount() > 0)
                            {
                                for (int i = 0; i < tblFields.getRowCount(); i++)
                                {
                                    if (((String) tblFields.getModel().getValueAt(i, 1)).contains(cmbFilter.getSelectedItem().toString()))
                                    {
                                        final int rowIndex = i;
                                        tblFields.setRowSelectionInterval(rowIndex, rowIndex);
                                        tblFields.setColumnSelectionInterval(1, 1);
                                        tblFields.requestFocus();

                                        SwingUtilities.invokeLater(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                tblFields.scrollRectToVisible(tblFields.getCellRect(rowIndex, 0, true));
                                            }
                                        });

                                        break;
                                    }
                                }
                            }
                            else if (cmbFilter.getSelectedItem().toString().trim().startsWith("func") && tblMethods.getRowCount() > 0)
                            {
                                for (int i = 0; i < tblMethods.getRowCount(); i++)
                                {
                                    if (((String) tblMethods.getModel().getValueAt(i, 1)).contains(cmbFilter.getSelectedItem().toString()))
                                    {
                                        final int rowIndex = i;
                                        tblMethods.setRowSelectionInterval(rowIndex, rowIndex);
                                        tblMethods.setColumnSelectionInterval(1, 1);
                                        tblMethods.requestFocus();

                                        SwingUtilities.invokeLater(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                tblMethods.scrollRectToVisible(tblMethods.getCellRect(rowIndex, 0, true));
                                            }
                                        });

                                        break;
                                    }
                                }

                            }
                        }

                        loadPrefs(true);
                    }
                    catch (Exception e)
                    {
                        String s = getStackTraceMessage(
                                "An error has occurred - give bspkrs this stack trace (which has been copied to the clipboard)\n", e);

                        System.err.println(s);

                        crashed = true;

                        final String errMsg = s;
                        SwingUtilities.invokeLater(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                progressBar.setString(" ");
                                progressBar.setValue(0);

                                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(errMsg), null);
                                JOptionPane.showMessageDialog(MappingGui.this, errMsg, "MMV - Error", JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                    finally
                    {
                        if (!crashed)
                        {
                            SwingUtilities.invokeLater(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    progressBar.setString(" ");
                                    progressBar.setValue(0);
                                    cmbFilter.setEnabled(true);
                                }
                            });
                        }
                        pnlProgress.setVisible(false);
                        cmbFilter.setEnabled(true);
                        btnSearch.setEnabled(true);
                    }
                }
            };

            curTask.start();
        }
    }

    class RefreshActionListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if (curTask != null && curTask.isAlive())
                return;

            final String mappingVersion = (String) cmbMappingVersion.getSelectedItem();
            savePrefs();

            pnlFilter.setVisible(false);
            pnlProgress.setVisible(true);
            tblClasses.setModel(classesDefaultModel);
            tblClasses.setEnabled(false);
            tblMethods.setModel(methodsDefaultModel);
            tblMethods.setEnabled(false);
            tblParams.setModel(paramsDefaultModel);
            tblParams.setEnabled(false);
            tblFields.setModel(fieldsDefaultModel);
            tblFields.setEnabled(false);

            loadPrefs(true);

            curTask = new Thread()
            {
                @Override
                public void run()
                {
                    boolean crashed = false;

                    try
                    {
                        IProgressListener progress = new IProgressListener()
                        {
                            private String currentText;

                            @Override
                            public void start(final int max, final String text)
                            {
                                currentText = text.equals("") ? " " : text;
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setString(currentText);
                                        if (max >= 0)
                                            progressBar.setMaximum(max);
                                        progressBar.setValue(0);
                                    }
                                });
                            }

                            @Override
                            public void set(final int value)
                            {
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setValue(value);
                                    }
                                });
                            }

                            @Override
                            public void set(final int value, final String text)
                            {
                                currentText = text.equals("") ? " " : text;
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setValue(value);
                                        progressBar.setString(currentText);
                                    }
                                });
                            }

                            @Override
                            public void setMax(final int max)
                            {
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        progressBar.setMaximum(max);
                                    }
                                });
                            }
                        };

                        if (!mcpInstances.containsKey(mappingVersion) || chkForceRefresh.isSelected())
                        {
                            progress.start(0, "Reading MCP configuration");
                            currentLoader = new McpMappingLoader(MappingGui.this, mappingVersion, progress);
                            mcpInstances.put(mappingVersion, currentLoader);
                            chkForceRefresh.setSelected(false);
                        }
                        else
                            currentLoader = mcpInstances.get(mappingVersion);

                        tblClasses.setModel(currentLoader.getClassModel());
                        tblClasses.setEnabled(true);
                        new TableColumnAdjuster(tblClasses).adjustColumns();
                        loadPrefs(true);
                    }
                    catch (CantLoadMCPMappingException e)
                    {
                        String s = getStackTraceMessage("", e);

                        System.err.println(s);

                        crashed = true;

                        final String errMsg = s;
                        SwingUtilities.invokeLater(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                progressBar.setString(" ");
                                progressBar.setValue(0);

                                JOptionPane.showMessageDialog(MappingGui.this, errMsg, "MMV - Error", JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                    catch (Exception e)
                    {
                        String s = getStackTraceMessage(
                                "An error has occurred - give bspkrs this stack trace (which has been copied to the clipboard)\n", e);

                        System.err.println(s);

                        crashed = true;

                        final String errMsg = s;
                        SwingUtilities.invokeLater(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                progressBar.setString(" ");
                                progressBar.setValue(0);

                                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(errMsg), null);
                                JOptionPane.showMessageDialog(MappingGui.this, errMsg, "MMV - Error", JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                    finally
                    {
                        if (!crashed)
                        {
                            SwingUtilities.invokeLater(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    progressBar.setString(" ");
                                    progressBar.setValue(0);
                                    cmbFilter.setEnabled(true);
                                }
                            });
                        }
                        pnlProgress.setVisible(false);
                        pnlFilter.setVisible(true);
                        cmbFilter.setEnabled(true);
                        btnSearch.setEnabled(true);
                        //                        btnSave.setEnabled(currentLoader.hasPendingEdits());
                        btnGetBotCommands.setEnabled(currentLoader.hasPendingCommands());
                    }
                }
            };

            curTask.start();
        }
    }

    public static void showHTMLDialog(Component parentComponent, Object message, String title, int messageType)
    {
        JLabel label = new JLabel();
        Font font = label.getFont();

        StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";");
        style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";");
        style.append("font-size:" + font.getSize() + "pt;");

        JEditorPane ep = new JEditorPane("text/html", "<html><body style=\"" + style + "\">" + message.toString() + "</body></html>");

        ep.addHyperlinkListener(new HyperlinkListener()
        {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e)
            {
                if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED))
                {
                    try
                    {
                        Desktop.getDesktop().browse(e.getURL().toURI());
                    }
                    catch (Throwable ignore)
                    {}
                }
            }
        });
        // Dunno why, but if I do this the About dialog no longer gets cut off...
        ep.setSize(100, 100);
        ep.setEditable(false);
        ep.setBackground(label.getBackground());
        JOptionPane.showMessageDialog(parentComponent, ep, title, messageType);
    }
}
/*
 * As found at http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
 * on 11/12/2013
 */
package bspkrs.mmv.gui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

/*
 *	Class to manage the widths of colunmns in a table.
 *
 *  Various properties control how the width of the column is calculated.
 *  Another property controls whether column width calculation should be dynamic.
 *  Finally, various Actions will be added to the table to allow the user
 *  to customize the functionality.
 *
 *  This class was designed to be used with tables that use an auto resize mode
 *  of AUTO_RESIZE_OFF. With all other modes you are constrained as the width
 *  of the columns must fit inside the table. So if you increase one column, one
 *  or more of the other columns must decrease. Because of this the resize mode
 *  of RESIZE_ALL_COLUMNS will work the best.
 */

public class TableColumnAdjuster implements PropertyChangeListener, TableModelListener
{
    private JTable                    table;
    private int                       spacing;
    private boolean                   isColumnHeaderIncluded;
    private boolean                   isColumnDataIncluded;
    private boolean                   isOnlyAdjustLarger;
    private boolean                   isDynamicAdjustment;
    private Map<TableColumn, Integer> columnSizes = new HashMap<TableColumn, Integer>();

    /*
     *  Specify the table and use default spacing
     */
    public TableColumnAdjuster(JTable table)
    {
        this(table, 6);
    }

    /*
     *  Specify the table and spacing
     */
    public TableColumnAdjuster(JTable table, int spacing)
    {
        this.table = table;
        this.spacing = spacing;
        setColumnHeaderIncluded(true);
        setColumnDataIncluded(true);
        setOnlyAdjustLarger(true);
        setDynamicAdjustment(false);
        installActions();
    }

    /*
     *  Adjust the widths of all the columns in the table
     */
    public void adjustColumns()
    {
        TableColumnModel tcm = table.getColumnModel();

        for (int i = 0; i < tcm.getColumnCount(); i++)
        {
            adjustColumn(i);
        }
    }

    /*
     *  Adjust the width of the specified column in the table
     */
    public void adjustColumn(final int column)
    {
        TableColumn tableColumn = table.getColumnModel().getColumn(column);

        if (!tableColumn.getResizable())
            return;

        int columnHeaderWidth = getColumnHeaderWidth(column);
        int columnDataWidth = getColumnDataWidth(column);
        int preferredWidth = Math.max(columnHeaderWidth, columnDataWidth);

        updateTableColumn(column, preferredWidth);
    }

    /*
     *  Calculated the width based on the column name
     */
    private int getColumnHeaderWidth(int column)
    {
        if (!isColumnHeaderIncluded)
            return 0;

        TableColumn tableColumn = table.getColumnModel().getColumn(column);
        Object value = tableColumn.getHeaderValue();
        TableCellRenderer renderer = tableColumn.getHeaderRenderer();

        if (renderer == null)
        {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, column);
        return c.getPreferredSize().width;
    }

    /*
     *  Calculate the width based on the widest cell renderer for the
     *  given column.
     */
    private int getColumnDataWidth(int column)
    {
        if (!isColumnDataIncluded)
            return 0;

        int preferredWidth = 0;
        int maxWidth = table.getColumnModel().getColumn(column).getMaxWidth();

        for (int row = 0; row < table.getRowCount(); row++)
        {
            preferredWidth = Math.max(preferredWidth, getCellDataWidth(row, column));

            //  We've exceeded the maximum width, no need to check other rows

            if (preferredWidth >= maxWidth)
                break;
        }

        return preferredWidth;
    }

    /*
     *  Get the preferred width for the specified cell
     */
    private int getCellDataWidth(int row, int column)
    {
        //  Inovke the renderer for the cell to calculate the preferred width

        TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
        Component c = table.prepareRenderer(cellRenderer, row, column);
        int width = c.getPreferredSize().width + table.getIntercellSpacing().width;

        return width;
    }

    /*
     *  Update the TableColumn with the newly calculated width
     */
    private void updateTableColumn(int column, int width)
    {
        final TableColumn tableColumn = table.getColumnModel().getColumn(column);

        if (!tableColumn.getResizable())
            return;

        width += spacing;

        //  Don't shrink the column width

        if (isOnlyAdjustLarger)
        {
            width = Math.max(width, tableColumn.getPreferredWidth());
        }

        columnSizes.put(tableColumn, new Integer(tableColumn.getWidth()));
        table.getTableHeader().setResizingColumn(tableColumn);
        tableColumn.setWidth(width);
    }

    /*
     *  Restore the widths of the columns in the table to its previous width
     */
    public void restoreColumns()
    {
        TableColumnModel tcm = table.getColumnModel();

        for (int i = 0; i < tcm.getColumnCount(); i++)
        {
            restoreColumn(i);
        }
    }

    /*
     *  Restore the width of the specified column to its previous width
     */
    private void restoreColumn(int column)
    {
        TableColumn tableColumn = table.getColumnModel().getColumn(column);
        Integer width = columnSizes.get(tableColumn);

        if (width != null)
        {
            table.getTableHeader().setResizingColumn(tableColumn);
            tableColumn.setWidth(width.intValue());
        }
    }

    /*
     *	Indicates whether to include the header in the width calculation
     */
    public void setColumnHeaderIncluded(boolean isColumnHeaderIncluded)
    {
        this.isColumnHeaderIncluded = isColumnHeaderIncluded;
    }

    /*
     *	Indicates whether to include the model data in the width calculation
     */
    public void setColumnDataIncluded(boolean isColumnDataIncluded)
    {
        this.isColumnDataIncluded = isColumnDataIncluded;
    }

    /*
     *	Indicates whether columns can only be increased in size
     */
    public void setOnlyAdjustLarger(boolean isOnlyAdjustLarger)
    {
        this.isOnlyAdjustLarger = isOnlyAdjustLarger;
    }

    /*
     *  Indicate whether changes to the model should cause the width to be
     *  dynamically recalculated.
     */
    public void setDynamicAdjustment(boolean isDynamicAdjustment)
    {
        //  May need to add or remove the TableModelListener when changed

        if (this.isDynamicAdjustment != isDynamicAdjustment)
        {
            if (isDynamicAdjustment)
            {
                table.addPropertyChangeListener(this);
                table.getModel().addTableModelListener(this);
            }
            else
            {
                table.removePropertyChangeListener(this);
                table.getModel().removeTableModelListener(this);
            }
        }

        this.isDynamicAdjustment = isDynamicAdjustment;
    }

    //
    //  Implement the PropertyChangeListener
    //
    @Override
    public void propertyChange(PropertyChangeEvent e)
    {
        //  When the TableModel changes we need to update the listeners
        //  and column widths

        if ("model".equals(e.getPropertyName()))
        {
            TableModel model = (TableModel) e.getOldValue();
            model.removeTableModelListener(this);

            model = (TableModel) e.getNewValue();
            model.addTableModelListener(this);
            adjustColumns();
        }
    }

    //
    //  Implement the TableModelListener
    //
    @Override
    public void tableChanged(TableModelEvent e)
    {
        if (!isColumnDataIncluded)
            return;

        //  A cell has been updated

        if (e.getType() == TableModelEvent.UPDATE)
        {
            int column = table.convertColumnIndexToView(e.getColumn());

            //  Only need to worry about an increase in width for this cell

            if (isOnlyAdjustLarger)
            {
                int row = e.getFirstRow();
                TableColumn tableColumn = table.getColumnModel().getColumn(column);

                if (tableColumn.getResizable())
                {
                    int width = getCellDataWidth(row, column);
                    updateTableColumn(column, width);
                }
            }

            //	Could be an increase of decrease so check all rows

            else
            {
                adjustColumn(column);
            }
        }

        //  The update affected more than one column so adjust all columns

        else
        {
            adjustColumns();
        }
    }

    /*
     *  Install Actions to give user control of certain functionality.
     */
    private void installActions()
    {
        installColumnAction(true, true, "adjustColumn", "control ADD");
        installColumnAction(false, true, "adjustColumns", "control shift ADD");
        installColumnAction(true, false, "restoreColumn", "control SUBTRACT");
        installColumnAction(false, false, "restoreColumns", "control shift SUBTRACT");

        installToggleAction(true, false, "toggleDynamic", "control MULTIPLY");
        installToggleAction(false, true, "toggleLarger", "control DIVIDE");
    }

    /*
     *  Update the input and action maps with a new ColumnAction
     */
    private void installColumnAction(
            boolean isSelectedColumn, boolean isAdjust, String key, String keyStroke)
    {
        Action action = new ColumnAction(isSelectedColumn, isAdjust);
        KeyStroke ks = KeyStroke.getKeyStroke(keyStroke);
        table.getInputMap().put(ks, key);
        table.getActionMap().put(key, action);
    }

    /*
     *  Update the input and action maps with new ToggleAction
     */
    private void installToggleAction(
            boolean isToggleDynamic, boolean isToggleLarger, String key, String keyStroke)
    {
        Action action = new ToggleAction(isToggleDynamic, isToggleLarger);
        KeyStroke ks = KeyStroke.getKeyStroke(keyStroke);
        table.getInputMap().put(ks, key);
        table.getActionMap().put(key, action);
    }

    /*
     *  Action to adjust or restore the width of a single column or all columns
     */
    class ColumnAction extends AbstractAction
    {
        private static final long serialVersionUID = 1L;
        private boolean           isSelectedColumn;
        private boolean           isAdjust;

        public ColumnAction(boolean isSelectedColumn, boolean isAdjust)
        {
            this.isSelectedColumn = isSelectedColumn;
            this.isAdjust = isAdjust;
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            //  Handle selected column(s) width change actions

            if (isSelectedColumn)
            {
                int[] columns = table.getSelectedColumns();

                for (int i = 0; i < columns.length; i++)
                {
                    if (isAdjust)
                        adjustColumn(columns[i]);
                    else
                        restoreColumn(columns[i]);
                }
            }
            else
            {
                if (isAdjust)
                    adjustColumns();
                else
                    restoreColumns();
            }
        }
    }

    /*
     *  Toggle properties of the TableColumnAdjuster so the user can
     *  customize the functionality to their preferences
     */
    class ToggleAction extends AbstractAction
    {
        private static final long serialVersionUID = 1L;
        private boolean           isToggleDynamic;
        private boolean           isToggleLarger;

        public ToggleAction(boolean isToggleDynamic, boolean isToggleLarger)
        {
            this.isToggleDynamic = isToggleDynamic;
            this.isToggleLarger = isToggleLarger;
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            if (isToggleDynamic)
            {
                setDynamicAdjustment(!isDynamicAdjustment);
                return;
            }

            if (isToggleLarger)
            {
                setOnlyAdjustLarger(!isOnlyAdjustLarger);
                return;
            }
        }
    }
}
/*
 * Copyright (C) 2014 bspkrs
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package bspkrs.mmv.version;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.prefs.Preferences;

public class AppVersionChecker
{
    private URL               versionURL;
    private final String      appName;
    private String            newVersion;
    private final String      currentVersion;
    private String            updateURL;
    private String[]          logMsg;
    private String[]          dialogMsg;
    private final Preferences versionCheckTracker;
    private final String      LAST_VERSION_FOUND  = "lastversionfound";
    private final String      RUNS_SINCE_LAST_MSG = "runs_since_last_message";
    private final String      CHECK_ERROR         = "check_error";
    private String            lastNewVersionFound;
    private final boolean     errorDetected;
    private int               runsSinceLastMessage;

    public AppVersionChecker(String appName, String currentVersion, String versionURL, String updateURL, String[] logMsg, String[] dialogMsg, int timeoutMS)
    {
        this.appName = appName;
        this.currentVersion = currentVersion;
        this.updateURL = updateURL;
        this.logMsg = logMsg;
        this.dialogMsg = dialogMsg;

        try
        {
            if (versionURL.startsWith("http://dl.dropboxusercontent.com"))
                versionURL = versionURL.replaceFirst("http", "https");

            this.versionURL = new URL(versionURL);
        }
        catch (Throwable ignore)
        {}

        String[] versionLines = loadTextFromURL(this.versionURL, new String[] { CHECK_ERROR }, timeoutMS);

        if ((versionLines.length == 0) || versionLines[0].trim().equals("<html>"))
            newVersion = CHECK_ERROR;
        else
            newVersion = versionLines[0].trim();

        errorDetected = newVersion.equals(CHECK_ERROR);

        versionCheckTracker = Preferences.userNodeForPackage(AppVersionChecker.class);

        lastNewVersionFound = versionCheckTracker.get(LAST_VERSION_FOUND, currentVersion);

        if (lastNewVersionFound.equals("<html>"))
            lastNewVersionFound = currentVersion;

        runsSinceLastMessage = versionCheckTracker.getInt(RUNS_SINCE_LAST_MSG, 0);

        if (errorDetected)
            newVersion = lastNewVersionFound;

        if (!errorDetected && !isCurrentVersion(lastNewVersionFound, newVersion))
        {
            runsSinceLastMessage = 0;
            lastNewVersionFound = newVersion;
        }
        else
            runsSinceLastMessage = runsSinceLastMessage % 10;

        versionCheckTracker.putInt(RUNS_SINCE_LAST_MSG, runsSinceLastMessage + 1);
        versionCheckTracker.put(LAST_VERSION_FOUND, lastNewVersionFound);

        // Override instantiated updateURL with second line of version file if it exists and is non-blank
        if ((versionLines.length > 1) && (versionLines[1].trim().length() != 0))
            this.updateURL = versionLines[1];

        setLogMessage(logMsg);
        setDialogMessage(dialogMsg);
    }

    public AppVersionChecker(String appName, String oldVer, String versionURL, String updateURL)
    {
        this(appName, oldVer, versionURL, updateURL, new String[] { "{appName} {oldVer} is out of date! Visit {updateURL} to download the latest release ({newVer})." }, new String[] { "{appName} {newVer} is out! Download the latest from {updateURL}" }, 5000);
    }

    public void checkVersionWithLogging()
    {
        if (!isCurrentVersion(currentVersion, newVersion))
            for (String msg : logMsg)
                System.out.println(msg);
    }

    public void setLogMessage(String[] logMsg)
    {
        this.logMsg = logMsg;

        for (int i = 0; i < this.logMsg.length; i++)
            this.logMsg[i] = replaceAllTags(this.logMsg[i]);
    }

    public void setDialogMessage(String[] dialogMsg)
    {
        this.dialogMsg = dialogMsg;

        for (int i = 0; i < this.dialogMsg.length; i++)
            this.dialogMsg[i] = replaceAllTags(this.dialogMsg[i]);

    }

    public String[] getLogMessage()
    {
        return logMsg;
    }

    public String[] getDialogMessage()
    {
        return dialogMsg;
    }

    public boolean isCurrentVersion()
    {
        return isCurrentVersion(runsSinceLastMessage == 0 ? currentVersion : lastNewVersionFound, newVersion);
    }

    public static boolean isCurrentVersion(String currentVersion, String newVersion)
    {
        return new NaturalOrderComparator().compare(currentVersion, newVersion) >= 0;
    }

    private String replaceAllTags(String s)
    {
        return s.replace("{oldVer}", currentVersion).replace("{newVer}", newVersion).replace("{appName}", appName).replace("{updateURL}", updateURL);
    }

    public static String[] loadTextFromURL(URL url, String[] defaultValue, int timeoutMS)
    {
        List<String> arraylist = new ArrayList<String>();
        Scanner scanner = null;
        try
        {
            URLConnection uc = url.openConnection();
            uc.setReadTimeout(timeoutMS);
            uc.setConnectTimeout(timeoutMS);
            scanner = new Scanner(uc.getInputStream(), "UTF-8");
        }
        catch (Throwable e)
        {
            return defaultValue;
        }

        while (scanner.hasNextLine())
        {
            arraylist.add(scanner.nextLine());
        }
        scanner.close();
        return arraylist.toArray(new String[arraylist.size()]);
    }
}
/*
NaturalOrderComparator.java -- Perform 'natural order' comparisons of strings in Java.
Copyright (C) 2003 by Pierre-Luc Paour <natorder@paour.com>

Based on the C version by Martin Pool, of which this is more or less a straight conversion.
Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.

changes by bspkrs: cleaned up Java compiler warnings
*/
package bspkrs.mmv.version;

import java.util.Comparator;

public class NaturalOrderComparator implements Comparator<Object>
{
    int compareRight(String a, String b)
    {
        int bias = 0;
        int ia = 0;
        int ib = 0;

        // The longest run of digits wins. That aside, the greatest
        // value wins, but we can't know that it will until we've scanned
        // both numbers to know that they have the same magnitude, so we
        // remember it in BIAS.
        for (;; ia++, ib++)
        {
            char ca = charAt(a, ia);
            char cb = charAt(b, ib);

            if (!Character.isDigit(ca) && !Character.isDigit(cb))
            {
                return bias;
            }
            else if (!Character.isDigit(ca))
            {
                return -1;
            }
            else if (!Character.isDigit(cb))
            {
                return +1;
            }
            else if (ca < cb)
            {
                if (bias == 0)
                {
                    bias = -1;
                }
            }
            else if (ca > cb)
            {
                if (bias == 0)
                    bias = +1;
            }
            else if (ca == 0 && cb == 0)
            {
                return bias;
            }
        }
    }

    @Override
    public int compare(Object o1, Object o2)
    {
        String a = o1.toString();
        String b = o2.toString();

        int ia = 0, ib = 0;
        int nza = 0, nzb = 0;
        char ca, cb;
        int result;

        while (true)
        {
            // only count the number of zeroes leading the last number compared
            nza = nzb = 0;

            ca = charAt(a, ia);
            cb = charAt(b, ib);

            // skip over leading spaces or zeros
            while (Character.isSpaceChar(ca) || ca == '0')
            {
                if (ca == '0')
                {
                    nza++;
                }
                else
                {
                    // only count consecutive zeroes
                    nza = 0;
                }

                ca = charAt(a, ++ia);
            }

            while (Character.isSpaceChar(cb) || cb == '0')
            {
                if (cb == '0')
                {
                    nzb++;
                }
                else
                {
                    // only count consecutive zeroes
                    nzb = 0;
                }

                cb = charAt(b, ++ib);
            }

            // process run of digits
            if (Character.isDigit(ca) && Character.isDigit(cb))
            {
                if ((result = compareRight(a.substring(ia), b.substring(ib))) != 0)
                {
                    return result;
                }
            }

            if (ca == 0 && cb == 0)
            {
                // The strings compare the same. Perhaps the caller
                // will want to call strcmp to break the tie.
                return nza - nzb;
            }

            if (ca < cb)
            {
                return -1;
            }
            else if (ca > cb)
            {
                return +1;
            }

            ++ia;
            ++ib;
        }
    }

    static char charAt(String s, int i)
    {
        if (i >= s.length())
        {
            return 0;
        }
        else
        {
            return s.charAt(i);
        }
    }
}
/*
 * Copyright (C) 2014 Alex "immibis" Campbell
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package immibis.bon;

public interface IProgressListener
{
    public void start(int max, String text);

    public void set(int value);

    public void set(int value, String text);

    public void setMax(int max);
}
/*
 * Copyright (C) 2014 Alex "immibis" Campbell
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package immibis.bon;

/**
 * E.g. "1.5.1 obfuscated", "1.5.1 searge", "1.5.1 MCP" are NameSets.
 */
public class NameSet
{
    public static enum Type
    {
        OBF,
        SRG,
        MCP
    }

    public static enum Side
    {
        UNIVERSAL,
        CLIENT,
        SERVER
    }

    public final Type   type;
    public final String mcVersion;
    public final Side   side;

    public NameSet(Type type, Side side, String mcVersion)
    {
        this.type = type;
        this.side = side;
        this.mcVersion = mcVersion;
    }

    @Override
    public boolean equals(Object obj)
    {
        try
        {
            NameSet ns = (NameSet) obj;
            return ns.type == type && ns.side == side && ns.mcVersion.equals(mcVersion);

        }
        catch (ClassCastException e)
        {
            return false;
        }
    }

    @Override
    public int hashCode()
    {
        return (side.ordinal() << 8) + type.ordinal() + mcVersion.hashCode();
    }

    @Override
    public String toString()
    {
        return mcVersion + " " + type + " " + side;
    }
}
/*
 * Copyright (C) 2014 Alex "immibis" Campbell
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package immibis.bon.gui;

public class Reference<T>
{
    public T val;

    public Reference()
    {}

    public Reference(T val)
    {
        this.val = val;
    }
}
/*
 * Copyright (C) 2014 Alex "immibis" Campbell, bspkrs
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package immibis.bon.gui;

import immibis.bon.NameSet;

public enum Side
{
    Universal(NameSet.Side.UNIVERSAL, "bin/minecraft", new int[] { 2, 0, 1 }),
    Client(NameSet.Side.CLIENT, "bin/minecraft", new int[] { 0 }),
    Server(NameSet.Side.SERVER, "bin/minecraft_server", new int[] { 1 });

    private Side(NameSet.Side nsside, String referencePath, int[] side)
    {
        this.nsside = nsside;
        this.referencePath = referencePath;
        this.intSide = side;
    }

    public final NameSet.Side nsside;
    public final String       referencePath;
    public final int[]        intSide;
}