001package jmri.jmrit.ctc.editor.code;
002
003import java.awt.Dimension;
004import java.awt.Point;
005import java.awt.Rectangle;
006
007import jmri.InstanceManager;
008import jmri.UserPreferencesManager;
009
010/**
011 * Use the JMRI UserPreferencesManager to store the size and location for
012 * the Editor windows.
013 *
014 * @author Gregory J. Bedlek Copyright (C) 2018, 2019
015 * @author Dave Sand Copyright (C) 2021
016 */
017public class AwtWindowProperties {
018    private final java.awt.Window _mMasterWindow;
019    private final String CTC_PACKAGE;
020
021    Point pt = null;
022    Dimension dim = null;
023
024    public AwtWindowProperties(java.awt.Window window, String filename, String windowName) {
025        _mMasterWindow = window;
026        CTC_PACKAGE = this.getClass().getPackage().getName();
027        setWindowState(window, windowName);
028    }
029
030    public final void setWindowState(java.awt.Window window, String windowName) {
031        Rectangle currentWindowRectangle = window.getBounds();
032        InstanceManager.getOptionalDefault(UserPreferencesManager.class).ifPresent((prefMgr) -> {
033            pt = prefMgr.getWindowLocation(CTC_PACKAGE + windowName);
034            dim = prefMgr.getWindowSize(CTC_PACKAGE + windowName);
035        });
036        log.debug("window {} :: {} :: {}", windowName, pt, dim);
037        if (pt == null) {
038            pt = new Point(_mMasterWindow.getX(), _mMasterWindow.getY());
039        }
040        if (dim == null) {
041            int windowWidth = (int) currentWindowRectangle.getWidth();
042            int windowHeight = (int) currentWindowRectangle.getHeight();
043            dim = new Dimension(windowWidth, windowHeight);
044        }
045        window.setBounds(new Rectangle(pt, dim));
046    }
047
048    public void saveWindowState(java.awt.Window window, String windowName) {
049        Rectangle rectangle = window.getBounds();
050        InstanceManager.getOptionalDefault(UserPreferencesManager.class).ifPresent((prefMgr) -> {
051            prefMgr.setWindowLocation(CTC_PACKAGE + windowName, new Point((int)rectangle.getX(), (int)rectangle.getY()));
052            prefMgr.setWindowSize(CTC_PACKAGE + windowName, new Dimension((int)rectangle.getWidth(), (int)rectangle.getHeight()));
053        });
054    }
055
056    public void saveWindowStateAndClose(java.awt.Window window, String windowName) {
057        saveWindowState(window, windowName);
058    }
059
060    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(AwtWindowProperties.class);
061}