From d4c7314f94f9b36a61dd33fb030e4ce6673a6ddb Mon Sep 17 00:00:00 2001 From: Marco Rebhan Date: Thu, 8 Jul 2021 16:31:22 +0200 Subject: [PATCH] Add methods to save and restore main window state --- .../enigma/gui/elements/MainWindow.java | 47 +++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/enigma-swing/src/main/java/cuchaz/enigma/gui/elements/MainWindow.java b/enigma-swing/src/main/java/cuchaz/enigma/gui/elements/MainWindow.java index 6e983509b..21cfd41d3 100644 --- a/enigma-swing/src/main/java/cuchaz/enigma/gui/elements/MainWindow.java +++ b/enigma-swing/src/main/java/cuchaz/enigma/gui/elements/MainWindow.java @@ -1,11 +1,12 @@ package cuchaz.enigma.gui.elements; -import java.awt.BorderLayout; -import java.awt.Container; +import java.awt.*; +import java.util.OptionalInt; import javax.swing.JFrame; import javax.swing.JMenuBar; +import cuchaz.enigma.config.ConfigSection; import cuchaz.enigma.gui.elements.rpanel.WorkspaceRPanelContainer; public class MainWindow { @@ -21,7 +22,7 @@ public MainWindow(String title) { Container contentPane = this.frame.getContentPane(); contentPane.setLayout(new BorderLayout()); - contentPane.add(workspace.getUi(), BorderLayout.CENTER); + contentPane.add(this.workspace.getUi(), BorderLayout.CENTER); contentPane.add(this.statusBar.getUi(), BorderLayout.SOUTH); } @@ -29,6 +30,46 @@ public void setVisible(boolean visible) { this.frame.setVisible(visible); } + /** + * Saves the state (window geometry and RPanel positions) of this main + * window. + * + * @param section the configuration section to write to + */ + public void saveState(ConfigSection section) { + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + Point location = this.frame.getLocationOnScreen(); + Dimension dim = this.frame.getSize(); + + section.setInt("X %s".formatted(screenSize.width), location.x); + section.setInt("Y %d".formatted(screenSize.height), location.y); + section.setInt("Width %d".formatted(screenSize.width), dim.width); + section.setInt("Height %d".formatted(screenSize.height), dim.height); + } + + public void restoreState(ConfigSection section) { + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + + OptionalInt width = section.getInt("Width %d".formatted(screenSize.width)); + OptionalInt height = section.getInt("Height %d".formatted(screenSize.height)); + OptionalInt x = section.getInt("X %d".formatted(screenSize.width)); + OptionalInt y = section.getInt("Y %d".formatted(screenSize.height)); + + if (width.isPresent() && height.isPresent()) { + this.frame.setSize(new Dimension(width.getAsInt(), height.getAsInt())); + } + + if (x.isPresent() && y.isPresent()) { + int ix = x.getAsInt(); + int iy = y.getAsInt(); + + // Ensure that the position is on the screen. + if (ix >= 0 && iy >= 0 && ix <= screenSize.width && iy <= screenSize.height) { + this.frame.setLocation(ix, iy); + } + } + } + public WorkspaceRPanelContainer workspace() { return this.workspace; }