Added ability to load CSS files

This commit is contained in:
delvh 2020-05-30 15:28:11 +02:00 committed by CyB3RC0nN0R
parent df47a2ca48
commit 11314f9ba9
7 changed files with 37 additions and 46 deletions

View File

@ -3,7 +3,6 @@ package envoy.client.ui;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Paths;
import java.util.Properties; import java.util.Properties;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -20,11 +19,13 @@ import javafx.scene.layout.Pane;
import javafx.stage.Stage; import javafx.stage.Stage;
import envoy.client.data.*; import envoy.client.data.*;
import envoy.client.event.ThemeChangeEvent;
import envoy.client.net.Client; import envoy.client.net.Client;
import envoy.client.net.WriteProxy; import envoy.client.net.WriteProxy;
import envoy.data.Message; import envoy.data.Message;
import envoy.data.User; import envoy.data.User;
import envoy.data.User.UserStatus; import envoy.data.User.UserStatus;
import envoy.event.EventBus;
import envoy.exception.EnvoyException; import envoy.exception.EnvoyException;
import envoy.util.EnvoyLog; import envoy.util.EnvoyLog;
@ -47,9 +48,6 @@ public final class Startup extends Application {
private Stage stage; private Stage stage;
private Scene previousScene; private Scene previousScene;
private final String[] CSSPaths = { "file://./src/main/resources/fxml/themes/base.css",
"file://./src/main/resources/fxml/themes/" + (settings.isUsingDefaultTheme() ? settings.getCurrentThemeName() : "custom") + ".css" };
private static final Settings settings = Settings.getInstance(); private static final Settings settings = Settings.getInstance();
private static final ClientConfig config = ClientConfig.getInstance(); private static final ClientConfig config = ClientConfig.getInstance();
private static final Logger logger = EnvoyLog.getLogger(Startup.class); private static final Logger logger = EnvoyLog.getLogger(Startup.class);
@ -62,17 +60,17 @@ public final class Startup extends Application {
this.stage = stage; this.stage = stage;
try { try {
// Load the configuration from client.properties first // Load the configuration from client.properties first
Properties properties = new Properties(); final Properties properties = new Properties();
properties.load(Startup.class.getClassLoader().getResourceAsStream("client.properties")); properties.load(Startup.class.getClassLoader().getResourceAsStream("client.properties"));
config.load(properties); config.load(properties);
// Override configuration values with command line arguments // Override configuration values with command line arguments
String[] args = getParameters().getRaw().toArray(new String[0]); final String[] args = getParameters().getRaw().toArray(new String[0]);
if (args.length > 0) config.load(args); if (args.length > 0) config.load(args);
// Check if all mandatory configuration values have been initialized // Check if all mandatory configuration values have been initialized
if (!config.isInitialized()) throw new EnvoyException("Configuration is not fully initialized"); if (!config.isInitialized()) throw new EnvoyException("Configuration is not fully initialized");
} catch (Exception e) { } catch (final Exception e) {
new Alert(AlertType.ERROR, "Error loading configuration values:\n" + e); new Alert(AlertType.ERROR, "Error loading configuration values:\n" + e);
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
@ -90,7 +88,7 @@ public final class Startup extends Application {
new Alert(AlertType.WARNING, "Ignoring local database.\nMessages will not be saved!").showAndWait(); new Alert(AlertType.WARNING, "Ignoring local database.\nMessages will not be saved!").showAndWait();
} else try { } else try {
localDB = new PersistentLocalDB(new File(config.getHomeDirectory(), config.getLocalDB().getPath())); localDB = new PersistentLocalDB(new File(config.getHomeDirectory(), config.getLocalDB().getPath()));
} catch (IOException e3) { } catch (final IOException e3) {
logger.log(Level.SEVERE, "Could not initialize local database", e3); logger.log(Level.SEVERE, "Could not initialize local database", e3);
new Alert(AlertType.ERROR, "Could not initialize local database!\n" + e3).showAndWait(); new Alert(AlertType.ERROR, "Could not initialize local database!\n" + e3).showAndWait();
System.exit(1); System.exit(1);
@ -111,9 +109,9 @@ public final class Startup extends Application {
try { try {
localDB.initializeUserStorage(); localDB.initializeUserStorage();
localDB.loadUserData(); localDB.loadUserData();
} catch (FileNotFoundException e) { } catch (final FileNotFoundException e) {
// The local database file has not yet been created, probably first login // The local database file has not yet been created, probably first login
} catch (Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
new Alert(AlertType.ERROR, "Error while loading local database: " + e + "\nChats will not be stored locally.").showAndWait(); new Alert(AlertType.ERROR, "Error while loading local database: " + e + "\nChats will not be stored locally.").showAndWait();
} }
@ -140,8 +138,10 @@ public final class Startup extends Application {
Platform.runLater(() -> { ((ChatSceneController) loader.getController()).initializeData(this, localDB, client, writeProxy); }); Platform.runLater(() -> { ((ChatSceneController) loader.getController()).initializeData(this, localDB, client, writeProxy); });
stage.setTitle("Envoy"); stage.setTitle("Envoy");
stage.getIcons().add(new Image(getClass().getResourceAsStream("/icons/envoy_logo.png"))); stage.getIcons().add(new Image(getClass().getResourceAsStream("/icons/envoy_logo.png")));
stage.show(); stage.show();
// TODO: Add capability to change custom CSS. In case of switching to a default
// theme, no further action is required
EventBus.getInstance().register(ThemeChangeEvent.class, theme -> applyCSS());
// Relay unread messages from cache // Relay unread messages from cache
if (cache != null && client.isOnline()) cache.relay(); if (cache != null && client.isOnline()) cache.relay();
@ -154,8 +154,7 @@ public final class Startup extends Application {
* @param fxmlLocation the location of the fxml file * @param fxmlLocation the location of the fxml file
* @param layout the layout to use * @param layout the layout to use
* @param savePrevious if true, the previous stage will be stored in this * @param savePrevious if true, the previous stage will be stored in this
* instance of Startup, else the variable storing it will * instance of Startup, else the variable storing it will be
* be
* set to null * set to null
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
@ -164,18 +163,16 @@ public final class Startup extends Application {
try { try {
// Clearing the loader so that a new Scene can be initialised // Clearing the loader so that a new Scene can be initialised
loader = new FXMLLoader(); loader = new FXMLLoader();
var rootNode = loader.<T>load(getClass().getResourceAsStream(fxmlLocation)); final var rootNode = loader.<T>load(getClass().getResourceAsStream(fxmlLocation));
var scene = new Scene(rootNode); final var scene = new Scene(rootNode);
previousScene = savePrevious ? stage.getScene() : null; previousScene = savePrevious ? stage.getScene() : null;
// Setting the visual appearance // Setting the visual appearance
scene.getStylesheets().addAll(CSSPaths);
System.out.println(Paths.get(".").toAbsolutePath().normalize().toString());
stage.setScene(scene); stage.setScene(scene);
applyCSS();
stage.show(); stage.show();
// return loader.getController(); } catch (final IOException e) {
} catch (IOException e) {
new Alert(AlertType.ERROR, "The screen could not be updated due to reasons. (...bad programming...)"); new Alert(AlertType.ERROR, "The screen could not be updated due to reasons. (...bad programming...)");
System.err.println("input: FXMLLocation: " + fxmlLocation + ", CSS paths: " + CSSPaths); System.err.println("input: FXMLLocation: " + fxmlLocation);
e.printStackTrace(); e.printStackTrace();
logger.severe("Something happened (while loading the new scene from " + fxmlLocation + ")"); logger.severe("Something happened (while loading the new scene from " + fxmlLocation + ")");
} }
@ -194,8 +191,9 @@ public final class Startup extends Application {
if (previousScene == null) throw new IllegalStateException("Someone tried restoring a null scene. (Something happened)"); if (previousScene == null) throw new IllegalStateException("Someone tried restoring a null scene. (Something happened)");
else { else {
// switching previous and current // switching previous and current
var temp = storeCurrent ? stage.getScene() : null; final var temp = storeCurrent ? stage.getScene() : null;
stage.setScene(previousScene); stage.setScene(previousScene);
applyCSS();
previousScene = temp; previousScene = temp;
stage.show(); stage.show();
} }
@ -208,7 +206,6 @@ public final class Startup extends Application {
@Override @Override
public void stop() throws Exception { public void stop() throws Exception {
try { try {
// Save Settings and PersistentLocalDB on shutdown // Save Settings and PersistentLocalDB on shutdown
logger.info("Closing connection..."); logger.info("Closing connection...");
client.close(); client.close();
@ -216,14 +213,11 @@ public final class Startup extends Application {
logger.info("Saving local database and settings..."); logger.info("Saving local database and settings...");
localDB.save(); localDB.save();
Settings.getInstance().save(); Settings.getInstance().save();
} catch (Exception e) { } catch (final Exception e) {
logger.log(Level.SEVERE, "Unable to save local files", e); logger.log(Level.SEVERE, "Unable to save local files", e);
} }
} }
@SuppressWarnings("javadoc")
public static void main(String[] args) { launch(args); }
/** /**
* @return the controller of the current scene or a {@link NullPointerException} * @return the controller of the current scene or a {@link NullPointerException}
* if there is none * if there is none
@ -235,21 +229,19 @@ public final class Startup extends Application {
} }
/** /**
* @return the CSSPaths * Sets the CSS files used for each scene. Should be called when the theme
* @since Envoy Client v0.1-beta * changes.
*/
public String[] getCSSPaths() { return CSSPaths; }
/**
* Changes the currently displayed theme
* *
* @since Envoy Client v0.1-beta * @since Envoy Client v0.1-beta
*/ */
public void changeTheme() { public void applyCSS() {
// the base.css file should never be changed during runtime final var styleSheets = stage.getScene().getStylesheets();
CSSPaths[1] = "file://.fxml/themes/" + (settings.isUsingDefaultTheme() ? settings.getCurrentThemeName() : "custom") + ".css"; styleSheets.clear();
var styleSheets = stage.getScene().getStylesheets(); styleSheets.add(getClass().getResource("/css/base.css").toExternalForm());
styleSheets.remove(styleSheets.size() - 1); styleSheets.add(getClass().getResource("/css/" + (settings.isUsingDefaultTheme() ? settings.getCurrentThemeName() : "custom") + ".css")
styleSheets.add(CSSPaths[1]); .toExternalForm());
} }
@SuppressWarnings("javadoc")
public static void main(String[] args) { launch(args); }
} }

View File

@ -1,3 +1,3 @@
server=http://kske.feste-ip.net server=localhost
port=43315 port=8080
localDB=.\\localDB localDB=.\\localDB

View File

@ -0,0 +1,4 @@
*{
-fx-font: 14pt "Serif";
-fx-background-color:#000000;
}

View File

@ -1,5 +0,0 @@
.root{
-fx-font: 200pt "Serif";
--background=#00FF00;
background: var(--background);
}