Skip to content

Commit

Permalink
Convert all AppPreference preferences to new type
Browse files Browse the repository at this point in the history
All preferences are now instances of `Preference<T>`. The few types that had additional update logic not use the change
listener to notify observers about it.

In order to really make this change effective, we no longer store any colors component-wise since they can easily be
stored as a single integer. For those preferences that once had component-wise storage, the static initializer ensures
backwards compatibility by detecting whether a new value is present and loading the old values if not.
  • Loading branch information
kwvanderlinde committed Oct 8, 2024
1 parent a2f7265 commit 110e1e6
Show file tree
Hide file tree
Showing 76 changed files with 742 additions and 2,009 deletions.
4 changes: 2 additions & 2 deletions src/main/java/net/rptools/lib/image/ImageUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public static BufferedImage createCompatibleImage(
Graphics2D g = null;
try {
g = compImg.createGraphics();
AppPreferences.getRenderQuality().setRenderingHints(g);
AppPreferences.renderQuality.get().setRenderingHints(g);
g.drawImage(img, 0, 0, width, height, null);
} finally {
if (g != null) {
Expand Down Expand Up @@ -442,7 +442,7 @@ public static ImageIcon scaleImage(ImageIcon icon, int w, int h) {
*/
public static BufferedImage scaleBufferedImage(BufferedImage image, int width, int height) {
ResampleOp resampleOp =
new ResampleOp(width, height, AppPreferences.getRenderQuality().getResampleOpFilter());
new ResampleOp(width, height, AppPreferences.renderQuality.get().getResampleOpFilter());
return resampleOp.filter(image, null);
}
}
2 changes: 1 addition & 1 deletion src/main/java/net/rptools/lib/image/ThumbnailManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ private Image createThumbnail(File file) throws IOException {
new BufferedImage(imgSize.width, imgSize.height, ImageUtil.pickBestTransparency(image));

Graphics2D g = thumbnailImage.createGraphics();
AppPreferences.getRenderQuality().setShrinkRenderingHints(g);
AppPreferences.renderQuality.get().setShrinkRenderingHints(g);
g.drawImage(image, 0, 0, imgSize.width, imgSize.height, null);
g.dispose();

Expand Down
8 changes: 4 additions & 4 deletions src/main/java/net/rptools/maptool/client/AppActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -2600,7 +2600,7 @@ protected void done() {
ImageManager.flush(); // Clear out the old campaign's images

AppState.setCampaignFile(campaignFile);
AppPreferences.setLoadDir(campaignFile.getParentFile());
AppPreferences.loadDirectory.set(campaignFile.getParentFile());
AppMenuBar.getMruManager().addMRUCampaign(campaignFile);
campaign.campaign.setName(AppState.getCampaignName()); // Update campaign name

Expand Down Expand Up @@ -2792,7 +2792,7 @@ private static void saveAndUpdateCampaignName(File selectedFile, Runnable onSucc
}
doSaveCampaign(campaignFile, onSuccess);
AppState.setCampaignFile(campaignFile);
AppPreferences.setSaveDir(campaignFile.getParentFile());
AppPreferences.saveDirectory.set(campaignFile.getParentFile());
AppMenuBar.getMruManager().addMRUCampaign(AppState.getCampaignFile());
if (MapTool.isHostingServer() || MapTool.isPersonalServer()) {
MapTool.serverCommand().setCampaignName(AppState.getCampaignName());
Expand Down Expand Up @@ -2846,7 +2846,7 @@ protected void executeAction() {
}
}
PersistenceUtil.saveMap(zr.getZone(), mapFile);
AppPreferences.setSaveMapDir(mapFile.getParentFile());
AppPreferences.mapSaveDirectory.set(mapFile.getParentFile());
MapTool.showInformation("msg.info.mapSaved");
} catch (IOException ioe) {
MapTool.showError("msg.error.failedSaveMap", ioe);
Expand Down Expand Up @@ -2973,7 +2973,7 @@ protected void done() {

try {
PersistedMap map = get();
AppPreferences.setLoadDir(mapFile.getParentFile());
AppPreferences.loadDirectory.set(mapFile.getParentFile());
if ((map.zone.getExposedArea() != null && !map.zone.getExposedArea().isEmpty())
|| (map.zone.getExposedAreaMetaData() != null
&& !map.zone.getExposedAreaMetaData().isEmpty())) {
Expand Down
1,826 changes: 264 additions & 1,562 deletions src/main/java/net/rptools/maptool/client/AppPreferences.java

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/main/java/net/rptools/maptool/client/AppState.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ public class AppState {
private static PropertyChangeSupport changeSupport = new PropertyChangeSupport(AppState.class);

static {
showLumensOverlay = AppPreferences.getLumensOverlayShowByDefault();
showLights = AppPreferences.getLightsShowByDefault();
showLumensOverlay = AppPreferences.lumensOverlayShowByDefault.get();
showLights = AppPreferences.lightsShowByDefault.get();
}

public static void addPropertyChangeListener(PropertyChangeListener listener) {
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/net/rptools/maptool/client/AppUpdate.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ public class AppUpdate {
*/
public static boolean gitHubReleases() {
// AppPreferences.setSkipAutoUpdate(false); // For testing only
if (AppPreferences.getSkipAutoUpdate()) return false;
if (AppPreferences.skipAutoUpdate.get()) {
return false;
}

// Default for Linux?
String DOWNLOAD_EXTENSION = ".deb";
Expand Down Expand Up @@ -75,7 +77,7 @@ public static boolean gitHubReleases() {
return false;
}

if (!AppPreferences.getSkipAutoUpdateRelease().equals(latestReleaseId)
if (!AppPreferences.skipAutoUpdateRelease.get().equals(latestReleaseId)
&& ModelVersionManager.isBefore(runningVersion, latestReleaseVersion)) {
JsonArray releaseAssets = latestRelease.get("assets").getAsJsonArray();

Expand Down Expand Up @@ -240,9 +242,11 @@ private static boolean showMessage(String releaseId, String tagName) {
options[1]);
boolean dontAsk = dontAskCheckbox.isSelected();

if (dontAsk) AppPreferences.setSkipAutoUpdate(true);
if (dontAsk) {
AppPreferences.skipAutoUpdate.set(true);
}

if (result == JOptionPane.CANCEL_OPTION) AppPreferences.setSkipAutoUpdateRelease(releaseId);
if (result == JOptionPane.CANCEL_OPTION) AppPreferences.skipAutoUpdateRelease.set(releaseId);

return (result == JOptionPane.YES_OPTION);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private void execute() {
private boolean executeAndContinue() {

int interval =
AppPreferences.getAutoSaveIncrement()
AppPreferences.autoSaveIncrement.get()
* 1000
* (DeveloperOptions.Toggle.AutoSaveMeasuredInSeconds.isEnabled() ? 1 : 60);

Expand Down
32 changes: 16 additions & 16 deletions src/main/java/net/rptools/maptool/client/ChatAutoSave.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import net.rptools.maptool.client.ui.commandpanel.CommandPanel;
import net.rptools.maptool.language.I18N;
import org.apache.logging.log4j.LogManager;
Expand All @@ -29,34 +30,35 @@
* @author frank
*/
public class ChatAutoSave {
private static Logger log = LogManager.getLogger(ChatAutoSave.class);
private static final ChatAutoSave self = new ChatAutoSave();
private static final Logger log = LogManager.getLogger(ChatAutoSave.class);

private final Timer countdown;
private TimerTask task;
private long delay;
private static String chatlog = null;
private String chatlog = null;

private ChatAutoSave() {
public ChatAutoSave() {
log.debug("Creating chat log autosave timer"); // $NON-NLS-1$
// Only way to set the delay is to call changeTimeout()
delay = 0;
this.delay = 0;
countdown = new Timer();
}

private static TimerTask createTimer(final long timeout) {
private TimerTask createTimer(final long timeout) {
TimerTask t =
new TimerTask() {
@Override
public void run() {
log.info("Running the task");

log.debug("Chat log autosave countdown complete from {}", timeout); // $NON-NLS-1$
if (chatlog == null) {
String filename = AppPreferences.getChatFilenameFormat();
String filename = AppPreferences.chatFilenameFormat.get();
// FJE Ugly kludge to replace older default entry with newer default
// TODO This is going into 1.3.b77 so remove it in 3-4 builds
if ("chatlog.html".equals(filename)) { // $NON-NLS-1$
AppPreferences.clearChatFilenameFormat();
filename = AppPreferences.getChatFilenameFormat();
AppPreferences.chatFilenameFormat.remove();
filename = AppPreferences.chatFilenameFormat.get();
}
chatlog = String.format(filename, new Date()).replace(':', '-');
}
Expand Down Expand Up @@ -89,13 +91,9 @@ public void run() {
return t;
}

private static ChatAutoSave getInstance() {
return self;
}

public static void changeTimeout(int timeout) {
getInstance().delay = timeout * 1000 * 60;
getInstance().start();
public void setTimeout(int timeout) {
delay = TimeUnit.MINUTES.toMillis(timeout);
start();
}

private void stop() {
Expand All @@ -106,6 +104,8 @@ private void stop() {
}

private void start() {
log.info("Starting the countdown again");

if (delay > 0) {
stop();
task = createTimer(delay);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -917,7 +917,7 @@ private void handle(EnforceZoneViewMsg msg) {
if (renderer == null) {
return;
}
if (AppPreferences.getFitGMView()) {
if (AppPreferences.fitGmView.get()) {
renderer.enforceView(x, y, scale, gmWidth, gmHeight);
} else {
renderer.setScale(scale);
Expand Down
30 changes: 17 additions & 13 deletions src/main/java/net/rptools/maptool/client/MapTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public class MapTool {
// Set it to 500 (from 100) for now to support larger asset window previews
// TODO: Add preferences option as well as add auto-purge after x days preferences
private static final Dimension THUMBNAIL_SIZE =
new Dimension(AppPreferences.getThumbnailSize(), AppPreferences.getThumbnailSize());
new Dimension(AppPreferences.thumbnailSize.get(), AppPreferences.thumbnailSize.get());

private static ThumbnailManager thumbnailManager;
private static String version = "DEVELOPMENT";
Expand All @@ -168,6 +168,7 @@ public class MapTool {
private static TaskBarFlasher taskbarFlasher;
private static MapToolLineParser parser = new MapToolLineParser();
private static String lastWhisperer;
private static ChatAutoSave chatAutoSave;

// Jamz: To support new command line parameters for multi-monitor support & enhanced PrintStream
private static boolean debug = false;
Expand Down Expand Up @@ -394,7 +395,7 @@ public static int confirmImpl(String title, int buttons, String message, Object.
* @return true if the token should be deleted.
*/
public static boolean confirmTokenDelete() {
if (!AppPreferences.getTokensWarnWhenDeleted()) {
if (!AppPreferences.tokensWarnWhenDeleted.get()) {
return true;
}

Expand All @@ -404,7 +405,7 @@ public static boolean confirmTokenDelete() {
// "Yes, don't show again" Button
if (val == 2) {
showInformation("msg.confirm.deleteToken.removed");
AppPreferences.setTokensWarnWhenDeleted(false);
AppPreferences.tokensWarnWhenDeleted.set(false);
}
// Any version of 'Yes' returns true, false otherwise
return val == JOptionPane.YES_OPTION || val == 2;
Expand All @@ -418,7 +419,7 @@ public static boolean confirmTokenDelete() {
* @return <code>true</code> if the user clicks either Yes button, <code>falsee</code> otherwise.
*/
public static boolean confirmDrawDelete() {
if (!AppPreferences.getDrawWarnWhenDeleted()) {
if (!AppPreferences.drawingsWarnWhenDeleted.get()) {
return true;
}

Expand All @@ -428,7 +429,7 @@ public static boolean confirmDrawDelete() {
// "Yes, don't show again" Button
if (val == JOptionPane.CANCEL_OPTION) {
showInformation("msg.confirm.deleteDraw.removed");
AppPreferences.setDrawWarnWhenDeleted(false);
AppPreferences.drawingsWarnWhenDeleted.set(false);
}
// Any version of 'Yes' returns true, otherwise false
return val == JOptionPane.YES_OPTION || val == JOptionPane.CANCEL_OPTION;
Expand Down Expand Up @@ -530,8 +531,8 @@ public static void showDocument(String url) {
* @param eventId the eventId of the sound.
*/
public static void playSound(String eventId) {
if (AppPreferences.getPlaySystemSounds()) {
if (AppPreferences.getPlaySystemSoundsOnlyWhenNotFocused() && isInFocus()) {
if (AppPreferences.playSystemSounds.get()) {
if (AppPreferences.playSystemSoundsOnlyWhenNotFocused.get() && isInFocus()) {
return;
}
SoundManager.playSoundEvent(eventId);
Expand Down Expand Up @@ -686,9 +687,12 @@ private static void initialize() {
}
AppActions.updateActions();

ToolTipManager.sharedInstance().setInitialDelay(AppPreferences.getToolTipInitialDelay());
ToolTipManager.sharedInstance().setDismissDelay(AppPreferences.getToolTipDismissDelay());
ChatAutoSave.changeTimeout(AppPreferences.getChatAutosaveTime());
ToolTipManager.sharedInstance().setInitialDelay(AppPreferences.toolTipInitialDelay.get());
ToolTipManager.sharedInstance().setDismissDelay(AppPreferences.toolTipDismissDelay.get());

chatAutoSave = new ChatAutoSave();
chatAutoSave.setTimeout(AppPreferences.chatAutoSaveTimeInMinutes.get());
AppPreferences.chatAutoSaveTimeInMinutes.onChange(chatAutoSave::setTimeout);

// TODO: make this more formal when we switch to mina
new ServerHeartBeatThread().start();
Expand Down Expand Up @@ -1276,7 +1280,7 @@ private static void postInitialize() {
}
}
// alternately load MRU campaign if preference set
else if (AppPreferences.getLoadMRUCampaignAtStart()) {
else if (AppPreferences.loadMruCampaignAtStart.get()) {
try {
campaignFile = AppStatePersisted.getMruCampaigns().getFirst();
if (campaignFile.exists()) {
Expand Down Expand Up @@ -1354,7 +1358,7 @@ public static String getLastWhisperer() {

public static boolean useToolTipsForUnformatedRolls() {
if (isPersonalServer() || getServerPolicy() == null) {
return AppPreferences.getUseToolTipForInlineRoll();
return AppPreferences.useToolTipForInlineRoll.get();
} else {
return getServerPolicy().getUseToolTipsForDefaultRollFormat();
}
Expand Down Expand Up @@ -1653,7 +1657,7 @@ public static void main(String[] args) {
factory.registerProtocol("lib", new LibraryURLStreamHandler());

// Syrinscape Protocols
if (AppPreferences.getSyrinscapeActive()) {
if (AppPreferences.syrinscapeActive.get()) {
factory.registerProtocol("syrinscape-fantasy", new SyrinscapeURLStreamHandler());
factory.registerProtocol("syrinscape-sci-fi", new SyrinscapeURLStreamHandler());
factory.registerProtocol("syrinscape-boardgame", new SyrinscapeURLStreamHandler());
Expand Down
11 changes: 7 additions & 4 deletions src/main/java/net/rptools/maptool/client/MapToolUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public static String nextTokenId(Zone zone, Token token, boolean force) {
String newName;
Integer newNum = null;

if (isToken && AppPreferences.getNewTokenNaming().equals(Token.NAME_USE_CREATURE)) {
if (isToken && AppPreferences.newTokenNaming.get().equals(Token.NAME_USE_CREATURE)) {
newName = I18N.getString("Token.name.creature");
} else if (!force) {
return baseName;
Expand All @@ -162,9 +162,12 @@ public static String nextTokenId(Zone zone, Token token, boolean force) {
newName = baseName;
}
}
boolean random = (isToken && AppPreferences.getDuplicateTokenNumber().equals(Token.NUM_RANDOM));
boolean addNumToGM = !AppPreferences.getTokenNumberDisplay().equals(Token.NUM_ON_NAME);
boolean addNumToName = !AppPreferences.getTokenNumberDisplay().equals(Token.NUM_ON_GM);
boolean random =
(isToken && AppPreferences.duplicateTokenNumber.get().equals(Token.NUM_RANDOM));

var tokenNumberDisplay = AppPreferences.tokenNumberDisplay.get();
boolean addNumToGM = !tokenNumberDisplay.equals(Token.NUM_ON_NAME);
boolean addNumToName = !tokenNumberDisplay.equals(Token.NUM_ON_GM);

/*
* If the token already has a number suffix, if the preferences indicate that token numbering should be random and this token is on the Token layer, or if the token already exists somewhere on
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public Object childEvaluate(
if (!MapTool.getParser().isMacroTrusted())
throw new ParserException(I18N.getText("macro.function.general.noPerm", functionName));

if (!AppPreferences.getAllowExternalMacroAccess())
if (!AppPreferences.allowExternalMacroAccess.get())
throw new ParserException(I18N.getText("macro.function.general.accessDenied", functionName));

// New function to save data to an external file.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public Object childEvaluate(
if (functionName.equalsIgnoreCase("isTrusted")) {
return MapTool.getParser().isMacroTrusted() ? BigDecimal.ONE : BigDecimal.ZERO;
} else if (functionName.equalsIgnoreCase("isExternalMacroAccessAllowed")) {
return AppPreferences.getAllowExternalMacroAccess() ? BigDecimal.ONE : BigDecimal.ZERO;
return AppPreferences.allowExternalMacroAccess.get() ? BigDecimal.ONE : BigDecimal.ZERO;
} else if ("isGM".equalsIgnoreCase(functionName)) {
if (parameters.isEmpty())
return MapTool.getPlayer().isGM() ? BigDecimal.ONE : BigDecimal.ZERO;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,25 +229,25 @@ public Object childEvaluate(
final var gridType =
gridConfig.has("type")
? gridConfig.getAsJsonPrimitive("type").getAsString()
: AppPreferences.getDefaultGridType();
: AppPreferences.defaultGridType.get();
final var grid = GridFactory.createGrid(gridType);

final var gridColor =
gridConfig.has("color")
? MapToolUtil.getColor(gridConfig.getAsJsonPrimitive("color").getAsString())
: AppPreferences.getDefaultGridColor();
: AppPreferences.defaultGridColor.get();
newMap.setGridColor(gridColor.getRGB());

final var gridUnitsPerCell =
gridConfig.has("units per cell")
? gridConfig.getAsJsonPrimitive("units per cell").getAsDouble()
: AppPreferences.getDefaultUnitsPerCell();
: AppPreferences.defaultUnitsPerCell.get();
newMap.setUnitsPerCell(gridUnitsPerCell);

final var gridSize =
gridConfig.has("size")
? gridConfig.getAsJsonPrimitive("size").getAsInt()
: AppPreferences.getDefaultGridSize();
: AppPreferences.defaultGridSize.get();
grid.setSize(gridSize);

final var gridOffsetX =
Expand Down
Loading

0 comments on commit 110e1e6

Please sign in to comment.