From 2eb9c5d16a9f7fd0ed55782e78a90b5de0c582ef Mon Sep 17 00:00:00 2001 From: Richard J Hancock Date: Fri, 5 Jul 2024 21:11:38 -0500 Subject: [PATCH 1/5] Sentry Additions Copyright updates Some warnings removed CI Updates --- .github/workflows/ci.yml | 24 +- .github/workflows/nightly-ci.yml | 16 +- MekHQ/build.gradle | 140 +------ MekHQ/sentry.properties | 1 + MekHQ/src/mekhq/AtBGameThread.java | 130 +++++-- MekHQ/src/mekhq/GameThread.java | 82 ++-- MekHQ/src/mekhq/IconPackage.java | 3 +- MekHQ/src/mekhq/MHQConstants.java | 90 ++--- MekHQ/src/mekhq/MHQOptions.java | 353 +++++++++++------- MekHQ/src/mekhq/MHQOptionsChangedEvent.java | 6 +- .../src/mekhq/MHQStaticDirectoryManager.java | 144 ++++--- MekHQ/src/mekhq/MekHQ.java | 143 ++++--- MekHQ/src/mekhq/NullEntityException.java | 18 + MekHQ/src/mekhq/Utilities.java | 340 ++++++++++------- 14 files changed, 868 insertions(+), 622 deletions(-) create mode 100644 MekHQ/sentry.properties diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 23236f1270..ddf2f6a103 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,6 +45,10 @@ jobs: fi exit 0 + - name: Add MMRevision file + run: | + echo ${{ steps.find_mm.outputs.mmBranch }} >> mekhq/mm-revision.txt + - name: Checkout MegaMek uses: actions/checkout@v4 with: @@ -67,6 +71,10 @@ jobs: fi exit 0 + - name: Add MMLRevision file + run: | + echo ${{ steps.find_mml.outputs.mmlBranch }} >> mekhq/mml-revision.txt + - name: Checkout MegaMekLab uses: actions/checkout@v4 with: @@ -87,6 +95,10 @@ jobs: build-scan-terms-of-use-url: "https://gradle.com/terms-of-service" build-scan-terms-of-use-agree: "yes" + - name: Add MHQRevision file + run: | + echo ${{ github.sha }} >> megamek/mhq-revision.txt + - name: Build with Gradle working-directory: mekhq run: ./gradlew build --stacktrace --scan @@ -105,14 +117,14 @@ jobs: fail_ci_if_error: false verbose: true - - name: Upload Windows Release + - name: Upload Tar GZ Artifact uses: actions/upload-artifact@v4 with: - name: mhq-release-win-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} - path: ./mekhq/MekHQ/build/distributions/mekhq-windows-*.zip + name: mhq-release-tgz-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} + path: mekhq/MekHQ/build/distributions/MekHQ-*.tar.gz - - name: Upload Nix/Mac Release + - name: Upload Zip Release uses: actions/upload-artifact@v4 with: - name: mhq-release-nix-mac-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} - path: ./mekhq/MekHQ/build/distributions/mekhq-unix-*.tar.gz + name: mhq-release-zip-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} + path: mekhq/MekHQ/build/distributions/MekHQ-*.zip diff --git a/.github/workflows/nightly-ci.yml b/.github/workflows/nightly-ci.yml index 63e190a43b..55ea200f41 100644 --- a/.github/workflows/nightly-ci.yml +++ b/.github/workflows/nightly-ci.yml @@ -50,6 +50,10 @@ jobs: build-scan-terms-of-use-url: "https://gradle.com/terms-of-service" build-scan-terms-of-use-agree: "yes" + - name: Add MHQRevision file + run: | + echo ${{ github.sha }} >> megamek/mhq-revision.txt + - name: Build with Gradle working-directory: megameklab run: ./gradlew clean build --stacktrace --scan @@ -61,14 +65,14 @@ jobs: name: ${{ matrix.os }}-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }}-ci-failure-logs path: mekhq/MekHQ/build/reports/ - - name: Upload Nix/Mac Releases + - name: Upload Tar GZ Artifact uses: actions/upload-artifact@v4 with: - name: mhq-release-nix-mac-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} - path: mekhq/MekHQ/build/distributions/mekhq-unix-*.tar.gz + name: mhq-release-tgz-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} + path: mekhq/MekHQ/build/distributions/MekHQ-*.tar.gz - - name: Upload Windows Release + - name: Upload Zip Release uses: actions/upload-artifact@v4 with: - name: mhq-release-win-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} - path: mekhq/MekHQ/build/distributions/mekhq-windows-*.zip + name: mhq-release-zip-${{ matrix.java-distribution }}-jdk${{ matrix.java-version }} + path: mekhq/MekHQ/build/distributions/MekHQ-*.zip diff --git a/MekHQ/build.gradle b/MekHQ/build.gradle index 04d9f05d86..3c15b9284d 100644 --- a/MekHQ/build.gradle +++ b/MekHQ/build.gradle @@ -8,6 +8,7 @@ plugins { id 'edu.sc.seis.launch4j' version '3.0.5' id 'jacoco' id 'java' + id "io.sentry.jvm.gradle" version "4.9.0" } java { @@ -199,6 +200,10 @@ task stageFiles(type: Copy) { include "${userdata}/data/universe/" include 'license.txt' include 'SubmitBug.html' + include "sentry.properties" + include "mm-revision.txt" + include "mml-revision.txt" + include "mhq-revision.txt" into fileStagingDir @@ -207,7 +212,7 @@ task stageFiles(type: Copy) { inputs.dir "${docs}" inputs.dir "${mmconf}" inputs.dir "${project.ext.plugins}" - inputs.files 'license.txt', 'SubmitBug.html' + inputs.files 'license.txt', 'SubmitBug.html', 'sentry.properties', 'mm-revision.txt', 'mml-revision.txt', 'mhq-revision.txt' outputs.dir fileStagingDir doLast { @@ -239,81 +244,8 @@ task createStartScripts (type: CreateStartScripts) { } distributions { - // Creates tasks which package distribution with MM jar and startup script in root directory - unix { - distributionBaseName = 'mekhq-unix' - contents { - // MegaMek Includes - from ("${mmDir}/megamek/build/files") - from ("${mmDir}/megamek/build/scripts") { - include 'mm*' - rename 'mm(.*)', 'mm-startup$1' - } - from ("${mmDir}/megamek/${docs}/history.txt") { - rename 'history.txt', 'mm-history.txt' - into 'docs' - } - from ("${mmDir}/megamek/${mmconf}/log4j2.xml") { - exclude 'log4j2.xml' - } - from ("${mmDir}/megamek/build/launch4j/lib") { - into "${lib}" - } - from (mmJar) { - into "${lib}" - } - from (mmJar) - - // MegaMek Includes - from ("${mmlDir}/megameklab/build/launch4j/lib") { - into "${lib}" - } - from ("${mmlDir}/megameklab/build/files/${data}/images") { - into "${data}/images" - } - from ("${mmlDir}/megameklab/build/scripts") { - include 'mml*' - rename 'mml(.*)', 'mml-startup$1' - } - from ("${mmlDir}/megameklab/${docs}/history.txt") { - rename 'history.txt', 'mml-history.txt' - into "${docs}" - } - from ("${mmlDir}/megameklab/${mmconf}/log4j2.xml") { - exclude 'log4j2.xml' - } - from (mmlJar) { - into "${lib}" - } - from (mmlJar) - - // MekHQ Includes - from ("docs/history.txt") { - rename 'history.txt', 'mhq-history.txt' - into 'docs' - } - from (fileStagingDir) { - exclude 'history.txt' - } - from (createStartScripts) { - include 'mhq*' - rename 'mhq(.*)', 'mhq-startup$1' - } - - from (project.sourceSets.main.runtimeClasspath.files - .findAll { it.name.endsWith(".jar") && !it.name.toLowerCase().startsWith("megamek") }) { - into "${lib}" - } - from(jar) { - into "${lib}" - } - from (jar) - duplicatesStrategy = 'exclude' - } - } - // Creates tasks which package distribution with MM jar wrapped in Windows executable - windows { - distributionBaseName = 'mekhq-windows' + main { + distributionBaseName = 'MekHQ' contents { // MegaMek Includes from ("${mmDir}/megamek/build/files") @@ -444,40 +376,11 @@ tasks.register("packagePrepWork") { dependsOn stageMM dependsOn createStartScripts dependsOn startScripts -} - -tasks.register("createAllMMExes") { dependsOn createAllExecutables dependsOn createMMExe dependsOn createMMLExe } -windowsDistZip { - description = 'Creates Windows distribution packaged as a zip archive' - dependsOn packagePrepWork - dependsOn createAllMMExes -} - -windowsDistTar { - description = 'Creates Windows distribution packaged as a zip archive' - dependsOn packagePrepWork - dependsOn createAllMMExes - archiveExtension = 'tar.gz' - compression = Compression.GZIP -} - -unixDistTar { - description = 'Creates *nix distribution packaged as a tar ball' - dependsOn packagePrepWork - archiveExtension = 'tar.gz' - compression = Compression.GZIP -} - -unixDistZip { - description = 'Creates *nix distribution packaged as a tar ball' - dependsOn packagePrepWork -} - distTar { description = 'Creates *nix distribution packaged as a tar ball' dependsOn packagePrepWork @@ -559,8 +462,8 @@ task assembleDist(overwrite: true) { group = 'distribution' dependsOn stageMM dependsOn test - dependsOn unixDistTar - dependsOn windowsDistZip + dependsOn distTar + dependsOn distZip } task buildFromRepo (type: GradleBuild) { @@ -639,29 +542,6 @@ task javadocJar(type: Jar) { archiveClassifier = 'javadoc' } -publishing { - publications { - publishMMLibrary(MavenPublication) { - artifactId = "mekhq${mmBranchTag}" - from components.java - artifact sourcesJar -// artifact javadocJar - - pom { - name = "MekHQ" - description = "MekHQ" - url = "https://megamek.org" - licenses { - license { - name = "GNU General Public License, version 3" - url = "https://www.gnu.org/licenses/gpl-3.0.en.html" - } - } - } - } - } -} - test { useJUnitPlatform() // report is always generated after tests run diff --git a/MekHQ/sentry.properties b/MekHQ/sentry.properties new file mode 100644 index 0000000000..541deecb31 --- /dev/null +++ b/MekHQ/sentry.properties @@ -0,0 +1 @@ +enabled=false diff --git a/MekHQ/src/mekhq/AtBGameThread.java b/MekHQ/src/mekhq/AtBGameThread.java index 5999a2217c..4cf7d4824a 100644 --- a/MekHQ/src/mekhq/AtBGameThread.java +++ b/MekHQ/src/mekhq/AtBGameThread.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2022 - The MegaMek Team. All Rights Reserved. + * Copyright (c) 2011-2024 - The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * @@ -18,32 +18,52 @@ */ package mekhq; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; + +import javax.swing.JOptionPane; + +import org.apache.logging.log4j.LogManager; + +import io.sentry.Sentry; import megamek.client.AbstractClient; import megamek.client.Client; import megamek.client.bot.BotClient; import megamek.client.bot.princess.Princess; import megamek.client.generator.RandomCallsignGenerator; import megamek.client.ui.swing.ClientGUI; -import megamek.common.*; +import megamek.common.Entity; +import megamek.common.IAero; +import megamek.common.Infantry; +import megamek.common.MapSettings; +import megamek.common.Minefield; +import megamek.common.UnitType; import megamek.common.planetaryconditions.PlanetaryConditions; import mekhq.campaign.force.Force; import mekhq.campaign.force.Lance; -import mekhq.campaign.mission.*; +import mekhq.campaign.mission.AtBContract; +import mekhq.campaign.mission.AtBDynamicScenario; +import mekhq.campaign.mission.AtBScenario; +import mekhq.campaign.mission.BotForce; +import mekhq.campaign.mission.Scenario; import mekhq.campaign.personnel.Person; import mekhq.campaign.unit.Unit; -import org.apache.logging.log4j.LogManager; - -import javax.swing.*; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.*; -import java.util.Comparator; - /** - * Enhanced version of GameThread which imports settings and non-player units into the MM game + * Enhanced version of GameThread which imports settings and non-player units + * into the MM game + * * @author Neoancient */ public class AtBGameThread extends GameThread { @@ -51,12 +71,12 @@ public class AtBGameThread extends GameThread { private final AtBScenario scenario; public AtBGameThread(String name, String password, Client c, MekHQ app, List units, - AtBScenario scenario) { + AtBScenario scenario) { this(name, password, c, app, units, scenario, true); } public AtBGameThread(String name, String password, Client c, MekHQ app, List units, - AtBScenario scenario, boolean started) { + AtBScenario scenario, boolean started) { super(name, password, c, app, units, scenario, started); this.scenario = Objects.requireNonNull(scenario); } @@ -103,7 +123,8 @@ public void run() { for (int i = 0; (i < MekHQ.getMHQOptions().getStartGameClientRetryCount()) && client.getGame().getPhase().isUnknown(); i++) { Thread.sleep(MekHQ.getMHQOptions().getStartGameClientDelay()); - LogManager.getLogger().warn("Client has not finished initialization, and is currently in an unknown phase."); + LogManager.getLogger() + .warn("Client has not finished initialization, and is currently in an unknown phase."); } if ((client.getGame() != null) && client.getGame().getPhase().isLounge()) { @@ -137,18 +158,26 @@ public void run() { mapSettings.setMedium(MapSettings.MEDIUM_ATMOSPHERE); } } else { - File mapgenFile = new File("data/mapgen/" + scenario.getMap() + ".xml"); // TODO : Remove inline file path + File mapgenFile = new File("data/mapgen/" + scenario.getMap() + ".xml"); // TODO : Remove inline + // file path try (InputStream is = new FileInputStream(mapgenFile)) { mapSettings = MapSettings.getInstance(is); } catch (FileNotFoundException ex) { - LogManager.getLogger().error("Could not load map file data/mapgen/" + scenario.getMap() + ".xml", ex); // TODO : Remove inline file path + Sentry.captureException(ex); + + LogManager.getLogger() + .error( + String.format("Could not load map file data/mapgen/%s.xml", scenario.getMap()), + ex); + // TODO: Remove inline file path } if (scenario.getBoardType() == Scenario.T_ATMOSPHERE) { mapSettings.setMedium(MapSettings.MEDIUM_ATMOSPHERE); } - // duplicate code, but getting a new instance of map settings resets the size parameters + // duplicate code, but getting a new instance of map settings resets the size + // parameters mapSettings.setBoardSize(scenario.getMapX(), scenario.getMapY()); mapSettings.setMapSize(1, 1); mapSettings.getBoardsSelectedVector().add(MapSettings.BOARD_GENERATED); @@ -189,11 +218,13 @@ public void run() { // minefields client.getLocalPlayer().setNbrMFActive(scenario.getNumPlayerMinefields(Minefield.TYPE_ACTIVE)); - client.getLocalPlayer().setNbrMFConventional(scenario.getNumPlayerMinefields(Minefield.TYPE_CONVENTIONAL)); + client.getLocalPlayer() + .setNbrMFConventional(scenario.getNumPlayerMinefields(Minefield.TYPE_CONVENTIONAL)); client.getLocalPlayer().setNbrMFInferno(scenario.getNumPlayerMinefields(Minefield.TYPE_INFERNO)); client.getLocalPlayer().setNbrMFVibra(scenario.getNumPlayerMinefields(Minefield.TYPE_VIBRABOMB)); - /* If the player is making a combat drop (either required by scenario + /* + * If the player is making a combat drop (either required by scenario * or player chose to deploy a DropShip), do not use deployment * delay for slower scout units. */ @@ -260,19 +291,21 @@ public void run() { } entities.add(entity); - // if we've swapped this entity in for a bot-controlled unit, copy the bot controlled unit's + // if we've swapped this entity in for a bot-controlled unit, copy the bot + // controlled unit's // deployment parameters to this entity. if ((scenario instanceof AtBDynamicScenario) && - ((AtBDynamicScenario) scenario).getPlayerUnitSwaps(). - containsKey(UUID.fromString(entity.getExternalIdAsString()))) { - Entity benchedEntity = ((AtBDynamicScenario) scenario).getPlayerUnitSwaps(). - get(UUID.fromString(entity.getExternalIdAsString())).entity; + ((AtBDynamicScenario) scenario).getPlayerUnitSwaps() + .containsKey(UUID.fromString(entity.getExternalIdAsString()))) { + Entity benchedEntity = ((AtBDynamicScenario) scenario).getPlayerUnitSwaps() + .get(UUID.fromString(entity.getExternalIdAsString())).entity; copyDeploymentParameters(benchedEntity, entity); } } client.sendAddEntity(entities); - // Run through the units again. This time add transported units to the correct linkage, + // Run through the units again. This time add transported units to the correct + // linkage, // but only if the transport itself is in the game too. for (Unit unit : units) { if (unit.hasTransportShipAssignment()) { @@ -282,7 +315,8 @@ public void run() { } } } - // Now, clean the list of any transports that don't have deployed units in the game + // Now, clean the list of any transports that don't have deployed units in the + // game Set emptyTransports = new HashSet<>(); for (UUID id : scenario.getPlayerTransportLinkages().keySet()) { if (scenario.getPlayerTransportLinkages().get(id).isEmpty()) { @@ -337,11 +371,15 @@ public void run() { } Princess botClient = new Princess(name, client.getHost(), client.getPort()); botClient.setBehaviorSettings(bf.getBehaviorSettings()); + try { botClient.connect(); } catch (Exception e) { - LogManager.getLogger().error("Could not connect with Bot name " + bf.getName(), e); + Sentry.captureException(e); + LogManager.getLogger().error(String.format("Could not connect with Bot name %s", bf.getName()), + e); } + swingGui.getLocalBots().put(name, botClient); // chill out while bot is created and connects to megamek @@ -355,7 +393,7 @@ public void run() { } // All player and bot units have been added to the lobby - // Prompt the player to autoload units into transports + // Prompt the player to auto load units into transports if (!scenario.getPlayerTransportLinkages().isEmpty()) { for (UUID id : scenario.getPlayerTransportLinkages().keySet()) { boolean loadDropShips = false; @@ -394,7 +432,8 @@ public void run() { // Now, send the load commands if (loadDropShips || loadSmallCraft || loadFighters || loadGround) { - // List of technicians assigned to transported units. Several units can share a tech. + // List of technicians assigned to transported units. Several units can share a + // tech. Set cargoTechs = new HashSet<>(); for (UUID cargoId : scenario.getPlayerTransportLinkages().get(id)) { Unit unit = campaign.getUnit(cargoId); @@ -407,7 +446,8 @@ public void run() { } } // Update the transport's passenger count with assigned techs - transport.getEntity().setNPassenger(transport.getEntity().getNPassenger() + cargoTechs.size()); + transport.getEntity() + .setNPassenger(transport.getEntity().getNPassenger() + cargoTechs.size()); client.sendUpdateEntity(transport.getEntity()); // And now load the units. Unit crews load as passengers here. Utilities.loadPlayerTransports(transport.getEntity().getId(), toLoad, @@ -421,6 +461,7 @@ public void run() { Thread.sleep(50); } } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("", ex); } finally { swingGui.setDisconnectQuietly(true); @@ -440,7 +481,8 @@ public void run() { */ private void configureBot(BotClient botClient, BotForce botForce, Scenario scenario) { try { - // Wait for the server to add the bot client, but allow a timeout rather than blocking + // Wait for the server to add the bot client, but allow a timeout rather than + // blocking int retryCount = 0; while ((botClient.getLocalPlayer() == null) && (retryCount++ < MekHQ.getMHQOptions().getStartGameBotClientRetryCount())) { @@ -452,11 +494,12 @@ private void configureBot(BotClient botClient, BotForce botForce, Scenario scena } if (botClient.getLocalPlayer() == null) { - LogManager.getLogger().error("Could not configure bot " + botClient.getName()); + LogManager.getLogger().error( + String.format("Could not configure bot %s", botClient.getName())); } else { botClient.getLocalPlayer().setTeam(botForce.getTeam()); - //set deployment + // set deployment botClient.getLocalPlayer().setStartingPos(botForce.getStartingPos()); botClient.getLocalPlayer().setStartOffset(botForce.getStartOffset()); botClient.getLocalPlayer().setStartWidth(botForce.getStartWidth()); @@ -475,6 +518,7 @@ private void configureBot(BotClient botClient, BotForce botForce, Scenario scena botClient.sendAddEntity(entities); } } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("", ex); } } @@ -533,11 +577,12 @@ protected List setupBotEntities(BotClient botClient, BotForce botForce, } /** - * Handles loading bot transported units onto their transports once a MegaMek scenario has + * Handles loading bot transported units onto their transports once a MegaMek + * scenario has * actually started. */ private void loadTransports(final Client client, final AtBScenario scenario, - final BotForce botForce) { + final BotForce botForce) { Map idMap = new HashMap<>(); // here we have to make sure that the server has loaded all the entities @@ -558,7 +603,8 @@ private void loadTransports(final Client client, final AtBScenario scenario, } List clientEntities = client.getEntitiesVector(); - // this is a bit inefficient, should really give the client/game the ability to look up an entity by external ID + // this is a bit inefficient, should really give the client/game the ability to + // look up an entity by external ID for (Entity entity : clientEntities) { if (entity.getOwnerId() == client.getLocalPlayerNumber()) { idMap.put(entity.getExternalIdAsString(), entity.getId()); @@ -572,7 +618,8 @@ private void loadTransports(final Client client, final AtBScenario scenario, Entity cargo = scenario.getExternalIDLookup().get(cargoID); // if the game contains the potential cargo unit - // and the potential transport can actually load it, send the load command to the server + // and the potential transport can actually load it, send the load command to + // the server if ((cargo != null) && idMap.containsKey(cargo.getExternalIdAsString()) && potentialTransport.canLoad(cargo, false)) { @@ -585,7 +632,8 @@ private void loadTransports(final Client client, final AtBScenario scenario, } /** - * Utility function to copy some deployment parameters between source and destination entities + * Utility function to copy some deployment parameters between source and + * destination entities */ private void copyDeploymentParameters(Entity source, Entity destination) { destination.setDeployRound(source.getDeployRound()); diff --git a/MekHQ/src/mekhq/GameThread.java b/MekHQ/src/mekhq/GameThread.java index 3deecffa21..6832e03409 100644 --- a/MekHQ/src/mekhq/GameThread.java +++ b/MekHQ/src/mekhq/GameThread.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2022 - The MegaMek Team. All Rights Reserved. + * Copyright (c) 2011-2024 - The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * @@ -18,6 +18,18 @@ */ package mekhq; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import org.apache.logging.log4j.LogManager; + +import io.sentry.Sentry; import megamek.client.AbstractClient; import megamek.client.Client; import megamek.client.CloseClientListener; @@ -26,24 +38,18 @@ import megamek.client.ui.swing.ClientGUI; import megamek.client.ui.swing.MegaMekGUI; import megamek.client.ui.swing.util.MegaMekController; -import megamek.common.*; -import megamek.common.planetaryconditions.PlanetaryConditions; +import megamek.common.Entity; +import megamek.common.MapSettings; +import megamek.common.WeaponOrderHandler; import megamek.common.preference.PreferenceManager; import mekhq.campaign.Campaign; import mekhq.campaign.force.Force; import mekhq.campaign.mission.BotForce; import mekhq.campaign.mission.Scenario; import mekhq.campaign.unit.Unit; -import org.apache.logging.log4j.LogManager; - -import java.awt.*; -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; class GameThread extends Thread implements CloseClientListener { - //region Variable Declarations + // region Variable Declarations protected String myname; protected String password; protected Client client; @@ -58,9 +64,9 @@ class GameThread extends Thread implements CloseClientListener { protected volatile boolean stop = false; private final Scenario scenario; - //endregion Variable Declarations + // endregion Variable Declarations - //region Constructors + // region Constructors public GameThread(String name, String password, Client c, MekHQ app, List units, Scenario s) { this(name, password, c, app, units, s, true); } @@ -69,7 +75,8 @@ public GameThread(String name, Client c, MekHQ app, List units, Scenario s this(name, "", c, app, units, s, started); } - public GameThread(String name, String password, Client c, MekHQ app, List units, Scenario s, boolean started) { + public GameThread(String name, String password, Client c, MekHQ app, List units, Scenario s, + boolean started) { super(name); myname = name.trim(); this.password = password; @@ -80,7 +87,7 @@ public GameThread(String name, String password, Client c, MekHQ app, List this.campaign = app.getCampaign(); this.scenario = Objects.requireNonNull(s); } - //endregion Constructors + // endregion Constructors public Client getClient() { return client; @@ -104,6 +111,7 @@ public void run() { try { client.connect(); } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("MegaMek client failed to connect to server", ex); return; } @@ -117,7 +125,8 @@ public void run() { for (int i = 0; (i < MekHQ.getMHQOptions().getStartGameClientRetryCount()) && client.getGame().getPhase().isUnknown(); i++) { Thread.sleep(MekHQ.getMHQOptions().getStartGameClientDelay()); - LogManager.getLogger().warn("Client has not finished initialization, and is currently in an unknown phase."); + LogManager.getLogger() + .warn("Client has not finished initialization, and is currently in an unknown phase."); } if ((client.getGame() != null) && client.getGame().getPhase().isLounge()) { @@ -152,24 +161,32 @@ public void run() { mapSettings.setMedium(MapSettings.MEDIUM_ATMOSPHERE); } } else { - File mapgenFile = new File("data/mapgen/" + scenario.getMap() + ".xml"); // TODO : remove inline file path + File mapgenFile = new File("data/mapgen/" + scenario.getMap() + ".xml"); // TODO : remove inline + // file path try (InputStream is = new FileInputStream(mapgenFile)) { mapSettings = MapSettings.getInstance(is); } catch (FileNotFoundException ex) { - LogManager.getLogger().error("Could not load map file data/mapgen/" + scenario.getMap() + ".xml", ex); // TODO : remove inline file path + LogManager.getLogger() + .error( + String.format("Could not load map file data/mapgen/%s.xml", + scenario.getMap()), + ex); + // TODO: remove inline file path } if (scenario.getBoardType() == Scenario.T_ATMOSPHERE) { mapSettings.setMedium(MapSettings.MEDIUM_ATMOSPHERE); } - // duplicate code, but getting a new instance of map settings resets the size parameters + // duplicate code, but getting a new instance of map settings resets the size + // parameters mapSettings.setBoardSize(scenario.getMapSizeX(), scenario.getMapSizeY()); mapSettings.setMapSize(1, 1); mapSettings.getBoardsSelectedVector().add(MapSettings.BOARD_GENERATED); } } else { - LogManager.getLogger().error("invalid map settings provided for scenario " + scenario.getName()); + LogManager.getLogger().error( + String.format("invalid map settings provided for scenario %s", scenario.getName())); } client.sendMapSettings(mapSettings); @@ -218,7 +235,9 @@ public void run() { try { botClient.connect(); } catch (Exception e) { - LogManager.getLogger().error("Could not connect with Bot name " + bf.getName(), e); + Sentry.captureException(e); + LogManager.getLogger().error( + String.format("Could not connect with Bot name %s", bf.getName()), e); } swingGui.getLocalBots().put(name, botClient); @@ -232,6 +251,7 @@ public void run() { Thread.sleep(50); } } catch (Exception e) { + Sentry.captureException(e); LogManager.getLogger().error("", e); } finally { swingGui.setDisconnectQuietly(true); @@ -247,11 +267,13 @@ public void run() { * camo, and entities * * @param botClient a BotClient to manage the bot - * @param botForce a BotForce that will send its info and entities to the botClient + * @param botForce a BotForce that will send its info and entities to the + * botClient */ private void configureBot(BotClient botClient, BotForce botForce) { try { - // Wait for the server to add the bot client, but allow a timeout rather than blocking + // Wait for the server to add the bot client, but allow a timeout rather than + // blocking int retryCount = 0; while ((botClient.getLocalPlayer() == null) && (retryCount++ < MekHQ.getMHQOptions().getStartGameBotClientRetryCount())) { @@ -263,11 +285,12 @@ private void configureBot(BotClient botClient, BotForce botForce) { } if (botClient.getLocalPlayer() == null) { - LogManager.getLogger().error("Could not configure bot " + botClient.getName()); + LogManager.getLogger().error( + String.format("Could not configure bot %s", botClient.getName())); } else { botClient.getLocalPlayer().setTeam(botForce.getTeam()); - //set deployment + // set deployment botClient.getLocalPlayer().setStartingPos(botForce.getStartingPos()); botClient.getLocalPlayer().setStartOffset(botForce.getStartOffset()); botClient.getLocalPlayer().setStartWidth(botForce.getStartWidth()); @@ -286,6 +309,7 @@ private void configureBot(BotClient botClient, BotForce botForce) { botClient.sendAddEntity(entities); } } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("", ex); } } @@ -298,9 +322,10 @@ protected List setupBotEntities(BotClient botClient, BotForce botForce, entity.setOwner(botClient.getLocalPlayer()); entity.setForceString(forceName); /* - Only overwrite deployment round for entities if they have an individual deployment round of zero. - Otherwise, we will overwrite entity specific deployment information. - */ + * Only overwrite deployment round for entities if they have an individual + * deployment round of zero. + * Otherwise, we will overwrite entity specific deployment information. + */ if (entity.getDeployRound() == 0) { entity.setDeployRound(botForce.getDeployRound()); } @@ -325,6 +350,7 @@ public void requestStop() { try { WeaponOrderHandler.saveWeaponOrderFile(); } catch (IOException e) { + Sentry.captureException(e); LogManager.getLogger().error("Error saving custom weapon orders!", e); } stop = true; diff --git a/MekHQ/src/mekhq/IconPackage.java b/MekHQ/src/mekhq/IconPackage.java index 5a2b02415a..363403c291 100644 --- a/MekHQ/src/mekhq/IconPackage.java +++ b/MekHQ/src/mekhq/IconPackage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020 - The MegaMek Team. All Rights Reserved + * Copyright (c) 2013-2024 - The MegaMek Team. All Rights Reserved * * This file is part of MekHQ. * @@ -24,6 +24,7 @@ /** * This is a convenience class that will keep all the various graphics + * * @author Jay Lawson */ public class IconPackage { diff --git a/MekHQ/src/mekhq/MHQConstants.java b/MekHQ/src/mekhq/MHQConstants.java index 70f1a462c7..8ddbcb18f1 100644 --- a/MekHQ/src/mekhq/MHQConstants.java +++ b/MekHQ/src/mekhq/MHQConstants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019-2022 - The MegaMek Team. All Rights Reserved. + * Copyright (c) 2019-2024 - The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * @@ -18,52 +18,54 @@ */ package mekhq; -import megamek.SuiteConstants; - import java.time.LocalDate; import java.time.Month; +import megamek.SuiteConstants; + /** * These are constants that hold across MekHQ. */ public final class MHQConstants extends SuiteConstants { - //region General Constants + // region General Constants public static final String PROJECT_NAME = "MekHQ"; public static final int ASTECH_TEAM_SIZE = 6; public static final int MAX_JUMP_RADIUS = 30; // public static final int PREGNANCY_STANDARD_DURATION = 280; // standard duration of a pregnancy in days (40 weeks) public static final String EGO_OBJECTIVE_NAME = "Player"; - //endregion General Constants + // endregion General Constants - //region Faction Generation Constants + // region Faction Generation Constants public static final int FACTION_GENERATOR_BORDER_RANGE_IS = 60; public static final int FACTION_GENERATOR_BORDER_RANGE_CLAN = 90; public static final int FACTION_GENERATOR_BORDER_RANGE_NEAR_PERIPHERY = 90; - public static final int FACTION_GENERATOR_BORDER_RANGE_DEEP_PERIPHERY = 210; // a bit more than this distance between HL and NC + public static final int FACTION_GENERATOR_BORDER_RANGE_DEEP_PERIPHERY = 210; // a bit more than this distance + // between HL and NC public static final LocalDate FORTRESS_REPUBLIC = LocalDate.of(3135, Month.NOVEMBER, 1); - //endregion Faction Generation Constants + // endregion Faction Generation Constants - //region GUI Constants + // region GUI Constants public static final String COMMAND_OPEN_POPUP = "SHIFT_F10"; public static final int BASE_SCROLLER_THRESHOLD = 20; - //endregion GUI Constants + // endregion GUI Constants - //region MHQOptions - //region Display + // region MHQOptions + // region Display public static final String DISPLAY_NODE = "mekhq/prefs/display"; public static final String DISPLAY_DATE_FORMAT = "displayDateFormat"; public static final String LONG_DISPLAY_DATE_FORMAT = "longDisplayDateFormat"; public static final String HISTORICAL_DAILY_LOG = "historicalDailyLog"; - public static final int MAX_HISTORICAL_LOG_DAYS = 120; // max number of days that will be stored in the history, also used as a limit in the UI + public static final int MAX_HISTORICAL_LOG_DAYS = 120; // max number of days that will be stored in the history, + // also used as a limit in the UI public static final String COMPANY_GENERATOR_STARTUP = "companyGeneratorStartup"; public static final String SHOW_COMPANY_GENERATOR = "showCompanyGenerator"; - //region Command Center Tab + // region Command Center Tab public static final String COMMAND_CENTER_USE_UNIT_MARKET = "commandCenterUseUnitMarket"; public static final String COMMAND_CENTER_MRMS = "commandCenterMRMS"; - //endregion Command Center Tab + // endregion Command Center Tab - //region Interstellar Map Tab + // region Interstellar Map Tab public static final String INTERSTELLAR_MAP_SHOW_JUMP_RADIUS = "interstellarMapShowJumpRadius"; public static final String INTERSTELLAR_MAP_SHOW_JUMP_RADIUS_MINIMUM_ZOOM = "interstellarMapShowJumpRadiusMinimumZoom"; public static final String INTERSTELLAR_MAP_JUMP_RADIUS_COLOUR = "interstellarMapJumpRadiusColour"; @@ -72,15 +74,15 @@ public final class MHQConstants extends SuiteConstants { public static final String INTERSTELLAR_MAP_PLANETARY_ACQUISITION_RADIUS_COLOUR = "interstellarMapPlanetaryAcquisitionRadiusColour"; public static final String INTERSTELLAR_MAP_SHOW_CONTRACT_SEARCH_RADIUS = "interstellarMapShowContractSearchRadius"; public static final String INTERSTELLAR_MAP_CONTRACT_SEARCH_RADIUS_COLOUR = "interstellarMapContractSearchRadiusColour"; - //endregion Interstellar Map Tab + // endregion Interstellar Map Tab - //region Personnel Tab + // region Personnel Tab public static final String PERSONNEL_FILTER_STYLE = "personnelFilterStyle"; public static final String PERSONNEL_FILTER_ON_PRIMARY_ROLE = "personnelFilterOnPrimaryRole"; - //endregion Personnel Tab - //endregion Display + // endregion Personnel Tab + // endregion Display - //region Colours + // region Colours public static final String DEPLOYED_FOREGROUND = "deployedForeground"; public static final String DEPLOYED_BACKGROUND = "deployedBackground"; public static final String BELOW_CONTRACT_MINIMUM_FOREGROUND = "belowContractMinimumForeground"; @@ -117,14 +119,14 @@ public final class MHQConstants extends SuiteConstants { public static final String FONT_COLOR_NEGATIVE = "fontColorNegative"; public static final String FONT_COLOR_POSITIVE = "fontColorPositive"; public static final String FONT_COLOR_WARNING = "fontColorWarning"; - //endregion Colours + // endregion Colours - //region Fonts + // region Fonts public static final String FONTS_NODE = "mekhq/prefs/fonts"; public static final String MEDICAL_VIEW_DIALOG_HANDWRITING_FONT = "medicalViewDialogHandwritingFont"; - //endregion Fonts + // endregion Fonts - //region Autosave + // region Autosave public static final String AUTOSAVE_NODE = "mekhq/prefs/autosave"; public static final String NO_SAVE_KEY = "noSave"; public static final String SAVE_DAILY_KEY = "saveDaily"; @@ -134,34 +136,34 @@ public final class MHQConstants extends SuiteConstants { public static final String SAVE_BEFORE_MISSIONS_KEY = "saveBeforeMissions"; public static final String MAXIMUM_NUMBER_SAVES_KEY = "maximumNumberAutoSaves"; public static final int DEFAULT_NUMBER_SAVES = 5; - //endregion Autosave + // endregion Autosave - //region New Day + // region New Day public static final String NEW_DAY_NODE = "mekhq/prefs/newDay"; public static final String NEW_DAY_ASTECH_POOL_FILL = "newDayAstechPoolFill"; public static final String NEW_DAY_MEDIC_POOL_FILL = "newDayMedicPoolFill"; public static final String NEW_DAY_MRMS = "newDayMRMS"; public static final String NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS = "newDayForceIconOperationalStatus"; public static final String NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS_STYLE = "newDayForceIconOperationalStatusStyle"; - //endregion New Day + // endregion New Day - //region Campaign XML Save Options + // region Campaign XML Save Options public static final String XML_SAVES_NODE = "mekhq/prefs/xmlsaves"; public static final String PREFER_GZIPPED_CAMPAIGN_FILE = "preferGzippedCampaignFile"; public static final String WRITE_CUSTOMS_TO_XML = "writeCustomsToXML"; public static final String SAVE_MOTHBALL_STATE = "saveMothballState"; - //endregion Campaign XML Save Options + // endregion Campaign XML Save Options - //region File Paths + // region File Paths public static final String FILE_PATH_NODE = "mekhq/prefs/filepaths"; public static final String RANK_SYSTEMS_DIRECTORY_PATH = "rankSystemsDirectoryPath"; public static final String INDIVIDUAL_RANK_SYSTEM_DIRECTORY_PATH = "individualRankSystemDirectoryPath"; public static final String UNIT_SPRITE_EXPORT_DIRECTORY_PATH = "unitSpriteExportDirectoryPath"; public static final String LAYERED_FORCE_ICON_DIRECTORY_PATH = "layeredForceIconDirectoryPath"; public static final String COMPANY_GENERATION_DIRECTORY_PATH = "companyGenerationDirectoryPath"; - //endregion File Paths + // endregion File Paths - //region Nag Tab + // region Nag Tab public static final String NAG_NODE = "mekhq/prefs/nags"; public static final String NAG_UNMAINTAINED_UNITS = "nagUnmaintainedUnits"; public static final String NAG_PREGNANT_COMBATANT = "nagPregnantCombatant"; @@ -177,9 +179,9 @@ public final class MHQConstants extends SuiteConstants { public static final String NAG_OUTSTANDING_SCENARIOS = "nagOutstandingScenarios"; public static final String NAG_CARGO_CAPACITY = "nagCargoCapacity"; public static final String NAG_INVALID_FACTION = "nagInvalidFaction"; - //endregion Nag Tab + // endregion Nag Tab - //region Miscellaneous Options + // region Miscellaneous Options public static final String MISCELLANEOUS_NODE = "mekhq/prefs/miscellaneous"; public static final String START_GAME_DELAY = "startGameDelay"; public static final String START_GAME_CLIENT_DELAY = "startGameClientDelay"; @@ -187,10 +189,10 @@ public final class MHQConstants extends SuiteConstants { public static final String START_GAME_BOT_CLIENT_DELAY = "startGameBotClientDelay"; public static final String START_GAME_BOT_CLIENT_RETRY_COUNT = "startGameBotClientRetryCount"; public static final String DEFAULT_COMPANY_GENERATION_METHOD = "defaultCompanyGenerationMethod"; - //endregion Miscellaneous Options - //endregion MHQOptions + // endregion Miscellaneous Options + // endregion MHQOptions - //region File Paths + // region File Paths // This holds all required file paths not saved as part of MekHQ Options public static final String LAYERED_FORCE_ICON_ADJUSTMENT_PATH = "Pieces/Adjustments/"; public static final String LAYERED_FORCE_ICON_ALPHANUMERIC_PATH = "Pieces/Alphanumerics/"; @@ -236,9 +238,9 @@ public final class MHQConstants extends SuiteConstants { public static final String USER_RANDOM_DEATH_CAUSES_FILE_PATH = "userdata/data/universe/randomDeathCauses.xml"; public static final String USER_RANKS_FILE_PATH = "userdata/data/universe/ranks.xml"; public static final String USER_CAMPAIGN_PRESET_DIRECTORY = "userdata/mmconf/campaignPresets/"; - public static final String STRATCON_MUL_FILES_DIRECTORY="data/scenariotemplates/fixedmuls/"; + public static final String STRATCON_MUL_FILES_DIRECTORY = "data/scenariotemplates/fixedmuls/"; - //region StratCon + // region StratCon public static final String STRATCON_REQUIRED_HOSTILE_FACILITY_MODS = "./data/scenariomodifiers/requiredHostileFacilityModifiers.xml"; public static final String STRATCON_HOSTILE_FACILITY_MODS = "./data/scenariomodifiers/hostileFacilityModifiers.xml"; public static final String STRATCON_ALLIED_FACILITY_MODS = "./data/scenariomodifiers/alliedFacilityModifiers.xml"; @@ -272,14 +274,14 @@ public final class MHQConstants extends SuiteConstants { public static final String SCENARIO_MODIFIER_ALLIED_GROUND_SUPPORT = "AlliedGroundSupportImmediate.xml"; public static final String SCENARIO_MODIFIER_ALLIED_AIR_SUPPORT = "AlliedAirSupportImmediate.xml"; public static final String SCENARIO_MODIFIER_ALLIED_ARTY_SUPPORT = "AlliedArtillerySupportImmediate.xml"; - //endregion StratCon + // endregion StratCon - //region StoryArcs + // region StoryArcs public static final String STORY_ARC_DIRECTORY = "data/storyarcs/"; public static final String USER_STORY_ARC_DIRECTORY = "userdata/storyarcs/"; public static final String STORY_ARC_FILE = "storyArc.xml"; public static final String STORY_ARC_CAMPAIGN_FILE = "initCampaign.cpnx.gz"; - //endregion StoryArcs + // endregion StoryArcs - //endregion File Paths + // endregion File Paths } diff --git a/MekHQ/src/mekhq/MHQOptions.java b/MekHQ/src/mekhq/MHQOptions.java index 10d0c4967d..b07659c907 100644 --- a/MekHQ/src/mekhq/MHQOptions.java +++ b/MekHQ/src/mekhq/MHQOptions.java @@ -18,25 +18,28 @@ */ package mekhq; +import java.awt.Color; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import javax.swing.UIManager; + import megamek.SuiteOptions; import megamek.common.annotations.Nullable; import mekhq.campaign.universe.enums.CompanyGenerationMethod; import mekhq.gui.enums.ForceIconOperationalStatusStyle; import mekhq.gui.enums.PersonnelFilterStyle; -import javax.swing.*; -import java.awt.*; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - public final class MHQOptions extends SuiteOptions { - //region Display Tab + // region Display Tab public String getDisplayDateFormat() { return userPreferences.node(MHQConstants.DISPLAY_NODE).get(MHQConstants.DISPLAY_DATE_FORMAT, "yyyy-MM-dd"); } public String getDisplayFormattedDate(final @Nullable LocalDate date) { - return (date != null) ? date.format(DateTimeFormatter.ofPattern(getDisplayDateFormat()).withLocale(getDateLocale())) : ""; + return (date != null) + ? date.format(DateTimeFormatter.ofPattern(getDisplayDateFormat()).withLocale(getDateLocale())) + : ""; } public void setDisplayDateFormat(String value) { @@ -48,11 +51,14 @@ public LocalDate parseDisplayFormattedDate(String text) { } public String getLongDisplayDateFormat() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).get(MHQConstants.LONG_DISPLAY_DATE_FORMAT, "EEEE, MMMM d, yyyy"); + return userPreferences.node(MHQConstants.DISPLAY_NODE).get(MHQConstants.LONG_DISPLAY_DATE_FORMAT, + "EEEE, MMMM d, yyyy"); } public String getLongDisplayFormattedDate(LocalDate date) { - return (date != null) ? date.format(DateTimeFormatter.ofPattern(getLongDisplayDateFormat()).withLocale(getDateLocale())) : ""; + return (date != null) + ? date.format(DateTimeFormatter.ofPattern(getLongDisplayDateFormat()).withLocale(getDateLocale())) + : ""; } public void setLongDisplayDateFormat(String value) { @@ -68,7 +74,8 @@ public void setHistoricalDailyLog(boolean value) { } public boolean getCompanyGeneratorStartup() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.COMPANY_GENERATOR_STARTUP, false); + return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.COMPANY_GENERATOR_STARTUP, + false); } public void setCompanyGeneratorStartup(final boolean value) { @@ -83,9 +90,10 @@ public void setShowCompanyGenerator(final boolean value) { userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.SHOW_COMPANY_GENERATOR, value); } - //region Command Center Tab + // region Command Center Tab public boolean getCommandCenterUseUnitMarket() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.COMMAND_CENTER_USE_UNIT_MARKET, true); + return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.COMMAND_CENTER_USE_UNIT_MARKET, + true); } public void setCommandCenterUseUnitMarket(boolean value) { @@ -99,76 +107,91 @@ public boolean getCommandCenterMRMS() { public void setCommandCenterMRMS(boolean value) { userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.COMMAND_CENTER_MRMS, value); } - //endregion Command Center Tab + // endregion Command Center Tab - //region Interstellar Map Tab + // region Interstellar Map Tab public boolean getInterstellarMapShowJumpRadius() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS, true); + return userPreferences.node(MHQConstants.DISPLAY_NODE) + .getBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS, true); } public void setInterstellarMapShowJumpRadius(final boolean value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS, value); + userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS, + value); } public double getInterstellarMapShowJumpRadiusMinimumZoom() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS_MINIMUM_ZOOM, 3d); + return userPreferences.node(MHQConstants.DISPLAY_NODE) + .getDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS_MINIMUM_ZOOM, 3d); } public void setInterstellarMapShowJumpRadiusMinimumZoom(final double value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS_MINIMUM_ZOOM, value); + userPreferences.node(MHQConstants.DISPLAY_NODE) + .putDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_JUMP_RADIUS_MINIMUM_ZOOM, value); } + public Color getInterstellarMapJumpRadiusColour() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.INTERSTELLAR_MAP_JUMP_RADIUS_COLOUR, Color.DARK_GRAY.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE) + .getInt(MHQConstants.INTERSTELLAR_MAP_JUMP_RADIUS_COLOUR, Color.DARK_GRAY.getRGB())); } public void setInterstellarMapJumpRadiusColour(final Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.INTERSTELLAR_MAP_JUMP_RADIUS_COLOUR, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.INTERSTELLAR_MAP_JUMP_RADIUS_COLOUR, + value.getRGB()); } public boolean getInterstellarMapShowPlanetaryAcquisitionRadius() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS, false); + return userPreferences.node(MHQConstants.DISPLAY_NODE) + .getBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS, false); } public void setInterstellarMapShowPlanetaryAcquisitionRadius(final boolean value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS, value); + userPreferences.node(MHQConstants.DISPLAY_NODE) + .putBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS, value); } public double getInterstellarMapShowPlanetaryAcquisitionRadiusMinimumZoom() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS_MINIMUM_ZOOM, 2d); + return userPreferences.node(MHQConstants.DISPLAY_NODE) + .getDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS_MINIMUM_ZOOM, 2d); } public void setInterstellarMapShowPlanetaryAcquisitionRadiusMinimumZoom(final double value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS_MINIMUM_ZOOM, value); + userPreferences.node(MHQConstants.DISPLAY_NODE) + .putDouble(MHQConstants.INTERSTELLAR_MAP_SHOW_PLANETARY_ACQUISITION_RADIUS_MINIMUM_ZOOM, value); } public Color getInterstellarMapPlanetaryAcquisitionRadiusColour() { - // new Color(80, 80, 80) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.INTERSTELLAR_MAP_PLANETARY_ACQUISITION_RADIUS_COLOUR, 0xFF505050)); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE) + .getInt(MHQConstants.INTERSTELLAR_MAP_PLANETARY_ACQUISITION_RADIUS_COLOUR, 0xFF505050)); } public void setInterstellarMapPlanetaryAcquisitionRadiusColour(final Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.INTERSTELLAR_MAP_PLANETARY_ACQUISITION_RADIUS_COLOUR, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE) + .putInt(MHQConstants.INTERSTELLAR_MAP_PLANETARY_ACQUISITION_RADIUS_COLOUR, value.getRGB()); } public boolean getInterstellarMapShowContractSearchRadius() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_CONTRACT_SEARCH_RADIUS, false); + return userPreferences.node(MHQConstants.DISPLAY_NODE) + .getBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_CONTRACT_SEARCH_RADIUS, false); } public void setInterstellarMapShowContractSearchRadius(final boolean value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_CONTRACT_SEARCH_RADIUS, value); + userPreferences.node(MHQConstants.DISPLAY_NODE) + .putBoolean(MHQConstants.INTERSTELLAR_MAP_SHOW_CONTRACT_SEARCH_RADIUS, value); } public Color getInterstellarMapContractSearchRadiusColour() { - // new Color(96, 96, 96) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.INTERSTELLAR_MAP_CONTRACT_SEARCH_RADIUS_COLOUR, 0xFF606060)); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE) + .getInt(MHQConstants.INTERSTELLAR_MAP_CONTRACT_SEARCH_RADIUS_COLOUR, 0xFF606060)); } public void setInterstellarMapContractSearchRadiusColour(final Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.INTERSTELLAR_MAP_CONTRACT_SEARCH_RADIUS_COLOUR, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE) + .putInt(MHQConstants.INTERSTELLAR_MAP_CONTRACT_SEARCH_RADIUS_COLOUR, value.getRGB()); } - //endregion Interstellar Map Tab + // endregion Interstellar Map Tab - //region Personnel Tab + // region Personnel Tab public PersonnelFilterStyle getPersonnelFilterStyle() { return PersonnelFilterStyle.valueOf(userPreferences.node(MHQConstants.DISPLAY_NODE) .get(MHQConstants.PERSONNEL_FILTER_STYLE, PersonnelFilterStyle.STANDARD.name())); @@ -179,18 +202,21 @@ public void setPersonnelFilterStyle(PersonnelFilterStyle value) { } public boolean getPersonnelFilterOnPrimaryRole() { - return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.PERSONNEL_FILTER_ON_PRIMARY_ROLE, false); + return userPreferences.node(MHQConstants.DISPLAY_NODE).getBoolean(MHQConstants.PERSONNEL_FILTER_ON_PRIMARY_ROLE, + false); } public void setPersonnelFilterOnPrimaryRole(boolean value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.PERSONNEL_FILTER_ON_PRIMARY_ROLE, value); + userPreferences.node(MHQConstants.DISPLAY_NODE).putBoolean(MHQConstants.PERSONNEL_FILTER_ON_PRIMARY_ROLE, + value); } - //endregion Personnel Tab - //endregion Display Tab + // endregion Personnel Tab + // endregion Display Tab - //region Colours + // region Colours public Color getDeployedForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.DEPLOYED_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.DEPLOYED_FOREGROUND, + Color.BLACK.getRGB())); } public void setDeployedForeground(Color value) { @@ -198,7 +224,8 @@ public void setDeployedForeground(Color value) { } public Color getDeployedBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.DEPLOYED_BACKGROUND, Color.LIGHT_GRAY.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.DEPLOYED_BACKGROUND, + Color.LIGHT_GRAY.getRGB())); } public void setDeployedBackground(Color value) { @@ -206,23 +233,28 @@ public void setDeployedBackground(Color value) { } public Color getBelowContractMinimumForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.BELOW_CONTRACT_MINIMUM_FOREGROUND, Color.RED.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE) + .getInt(MHQConstants.BELOW_CONTRACT_MINIMUM_FOREGROUND, Color.RED.getRGB())); } public void setBelowContractMinimumForeground(Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.BELOW_CONTRACT_MINIMUM_FOREGROUND, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.BELOW_CONTRACT_MINIMUM_FOREGROUND, + value.getRGB()); } public Color getBelowContractMinimumBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.BELOW_CONTRACT_MINIMUM_BACKGROUND, UIManager.getColor("Table.background").getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt( + MHQConstants.BELOW_CONTRACT_MINIMUM_BACKGROUND, UIManager.getColor("Table.background").getRGB())); } public void setBelowContractMinimumBackground(Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.BELOW_CONTRACT_MINIMUM_BACKGROUND, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.BELOW_CONTRACT_MINIMUM_BACKGROUND, + value.getRGB()); } public Color getInTransitForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.IN_TRANSIT_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.IN_TRANSIT_FOREGROUND, + Color.BLACK.getRGB())); } public void setInTransitForeground(Color value) { @@ -230,7 +262,8 @@ public void setInTransitForeground(Color value) { } public Color getInTransitBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.IN_TRANSIT_BACKGROUND, Color.MAGENTA.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.IN_TRANSIT_BACKGROUND, + Color.MAGENTA.getRGB())); } public void setInTransitBackground(Color value) { @@ -238,7 +271,8 @@ public void setInTransitBackground(Color value) { } public Color getRefittingForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.REFITTING_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.REFITTING_FOREGROUND, + Color.BLACK.getRGB())); } public void setRefittingForeground(Color value) { @@ -246,7 +280,8 @@ public void setRefittingForeground(Color value) { } public Color getRefittingBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.REFITTING_BACKGROUND, Color.CYAN.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.REFITTING_BACKGROUND, + Color.CYAN.getRGB())); } public void setRefittingBackground(Color value) { @@ -254,7 +289,8 @@ public void setRefittingBackground(Color value) { } public Color getMothballingForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLING_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLING_FOREGROUND, + Color.BLACK.getRGB())); } public void setMothballingForeground(Color value) { @@ -262,8 +298,8 @@ public void setMothballingForeground(Color value) { } public Color getMothballingBackground() { - // new Color(153, 153, 255) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLING_BACKGROUND, 0xFF9999FF)); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLING_BACKGROUND, + 0xFF9999FF)); } public void setMothballingBackground(Color value) { @@ -271,7 +307,8 @@ public void setMothballingBackground(Color value) { } public Color getMothballedForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLED_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLED_FOREGROUND, + Color.BLACK.getRGB())); } public void setMothballedForeground(Color value) { @@ -279,8 +316,8 @@ public void setMothballedForeground(Color value) { } public Color getMothballedBackground() { - // new Color(204, 204, 255) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLED_BACKGROUND, 0xFFCCCCFF)); + return new Color( + userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.MOTHBALLED_BACKGROUND, 0xFFCCCCFF)); } public void setMothballedBackground(Color value) { @@ -288,7 +325,8 @@ public void setMothballedBackground(Color value) { } public Color getNotRepairableForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NOT_REPAIRABLE_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NOT_REPAIRABLE_FOREGROUND, + Color.BLACK.getRGB())); } public void setNotRepairableForeground(Color value) { @@ -296,8 +334,8 @@ public void setNotRepairableForeground(Color value) { } public Color getNotRepairableBackground() { - // new Color(190, 150, 55) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NOT_REPAIRABLE_BACKGROUND, 0xFFBE9637)); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NOT_REPAIRABLE_BACKGROUND, + 0xFFBE9637)); } public void setNotRepairableBackground(Color value) { @@ -305,7 +343,8 @@ public void setNotRepairableBackground(Color value) { } public Color getNonFunctionalForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NON_FUNCTIONAL_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NON_FUNCTIONAL_FOREGROUND, + Color.BLACK.getRGB())); } public void setNonFunctionalForeground(Color value) { @@ -313,8 +352,8 @@ public void setNonFunctionalForeground(Color value) { } public Color getNonFunctionalBackground() { - // new Color(205, 92, 92) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NON_FUNCTIONAL_BACKGROUND, 0xFFCD5C5C)); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NON_FUNCTIONAL_BACKGROUND, + 0xFFCD5C5C)); } public void setNonFunctionalBackground(Color value) { @@ -322,24 +361,28 @@ public void setNonFunctionalBackground(Color value) { } public Color getNeedsPartsFixedForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NEEDS_PARTS_FIXED_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE) + .getInt(MHQConstants.NEEDS_PARTS_FIXED_FOREGROUND, Color.BLACK.getRGB())); } public void setNeedsPartsFixedForeground(Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.NEEDS_PARTS_FIXED_FOREGROUND, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.NEEDS_PARTS_FIXED_FOREGROUND, + value.getRGB()); } public Color getNeedsPartsFixedBackground() { - // new Color(238, 238, 0) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.NEEDS_PARTS_FIXED_BACKGROUND, 0xFFEEEE00)); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE) + .getInt(MHQConstants.NEEDS_PARTS_FIXED_BACKGROUND, 0xFFEEEE00)); } public void setNeedsPartsFixedBackground(Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.NEEDS_PARTS_FIXED_BACKGROUND, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.NEEDS_PARTS_FIXED_BACKGROUND, + value.getRGB()); } public Color getUnmaintainedForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNMAINTAINED_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNMAINTAINED_FOREGROUND, + Color.BLACK.getRGB())); } public void setUnmaintainedForeground(Color value) { @@ -347,7 +390,8 @@ public void setUnmaintainedForeground(Color value) { } public Color getUnmaintainedBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNMAINTAINED_BACKGROUND, Color.ORANGE.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNMAINTAINED_BACKGROUND, + Color.ORANGE.getRGB())); } public void setUnmaintainedBackground(Color value) { @@ -355,7 +399,8 @@ public void setUnmaintainedBackground(Color value) { } public Color getUncrewedForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNCREWED_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNCREWED_FOREGROUND, + Color.BLACK.getRGB())); } public void setUncrewedForeground(Color value) { @@ -363,8 +408,8 @@ public void setUncrewedForeground(Color value) { } public Color getUncrewedBackground() { - // new Color(218, 130, 255) - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNCREWED_BACKGROUND, 0xFFDA82FF)); + return new Color( + userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.UNCREWED_BACKGROUND, 0xFFDA82FF)); } public void setUncrewedBackground(Color value) { @@ -372,7 +417,8 @@ public void setUncrewedBackground(Color value) { } public Color getLoanOverdueForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.LOAN_OVERDUE_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.LOAN_OVERDUE_FOREGROUND, + Color.BLACK.getRGB())); } public void setLoanOverdueForeground(Color value) { @@ -380,7 +426,8 @@ public void setLoanOverdueForeground(Color value) { } public Color getLoanOverdueBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.LOAN_OVERDUE_BACKGROUND, Color.RED.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.LOAN_OVERDUE_BACKGROUND, + Color.RED.getRGB())); } public void setLoanOverdueBackground(Color value) { @@ -388,7 +435,8 @@ public void setLoanOverdueBackground(Color value) { } public Color getInjuredForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.INJURED_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.INJURED_FOREGROUND, + Color.BLACK.getRGB())); } public void setInjuredForeground(Color value) { @@ -396,7 +444,8 @@ public void setInjuredForeground(Color value) { } public Color getInjuredBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.INJURED_BACKGROUND, Color.RED.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.INJURED_BACKGROUND, + Color.RED.getRGB())); } public void setInjuredBackground(Color value) { @@ -404,7 +453,8 @@ public void setInjuredBackground(Color value) { } public Color getHealedInjuriesForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.HEALED_INJURIES_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.HEALED_INJURIES_FOREGROUND, + Color.BLACK.getRGB())); } public void setHealedInjuriesForeground(Color value) { @@ -412,7 +462,8 @@ public void setHealedInjuriesForeground(Color value) { } public Color getHealedInjuriesBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.HEALED_INJURIES_BACKGROUND, 0xEE9A00)); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.HEALED_INJURIES_BACKGROUND, + 0xEE9A00)); } public void setHealedInjuriesBackground(Color value) { @@ -420,7 +471,8 @@ public void setHealedInjuriesBackground(Color value) { } public Color getPregnantForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.PREGNANT_FOREGROUND, Color.BLACK.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.PREGNANT_FOREGROUND, + Color.BLACK.getRGB())); } public void setPregnantForeground(Color value) { @@ -428,7 +480,8 @@ public void setPregnantForeground(Color value) { } public Color getPregnantBackground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.PREGNANT_BACKGROUND, 0X2BAD43)); + return new Color( + userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.PREGNANT_BACKGROUND, 0X2BAD43)); } public void setPregnantBackground(Color value) { @@ -436,15 +489,18 @@ public void setPregnantBackground(Color value) { } public Color getStratConHexCoordForeground() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.STRATCON_HEX_COORD_FOREGROUND, Color.GREEN.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE) + .getInt(MHQConstants.STRATCON_HEX_COORD_FOREGROUND, Color.GREEN.getRGB())); } public void setStratConHexCoordForeground(Color value) { - userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.STRATCON_HEX_COORD_FOREGROUND, value.getRGB()); + userPreferences.node(MHQConstants.DISPLAY_NODE).putInt(MHQConstants.STRATCON_HEX_COORD_FOREGROUND, + value.getRGB()); } public Color getFontColorNegative() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.FONT_COLOR_NEGATIVE, Color.RED.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.FONT_COLOR_NEGATIVE, + Color.RED.getRGB())); } /** @@ -459,7 +515,8 @@ public void setFontColorNegative(Color value) { } public Color getFontColorPositive() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.FONT_COLOR_POSITIVE, Color.GREEN.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.FONT_COLOR_POSITIVE, + Color.GREEN.getRGB())); } /** @@ -474,7 +531,8 @@ public void setFontColorPositive(Color value) { } public Color getFontColorWarning() { - return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.FONT_COLOR_WARNING, Color.ORANGE.getRGB())); + return new Color(userPreferences.node(MHQConstants.DISPLAY_NODE).getInt(MHQConstants.FONT_COLOR_WARNING, + Color.ORANGE.getRGB())); } /** @@ -501,19 +559,20 @@ public String convertFontColorToHexColor(Color color) { return String.format("#%02x%02x%02x", red, green, blue); } - //endregion Colours + // endregion Colours - //region Fonts + // region Fonts public String getMedicalViewDialogHandwritingFont() { - return userPreferences.node(MHQConstants.FONTS_NODE).get(MHQConstants.MEDICAL_VIEW_DIALOG_HANDWRITING_FONT, "Angelina"); + return userPreferences.node(MHQConstants.FONTS_NODE).get(MHQConstants.MEDICAL_VIEW_DIALOG_HANDWRITING_FONT, + "Angelina"); } public void setMedicalViewDialogHandwritingFont(final String value) { userPreferences.node(MHQConstants.FONTS_NODE).put(MHQConstants.MEDICAL_VIEW_DIALOG_HANDWRITING_FONT, value); } - //endregion Fonts + // endregion Fonts - //region Autosave + // region Autosave public boolean getNoAutosaveValue() { return userPreferences.node(MHQConstants.AUTOSAVE_NODE).getBoolean(MHQConstants.NO_SAVE_KEY, false); } @@ -555,7 +614,8 @@ public void setAutosaveYearlyValue(boolean value) { } public boolean getAutosaveBeforeMissionsValue() { - return userPreferences.node(MHQConstants.AUTOSAVE_NODE).getBoolean(MHQConstants.SAVE_BEFORE_MISSIONS_KEY, false); + return userPreferences.node(MHQConstants.AUTOSAVE_NODE).getBoolean(MHQConstants.SAVE_BEFORE_MISSIONS_KEY, + false); } public void setAutosaveBeforeMissionsValue(boolean value) { @@ -570,9 +630,9 @@ public int getMaximumNumberOfAutosavesValue() { public void setMaximumNumberOfAutosavesValue(int value) { userPreferences.node(MHQConstants.AUTOSAVE_NODE).putInt(MHQConstants.MAXIMUM_NUMBER_SAVES_KEY, value); } - //endregion Autosave + // endregion Autosave - //region New Day + // region New Day public boolean getNewDayAstechPoolFill() { return userPreferences.node(MHQConstants.NEW_DAY_NODE).getBoolean(MHQConstants.NEW_DAY_ASTECH_POOL_FILL, true); } @@ -598,28 +658,35 @@ public void setNewDayMRMS(final boolean value) { } public boolean getNewDayForceIconOperationalStatus() { - return userPreferences.node(MHQConstants.NEW_DAY_NODE).getBoolean(MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS, true); + return userPreferences.node(MHQConstants.NEW_DAY_NODE) + .getBoolean(MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS, true); } public void setNewDayForceIconOperationalStatus(final boolean value) { - userPreferences.node(MHQConstants.NEW_DAY_NODE).putBoolean(MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS, value); + userPreferences.node(MHQConstants.NEW_DAY_NODE).putBoolean(MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS, + value); } public ForceIconOperationalStatusStyle getNewDayForceIconOperationalStatusStyle() { - return ForceIconOperationalStatusStyle.valueOf(userPreferences.node(MHQConstants.NEW_DAY_NODE).get(MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS_STYLE, ForceIconOperationalStatusStyle.BORDER.name())); + return ForceIconOperationalStatusStyle.valueOf(userPreferences.node(MHQConstants.NEW_DAY_NODE).get( + MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS_STYLE, + ForceIconOperationalStatusStyle.BORDER.name())); } public void setNewDayForceIconOperationalStatusStyle(final ForceIconOperationalStatusStyle value) { - userPreferences.node(MHQConstants.NEW_DAY_NODE).put(MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS_STYLE, value.name()); + userPreferences.node(MHQConstants.NEW_DAY_NODE).put(MHQConstants.NEW_DAY_FORCE_ICON_OPERATIONAL_STATUS_STYLE, + value.name()); } - //endregion New Day + // endregion New Day - //region Campaign XML Save Options + // region Campaign XML Save Options /** - * @return A value indicating if the campaign should be written to a gzipped file, if possible. + * @return A value indicating if the campaign should be written to a gzipped + * file, if possible. */ public boolean getPreferGzippedOutput() { - return userPreferences.node(MHQConstants.XML_SAVES_NODE).getBoolean(MHQConstants.PREFER_GZIPPED_CAMPAIGN_FILE, true); + return userPreferences.node(MHQConstants.XML_SAVES_NODE).getBoolean(MHQConstants.PREFER_GZIPPED_CAMPAIGN_FILE, + true); } /** @@ -627,7 +694,8 @@ public boolean getPreferGzippedOutput() { * This allows the Save dialog to present the user with the correct file * type on subsequent saves. * - * @param value A value indicating whether or not the campaign should be gzipped if possible. + * @param value A value indicating whether or not the campaign should be gzipped + * if possible. */ public void setPreferGzippedOutput(boolean value) { userPreferences.node(MHQConstants.XML_SAVES_NODE).putBoolean(MHQConstants.PREFER_GZIPPED_CAMPAIGN_FILE, value); @@ -648,52 +716,63 @@ public boolean getSaveMothballState() { public void setSaveMothballState(boolean value) { userPreferences.node(MHQConstants.XML_SAVES_NODE).putBoolean(MHQConstants.SAVE_MOTHBALL_STATE, value); } - //endregion Campaign XML Save Options + // endregion Campaign XML Save Options - //region File Paths + // region File Paths /** - * @return the path of the folder to load when loading or saving bulk rank systems + * @return the path of the folder to load when loading or saving bulk rank + * systems */ public String getRankSystemsPath() { - return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.RANK_SYSTEMS_DIRECTORY_PATH, "userdata/data/universe/"); + return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.RANK_SYSTEMS_DIRECTORY_PATH, + "userdata/data/universe/"); } /** - * This sets the path where one saves or loads their rank systems from, as this is not required + * This sets the path where one saves or loads their rank systems from, as this + * is not required * for any data but improves UX. * - * @param value the path where the person saved their last bulk rank system export + * @param value the path where the person saved their last bulk rank system + * export */ public void setRankSystemsPath(final String value) { userPreferences.node(MHQConstants.FILE_PATH_NODE).put(MHQConstants.RANK_SYSTEMS_DIRECTORY_PATH, value); } /** - * @return the path of the folder to load when loading or saving an individual rank system + * @return the path of the folder to load when loading or saving an individual + * rank system */ public String getIndividualRankSystemPath() { - return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.INDIVIDUAL_RANK_SYSTEM_DIRECTORY_PATH, "userdata/data/universe/"); + return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.INDIVIDUAL_RANK_SYSTEM_DIRECTORY_PATH, + "userdata/data/universe/"); } /** - * This sets the path where one saves or loads their individual rank system, as this is not + * This sets the path where one saves or loads their individual rank system, as + * this is not * required for any data but improves UX. * - * @param value the path where the person saved their last individual rank system. + * @param value the path where the person saved their last individual rank + * system. */ public void setIndividualRankSystemPath(final String value) { - userPreferences.node(MHQConstants.FILE_PATH_NODE).put(MHQConstants.INDIVIDUAL_RANK_SYSTEM_DIRECTORY_PATH, value); + userPreferences.node(MHQConstants.FILE_PATH_NODE).put(MHQConstants.INDIVIDUAL_RANK_SYSTEM_DIRECTORY_PATH, + value); } /** * @return the path of the folder to load when exporting a unit sprite */ public String getUnitSpriteExportPath() { - return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.UNIT_SPRITE_EXPORT_DIRECTORY_PATH, ""); + return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.UNIT_SPRITE_EXPORT_DIRECTORY_PATH, + ""); } /** - * This sets the path where one saves their unit sprite during export, as this is not + * This sets the path where one saves their unit sprite during export, as this + * is not * required for any data but improves UX. * * @param value the path where the person saved their last unit sprite export @@ -706,29 +785,33 @@ public void setUnitSpriteExportPath(final String value) { * @return the path of the folder to load when exporting a layered force icon */ public String getLayeredForceIconPath() { - return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.LAYERED_FORCE_ICON_DIRECTORY_PATH, "userdata/data/images/force/"); + return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.LAYERED_FORCE_ICON_DIRECTORY_PATH, + "userdata/data/images/force/"); } /** - * This sets the path where one saves their layered force icon during export, as this is not + * This sets the path where one saves their layered force icon during export, as + * this is not * required for any data but improves UX. * - * @param value the path where the person saved their last layered force icon export + * @param value the path where the person saved their last layered force icon + * export */ public void setLayeredForceIconPath(final String value) { userPreferences.node(MHQConstants.FILE_PATH_NODE).put(MHQConstants.LAYERED_FORCE_ICON_DIRECTORY_PATH, value); } public String getCompanyGenerationDirectoryPath() { - return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.COMPANY_GENERATION_DIRECTORY_PATH, "mmconf/mhqCompanyGenerationPresets/"); + return userPreferences.node(MHQConstants.FILE_PATH_NODE).get(MHQConstants.COMPANY_GENERATION_DIRECTORY_PATH, + "mmconf/mhqCompanyGenerationPresets/"); } public void setCompanyGenerationDirectoryPath(final String value) { userPreferences.node(MHQConstants.FILE_PATH_NODE).put(MHQConstants.COMPANY_GENERATION_DIRECTORY_PATH, value); } - //endregion File Paths + // endregion File Paths - //region Nag Tab + // region Nag Tab public boolean getNagDialogIgnore(final String key) { return userPreferences.node(MHQConstants.NAG_NODE).getBoolean(key, false); } @@ -736,9 +819,9 @@ public boolean getNagDialogIgnore(final String key) { public void setNagDialogIgnore(final String key, final boolean value) { userPreferences.node(MHQConstants.NAG_NODE).putBoolean(key, value); } - //endregion Nag Tab + // endregion Nag Tab - //region Miscellaneous Options + // region Miscellaneous Options public int getStartGameDelay() { return userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).getInt(MHQConstants.START_GAME_DELAY, 1000); } @@ -752,31 +835,38 @@ public int getStartGameClientDelay() { } public void setStartGameClientDelay(final int startGameClientDelay) { - userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_CLIENT_DELAY, startGameClientDelay); + userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_CLIENT_DELAY, + startGameClientDelay); } public int getStartGameClientRetryCount() { - return userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).getInt(MHQConstants.START_GAME_CLIENT_RETRY_COUNT, 1000); + return userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).getInt(MHQConstants.START_GAME_CLIENT_RETRY_COUNT, + 1000); } public void setStartGameClientRetryCount(final int startGameClientRetryCount) { - userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_CLIENT_RETRY_COUNT, startGameClientRetryCount); + userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_CLIENT_RETRY_COUNT, + startGameClientRetryCount); } public int getStartGameBotClientDelay() { - return userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).getInt(MHQConstants.START_GAME_BOT_CLIENT_DELAY, 50); + return userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).getInt(MHQConstants.START_GAME_BOT_CLIENT_DELAY, + 50); } public void setStartGameBotClientDelay(final int startGameBotClientDelay) { - userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_BOT_CLIENT_DELAY, startGameBotClientDelay); + userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_BOT_CLIENT_DELAY, + startGameBotClientDelay); } public int getStartGameBotClientRetryCount() { - return userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).getInt(MHQConstants.START_GAME_BOT_CLIENT_RETRY_COUNT, 250); + return userPreferences.node(MHQConstants.MISCELLANEOUS_NODE) + .getInt(MHQConstants.START_GAME_BOT_CLIENT_RETRY_COUNT, 250); } public void setStartGameBotClientRetryCount(final int startGameBotClientRetryCount) { - userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_BOT_CLIENT_RETRY_COUNT, startGameBotClientRetryCount); + userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).putInt(MHQConstants.START_GAME_BOT_CLIENT_RETRY_COUNT, + startGameBotClientRetryCount); } public CompanyGenerationMethod getDefaultCompanyGenerationMethod() { @@ -785,7 +875,8 @@ public CompanyGenerationMethod getDefaultCompanyGenerationMethod() { } public void setDefaultCompanyGenerationMethod(final CompanyGenerationMethod value) { - userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).put(MHQConstants.DEFAULT_COMPANY_GENERATION_METHOD, value.name()); + userPreferences.node(MHQConstants.MISCELLANEOUS_NODE).put(MHQConstants.DEFAULT_COMPANY_GENERATION_METHOD, + value.name()); } - //endregion Miscellaneous Options + // endregion Miscellaneous Options } diff --git a/MekHQ/src/mekhq/MHQOptionsChangedEvent.java b/MekHQ/src/mekhq/MHQOptionsChangedEvent.java index 936245d075..270d59c614 100644 --- a/MekHQ/src/mekhq/MHQOptionsChangedEvent.java +++ b/MekHQ/src/mekhq/MHQOptionsChangedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2022 - The MegaMek Team. All Rights Reserved. + * Copyright (c) 2020-2024 - The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * @@ -25,9 +25,9 @@ * The event handlers cannot modify these options. */ public class MHQOptionsChangedEvent extends MMEvent { - //region Constructors + // region Constructors public MHQOptionsChangedEvent() { super(); } - //endregion Constructors + // endregion Constructors } diff --git a/MekHQ/src/mekhq/MHQStaticDirectoryManager.java b/MekHQ/src/mekhq/MHQStaticDirectoryManager.java index bc4252b172..cf12d55263 100644 --- a/MekHQ/src/mekhq/MHQStaticDirectoryManager.java +++ b/MekHQ/src/mekhq/MHQStaticDirectoryManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2021 - The MegaMek Team. All Rights Reserved. + * Copyright (c) 2020-2024 - The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * @@ -18,41 +18,44 @@ */ package mekhq; +import java.io.File; + +import org.apache.logging.log4j.LogManager; + import megamek.client.ui.swing.tileset.MMStaticDirectoryManager; import megamek.common.annotations.Nullable; import megamek.common.util.fileUtils.AbstractDirectory; import megamek.common.util.fileUtils.DirectoryItems; import megamek.common.util.fileUtils.ImageFileFactory; import mekhq.io.AwardFileFactory; -import org.apache.logging.log4j.LogManager; - -import java.io.File; public class MHQStaticDirectoryManager extends MMStaticDirectoryManager { - //region Variable Declarations + // region Variable Declarations private static AbstractDirectory forceIconDirectory; private static AbstractDirectory awardIconDirectory; private static AbstractDirectory storySplashDirectory; private static AbstractDirectory userStorySplashDirectory; private static AbstractDirectory userStoryPortraitDirectory; - // Re-parsing Prevention Variables: They are True at startup and when the specified directory - // should be re-parsed, and are used to avoid re-parsing the directory repeatedly when there's + // Re-parsing Prevention Variables: They are True at startup and when the + // specified directory + // should be re-parsed, and are used to avoid re-parsing the directory + // repeatedly when there's // an error. private static boolean parseForceIconDirectory = true; private static boolean parseAwardIconDirectory = true; private static boolean parseStorySplashDirectory = true; private static boolean parseUserStorySplashDirectory = true; private static boolean parseUserStoryPortraitDirectory = true; - //endregion Variable Declarations + // endregion Variable Declarations - //region Constructors + // region Constructors protected MHQStaticDirectoryManager() { // This class is not to be instantiated } - //endregion Constructors + // endregion Constructors - //region Initialization + // region Initialization /** * This initializes all of the directories under this manager */ @@ -69,9 +72,11 @@ public static void initialize() { * @see #refreshForceIcons() */ private static void initializeForceIcons() { - // Read in and parse MekHQ's force icon folder only when first called or when refreshed + // Read in and parse MekHQ's force icon folder only when first called or when + // refreshed if (parseForceIconDirectory) { - // Set parseForceIconDirectory to false to avoid parsing repeatedly when something fails + // Set parseForceIconDirectory to false to avoid parsing repeatedly when + // something fails parseForceIconDirectory = false; try { forceIconDirectory = new DirectoryItems(new File("data/images/force"), // TODO : Remove inline file path @@ -88,12 +93,15 @@ private static void initializeForceIcons() { * @see #refreshAwardIcons() */ private static void initializeAwardIcons() { - // Read in and parse MekHQ's award icon folder only when first called or when refreshed + // Read in and parse MekHQ's award icon folder only when first called or when + // refreshed if (parseAwardIconDirectory) { - // Set parseAwardIconDirectory to false to avoid parsing repeatedly when something fails + // Set parseAwardIconDirectory to false to avoid parsing repeatedly when + // something fails parseAwardIconDirectory = false; try { - awardIconDirectory = new DirectoryItems(new File("data/images/awards"), // TODO : Remove inline file path + awardIconDirectory = new DirectoryItems(new File("data/images/awards"), // TODO : Remove inline file + // path new AwardFileFactory()); } catch (Exception e) { LogManager.getLogger().error("Could not parse the award icon directory!", e); @@ -102,14 +110,17 @@ private static void initializeAwardIcons() { } /** - * Parses MekHQ's storyarcs icon folder when first called or when it was refreshed. + * Parses MekHQ's storyarcs icon folder when first called or when it was + * refreshed. * * @see #refreshStorySplash() */ private static void initializeStorySplash() { - // Read in and parse MekHQ's force icon folder only when first called or when refreshed + // Read in and parse MekHQ's force icon folder only when first called or when + // refreshed if (parseStorySplashDirectory) { - // Set parseForceIconDirectory to false to avoid parsing repeatedly when something fails + // Set parseForceIconDirectory to false to avoid parsing repeatedly when + // something fails parseStorySplashDirectory = false; try { File f = new File("data/images/storysplash"); @@ -123,13 +134,16 @@ private static void initializeStorySplash() { } /** - * Parses the user's Story Arc portraits directory when first called or when it was refreshed + * Parses the user's Story Arc portraits directory when first called or when it + * was refreshed * */ public static void initializeUserStoryPortraits(String path) { - // Read in and parse MekHQ's force icon folder only when first called or when refreshed + // Read in and parse MekHQ's force icon folder only when first called or when + // refreshed if (parseUserStoryPortraitDirectory) { - // Set parseForceIconDirectory to false to avoid parsing repeatedly when something fails + // Set parseForceIconDirectory to false to avoid parsing repeatedly when + // something fails parseUserStoryPortraitDirectory = false; try { File f = new File(path); @@ -143,13 +157,16 @@ public static void initializeUserStoryPortraits(String path) { } /** - * Parses the user's Story Arc storyarcs directory when first called or when it was refreshed + * Parses the user's Story Arc storyarcs directory when first called or when it + * was refreshed * */ public static void initializeUserStorySplash(String path) { - // Read in and parse MekHQ's force icon folder only when first called or when refreshed + // Read in and parse MekHQ's force icon folder only when first called or when + // refreshed if (parseUserStorySplashDirectory) { - // Set parseForceIconDirectory to false to avoid parsing repeatedly when something fails + // Set parseForceIconDirectory to false to avoid parsing repeatedly when + // something fails parseUserStorySplashDirectory = false; try { File f = new File(path); @@ -161,14 +178,17 @@ public static void initializeUserStorySplash(String path) { } } } - //endregion Initialization + // endregion Initialization - //region Getters + // region Getters /** - * Returns an AbstractDirectory object containing all force icon filenames found in MekHQ's + * Returns an AbstractDirectory object containing all force icon filenames found + * in MekHQ's * force icon folder. - * @return an AbstractDirectory object with the force icon folders and filenames. - * May be null if the directory cannot be parsed. + * + * @return an AbstractDirectory object with the force icon folders and + * filenames. + * May be null if the directory cannot be parsed. */ public static @Nullable AbstractDirectory getForceIcons() { initializeForceIcons(); @@ -176,10 +196,13 @@ public static void initializeUserStorySplash(String path) { } /** - * Returns an AbstractDirectory object containing all award icon filenames found in MekHQ's + * Returns an AbstractDirectory object containing all award icon filenames found + * in MekHQ's * award icon folder. - * @return an AbstractDirectory object with the award icon folders and filenames. - * May be null if the directory cannot be parsed. + * + * @return an AbstractDirectory object with the award icon folders and + * filenames. + * May be null if the directory cannot be parsed. */ public static @Nullable AbstractDirectory getAwardIcons() { initializeAwardIcons(); @@ -187,10 +210,13 @@ public static void initializeUserStorySplash(String path) { } /** - * Returns an AbstractDirectory object containing all story icon filenames found in MekHQ's + * Returns an AbstractDirectory object containing all story icon filenames found + * in MekHQ's * storyarc icon folder. - * @return an AbstractDirectory object with the story icon folders and filenames. - * May be null if the directory cannot be parsed. + * + * @return an AbstractDirectory object with the story icon folders and + * filenames. + * May be null if the directory cannot be parsed. */ public static @Nullable AbstractDirectory getStorySplash() { initializeStorySplash(); @@ -198,32 +224,40 @@ public static void initializeUserStorySplash(String path) { } /** - * Returns an AbstractDirectory object containing all story portrait filenames found in the user's + * Returns an AbstractDirectory object containing all story portrait filenames + * found in the user's * storyarc portraits folder. - * @return an AbstractDirectory object with the story portrait folders and filenames. - * May be null if the directory cannot be parsed. + * + * @return an AbstractDirectory object with the story portrait folders and + * filenames. + * May be null if the directory cannot be parsed. */ public static @Nullable AbstractDirectory getUserStoryPortraits() { - //we do not initialize here because initialization requires a specific path + // we do not initialize here because initialization requires a specific path return userStoryPortraitDirectory; } /** - * Returns an AbstractDirectory object containing all story arc image filenames found in the user's + * Returns an AbstractDirectory object containing all story arc image filenames + * found in the user's * storyarc folder. - * @return an AbstractDirectory object with the story portrait folders and filenames. - * May be null if the directory cannot be parsed. + * + * @return an AbstractDirectory object with the story portrait folders and + * filenames. + * May be null if the directory cannot be parsed. */ public static @Nullable AbstractDirectory getUserStorySplash() { - //we do not initialize here because initialization requires a specific path + // we do not initialize here because initialization requires a specific path return userStorySplashDirectory; } - //endregion Getters + // endregion Getters - //region Refreshers + // region Refreshers /** - * Re-reads MekHQ's force icon folder and returns the updated AbstractDirectory object. This - * will update the AbstractDirectory object with changes to the force icons (like added image + * Re-reads MekHQ's force icon folder and returns the updated AbstractDirectory + * object. This + * will update the AbstractDirectory object with changes to the force icons + * (like added image * files and folders) while MekHQ is running. * * @see #getForceIcons() @@ -234,8 +268,10 @@ public static AbstractDirectory refreshForceIcons() { } /** - * Re-reads MekHQ's award icon folder and returns the updated AbstractDirectory object. This - * will update the AbstractDirectory object with changes to the award icons (like added image + * Re-reads MekHQ's award icon folder and returns the updated AbstractDirectory + * object. This + * will update the AbstractDirectory object with changes to the award icons + * (like added image * files and folders) while MekHQ is running. * * @see #getAwardIcons() @@ -246,8 +282,10 @@ public static AbstractDirectory refreshAwardIcons() { } /** - * Re-reads MekHQ's story icon folder and returns the updated AbstractDirectory object. This - * will update the AbstractDirectory object with changes to the story icons (like added image + * Re-reads MekHQ's story icon folder and returns the updated AbstractDirectory + * object. This + * will update the AbstractDirectory object with changes to the story icons + * (like added image * files and folders) while MekHQ is running. * * @see #getStorySplash() @@ -256,5 +294,5 @@ public static AbstractDirectory refreshStorySplash() { parseStorySplashDirectory = true; return getStorySplash(); } - //endregion Refreshers + // endregion Refreshers } diff --git a/MekHQ/src/mekhq/MekHQ.java b/MekHQ/src/mekhq/MekHQ.java index 1405cfcc4d..a051ed446f 100644 --- a/MekHQ/src/mekhq/MekHQ.java +++ b/MekHQ/src/mekhq/MekHQ.java @@ -21,7 +21,33 @@ */ package mekhq; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.Window; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; +import java.util.stream.Stream; + +import javax.swing.InputMap; +import javax.swing.JOptionPane; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.text.DefaultEditorKit; + +import org.apache.logging.log4j.LogManager; + +import io.sentry.Sentry; import megamek.MegaMek; +import megamek.SuiteConstants; import megamek.client.Client; import megamek.client.generator.RandomNameGenerator; import megamek.client.generator.RandomUnitGenerator; @@ -55,26 +81,12 @@ import mekhq.gui.utilities.ObservableString; import mekhq.service.AutosaveService; import mekhq.service.IAutosaveService; -import org.apache.logging.log4j.LogManager; - -import javax.swing.*; -import javax.swing.text.DefaultEditorKit; -import java.awt.*; -import java.awt.event.KeyEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.FileNotFoundException; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import java.util.stream.Stream; /** * The main class of the application. */ public class MekHQ implements GameListener { - //region Variable Declarations + // region Variable Declarations private static final SuitePreferences mhqPreferences = new SuitePreferences(); private static final MHQOptions mhqOptions = new MHQOptions(); private static final EventBus EVENT_BUS = new EventBus(); @@ -104,7 +116,7 @@ public class MekHQ implements GameListener { private IconPackage iconPackage = new IconPackage(); private final IAutosaveService autosaveService; - //endregion Variable Declarations + // endregion Variable Declarations public static SuitePreferences getMHQPreferences() { return mhqPreferences; @@ -163,9 +175,9 @@ private MekHQ() { */ protected void startup() { // Setup user preferences - MegaMek.getMMPreferences().loadFromFile(MHQConstants.MM_PREFERENCES_FILE); - MegaMekLab.getMMLPreferences().loadFromFile(MHQConstants.MML_PREFERENCES_FILE); - getMHQPreferences().loadFromFile(MHQConstants.MHQ_PREFERENCES_FILE); + MegaMek.getMMPreferences().loadFromFile(SuiteConstants.MM_PREFERENCES_FILE); + MegaMekLab.getMMLPreferences().loadFromFile(SuiteConstants.MML_PREFERENCES_FILE); + getMHQPreferences().loadFromFile(SuiteConstants.MHQ_PREFERENCES_FILE); setUserPreferences(); @@ -188,7 +200,7 @@ public void restart() { } @Deprecated // These need to be migrated to the Suite Constants / Suite Options Setup - private void setUserPreferences() { + private static void setUserPreferences() { try { PreferencesNode preferences = MekHQ.getMHQPreferences().forClass(MekHQ.class); @@ -221,6 +233,7 @@ private void setUserPreferences() { financesDirectory = new ObservableString("financesDirectory", "."); preferences.manage(new StringPreference(financesDirectory)); } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("Failed to set user preferences", ex); } } @@ -240,9 +253,9 @@ public void exit() { campaignGUI.getFrame().dispose(); } - MegaMek.getMMPreferences().saveToFile(MHQConstants.MM_PREFERENCES_FILE); - MegaMekLab.getMMLPreferences().saveToFile(MHQConstants.MML_PREFERENCES_FILE); - getMHQPreferences().saveToFile(MHQConstants.MHQ_PREFERENCES_FILE); + MegaMek.getMMPreferences().saveToFile(SuiteConstants.MM_PREFERENCES_FILE); + MegaMekLab.getMMLPreferences().saveToFile(SuiteConstants.MML_PREFERENCES_FILE); + getMHQPreferences().saveToFile(SuiteConstants.MHQ_PREFERENCES_FILE); System.exit(0); } @@ -255,12 +268,29 @@ public void showNewView() { * Main method launching the application. */ public static void main(String... args) { + // Configure Sentry with defaults. Although the client defaults to enabled, the + // properties file is used to disable + // it and additional configuration can be done inside of the sentry.properties + // file. The defaults for everything else is set here. + Sentry.init(options -> { + options.setEnableExternalConfiguration(true); + options.setDsn("https://a05b2064798e2b8d46ac620b4497a072@sentry.tapenvy.us/10"); + options.setEnvironment("production"); + options.setTracesSampleRate(0.2); + options.setDebug(true); + options.setServerName("MegaMekClient"); + options.setRelease(SuiteConstants.VERSION.toString()); + }); + // First, create a global default exception handler Thread.setDefaultUncaughtExceptionHandler((thread, t) -> { + Sentry.captureException(t); LogManager.getLogger().error("Uncaught Exception Detected", t); final String name = t.getClass().getName(); JOptionPane.showMessageDialog(null, - String.format("Uncaught %s detected. Please open up an issue containing all logs, campaign save file, and customs at https://github.com/MegaMek/mekhq/issues", name), + String.format( + "Uncaught %s detected. Please open up an issue containing all logs, campaign save file, and customs at https://github.com/MegaMek/mekhq/issues", + name), "Uncaught " + name, JOptionPane.ERROR_MESSAGE); }); @@ -277,7 +307,9 @@ public static void main(String... args) { } public static void initializeLogging(final String originProject) { - LogManager.getLogger().info(getUnderlyingInformation(originProject)); + if (LogManager.getLogger().isInfoEnabled()) { + LogManager.getLogger().info(getUnderlyingInformation(originProject)); + } } /** @@ -334,6 +366,7 @@ public void joinGame(Scenario scenario, List meks) { try { client = new Client(playerName, serverAddress, port); } catch (Exception e) { + Sentry.captureException(e); LogManager.getLogger().error("Failed to connect to server properly", e); return; } @@ -417,52 +450,52 @@ public synchronized void stopHost() { @Override public void gameBoardChanged(GameBoardChangeEvent e) { - + // Why Empty? } @Override public void gameBoardNew(GameBoardNewEvent e) { - + // Why Empty? } @Override public void gameEnd(GameEndEvent e) { - + // Why Empty? } @Override public void gameEntityChange(GameEntityChangeEvent e) { - + // Why Empty? } @Override public void gameEntityNew(GameEntityNewEvent e) { - + // Why Empty? } @Override public void gameEntityNewOffboard(GameEntityNewOffboardEvent e) { - + // Why Empty? } @Override public void gameEntityRemove(GameEntityRemoveEvent e) { - + // Why Empty? } @Override public void gameMapQuery(GameMapQueryEvent e) { - + // Why Empty? } @Override public void gameNewAction(GameNewActionEvent e) { - + // Why Empty? } @Override public void gamePhaseChange(GamePhaseChangeEvent e) { - + // Why Empty? } @Override @@ -486,7 +519,8 @@ public void gameVictory(GameVictoryEvent gve) { resolveDialog.setVisible(true); if (!getCampaign().getRetirementDefectionTracker().getRetirees().isEmpty()) { - RetirementDefectionDialog rdd = new RetirementDefectionDialog(campaignGUI, campaignGUI.getCampaign().getMission(currentScenario.getMissionId()), false); + RetirementDefectionDialog rdd = new RetirementDefectionDialog(campaignGUI, + campaignGUI.getCampaign().getMission(currentScenario.getMissionId()), false); rdd.setLocation(rdd.getLocation().x, 0); rdd.setVisible(true); @@ -518,7 +552,8 @@ public void gameVictory(GameVictoryEvent gve) { autoAwardsController.PostScenarioController(getCampaign(), personnel, scenarioKills); } - // we need to trigger ScenarioResolvedEvent before stopping the thread or currentScenario may become null + // we need to trigger ScenarioResolvedEvent before stopping the thread or + // currentScenario may become null MekHQ.triggerEvent(new ScenarioResolvedEvent(currentScenario)); gameThread.requestStop(); @@ -532,50 +567,53 @@ public void gameVictory(GameVictoryEvent gve) { final File tempImageDirectory = new File("data/images/temp"); if (tempImageDirectory.isDirectory()) { // This can't be null because of the above - Stream.of(tempImageDirectory.listFiles()).filter(file -> file.getName().endsWith(".png")).forEach(File::delete); + Stream.of(tempImageDirectory.listFiles()).filter(file -> file.getName().endsWith(".png")) + .forEach(File::delete); } } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("", ex); } } @Override public void gamePlayerChange(GamePlayerChangeEvent e) { - + // Why Empty? } @Override public void gamePlayerChat(GamePlayerChatEvent e) { - + // Why Empty? } @Override public void gamePlayerConnected(GamePlayerConnectedEvent e) { - + // Why Empty? } @Override public void gamePlayerDisconnected(GamePlayerDisconnectedEvent e) { - + // Why Empty? } @Override public void gameReport(GameReportEvent e) { - + // Why Empty? } @Override public void gameSettingsChange(GameSettingsChangeEvent e) { - + // Why Empty? } @Override public void gameTurnChange(GameTurnChangeEvent e) { - + // Why Empty? } @Override public void gameClientFeedbackRequest(GameCFREvent e) { + // Why Empty? } public IconPackage getIconPackage() { @@ -585,15 +623,15 @@ public IconPackage getIconPackage() { /* * Access methods for event bus. */ - static public void registerHandler(Object handler) { + public static void registerHandler(Object handler) { EVENT_BUS.register(handler); } - static public boolean triggerEvent(MMEvent event) { + public static boolean triggerEvent(MMEvent event) { return EVENT_BUS.trigger(event); } - static public void unregisterHandler(Object handler) { + public static void unregisterHandler(Object handler) { EVENT_BUS.unregister(handler); } @@ -646,9 +684,10 @@ public void propertyChange(PropertyChangeEvent evt) { } private static void addOSXKeyStrokes(InputMap inputMap) { - inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_DOWN_MASK), DefaultEditorKit.copyAction); - inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.META_DOWN_MASK), DefaultEditorKit.cutAction); - inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.META_DOWN_MASK), DefaultEditorKit.pasteAction); - inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.META_DOWN_MASK), DefaultEditorKit.selectAllAction); + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.META_DOWN_MASK), DefaultEditorKit.copyAction); + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.META_DOWN_MASK), DefaultEditorKit.cutAction); + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.META_DOWN_MASK), DefaultEditorKit.pasteAction); + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.META_DOWN_MASK), + DefaultEditorKit.selectAllAction); } } diff --git a/MekHQ/src/mekhq/NullEntityException.java b/MekHQ/src/mekhq/NullEntityException.java index d6b2b450d9..946592f0fe 100644 --- a/MekHQ/src/mekhq/NullEntityException.java +++ b/MekHQ/src/mekhq/NullEntityException.java @@ -1,3 +1,21 @@ +/* Copyright (c) 2019-2024 - The MegaMek Team. All Rights Reserved. + * + * This file is part of MekHQ. + * + * MekHQ is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * MekHQ is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with MekHQ. If not, see . + */ + package mekhq; public class NullEntityException extends Exception { diff --git a/MekHQ/src/mekhq/Utilities.java b/MekHQ/src/mekhq/Utilities.java index 9823df920b..28df784bdb 100644 --- a/MekHQ/src/mekhq/Utilities.java +++ b/MekHQ/src/mekhq/Utilities.java @@ -1,6 +1,6 @@ /* * Copyright (c) 2009 - Jay Lawson (jaylawson39 at yahoo.com). All Rights Reserved. - * Copyright (c) 2019-2022 - The MegaMek Team. All Rights Reserved. + * Copyright (c) 2019-2024 - The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * @@ -19,6 +19,28 @@ */ package mekhq; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; +import java.util.function.Consumer; + +import javax.swing.JTable; +import javax.swing.table.TableModel; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.logging.log4j.LogManager; +import org.w3c.dom.Node; + +import io.sentry.Sentry; import megamek.client.Client; import megamek.client.generator.RandomNameGenerator; import megamek.codeUtilities.ObjectUtility; @@ -40,23 +62,12 @@ import mekhq.campaign.unit.CrewType; import mekhq.campaign.unit.Unit; import mekhq.campaign.unit.UnitTechProgression; -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVPrinter; -import org.apache.logging.log4j.LogManager; -import org.w3c.dom.Node; - -import javax.swing.*; -import javax.swing.table.TableModel; -import java.awt.*; -import java.awt.image.BufferedImage; -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.List; -import java.util.*; -import java.util.function.Consumer; public class Utilities { + private Utilities() { + throw new IllegalStateException("Utilities - Utility Class"); + } + private static final ResourceBundle resourceMap = ResourceBundle.getBundle("mekhq.resources.Utilities", MekHQ.getMHQOptions().getLocale()); @@ -65,12 +76,12 @@ public class Utilities { private static final String[] romanNumerals = "M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I".split(","); public static int roll3d6() { - Vector rolls = new Vector<>(); + ArrayList rolls = new ArrayList<>(); rolls.add(Compute.d6()); rolls.add(Compute.d6()); rolls.add(Compute.d6()); Collections.sort(rolls); - return (rolls.elementAt(0) + rolls.elementAt(1)); + return (rolls.get(0) + rolls.get(1)); } /** @@ -94,8 +105,12 @@ public static List getMunitionsFor(Entity entity, AmmoType currentAmmo final Vector munitions = AmmoType.getMunitionsFor(currentAmmoType.getAmmoType()); if (munitions == null) { - LogManager.getLogger().error(String.format("Cannot getMunitions for %s because of a null munitions list for ammo type %d", - entity.getDisplayName(), currentAmmoType.getAmmoType())); + if (LogManager.getLogger().isErrorEnabled()) { + LogManager.getLogger() + .error(String.format( + "Cannot getMunitions for %s because of a null munitions list for ammo type %d", + entity.getDisplayName(), currentAmmoType.getAmmoType())); + } return Collections.emptyList(); } @@ -105,7 +120,8 @@ public static List getMunitionsFor(Entity entity, AmmoType currentAmmo // TODO : clan/IS limitations? if ((entity instanceof Aero) - && !ammoType.canAeroUse(entity.getGame().getOptions().booleanOption(OptionsConstants.ADVAERORULES_AERO_ARTILLERY_MUNITIONS))) { + && !ammoType.canAeroUse(entity.getGame().getOptions() + .booleanOption(OptionsConstants.ADVAERORULES_AERO_ARTILLERY_MUNITIONS))) { continue; } @@ -116,7 +132,8 @@ public static List getMunitionsFor(Entity entity, AmmoType currentAmmo if (techLvl < Utilities.getSimpleTechLevel(lvl)) { continue; - } else if (TechConstants.isClan(currentAmmoType.getTechLevel(entity.getTechLevelYear())) != TechConstants.isClan(lvl)) { + } else if (TechConstants.isClan(currentAmmoType.getTechLevel(entity.getTechLevelYear())) != TechConstants + .isClan(lvl)) { continue; } @@ -125,7 +142,8 @@ public static List getMunitionsFor(Entity entity, AmmoType currentAmmo continue; } - // When dealing with machine guns, Protos can only use proto-specific machine gun ammo + // When dealing with machine guns, Protos can only use proto-specific machine + // gun ammo if ((entity instanceof Protomech) && ammoType.hasFlag(AmmoType.F_MG) && !ammoType.hasFlag(AmmoType.F_PROTOMECH)) { @@ -143,7 +161,7 @@ public static List getMunitionsFor(Entity entity, AmmoType currentAmmo && (ammoType.hasFlag(AmmoType.F_BATTLEARMOR) == currentAmmoType.hasFlag(AmmoType.F_BATTLEARMOR)) && (ammoType.hasFlag(AmmoType.F_ENCUMBERING) == currentAmmoType.hasFlag(AmmoType.F_ENCUMBERING)) && ((ammoType.getTonnage(entity) == currentAmmoType.getTonnage(entity)) - || ammoType.hasFlag(AmmoType.F_CAP_MISSILE))) { + || ammoType.hasFlag(AmmoType.F_CAP_MISSILE))) { ammoTypes.add(ammoType); } } @@ -153,9 +171,10 @@ public static List getMunitionsFor(Entity entity, AmmoType currentAmmo /** * Returns the last file modified in a directory and all subdirectories * that conforms to a FilenameFilter - * @param dir direction name - * @param filter filter for the file's name - * @return the last file modified in that dir that fits the filter + * + * @param dir direction name + * @param filter filter for the file's name + * @return the last file modified in that dir that fits the filter */ public static @Nullable File lastFileModified(String dir, FilenameFilter filter) { File fl = new File(dir); @@ -174,7 +193,8 @@ public static List getMunitionsFor(Entity entity, AmmoType currentAmmo } } - // ok now we need to recursively search any subdirectories, so see if they contain more + // ok now we need to recursively search any subdirectories, so see if they + // contain more // recent files files = fl.listFiles(); if (files != null) { @@ -230,10 +250,16 @@ public static ArrayList getAllVariants(Entity en, Campaign campaign) { // If the unit doesn't meet the tech filter criteria we continue ITechnology techProg = UnitTechProgression.getProgression(summary, campaign.getTechFaction(), true); if (techProg == null) { - // This should never happen unless there was an exception thrown when calculating the progression. - // In such a case we will log it and take the least restrictive action, which is to let it through. - LogManager.getLogger().warn("Could not determine tech progression for " + summary.getName() - + ", including among available refits."); + // This should never happen unless there was an exception thrown when + // calculating the progression. + // In such a case we will log it and take the least restrictive action, which is + // to let it through. + if (LogManager.getLogger().isWarnEnabled()) { + LogManager.getLogger().warn( + String.format( + "Could not determine tech progression for %s, including among available refits.", + summary.getName())); + } } else if (!campaign.isLegal(techProg)) { continue; } @@ -279,7 +305,8 @@ public static boolean isOmniVariant(Entity entity1, Entity entity2) { || (entity1.getOArmor(loc) != entity2.getOArmor(loc))) { return false; } - // Go through the base entity and make a list of all fixed equipment in this location. + // Go through the base entity and make a list of all fixed equipment in this + // location. for (int slot = 0; slot < entity1.getNumberOfCriticals(loc); slot++) { CriticalSlot crit = entity1.getCritical(loc, slot); if ((null != crit) && (crit.getType() == CriticalSlot.TYPE_EQUIPMENT) @@ -292,8 +319,10 @@ public static boolean isOmniVariant(Entity entity1, Entity entity2) { } } } - // Go through the critical slots in this location for the second entity and remove all - // fixed equipment from the list. If not found or something is left over, there is a + // Go through the critical slots in this location for the second entity and + // remove all + // fixed equipment from the list. If not found or something is left over, there + // is a // fixed equipment difference. for (int slot = 0; slot < entity2.getNumberOfCriticals(loc); slot++) { CriticalSlot crit = entity1.getCritical(loc, slot); @@ -333,7 +362,8 @@ public static int generateExpLevel(int bonus) { } /** - * Simple utility function to take a specified number and randomize it a little bit + * Simple utility function to take a specified number and randomize it a little + * bit * roll 1d6 results in: * 1: target - 2 * 2: target - 1 @@ -356,8 +386,8 @@ public static int randomSkillFromTarget(int target) { } public static Map> genRandomCrewWithCombinedSkill(Campaign c, - Unit u, - String factionCode) { + Unit u, + String factionCode) { Objects.requireNonNull(c); Objects.requireNonNull(u); Objects.requireNonNull(u.getEntity(), "Unit needs to have a valid Entity attached"); @@ -370,13 +400,15 @@ public static Map> genRandomCrewWithCombinedSkill(C Person navigator = null; Person consoleCmdr = null; - // If the entire crew is dead, we still want to generate them. This is because they might + // If the entire crew is dead, we still want to generate them. This is because + // they might // not be truly dead - this will be the case for BA for example - // Also, the user may choose to GM make them un-dead in the resolve scenario dialog + // Also, the user may choose to GM make them un-dead in the resolve scenario + // dialog // Generate solo crews if (u.usesSoloPilot()) { - //region Solo Pilot + // region Solo Pilot Person p; if (u.getEntity() instanceof LandAirMech) { p = c.newPerson(PersonnelRole.LAM_PILOT, factionCode, oldCrew.getGender()); @@ -417,7 +449,7 @@ public static Map> genRandomCrewWithCombinedSkill(C p.addSkill(SkillType.S_GUN_VEE, SkillType.getType(SkillType.S_GUN_VEE).getTarget() - oldCrew.getGunnery(), 0); } else { - //assume tanker if we got here + // assume tanker if we got here p = c.newPerson(PersonnelRole.GROUND_VEHICLE_DRIVER, factionCode, oldCrew.getGender()); p.addSkill(SkillType.S_PILOT_GVEE, SkillType.getType(SkillType.S_PILOT_GVEE).getTarget() - oldCrew.getPiloting(), 0); @@ -427,10 +459,10 @@ public static Map> genRandomCrewWithCombinedSkill(C migrateCrewData(p, oldCrew, 0, true); drivers.add(p); - //endregion Solo Pilot + // endregion Solo Pilot } else { if (oldCrew.getSlotCount() > 1) { - //region Multi-Slot Crew + // region Multi-Slot Crew for (int slot = 0; slot < oldCrew.getSlotCount(); slot++) { Person p = null; if (u.getEntity() instanceof Mech) { @@ -455,21 +487,28 @@ public static Map> genRandomCrewWithCombinedSkill(C drivers.add(p); } } - //endregion Multi-Slot Crew + // endregion Multi-Slot Crew } - // This is a nightmare case, not just for BA. We are also currently assuming that MM and - // therefore the MUL will contain the correct number of crew if more than 1 is included. - // TODO : This should not be an else statement, but rather based on a comparison between - // TODO : the numberPeopleGenerated and a fixed u.getFullCrewSize() (because that doesn't - // TODO : necessarily provide the correct number when called based on my current read on + // This is a nightmare case, not just for BA. We are also currently assuming + // that MM and + // therefore the MUL will contain the correct number of crew if more than 1 is + // included. + // TODO : This should not be an else statement, but rather based on a comparison + // between + // TODO : the numberPeopleGenerated and a fixed u.getFullCrewSize() (because + // that doesn't + // TODO : necessarily provide the correct number when called based on my current + // read on // TODO : 26-Feb-2020) else { // Generate drivers for multi-crewed vehicles and vessels - //Uggh, BA are a nightmare. The getTotalDriverNeeds will adjust for missing/destroyed suits - //but we can't change that because lots of other stuff needs that to be right, so we will hack - //it here to make it the starting squad size - int driversNeeded = u.getTotalDriverNeeds(); + // Uggh, BA are a nightmare. The getTotalDriverNeeds will adjust for + // missing/destroyed suits + // but we can't change that because lots of other stuff needs that to be right, + // so we will hack + // it here to make it the starting squad size + int driversNeeded = u.getTotalDriverNeeds(); if (u.getEntity() instanceof BattleArmor) { driversNeeded = ((BattleArmor) u.getEntity()).getSquadSize(); } @@ -515,7 +554,7 @@ public static Map> genRandomCrewWithCombinedSkill(C SkillType.S_GUN_MECH).getTarget() - oldCrew.getGunnery(), 0); } else { - //assume tanker if we got here + // assume tanker if we got here p = c.newPerson(PersonnelRole.GROUND_VEHICLE_DRIVER, factionCode, oldCrew.getGender(numberPeopleGenerated)); p.addSkill(SkillType.S_PILOT_GVEE, SkillType.getType( @@ -530,7 +569,7 @@ public static Map> genRandomCrewWithCombinedSkill(C drivers.add(p); } - // Rebalance as needed to balance + // Re-balance as needed to balance if (!drivers.isEmpty()) { if (u.getEntity() instanceof SmallCraft || u.getEntity() instanceof Jumpship) { rebalanceCrew(oldCrew.getPiloting(), drivers, SkillType.S_PILOT_SPACE); @@ -564,12 +603,13 @@ public static Map> genRandomCrewWithCombinedSkill(C - oldCrew.getGunnery(), 0); } else { - //assume tanker if we got here + // assume tanker if we got here p = c.newPerson(PersonnelRole.VEHICLE_GUNNER, factionCode, oldCrew.getGender(numberPeopleGenerated)); p.addSkill(SkillType.S_GUN_VEE, randomSkillFromTarget( SkillType.getType(SkillType.S_GUN_VEE).getTarget() - - oldCrew.getGunnery()), 0); + - oldCrew.getGunnery()), + 0); } migrateCrewData(p, oldCrew, numberPeopleGenerated++, true); @@ -589,7 +629,8 @@ public static Map> genRandomCrewWithCombinedSkill(C for (int slot = 0; slot < u.getTotalCrewNeeds(); slot++) { Person p = c.newPerson(u.getEntity().isSupportVehicle() - ? PersonnelRole.VEHICLE_CREW : PersonnelRole.VESSEL_CREW, + ? PersonnelRole.VEHICLE_CREW + : PersonnelRole.VESSEL_CREW, factionCode, oldCrew.getGender(numberPeopleGenerated)); migrateCrewData(p, oldCrew, numberPeopleGenerated++, false); @@ -609,7 +650,7 @@ public static Map> genRandomCrewWithCombinedSkill(C } } - //region Data Gathering + // region Data Gathering Map> result = new HashMap<>(); if (!drivers.isEmpty()) { if (u.usesSoloPilot()) { @@ -632,13 +673,14 @@ public static Map> genRandomCrewWithCombinedSkill(C if (null != consoleCmdr) { result.put(CrewType.TECH_OFFICER, Collections.singletonList(consoleCmdr)); } - //endregion Data Gathering + // endregion Data Gathering return result; } /** * Adjusts the skill levels of the given list of people in the given skill - * until the average skill level matches the given desired skill level (desiredSkill) + * until the average skill level matches the given desired skill level + * (desiredSkill) */ private static void rebalanceCrew(int desiredSkill, List people, String skillType) { int totalGunnery = 0; @@ -655,12 +697,14 @@ private static void rebalanceCrew(int desiredSkill, List people, String // instead of using a monte carlo method: // pick a random person from the crew, update their desired skill one point in - // the direction we want to go. Eventually we will reach the desired skill we want. + // the direction we want to go. Eventually we will reach the desired skill we + // want. while (averageGunnery != desiredSkill) { Person person = ObjectUtility.getRandomItem(eligiblePeople); int skillLevel = person.getSkill(skillType).getLevel(); - // this is put in place to prevent skills from going below minimum or above maximum + // this is put in place to prevent skills from going below minimum or above + // maximum // we eliminate people from the group of that can have their skills changed // if they would do so. boolean skillCannotChange = true; @@ -670,7 +714,8 @@ private static void rebalanceCrew(int desiredSkill, List people, String eligiblePeople.remove(person); person = ObjectUtility.getRandomItem(eligiblePeople); - // if we can't drop anyone's skill any lower or raise it any higher then forget it + // if we can't drop anyone's skill any lower or raise it any higher then forget + // it if (person == null) { return; } @@ -689,29 +734,36 @@ private static void rebalanceCrew(int desiredSkill, List people, String } /** - * Function that determines what name should be used by a person that is created through crew + * Function that determines what name should be used by a person that is created + * through crew * And then assigns them a pre-selected portrait, provided one is to their index * Additionally, any extraData parameters should be migrated here + * * @param p the person to be renamed, if applicable * @param oldCrew the crew object they were a part of * @param crewIndex the index of the person in the crew - * @param crewOptions whether or not to run the populateOptionsFromCrew for this person + * @param crewOptions whether or not to run the populateOptionsFromCrew for this + * person */ private static void migrateCrewData(Person p, Crew oldCrew, int crewIndex, boolean crewOptions) { if (crewOptions) { populateOptionsFromCrew(p, oldCrew); } - // this is a bit of a hack, but instead of tracking it elsewhere we only set gender to - // male or female when a name is generated. G_RANDOMIZE will therefore only be returned for - // crew that don't have names, so we can just leave them with their randomly generated name + // this is a bit of a hack, but instead of tracking it elsewhere we only set + // gender to + // male or female when a name is generated. G_RANDOMIZE will therefore only be + // returned for + // crew that don't have names, so we can just leave them with their randomly + // generated name if (oldCrew.getGender(crewIndex) != Gender.RANDOMIZE) { String givenName = oldCrew.getExtraDataValue(crewIndex, Crew.MAP_GIVEN_NAME); if (StringUtility.isNullOrBlank(givenName)) { String name = oldCrew.getName(crewIndex); - if (!(name.equalsIgnoreCase(RandomNameGenerator.UNNAMED) || name.equalsIgnoreCase(RandomNameGenerator.UNNAMED_FULL_NAME))) { + if (!(name.equalsIgnoreCase(RandomNameGenerator.UNNAMED) + || name.equalsIgnoreCase(RandomNameGenerator.UNNAMED_FULL_NAME))) { p.migrateName(name); } } else { @@ -737,10 +789,11 @@ private static void migrateCrewData(Person p, Crew oldCrew, int crewIndex, boole } /** - * Worker function that takes the PersonnelOptions (SPAs, in other words) from the given + * Worker function that takes the PersonnelOptions (SPAs, in other words) from + * the given * "old crew" and sets them for a person. * - * @param p The person whose SPAs to populate + * @param p The person whose SPAs to populate * @param oldCrew The entity the SPAs of whose crew we're importing */ private static void populateOptionsFromCrew(Person p, Crew oldCrew) { @@ -782,24 +835,24 @@ public static boolean rollProbability(int prob) { } public static int getAgeByExpLevel(int expLevel, boolean clan) { - int baseage = 19; - int ndice = 1; + int baseAge = 19; + int nDice = 1; switch (expLevel) { case SkillType.EXP_REGULAR: - ndice = 2; + nDice = 2; break; case SkillType.EXP_VETERAN: - ndice = 3; + nDice = 3; break; case SkillType.EXP_ELITE: - ndice = 4; + nDice = 4; break; default: break; } - int age = baseage; - while (ndice > 0) { + int age = baseAge; + while (nDice > 0) { int roll = Compute.d6(); // reroll all sixes once if (roll == 6) { @@ -810,7 +863,7 @@ public static int getAgeByExpLevel(int expLevel, boolean clan) { roll = (int) Math.ceil(roll / 2.0); } age += roll; - ndice--; + nDice--; } return age; } @@ -875,29 +928,37 @@ public static int getSimpleTechLevel(int level) { /** * Copied an existing file into a new file - * @param inFile the existing input file + * + * @param inFile the existing input file * @param outFile the new file to copy into - * @see Rose India's tutorial - * for the original code source + * @see Rose + * India's tutorial + * for the original code source */ public static void copyfile(final File inFile, final File outFile) { try (FileInputStream fis = new FileInputStream(inFile); - FileOutputStream fos = new FileOutputStream(outFile)) { + FileOutputStream fos = new FileOutputStream(outFile)) { byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) > 0) { fos.write(buf, 0, len); } - LogManager.getLogger().info(String.format("Copied file %s to file %s", inFile.getPath(), outFile.getPath())); + + if (LogManager.getLogger().isInfoEnabled()) { + LogManager.getLogger() + .info(String.format("Copied file %s to file %s", inFile.getPath(), outFile.getPath())); + } } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("", ex); } } /** * Export a JTable to a CSV file - * @param table the table to save to csv - * @param file the file to save to + * + * @param table the table to save to csv + * @param file the file to save to * @return a csv formatted export of the table */ public static String exportTableToCSV(JTable table, File file) { @@ -983,7 +1044,7 @@ public static String getRomanNumeralsFromArabicNumber(int level, boolean checkZe // Roman numeral, prepended with a space for display purposes StringBuilder roman = new StringBuilder(" "); - int num = level+1; + int num = level + 1; for (int i = 0; i < arabicNumbers.length; i++) { while (num > arabicNumbers[i]) { @@ -998,8 +1059,7 @@ public static String getRomanNumeralsFromArabicNumber(int level, boolean checkZe public static Map sortMapByValue(Map unsortMap, boolean highFirst) { // Convert Map to List - List> list = - new LinkedList<>(unsortMap.entrySet()); + List> list = new LinkedList<>(unsortMap.entrySet()); // Sort list with comparator, to compare the Map values list.sort(Map.Entry.comparingByValue()); @@ -1022,8 +1082,8 @@ public static Map sortMapByValue(Map unsortMap } public static boolean isLikelyCapture(Entity en) { - //most of these conditions are now controlled better in en.canEscape, but there - //are some additional ones we want to add + // most of these conditions are now controlled better in en.canEscape, but there + // are some additional ones we want to add if (!en.canEscape()) { return true; } @@ -1031,7 +1091,8 @@ public static boolean isLikelyCapture(Entity en) { } /** - * Run through the directory and call parser.parse(fis) for each XML file found. Don't recurse. + * Run through the directory and call parser.parse(fis) for each XML file found. + * Don't recurse. */ public static void parseXMLFiles(String dirName, Consumer parser) { parseXMLFiles(dirName, parser, false); @@ -1057,7 +1118,9 @@ public static void parseXMLFiles(String dirName, Consumer parse parser.accept(fis); } catch (Exception ex) { // Ignore this file then - LogManager.getLogger().error("Exception trying to parse " + file.getPath() + " - ignoring.", ex); + LogManager.getLogger().error( + String.format("Exception trying to parse %s - ignoring.", file.getPath()), + ex); } } } @@ -1073,7 +1136,7 @@ public static void parseXMLFiles(String dirName, Consumer parse if (null != dirs && dirs.length > 0) { Arrays.sort(dirs, Comparator.comparing(File::getPath)); for (File subDirectory : dirs) { - if (subDirectory.isDirectory() ) { + if (subDirectory.isDirectory()) { parseXMLFiles(subDirectory.getPath(), parser, true); } } @@ -1093,38 +1156,43 @@ public static BufferedImage toBufferedImage(Image img) { } // Create a buffered image with transparency - BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); + BufferedImage bImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // Draw the image on to the buffered image - Graphics2D bGr = bimage.createGraphics(); + Graphics2D bGr = bImage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); // Return the buffered image - return bimage; + return bImage; } /** - * Handles loading a player's transported units onto their transports once a megamek scenario has actually started. - * This separates loading air and ground units, since map type and planetary conditions may prohibit ground unit deployment + * Handles loading a player's transported units onto their transports once a + * megamek scenario has actually started. + * This separates loading air and ground units, since map type and planetary + * conditions may prohibit ground unit deployment * while the player wants fighters launched to defend the transport - * @param trnId - The MM id of the transport entity we want to load - * @param toLoad - List of Entity ids for the units we want to load into this transport - * @param client - the player's Client instance - * @param loadDropShips - Should DropShip units be loaded? + * + * @param trnId - The MM id of the transport entity we want to load + * @param toLoad - List of Entity ids for the units we want to load into + * this transport + * @param client - the player's Client instance + * @param loadDropShips - Should DropShip units be loaded? * @param loadSmallCraft - Should Small Craft units be loaded? - * @param loadFighters - Should aero type units be loaded? - * @param loadGround - should ground units be loaded? + * @param loadFighters - Should aero type units be loaded? + * @param loadGround - should ground units be loaded? */ public static void loadPlayerTransports(int trnId, Set toLoad, Client client, - boolean loadDropShips, boolean loadSmallCraft, - boolean loadFighters, boolean loadGround) { + boolean loadDropShips, boolean loadSmallCraft, + boolean loadFighters, boolean loadGround) { if (!loadDropShips && !loadSmallCraft && !loadFighters && !loadGround) { // Nothing to do. Get outta here! return; } Entity transport = client.getEntity(trnId); - // Reset transporter status, as currentSpace might still retain updates from when the Unit + // Reset transporter status, as currentSpace might still retain updates from + // when the Unit // was assigned to the Transport on the TO&E tab transport.resetTransporter(); for (int id : toLoad) { @@ -1132,7 +1200,8 @@ public static void loadPlayerTransports(int trnId, Set toLoad, Client c if (cargo == null) { continue; } - // Find a bay with space in it and update that space so the next unit can process + // Find a bay with space in it and update that space so the next unit can + // process cargo.setTargetBay(selectBestBayFor(cargo, transport)); } // Reset transporter status again so that sendLoadEntity can process correctly @@ -1164,20 +1233,26 @@ public static void loadPlayerTransports(int trnId, Set toLoad, Client c private static void sendLoadEntity(Client client, int id, int trnId, Entity cargo) { client.sendLoadEntity(id, trnId, cargo.getTargetBay()); - // Add a wait to make sure that we don't start processing client.sendLoadEntity out of order + // Add a wait to make sure that we don't start processing client.sendLoadEntity + // out of order try { Thread.sleep(500); } catch (Exception ex) { + Sentry.captureException(ex); LogManager.getLogger().error("", ex); } } /** - * Method that loops through a Transport ship's bays and finds one with enough available space to load the Cargo unit - * Helps assign a bay number to the Unit record so that transport bays can be automatically filled once a game of MegaMek is started - * @param cargo The Entity we wish to load into a bay + * Method that loops through a Transport ship's bays and finds one with enough + * available space to load the Cargo unit + * Helps assign a bay number to the Unit record so that transport bays can be + * automatically filled once a game of MegaMek is started + * + * @param cargo The Entity we wish to load into a bay * @param transport The Bay-equipped Entity we want to load Cargo aboard - * @return integer representing the (lowest) bay number on Transport that has space to carry Cargo + * @return integer representing the (lowest) bay number on Transport that has + * space to carry Cargo */ public static int selectBestBayFor(Entity cargo, Entity transport) { if (cargo.getUnitType() == UnitType.DROPSHIP) { @@ -1186,7 +1261,8 @@ public static int selectBestBayFor(Entity cargo, Entity transport) { return dockingCollar.getCollarNumber(); } } - } if (cargo.getUnitType() == UnitType.SMALL_CRAFT) { + } + if (cargo.getUnitType() == UnitType.SMALL_CRAFT) { for (Bay b : transport.getTransportBays()) { if ((b instanceof SmallCraftBay) && b.canLoad(cargo)) { // Load 1 unit into the bay @@ -1260,16 +1336,20 @@ public static int selectBestBayFor(Entity cargo, Entity transport) { } /** - * Testable function to get the original unit based on information from a new unit + * Testable function to get the original unit based on information from a new + * unit + * * @param newE new Entity we want to read information from - * @return MechSummary that most closely represents the original of the new Entity + * @return MechSummary that most closely represents the original of the new + * Entity * @throws EntityLoadingException */ public static MechSummary retrieveOriginalUnit(Entity newE) throws EntityLoadingException { MechSummaryCache cacheInstance = MechSummaryCache.getInstance(); cacheInstance.loadMechData(); - // I need to change the new entity to the one from the mtf file now, so that equipment numbers will match + // I need to change the new entity to the one from the mtf file now, so that + // equipment numbers will match MechSummary summary = cacheInstance.getMech(newE.getFullChassis() + " " + newE.getModel()); if (null == summary) { @@ -1291,7 +1371,8 @@ public static List generateEntityStub(List entities) { List stub = new ArrayList<>(); for (Entity en : entities) { if (null == en) { - stub.add("No random assignment table found for faction"); + stub.add("No random assignment table found for faction"); } else { stub.add("" + en.getCrew().getName() + " (" + en.getCrew().getGunnery() + '/' + @@ -1304,14 +1385,16 @@ public static List generateEntityStub(List entities) { } /** - * Display a descriptive character string for the deployment parameters in an object that implements IPlayerSettings + * Display a descriptive character string for the deployment parameters in an + * object that implements IPlayerSettings + * * @param player object that implements IPlayerSettings * @return A character string */ public static String getDeploymentString(Player player) { StringBuilder result = new StringBuilder(""); - if(player.getStartingPos() >=0 + if (player.getStartingPos() >= 0 && player.getStartingPos() <= IStartingPositions.START_LOCATION_NAMES.length) { result.append(IStartingPositions.START_LOCATION_NAMES[player.getStartingPos()]); } @@ -1340,7 +1423,9 @@ public static String getDeploymentString(IPlayerSettings settings) { } /** - * Create a Player object from IPlayerSettings parameters. Useful for tracking these variables in dialogs. + * Create a Player object from IPlayerSettings parameters. Useful for tracking + * these variables in dialogs. + * * @param settings an object that implements IPlayerSettings * @return A Player object */ @@ -1358,9 +1443,11 @@ public static Player createPlayer(IPlayerSettings settings) { } /** - * Update values of an object that implements IPlayerSettings from a player object + * Update values of an object that implements IPlayerSettings from a player + * object + * * @param settings An object that implements IPlayerSettings - * @param player A Player object from which to read values + * @param player A Player object from which to read values */ public static void updatePlayerSettings(IPlayerSettings settings, Player player) { settings.setStartingPos(player.getStartingPos()); @@ -1370,6 +1457,5 @@ public static void updatePlayerSettings(IPlayerSettings settings, Player player) settings.setStartingAnyNWy(player.getStartingAnyNWy()); settings.setStartingAnySEx(player.getStartingAnySEx()); settings.setStartingAnySEy(player.getStartingAnySEy()); - } } From c9714baad5c9a2355189967fc7e9d9ed362d9ff1 Mon Sep 17 00:00:00 2001 From: Richard J Hancock Date: Sat, 6 Jul 2024 21:24:31 -0500 Subject: [PATCH 2/5] Removed extra spacing on logger per request --- MekHQ/src/mekhq/AtBGameThread.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/MekHQ/src/mekhq/AtBGameThread.java b/MekHQ/src/mekhq/AtBGameThread.java index 4cf7d4824a..c175549816 100644 --- a/MekHQ/src/mekhq/AtBGameThread.java +++ b/MekHQ/src/mekhq/AtBGameThread.java @@ -150,7 +150,8 @@ public void run() { mapSettings.setMedium(MapSettings.MEDIUM_SPACE); mapSettings.getBoardsSelectedVector().add(MapSettings.BOARD_GENERATED); } else if (scenario.isUsingFixedMap()) { - String board = scenario.getMap().replace(".board", ""); // TODO : remove inline file type + // TODO : remove inline file type + String board = scenario.getMap().replace(".board", ""); board = board.replace("\\", "/"); mapSettings.getBoardsSelectedVector().add(board); @@ -158,18 +159,16 @@ public void run() { mapSettings.setMedium(MapSettings.MEDIUM_ATMOSPHERE); } } else { - File mapgenFile = new File("data/mapgen/" + scenario.getMap() + ".xml"); // TODO : Remove inline - // file path + // TODO : Remove inline file path + File mapgenFile = new File("data/mapgen/" + scenario.getMap() + ".xml"); try (InputStream is = new FileInputStream(mapgenFile)) { mapSettings = MapSettings.getInstance(is); } catch (FileNotFoundException ex) { Sentry.captureException(ex); - - LogManager.getLogger() - .error( - String.format("Could not load map file data/mapgen/%s.xml", scenario.getMap()), - ex); // TODO: Remove inline file path + LogManager.getLogger().error( + String.format("Could not load map file data/mapgen/%s.xml", scenario.getMap()), + ex); } if (scenario.getBoardType() == Scenario.T_ATMOSPHERE) { From 804dc66d322b509fa4907d8c8c4831c806d1d278 Mon Sep 17 00:00:00 2001 From: Richard J Hancock Date: Sat, 6 Jul 2024 21:52:06 -0500 Subject: [PATCH 3/5] Minor changes related to SK Removal --- .github/workflows/ci.yml | 6 +++--- .github/workflows/nightly-ci.yml | 2 +- MekHQ/build.gradle | 1 - build.gradle | 3 --- 4 files changed, 4 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ddf2f6a103..ecc33ba1e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,7 +47,7 @@ jobs: - name: Add MMRevision file run: | - echo ${{ steps.find_mm.outputs.mmBranch }} >> mekhq/mm-revision.txt + echo ${{ steps.find_mm.outputs.mmBranch }} >> mekhq/mekhq/mm-revision.txt - name: Checkout MegaMek uses: actions/checkout@v4 @@ -73,7 +73,7 @@ jobs: - name: Add MMLRevision file run: | - echo ${{ steps.find_mml.outputs.mmlBranch }} >> mekhq/mml-revision.txt + echo ${{ steps.find_mml.outputs.mmlBranch }} >> mekhq/mekhq/mml-revision.txt - name: Checkout MegaMekLab uses: actions/checkout@v4 @@ -97,7 +97,7 @@ jobs: - name: Add MHQRevision file run: | - echo ${{ github.sha }} >> megamek/mhq-revision.txt + echo ${{ github.sha }} >> mekhq/mekhq/mhq-revision.txt - name: Build with Gradle working-directory: mekhq diff --git a/.github/workflows/nightly-ci.yml b/.github/workflows/nightly-ci.yml index 55ea200f41..a94550ba71 100644 --- a/.github/workflows/nightly-ci.yml +++ b/.github/workflows/nightly-ci.yml @@ -52,7 +52,7 @@ jobs: - name: Add MHQRevision file run: | - echo ${{ github.sha }} >> megamek/mhq-revision.txt + echo ${{ github.sha }} >> mekhq/mekhq/mhq-revision.txt - name: Build with Gradle working-directory: megameklab diff --git a/MekHQ/build.gradle b/MekHQ/build.gradle index 3c15b9284d..d1e56a318a 100644 --- a/MekHQ/build.gradle +++ b/MekHQ/build.gradle @@ -4,7 +4,6 @@ import java.time.LocalDateTime plugins { id 'application' - id 'maven-publish' id 'edu.sc.seis.launch4j' version '3.0.5' id 'jacoco' id 'java' diff --git a/build.gradle b/build.gradle index ee82a8b115..6a9fbcd177 100644 --- a/build.gradle +++ b/build.gradle @@ -11,9 +11,6 @@ java { allprojects { repositories { mavenCentral() - maven { - url 'https://jitpack.io' - } } } From 5af7f29b772e8eb73323f8e78f4b24f175a3c2cb Mon Sep 17 00:00:00 2001 From: Richard J Hancock Date: Sat, 6 Jul 2024 22:10:07 -0500 Subject: [PATCH 4/5] Fixed casing for MHQ Revision File --- .github/workflows/nightly-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/nightly-ci.yml b/.github/workflows/nightly-ci.yml index a94550ba71..dbf5b501ac 100644 --- a/.github/workflows/nightly-ci.yml +++ b/.github/workflows/nightly-ci.yml @@ -52,7 +52,7 @@ jobs: - name: Add MHQRevision file run: | - echo ${{ github.sha }} >> mekhq/mekhq/mhq-revision.txt + echo ${{ github.sha }} >> mekhq/MekHQ/mhq-revision.txt - name: Build with Gradle working-directory: megameklab From 5222f644c2c3c11aba36c465e966361c7bfebdf0 Mon Sep 17 00:00:00 2001 From: Richard J Hancock Date: Sat, 6 Jul 2024 22:11:42 -0500 Subject: [PATCH 5/5] Additional Paths for Revision files --- .github/workflows/ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ecc33ba1e9..a80d15c048 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,7 +47,7 @@ jobs: - name: Add MMRevision file run: | - echo ${{ steps.find_mm.outputs.mmBranch }} >> mekhq/mekhq/mm-revision.txt + echo ${{ steps.find_mm.outputs.mmBranch }} >> mekhq/MekHQ/mm-revision.txt - name: Checkout MegaMek uses: actions/checkout@v4 @@ -73,7 +73,7 @@ jobs: - name: Add MMLRevision file run: | - echo ${{ steps.find_mml.outputs.mmlBranch }} >> mekhq/mekhq/mml-revision.txt + echo ${{ steps.find_mml.outputs.mmlBranch }} >> mekhq/MekHQ/mml-revision.txt - name: Checkout MegaMekLab uses: actions/checkout@v4 @@ -97,7 +97,7 @@ jobs: - name: Add MHQRevision file run: | - echo ${{ github.sha }} >> mekhq/mekhq/mhq-revision.txt + echo ${{ github.sha }} >> mekhq/MekHQ/mhq-revision.txt - name: Build with Gradle working-directory: mekhq