server
Clone or download
Modified Files
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<modelVersion>4.0.0</modelVersion>
<groupId>com.stream_pi</groupId>
<groupId>com.stream-pi</groupId>
<artifactId>server</artifactId>
<artifactId>server</artifactId>
<version>1.0.0</version>
<version>1.0.0-SNAPSHOT</version>
<properties>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.target>11</maven.compiler.target>
<client.plugin.version>0.1.36</client.plugin.version>
<client.plugin.version>0.1.36</client.plugin.version>
<JavaFXVersion>16-ea+6</JavaFXVersion>
<JavaFXVersion>16-ea+6</JavaFXVersion>
<CommonsBeanUtilsVersion>1.9.4</CommonsBeanUtilsVersion>
<CommonsBeanUtilsVersion>1.9.4</CommonsBeanUtilsVersion>
<CommonsConfigurationVersion>2.7</CommonsConfigurationVersion>
<CommonsConfigurationVersion>2.7</CommonsConfigurationVersion>
<ActionAPIVersion>1.0.0</ActionAPIVersion>
<ActionAPIVersion>1.0.0-SNAPSHOT</ActionAPIVersion>
<ThemeAPIVersion>1.0.0</ThemeAPIVersion>
<ThemeAPIVersion>1.0.0-SNAPSHOT</ThemeAPIVersion>
<UtilVersion>1.0.0</UtilVersion>
<UtilVersion>1.0.0-SNAPSHOT</UtilVersion>
<!--CommAPIVersion>1.0.0</CommAPIVersion-->
<Log4JVersion>2.14.0</Log4JVersion>
<Log4JVersion>2.14.0</Log4JVersion>
<IkonliVersion>11.5.0</IkonliVersion>
<IkonliVersion>11.5.0</IkonliVersion>
<IkonliFA5PackVersion>11.5.0</IkonliFA5PackVersion>
<IkonliFA5PackVersion>11.5.0</IkonliFA5PackVersion>
<MainClassName>com.stream_pi.server.Main</MainClassName>
<MainClassName>com.stream_pi.server.Main</MainClassName>
</properties>
</properties>
<dependencies>
<dependencies>
<dependency>
<dependency>
<groupId>org.openjfx</groupId>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<artifactId>javafx-controls</artifactId>
<version>${JavaFXVersion}</version>
<version>${JavaFXVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>org.openjfx</groupId>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<artifactId>javafx-media</artifactId>
<version>${JavaFXVersion}</version>
<version>${JavaFXVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>org.kordamp.ikonli</groupId>
<groupId>org.kordamp.ikonli</groupId>
<artifactId>ikonli-fontawesome5-pack</artifactId>
<artifactId>ikonli-fontawesome5-pack</artifactId>
<version>${IkonliFA5PackVersion}</version>
<version>${IkonliFA5PackVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>org.kordamp.ikonli</groupId>
<groupId>org.kordamp.ikonli</groupId>
<artifactId>ikonli-javafx</artifactId>
<artifactId>ikonli-javafx</artifactId>
<version>${IkonliVersion}</version>
<version>${IkonliVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>org.openjfx</groupId>
<groupId>org.openjfx</groupId>
<artifactId>javafx-base</artifactId>
<artifactId>javafx-base</artifactId>
<version>${JavaFXVersion}</version>
<version>${JavaFXVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.stream_pi</groupId>
<groupId>com.stream-pi</groupId>
<artifactId>actionapi</artifactId>
<artifactId>action-api</artifactId>
<version>${ActionAPIVersion}</version>
<version>${ActionAPIVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.stream_pi</groupId>
<groupId>com.stream-pi</groupId>
<artifactId>util</artifactId>
<artifactId>util</artifactId>
<version>${UtilVersion}</version>
<version>${UtilVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.stream_pi</groupId>
<groupId>com.stream-pi</groupId>
<artifactId>themeapi</artifactId>
<artifactId>theme-api</artifactId>
<version>${ThemeAPIVersion}</version>
<version>${ThemeAPIVersion}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>org.json</groupId>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<artifactId>json</artifactId>
<version>20201115</version>
<version>20201115</version>
</dependency>
</dependency>
</dependencies>
</dependencies>
<repositories>
<repositories>
<repository>
<repository>
<id>gluon-releases</id>
<id>gluon-releases</id>
<url>http://nexus.gluonhq.com/nexus/content/repositories/releases/</url>
<url>http://nexus.gluonhq.com/nexus/content/repositories/releases/</url>
</repository>
</repository>
</repositories>
</repositories>
<build>
<build>
<plugins>
<plugins>
<plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.8.1</version>
<configuration>
<configuration>
<release>11</release>
<release>11</release>
</configuration>
</configuration>
</plugin>
</plugin>
<plugin>
<plugin>
<groupId>org.openjfx</groupId>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.5</version>
<version>0.0.5</version>
<configuration>
<configuration>
<commandlineArgs>-DStreamPi.startupRunnerFileName=run_min -DStreamPi.startupMode=maximise</commandlineArgs>
<commandlineArgs>-DStreamPi.startupRunnerFileName=run_min -DStreamPi.startupMode=maximise</commandlineArgs>
<options>
<options>
<option>-Dglass.gtk.uiScale=1.0</option>
<option>-Dglass.gtk.uiScale=1.0</option>
</options>
</options>
<mainClass>${MainClassName}</mainClass>
<mainClass>${MainClassName}</mainClass>
</configuration>
</configuration>
</plugin>
</plugin>
<plugin>
<plugin>
<groupId>com.gluonhq</groupId>
<groupId>com.gluonhq</groupId>
<artifactId>client-maven-plugin</artifactId>
<artifactId>client-maven-plugin</artifactId>
<version>${client.plugin.version}</version>
<version>${client.plugin.version}</version>
<configuration>
<configuration>
<nativeImageArgs>
<nativeImageArgs>
<list>--initialize-at-build-time=com.sun.org.apache.xml.internal.serializer.ToXMLStream</list>
<list>--initialize-at-build-time=com.sun.org.apache.xml.internal.serializer.ToXMLStream</list>
<!--list>-Dsvm.targetName=android</list-->
<!--list>-Dsvm.targetName=android</list-->
</nativeImageArgs>
</nativeImageArgs>
<bundlesList>
<bundlesList>
<list>com.sun.org.apache.xerces.internal.impl.msg.XMLMessages</list>
<list>com.sun.org.apache.xerces.internal.impl.msg.XMLMessages</list>
</bundlesList>
</bundlesList>
<reflectionList>
<reflectionList>
<list>java.util.logging.FileHandler</list>
<list>java.util.logging.FileHandler</list>
</reflectionList>
</reflectionList>
<mainClass>${MainClassName}</mainClass>
<mainClass>${MainClassName}</mainClass>
</configuration>
</configuration>
</plugin>
</plugin>
<plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<version>3.2.0</version>
<configuration>
<configuration>
<includeEmptyDirs>true</includeEmptyDirs>
<includeEmptyDirs>true</includeEmptyDirs>
</configuration>
</configuration>
</plugin>
</plugin>
</plugins>
</plugins>
</build>
</build>
<pluginRepositories>
<pluginRepositories>
<pluginRepository>
<pluginRepository>
<id>gluon-releases</id>
<id>gluon-releases</id>
<url>http://nexus.gluonhq.com/nexus/content/repositories/releases/</url>
<url>http://nexus.gluonhq.com/nexus/content/repositories/releases/</url>
</pluginRepository>
</pluginRepository>
<pluginRepository>
<pluginRepository>
<id>gluon-snapshots</id>
<id>gluon-snapshots</id>
<url>https://nexus.gluonhq.com/nexus/content/repositories/public-snapshots</url>
<url>https://nexus.gluonhq.com/nexus/content/repositories/public-snapshots</url>
</pluginRepository>
</pluginRepository>
</pluginRepositories>
</pluginRepositories>
</project>
</project>
/*
/*
Stream-Pi - Free & Open-Source Modular Cross-Platform Programmable Macropad
Stream-Pi - Free & Open-Source Modular Cross-Platform Programmable Macropad
Copyright (C) 2019-2021 Debayan Sutradhar (rnayabed), Samuel Quiñones (SamuelQuinones)
Copyright (C) 2019-2021 Debayan Sutradhar (rnayabed), Samuel Quiñones (SamuelQuinones)
This program is free software: you can redistribute it and/or modify
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
(at your option) any later version.
This program is distributed in the hope that it will be useful,
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU General Public License for more details.
Written by : Debayan Sutradhar (rnayabed)
Written by : Debayan Sutradhar (rnayabed)
*/
*/
package com.stream_pi.server.action;
package com.stream_pi.server.action;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamResult;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.actionapi.action.PropertySaver;
import com.stream_pi.action_api.action.PropertySaver;
import com.stream_pi.actionapi.action.ServerConnection;
import com.stream_pi.action_api.action.ServerConnection;
import com.stream_pi.actionapi.actionproperty.ServerProperties;
import com.stream_pi.action_api.actionproperty.ServerProperties;
import com.stream_pi.actionapi.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.actionapi.actionproperty.property.Type;
import com.stream_pi.action_api.actionproperty.property.Type;
import com.stream_pi.actionapi.normalaction.NormalAction;
import com.stream_pi.action_api.normalaction.NormalAction;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.StreamPiException;
import com.stream_pi.util.exception.StreamPiException;
import com.stream_pi.util.version.Version;
import com.stream_pi.util.version.Version;
import com.stream_pi.util.xmlconfighelper.XMLConfigHelper;
import com.stream_pi.util.xmlconfighelper.XMLConfigHelper;
import org.w3c.dom.NodeList;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Node;
import java.io.File;
import java.io.File;
import java.lang.module.*;
import java.lang.module.*;
import java.nio.file.Path;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashMap;
import java.util.List;
import java.util.List;
import java.util.ServiceLoader;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Collectors;
import org.w3c.dom.Element;
import org.w3c.dom.Element;
public class NormalActionPlugins
public class NormalActionPlugins
{
{
private static NormalActionPlugins instance = null;
private static NormalActionPlugins instance = null;
private final Logger logger;
private final Logger logger;
private File configFile;
private File configFile;
private Document document;
private Document document;
private static String pluginsLocation = null;
private static String pluginsLocation = null;
/**
/**
* Singleton class instance getter. Creates new one, when asked for the first time
* Singleton class instance getter. Creates new one, when asked for the first time
*
*
* @return returns instance of NormalActionPlugins (one and only, always)
* @return returns instance of NormalActionPlugins (one and only, always)
*/
*/
public static synchronized NormalActionPlugins getInstance()
public static synchronized NormalActionPlugins getInstance()
{
{
if(instance == null)
if(instance == null)
{
{
instance = new NormalActionPlugins();
instance = new NormalActionPlugins();
}
}
return instance;
return instance;
}
}
/**
/**
* Sets the folder location where the plugin JARs and their dependencies are stored
* Sets the folder location where the plugin JARs and their dependencies are stored
*
*
* @param location Folder location
* @param location Folder location
*/
*/
public static void setPluginsLocation(String location)
public static void setPluginsLocation(String location)
{
{
pluginsLocation = location;
pluginsLocation = location;
}
}
/**
/**
* Private constructor
* Private constructor
*/
*/
private NormalActionPlugins()
private NormalActionPlugins()
{
{
logger = Logger.getLogger(NormalActionPlugins.class.getName());
logger = Logger.getLogger(NormalActionPlugins.class.getName());
normalPluginsHashmap = new HashMap<>();
normalPluginsHashmap = new HashMap<>();
}
}
/**
/**
* init Method
* init Method
*/
*/
public void init() throws SevereException, MinorException
public void init() throws SevereException, MinorException
{
{
registerPlugins();
registerPlugins();
initPlugins();
initPlugins();
}
}
/**
/**
* Used to fetch list of all external Plugins
* Used to fetch list of all external Plugins
*
*
* @return List of plugins
* @return List of plugins
*/
*/
public List<NormalAction> getPlugins()
public List<NormalAction> getPlugins()
{
{
return normalPlugins;
return normalPlugins;
}
}
/**
/**
* Returns a plugin by its module name
* Returns a plugin by its module name
*
*
* @param name Module Name
* @param name Module Name
* @return The plugin. If not found, then null is returned
* @return The plugin. If not found, then null is returned
*/
*/
public NormalAction getPluginByModuleName(String name)
public NormalAction getPluginByModuleName(String name)
{
{
logger.info("Plugin being requested : "+name);
logger.info("Plugin being requested : "+name);
Integer index = normalPluginsHashmap.getOrDefault(name, -1);
Integer index = normalPluginsHashmap.getOrDefault(name, -1);
if(index != -1)
if(index != -1)
{
{
return normalPlugins.get(index);
return normalPlugins.get(index);
}
}
return null;
return null;
}
}
private List<NormalAction> normalPlugins = null;
private List<NormalAction> normalPlugins = null;
HashMap<String, Integer> normalPluginsHashmap;
HashMap<String, Integer> normalPluginsHashmap;
/**
/**
* Used to register plugins from plugin location
* Used to register plugins from plugin location
*/
*/
public void registerPlugins() throws SevereException, MinorException
public void registerPlugins() throws SevereException, MinorException
{
{
logger.info("Registering external plugins from "+pluginsLocation+" ...");
logger.info("Registering external plugins from "+pluginsLocation+" ...");
try
try
{
{
configFile = new File(pluginsLocation+"/config.xml");
configFile = new File(pluginsLocation+"/config.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
document = docBuilder.parse(configFile);
document = docBuilder.parse(configFile);
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Plugins","Error reading plugins config.xml. Cannot continue.");
throw new SevereException("Plugins","Error reading plugins config.xml. Cannot continue.");
}
}
ArrayList<NormalAction> errorModules = new ArrayList<>();
ArrayList<NormalAction> errorModules = new ArrayList<>();
ArrayList<String> errorModuleError = new ArrayList<>();
ArrayList<String> errorModuleError = new ArrayList<>();
ArrayList<Action> pluginsConfigs = new ArrayList<>();
ArrayList<Action> pluginsConfigs = new ArrayList<>();
NodeList actionsNode = document.getElementsByTagName("actions").item(0).getChildNodes();
NodeList actionsNode = document.getElementsByTagName("actions").item(0).getChildNodes();
for(int i =0;i<actionsNode.getLength();i++)
for(int i =0;i<actionsNode.getLength();i++)
{
{
Node eachActionNode = actionsNode.item(i);
Node eachActionNode = actionsNode.item(i);
if(eachActionNode.getNodeType() != Node.ELEMENT_NODE)
if(eachActionNode.getNodeType() != Node.ELEMENT_NODE)
continue;
continue;
if(!eachActionNode.getNodeName().equals("action"))
if(!eachActionNode.getNodeName().equals("action"))
continue;
continue;
Element eachActionElement = (Element) eachActionNode;
Element eachActionElement = (Element) eachActionNode;
String name;
String name;
Version version;
Version version;
try
try
{
{
name = XMLConfigHelper.getStringProperty(eachActionElement, "module-name");
name = XMLConfigHelper.getStringProperty(eachActionElement, "module-name");
version = new Version(XMLConfigHelper.getStringProperty(eachActionElement, "version"));
version = new Version(XMLConfigHelper.getStringProperty(eachActionElement, "version"));
}
}
catch (Exception e)
catch (Exception e)
{
{
logger.log(Level.WARNING, "Skipping configuration because invalid ...");
logger.log(Level.WARNING, "Skipping configuration because invalid ...");
e.printStackTrace();
e.printStackTrace();
continue;
continue;
}
}
ServerProperties serverProperties = new ServerProperties();
ServerProperties serverProperties = new ServerProperties();
NodeList serverPropertiesNodeList = eachActionElement.getElementsByTagName("properties").item(0).getChildNodes();
NodeList serverPropertiesNodeList = eachActionElement.getElementsByTagName("properties").item(0).getChildNodes();
for(int j = 0;j<serverPropertiesNodeList.getLength();j++)
for(int j = 0;j<serverPropertiesNodeList.getLength();j++)
{
{
Node eachPropertyNode = serverPropertiesNodeList.item(j);
Node eachPropertyNode = serverPropertiesNodeList.item(j);
if(eachPropertyNode.getNodeType() != Node.ELEMENT_NODE)
if(eachPropertyNode.getNodeType() != Node.ELEMENT_NODE)
continue;
continue;
if(!eachPropertyNode.getNodeName().equals("property"))
if(!eachPropertyNode.getNodeName().equals("property"))
continue;
continue;
Element eachPropertyElement = (Element) eachPropertyNode;
Element eachPropertyElement = (Element) eachPropertyNode;
try
try
{
{
Property property = new Property(XMLConfigHelper.getStringProperty(eachPropertyElement, "name"), Type.STRING);
Property property = new Property(XMLConfigHelper.getStringProperty(eachPropertyElement, "name"), Type.STRING);
property.setRawValue(XMLConfigHelper.getStringProperty(eachPropertyElement, "value"));
property.setRawValue(XMLConfigHelper.getStringProperty(eachPropertyElement, "value"));
serverProperties.addProperty(property);
serverProperties.addProperty(property);
}
}
catch (Exception e)
catch (Exception e)
{
{
logger.log(Level.WARNING, "Skipping property because invalid ...");
logger.log(Level.WARNING, "Skipping property because invalid ...");
e.printStackTrace();
e.printStackTrace();
}
}
}
}
Action action = new Action(ActionType.NORMAL);
Action action = new Action(ActionType.NORMAL);
action.setModuleName(name);
action.setModuleName(name);
action.setVersion(version);
action.setVersion(version);
action.getServerProperties().set(serverProperties);
action.getServerProperties().set(serverProperties);
pluginsConfigs.add(action);
pluginsConfigs.add(action);
}
}
logger.info("Size : "+pluginsConfigs.size());
logger.info("Size : "+pluginsConfigs.size());
Path pluginsDir = Paths.get(pluginsLocation); // Directory with plugins JARs
Path pluginsDir = Paths.get(pluginsLocation); // Directory with plugins JARs
try
try
{
{
// Search for plugins in the plugins directory
// Search for plugins in the plugins directory
ModuleFinder pluginsFinder = ModuleFinder.of(pluginsDir);
ModuleFinder pluginsFinder = ModuleFinder.of(pluginsDir);
// Find all names of all found plugin modules
// Find all names of all found plugin modules
List<String> p = pluginsFinder
List<String> p = pluginsFinder
.findAll()
.findAll()
.stream()
.stream()
.map(ModuleReference::descriptor)
.map(ModuleReference::descriptor)
.map(ModuleDescriptor::name)
.map(ModuleDescriptor::name)
.collect(Collectors.toList());
.collect(Collectors.toList());
// Create configuration that will resolve plugin modules
// Create configuration that will resolve plugin modules
// (verify that the graph of modules is correct)
// (verify that the graph of modules is correct)
Configuration pluginsConfiguration = ModuleLayer
Configuration pluginsConfiguration = ModuleLayer
.boot()
.boot()
.configuration()
.configuration()
.resolve(pluginsFinder, ModuleFinder.of(), p);
.resolve(pluginsFinder, ModuleFinder.of(), p);
// Create a module layer for plugins
// Create a module layer for plugins
ModuleLayer layer = ModuleLayer
ModuleLayer layer = ModuleLayer
.boot()
.boot()
.defineModulesWithOneLoader(pluginsConfiguration, ClassLoader.getSystemClassLoader());
.defineModulesWithOneLoader(pluginsConfiguration, ClassLoader.getSystemClassLoader());
logger.info("Loading plugins from jar ...");
logger.info("Loading plugins from jar ...");
// Now you can use the new module layer to find service implementations in it
// Now you can use the new module layer to find service implementations in it
normalPlugins = ServiceLoader
normalPlugins = ServiceLoader
.load(layer, NormalAction.class).stream()
.load(layer, NormalAction.class).stream()
.map(ServiceLoader.Provider::get)
.map(ServiceLoader.Provider::get)
.collect(Collectors.toList());
.collect(Collectors.toList());
logger.info("...Done!");
logger.info("...Done!");
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new MinorException("Error", "Error loading modules\n"+e.getMessage()+"\nPlease fix the errors. Other plugins wont be loaded.");
throw new MinorException("Error", "Error loading modules\n"+e.getMessage()+"\nPlease fix the errors. Other plugins wont be loaded.");
}
}
sortedPlugins = new HashMap<>();
sortedPlugins = new HashMap<>();
for (NormalAction eachPlugin : normalPlugins)
for (NormalAction eachPlugin : normalPlugins)
{
{
try
try
{
{
eachPlugin.setPropertySaver(propertySaver);
eachPlugin.setPropertySaver(propertySaver);
eachPlugin.setServerConnection(serverConnection);
eachPlugin.setServerConnection(serverConnection);
eachPlugin.initProperties();
eachPlugin.initProperties();
Action foundAction = null;
Action foundAction = null;
for (Action action : pluginsConfigs) {
for (Action action : pluginsConfigs) {
if (action.getModuleName().equals(eachPlugin.getModuleName())
if (action.getModuleName().equals(eachPlugin.getModuleName())
&& action.getVersion().isEqual(eachPlugin.getVersion())) {
&& action.getVersion().isEqual(eachPlugin.getVersion())) {
foundAction = action;
foundAction = action;
List<Property> eachPluginStoredProperties = action.getServerProperties().get();
List<Property> eachPluginStoredProperties = action.getServerProperties().get();
List<Property> eachPluginCodeProperties = eachPlugin.getServerProperties().get();
List<Property> eachPluginCodeProperties = eachPlugin.getServerProperties().get();
for (int i =0;i< eachPluginCodeProperties.size(); i++) {
for (int i =0;i< eachPluginCodeProperties.size(); i++) {
Property eachPluginCodeProperty = eachPluginCodeProperties.get(i);
Property eachPluginCodeProperty = eachPluginCodeProperties.get(i);
Property foundProp = null;
Property foundProp = null;
for (Property eachPluginStoredProperty : eachPluginStoredProperties) {
for (Property eachPluginStoredProperty : eachPluginStoredProperties) {
if (eachPluginCodeProperty.getName().equals(eachPluginStoredProperty.getName())) {
if (eachPluginCodeProperty.getName().equals(eachPluginStoredProperty.getName())) {
eachPluginCodeProperty.setRawValue(eachPluginStoredProperty.getRawValue());
eachPluginCodeProperty.setRawValue(eachPluginStoredProperty.getRawValue());
foundProp = eachPluginStoredProperty;
foundProp = eachPluginStoredProperty;
}
}
}
}
eachPluginCodeProperties.set(i, eachPluginCodeProperty);
eachPluginCodeProperties.set(i, eachPluginCodeProperty);
if (foundProp != null) {
if (foundProp != null) {
eachPluginStoredProperties.remove(foundProp);
eachPluginStoredProperties.remove(foundProp);
}
}
}
}
eachPlugin.getServerProperties().set(eachPluginCodeProperties);
eachPlugin.getServerProperties().set(eachPluginCodeProperties);
break;
break;
}
}
}
}
if (foundAction != null)
if (foundAction != null)
pluginsConfigs.remove(foundAction);
pluginsConfigs.remove(foundAction);
else
else
{
{
List<Property> eachPluginStoredProperties = eachPlugin.getServerProperties().get();
List<Property> eachPluginStoredProperties = eachPlugin.getServerProperties().get();
for(Property property :eachPluginStoredProperties)
for(Property property :eachPluginStoredProperties)
{
{
if(property.getType() == Type.STRING || property.getType() == Type.INTEGER || property.getType() == Type.DOUBLE)
if(property.getType() == Type.STRING || property.getType() == Type.INTEGER || property.getType() == Type.DOUBLE)
property.setRawValue(property.getDefaultRawValue());
property.setRawValue(property.getDefaultRawValue());
}
}
}
}
if (!sortedPlugins.containsKey(eachPlugin.getCategory())) {
if (!sortedPlugins.containsKey(eachPlugin.getCategory())) {
ArrayList<NormalAction> actions = new ArrayList<>();
ArrayList<NormalAction> actions = new ArrayList<>();
sortedPlugins.put(eachPlugin.getCategory(), actions);
sortedPlugins.put(eachPlugin.getCategory(), actions);
}
}
sortedPlugins.get(eachPlugin.getCategory()).add(eachPlugin);
sortedPlugins.get(eachPlugin.getCategory()).add(eachPlugin);
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
errorModules.add(eachPlugin);
errorModules.add(eachPlugin);
errorModuleError.add(e.getMessage());
errorModuleError.add(e.getMessage());
}
}
}
}
try {
try {
saveServerSettings();
saveServerSettings();
} catch (MinorException e) {
} catch (MinorException e) {
e.printStackTrace();
e.printStackTrace();
}
}
logger.log(Level.INFO, "All plugins registered!");
logger.log(Level.INFO, "All plugins registered!");
if(errorModules.size() > 0)
if(errorModules.size() > 0)
{
{
StringBuilder errors = new StringBuilder("The following action modules could not be loaded:");
StringBuilder errors = new StringBuilder("The following action modules could not be loaded:");
for(int i = 0; i<errorModules.size(); i++)
for(int i = 0; i<errorModules.size(); i++)
{
{
normalPlugins.remove(errorModules.get(i));
normalPlugins.remove(errorModules.get(i));
errors.append("\n * ").append(errorModules.get(i).getModuleName()).append("\n(")
errors.append("\n * ").append(errorModules.get(i).getModuleName()).append("\n(")
.append(errorModuleError.get(i)).append(")");
.append(errorModuleError.get(i)).append(")");
}
}
throw new MinorException("Plugins", errors.toString());
throw new MinorException("Plugins", errors.toString());
}
}
for(int i = 0;i<normalPlugins.size();i++)
for(int i = 0;i<normalPlugins.size();i++)
{
{
normalPluginsHashmap.put(normalPlugins.get(i).getModuleName(), i);
normalPluginsHashmap.put(normalPlugins.get(i).getModuleName(), i);
}
}
}
}
/**
/**
* Used to init plugins
* Used to init plugins
*/
*/
public void initPlugins() throws MinorException
public void initPlugins() throws MinorException
{
{
StringBuilder errors = new StringBuilder("There were errors registering the following plugins. As a result, they have been omitted : ");
StringBuilder errors = new StringBuilder("There were errors registering the following plugins. As a result, they have been omitted : ");
boolean isError = false;
boolean isError = false;
for(NormalAction eachPlugin : normalPlugins)
for(NormalAction eachPlugin : normalPlugins)
{
{
try
try
{
{
eachPlugin.initAction();
eachPlugin.initAction();
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
isError = true;
isError = true;
errors.append("\n* ")
errors.append("\n* ")
.append(eachPlugin.getName())
.append(eachPlugin.getName())
.append(" - ")
.append(" - ")
.append(eachPlugin.getModuleName())
.append(eachPlugin.getModuleName())
.append("\n");
.append("\n");
if(e instanceof StreamPiException)
if(e instanceof StreamPiException)
errors.append(((MinorException) e).getShortMessage());
errors.append(((MinorException) e).getShortMessage());
errors.append("\n");
errors.append("\n");
}
}
}
}
if(isError)
if(isError)
{
{
throw new MinorException("Plugin init error", errors.toString());
throw new MinorException("Plugin init error", errors.toString());
}
}
}
}
HashMap<String, ArrayList<NormalAction>> sortedPlugins;
HashMap<String, ArrayList<NormalAction>> sortedPlugins;
/**
/**
* Gets list of sorted plugins
* Gets list of sorted plugins
*
*
* @return Hashmap with category key, and list of plugins of each category
* @return Hashmap with category key, and list of plugins of each category
*/
*/
public HashMap<String, ArrayList<NormalAction>> getSortedPlugins()
public HashMap<String, ArrayList<NormalAction>> getSortedPlugins()
{
{
return sortedPlugins;
return sortedPlugins;
}
}
/**
/**
* @return Gets actions element from the config.xml in plugins folder
* @return Gets actions element from the config.xml in plugins folder
*/
*/
private Element getActionsElement()
private Element getActionsElement()
{
{
return (Element) document.getElementsByTagName("actions").item(0);
return (Element) document.getElementsByTagName("actions").item(0);
}
}
/**
/**
* Saves ServerProperties of every plugin in config.xml in plugins folder
* Saves ServerProperties of every plugin in config.xml in plugins folder
*
*
* @throws MinorException Thrown when failed to save settings
* @throws MinorException Thrown when failed to save settings
*/
*/
public void saveServerSettings() throws MinorException
public void saveServerSettings() throws MinorException
{
{
XMLConfigHelper.removeChilds(getActionsElement());
XMLConfigHelper.removeChilds(getActionsElement());
for(NormalAction normalAction : normalPlugins)
for(NormalAction normalAction : normalPlugins)
{
{
Element actionElement = document.createElement("action");
Element actionElement = document.createElement("action");
getActionsElement().appendChild(actionElement);
getActionsElement().appendChild(actionElement);
Element moduleNameElement = document.createElement("module-name");
Element moduleNameElement = document.createElement("module-name");
moduleNameElement.setTextContent(normalAction.getModuleName());
moduleNameElement.setTextContent(normalAction.getModuleName());
actionElement.appendChild(moduleNameElement);
actionElement.appendChild(moduleNameElement);
Element versionElement = document.createElement("version");
Element versionElement = document.createElement("version");
versionElement.setTextContent(normalAction.getVersion().getText());
versionElement.setTextContent(normalAction.getVersion().getText());
actionElement.appendChild(versionElement);
actionElement.appendChild(versionElement);
Element propertiesElement = document.createElement("properties");
Element propertiesElement = document.createElement("properties");
actionElement.appendChild(propertiesElement);
actionElement.appendChild(propertiesElement);
for(String key : normalAction.getServerProperties().getNames())
for(String key : normalAction.getServerProperties().getNames())
{
{
for(Property eachProperty : normalAction.getServerProperties().getMultipleProperties(key))
for(Property eachProperty : normalAction.getServerProperties().getMultipleProperties(key))
{
{
Element propertyElement = document.createElement("property");
Element propertyElement = document.createElement("property");
propertiesElement.appendChild(propertyElement);
propertiesElement.appendChild(propertyElement);
Element nameElement = document.createElement("name");
Element nameElement = document.createElement("name");
nameElement.setTextContent(eachProperty.getName());
nameElement.setTextContent(eachProperty.getName());
propertyElement.appendChild(nameElement);
propertyElement.appendChild(nameElement);
Element valueElement = document.createElement("value");
Element valueElement = document.createElement("value");
valueElement.setTextContent(eachProperty.getRawValue());
valueElement.setTextContent(eachProperty.getRawValue());
propertyElement.appendChild(valueElement);
propertyElement.appendChild(valueElement);
}
}
}
}
}
}
save();
save();
}
}
private PropertySaver propertySaver = null;
private PropertySaver propertySaver = null;
/**
/**
* Set PropertySaver class
* Set PropertySaver class
* @param propertySaver instance of PropertySaver
* @param propertySaver instance of PropertySaver
*/
*/
public void setPropertySaver(PropertySaver propertySaver)
public void setPropertySaver(PropertySaver propertySaver)
{
{
this.propertySaver = propertySaver;
this.propertySaver = propertySaver;
}
}
private ServerConnection serverConnection = null;
private ServerConnection serverConnection = null;
/**
/**
* Set setServerConnection class
* Set setServerConnection class
* @param serverConnection instance of ServerConnection
* @param serverConnection instance of ServerConnection
*/
*/
public void setServerConnection(ServerConnection serverConnection)
public void setServerConnection(ServerConnection serverConnection)
{
{
this.serverConnection = serverConnection;
this.serverConnection = serverConnection;
}
}
/**
/**
* Get plugin from index from list
* Get plugin from index from list
*
*
* @param index of plugin
* @param index of plugin
* @return found plugin
* @return found plugin
*/
*/
public NormalAction getActionFromIndex(int index)
public NormalAction getActionFromIndex(int index)
{
{
return normalPlugins.get(index);
return normalPlugins.get(index);
}
}
/**
/**
* Calls onShutDown method in every plugin
* Calls onShutDown method in every plugin
*/
*/
public void shutDownActions()
public void shutDownActions()
{
{
if(normalPlugins != null)
if(normalPlugins != null)
{
{
for(NormalAction eachPlugin : normalPlugins)
for(NormalAction eachPlugin : normalPlugins)
{
{
try
try
{
{
eachPlugin.onShutDown();
eachPlugin.onShutDown();
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
normalPlugins.clear();
normalPlugins.clear();
}
}
}
}
/**
/**
* Saves all Server Properties of each Plugin in config.xml in Plugins folder
* Saves all Server Properties of each Plugin in config.xml in Plugins folder
* @throws MinorException thrown when failed to save
* @throws MinorException thrown when failed to save
*/
*/
public void save() throws MinorException
public void save() throws MinorException
{
{
try
try
{
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(configFile);
Result output = new StreamResult(configFile);
Source input = new DOMSource(document);
Source input = new DOMSource(document);
transformer.transform(input, output);
transformer.transform(input, output);
}
}
catch (Exception e)
catch (Exception e)
{
{
throw new MinorException("Config", "unable to save server plugins settings");
throw new MinorException("Config", "unable to save server plugins settings");
}
}
}
}
}
}
/*
/*
Stream-Pi - Free & Open-Source Modular Cross-Platform Programmable Macropad
Stream-Pi - Free & Open-Source Modular Cross-Platform Programmable Macropad
Copyright (C) 2019-2021 Debayan Sutradhar (rnayabed), Samuel Quiñones (SamuelQuinones)
Copyright (C) 2019-2021 Debayan Sutradhar (rnayabed), Samuel Quiñones (SamuelQuinones)
This program is free software: you can redistribute it and/or modify
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
(at your option) any later version.
This program is distributed in the hope that it will be useful,
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU General Public License for more details.
Written by : Debayan Sutradhar (rnayabed)
Written by : Debayan Sutradhar (rnayabed)
*/
*/
package com.stream_pi.server.client;
package com.stream_pi.server.client;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import java.util.HashMap;
import java.util.HashMap;
import java.util.Set;
import java.util.Set;
import java.util.UUID;
import java.util.UUID;
public class ClientProfile implements Cloneable {
public class ClientProfile implements Cloneable {
private String name, ID;
private String name, ID;
private int rows, cols, actionSize, actionGap;
private int rows, cols, actionSize, actionGap;
private final HashMap<String, Action> actions;
private final HashMap<String, Action> actions;
public ClientProfile(String name, String ID, int rows, int cols, int actionSize, int actionGap)
public ClientProfile(String name, String ID, int rows, int cols, int actionSize, int actionGap)
{
{
this.actions = new HashMap<>();
this.actions = new HashMap<>();
this.ID = ID;
this.ID = ID;
this.name = name;
this.name = name;
this.rows = rows;
this.rows = rows;
this.cols = cols;
this.cols = cols;
this.actionGap = actionGap;
this.actionGap = actionGap;
this.actionSize = actionSize;
this.actionSize = actionSize;
}
}
public ClientProfile(String name, int rows, int cols, int actionSize, int actionGap)
public ClientProfile(String name, int rows, int cols, int actionSize, int actionGap)
{
{
this(name, UUID.randomUUID().toString(), rows, cols, actionSize, actionGap);
this(name, UUID.randomUUID().toString(), rows, cols, actionSize, actionGap);
}
}
public Action getActionByID(String ID)
public Action getActionByID(String ID)
{
{
return actions.get(ID);
return actions.get(ID);
}
}
public void removeActionByID(String ID)
public void removeActionByID(String ID)
{
{
actions.remove(ID);
actions.remove(ID);
}
}
public Set<String> getActionsKeySet() {
public Set<String> getActionsKeySet() {
return actions.keySet();
return actions.keySet();
}
}
public synchronized void addAction(Action action) throws CloneNotSupportedException {
public synchronized void addAction(Action action) throws CloneNotSupportedException {
actions.put(action.getID(), action.clone());
actions.put(action.getID(), action.clone());
}
}
public String getID()
public String getID()
{
{
return ID;
return ID;
}
}
public String getName()
public String getName()
{
{
return name;
return name;
}
}
public int getRows()
public int getRows()
{
{
return rows;
return rows;
}
}
public int getCols()
public int getCols()
{
{
return cols;
return cols;
}
}
public int getActionSize()
public int getActionSize()
{
{
return actionSize;
return actionSize;
}
}
public int getActionGap()
public int getActionGap()
{
{
return actionGap;
return actionGap;
}
}
public void setRows(int rows)
public void setRows(int rows)
{
{
this.rows = rows;
this.rows = rows;
}
}
public void setCols(int cols)
public void setCols(int cols)
{
{
this.cols = cols;
this.cols = cols;
}
}
public void setID(String ID)
public void setID(String ID)
{
{
this.ID = ID;
this.ID = ID;
}
}
public void setActionSize(int actionSize)
public void setActionSize(int actionSize)
{
{
this.actionSize = actionSize;
this.actionSize = actionSize;
}
}
public void setActionGap(int actionGap)
public void setActionGap(int actionGap)
{
{
this.actionGap = actionGap;
this.actionGap = actionGap;
}
}
public void setName(String name)
public void setName(String name)
{
{
this.name = name;
this.name = name;
}
}
public Object clone() throws CloneNotSupportedException
public Object clone() throws CloneNotSupportedException
{
{
return super.clone();
return super.clone();
}
}
}
}
package com.stream_pi.server.connection;
package com.stream_pi.server.connection;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.actionapi.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.actionapi.action.Location;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.actionapi.actionproperty.ClientProperties;
import com.stream_pi.action_api.actionproperty.ClientProperties;
import com.stream_pi.actionapi.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.actionapi.actionproperty.property.Type;
import com.stream_pi.action_api.actionproperty.property.Type;
import com.stream_pi.actionapi.normalaction.NormalAction;
import com.stream_pi.action_api.normalaction.NormalAction;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientTheme;
import com.stream_pi.server.client.ClientTheme;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlertType;
import com.stream_pi.util.alert.StreamPiAlertType;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.StreamPiException;
import com.stream_pi.util.exception.StreamPiException;
import com.stream_pi.util.platform.Platform;
import com.stream_pi.util.platform.Platform;
import com.stream_pi.util.platform.ReleaseStatus;
import com.stream_pi.util.platform.ReleaseStatus;
import com.stream_pi.util.version.Version;
import com.stream_pi.util.version.Version;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.IOException;
import java.net.Socket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class ClientConnection extends Thread{
public class ClientConnection extends Thread
{
private Socket socket;
private Socket socket;
private ServerListener serverListener;
private ServerListener serverListener;
private AtomicBoolean stop = new AtomicBoolean(false);
private AtomicBoolean stop = new AtomicBoolean(false);
private DataInputStream dis;
private DataInputStream dis;
private DataOutputStream dos;
private DataOutputStream dos;
private Logger logger;
private Logger logger;
private Client client = null;
private Client client = null;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
public ClientConnection(Socket socket, ServerListener serverListener, ExceptionAndAlertHandler exceptionAndAlertHandler)
public ClientConnection(Socket socket, ServerListener serverListener, ExceptionAndAlertHandler exceptionAndAlertHandler)
{
{
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
//actionIconsToBeSent = new ArrayList__();
//actionIconsToBeSent = new ArrayList__();
this.socket = socket;
this.socket = socket;
this.serverListener = serverListener;
this.serverListener = serverListener;
logger = Logger.getLogger(ClientConnection.class.getName());
logger = Logger.getLogger(ClientConnection.class.getName());
try
try
{
{
dis = new DataInputStream(socket.getInputStream());
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
dos = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException("Unable to start socket streams"));
exceptionAndAlertHandler.handleMinorException(new MinorException("Unable to start socket streams"));
}
}
start();
start();
}
}
public synchronized void exit()
public synchronized void exit()
{
{
if(stop.get())
if(stop.get())
return;
return;
logger.info("Stopping ...");
logger.info("Stopping ...");
try
try
{
{
if(socket !=null)
if(socket !=null)
{
{
logger.info("Stopping connection "+socket.getRemoteSocketAddress());
logger.info("Stopping connection "+socket.getRemoteSocketAddress());
disconnect();
disconnect();
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
}
}
public synchronized void exitAndRemove()
public synchronized void exitAndRemove()
{
{
exit();
exit();
removeConnection();
removeConnection();
serverListener.clearTemp();
serverListener.clearTemp();
}
}
public void removeConnection()
public void removeConnection()
{
{
ClientConnections.getInstance().removeConnection(this);
ClientConnections.getInstance().removeConnection(this);
}
}
public synchronized void writeToStream(String text) throws SevereException
public synchronized void writeToStream(String text) throws SevereException
{
{
try
try
{
{
byte[] txtBytes = text.getBytes();
byte[] txtBytes = text.getBytes();
Thread.sleep(50);
Thread.sleep(50);
dos.writeUTF("string:: ::");
dos.writeUTF("string:: ::");
dos.flush();
dos.flush();
dos.writeInt(txtBytes.length);
dos.writeInt(txtBytes.length);
dos.flush();
dos.flush();
write(txtBytes);
write(txtBytes);
dos.flush();
dos.flush();
}
}
catch (IOException | InterruptedException e)
catch (IOException | InterruptedException e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Unable to write to io Stream!");
throw new SevereException("Unable to write to io Stream!");
}
}
}
}
public synchronized void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
public synchronized void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
{
{
try
try
{
{
logger.info("Sending action Icon...");
logger.info("Sending action Icon...");
//Thread.sleep(50);
//Thread.sleep(50);
System.out.println("1");
System.out.println("1");
dos.writeUTF("action_icon::"+profileID+"!!"+actionID+"!!::"+icon.length);
dos.writeUTF("action_icon::"+profileID+"!!"+actionID+"!!::"+icon.length);
System.out.println("2");
System.out.println("2");
dos.flush();
dos.flush();
System.out.println("3");
System.out.println("3");
dos.writeInt(icon.length);
dos.writeInt(icon.length);
System.out.println("4");
System.out.println("4");
dos.flush();
dos.flush();
System.out.println("5");
System.out.println("5");
write(icon);
write(icon);
System.out.println("6");
System.out.println("6");
dos.flush();
dos.flush();
System.out.println("7");
System.out.println("7");
}
}
catch (IOException e)
catch (IOException e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Unable to write to io Stream!");
throw new SevereException("Unable to write to io Stream!");
}
}
}
}
public void write(byte[] array) throws SevereException
public void write(byte[] array) throws SevereException
{
{
try
try
{
{
dos.write(array);
dos.write(array);
}
}
catch (IOException e)
catch (IOException e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Unable to write to io Stream!");
throw new SevereException("Unable to write to io Stream!");
}
}
}
}
public void initAfterConnectionQueryReceive(String[] arr) throws StreamPiException
public void initAfterConnectionQueryReceive(String[] arr) throws StreamPiException
{
{
logger.info("Setting up client object ...");
logger.info("Setting up client object ...");
Version clientVersion;
Version clientVersion;
Version commsStandard;
Version commsStandard;
Version themesStandard;
Version themesStandard;
ReleaseStatus releaseStatus;
ReleaseStatus releaseStatus;
try
try
{
{
clientVersion = new Version(arr[1]);
clientVersion = new Version(arr[1]);
releaseStatus = ReleaseStatus.valueOf(arr[2]);
releaseStatus = ReleaseStatus.valueOf(arr[2]);
commsStandard = new Version(arr[3]);
commsStandard = new Version(arr[3]);
themesStandard = new Version(arr[4]);
themesStandard = new Version(arr[4]);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exitAndRemove();
exitAndRemove();
throw new MinorException(e.getShortMessage()+" (client '"+socket.getRemoteSocketAddress()+"' )");
throw new MinorException(e.getShortMessage()+" (client '"+socket.getRemoteSocketAddress()+"' )");
}
}
if(!commsStandard.isEqual(ServerInfo.getInstance().getCommStandardVersion()))
if(!commsStandard.isEqual(ServerInfo.getInstance().getCommStandardVersion()))
{
{
String errTxt = "Server and client Communication standards do not match. Make sure you are on the latest version of server and client.\n" +
String errTxt = "Server and client Communication standards do not match. Make sure you are on the latest version of server and client.\n" +
"Server Comms. Standard : "+ServerInfo.getInstance().getCommStandardVersion().getText()+
"Server Comms. Standard : "+ServerInfo.getInstance().getCommStandardVersion().getText()+
"\nclient Comms. Standard : "+commsStandard.getText();
"\nclient Comms. Standard : "+commsStandard.getText();
disconnect(errTxt);
disconnect(errTxt);
throw new MinorException(errTxt);
throw new MinorException(errTxt);
}
}
client = new Client(clientVersion, releaseStatus, commsStandard, themesStandard, arr[5], Platform.valueOf(arr[8]), socket.getRemoteSocketAddress());
client = new Client(clientVersion, releaseStatus, commsStandard, themesStandard, arr[5], Platform.valueOf(arr[8]), socket.getRemoteSocketAddress());
client.setStartupDisplayWidth(Double.parseDouble(arr[6]));
client.setStartupDisplayWidth(Double.parseDouble(arr[6]));
client.setStartupDisplayHeight(Double.parseDouble(arr[7]));
client.setStartupDisplayHeight(Double.parseDouble(arr[7]));
client.setDefaultProfileID(arr[9]);
client.setDefaultProfileID(arr[9]);
client.setDefaultThemeFullName(arr[10]);
client.setDefaultThemeFullName(arr[10]);
//call get profiles command.
//call get profiles command.
serverListener.clearTemp();
serverListener.clearTemp();
}
}
public synchronized Client getClient()
public synchronized Client getClient()
{
{
return client;
return client;
}
}
@Override
@Override
public void run() {
public void run() {
try {
try {
initAfterConnectionQuerySend();
initAfterConnectionQuerySend();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
exitAndRemove();
exitAndRemove();
return;
return;
}
}
try
try
{
{
while(!stop.get())
while(!stop.get())
{
{
String msg = "";
String msg = "";
try
try
{
{
String raw = dis.readUTF();
String raw = dis.readUTF();
int length = dis.readInt();
int length = dis.readInt();
System.out.println("SIZE TO READ : "+length);
System.out.println("SIZE TO READ : "+length);
String[] precursor = raw.split("::");
String[] precursor = raw.split("::");
String inputType = precursor[0];
String inputType = precursor[0];
String secondArg = precursor[1];
String secondArg = precursor[1];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
/*int count;
/*int count;
int chunkSize = 512;
int chunkSize = 512;
while (length>0)
while (length>0)
{
{
if(chunkSize > length)
if(chunkSize > length)
chunkSize = length;
chunkSize = length;
else
else
chunkSize = 512;
chunkSize = 512;
byte[] buffer = new byte[chunkSize];
byte[] buffer = new byte[chunkSize];
count = dis.read(buffer);
count = dis.read(buffer);
System.out.println(count);
System.out.println(count);
byteArrayOutputStream.write(buffer);
byteArrayOutputStream.write(buffer);
length-=count;
length-=count;
}*/
}*/
/*byte[] buffer = new byte[8192];
/*byte[] buffer = new byte[8192];
int read;
int read;
while((read = dis.read(buffer)) != -1){
while((read = dis.read(buffer)) != -1){
System.out.println("READ : "+read);
System.out.println("READ : "+read);
byteArrayOutputStream.write(buffer, 0, read);
byteArrayOutputStream.write(buffer, 0, read);
}
}
System.out.println("READ : "+byteArrayOutputStream.size());
System.out.println("READ : "+byteArrayOutputStream.size());
byteArrayOutputStream.close();
byteArrayOutputStream.close();
byte[] bArr = byteArrayOutputStream.toByteArray();*/
byte[] bArr = byteArrayOutputStream.toByteArray();*/
byte[] bArr = new byte[length];
byte[] bArr = new byte[length];
dis.readFully(bArr);
dis.readFully(bArr);
if(inputType.equals("string"))
if(inputType.equals("string"))
{
{
msg = new String(bArr);
msg = new String(bArr);
}
}
else if(inputType.equals("action_icon"))
else if(inputType.equals("action_icon"))
{
{
String[] secondArgSep = secondArg.split("!!");
String[] secondArgSep = secondArg.split("!!");
String profileID = secondArgSep[0];
String profileID = secondArgSep[0];
String actionID = secondArgSep[1];
String actionID = secondArgSep[1];
getClient().getProfileByID(profileID).getActionByID(actionID).setIcon(bArr);
getClient().getProfileByID(profileID).getActionByID(actionID).setIcon(bArr);
//serverListener.clearTemp();
//serverListener.clearTemp();
continue;
continue;
}
}
}
}
catch (IOException e)
catch (IOException e)
{
{
logger.log(Level.SEVERE, e.getMessage());
logger.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
e.printStackTrace();
serverListener.clearTemp();
serverListener.clearTemp();
if(!stop.get())
if(!stop.get())
{
{
removeConnection();
removeConnection();
throw new MinorException("Accidentally disconnected from "+getClient().getNickName()+".");
throw new MinorException("Accidentally disconnected from "+getClient().getNickName()+".");
}
}
exitAndRemove();
exitAndRemove();
return;
return;
}
}
logger.info("Received text : '"+msg+"'");
logger.info("Received text : '"+msg+"'");
String[] sep = msg.split("::");
String[] sep = msg.split("::");
String command = sep[0];
String command = sep[0];
switch (command)
switch (command)
{
{
case "disconnect" : clientDisconnected(msg);
case "disconnect" : clientDisconnected(msg);
break;
break;
case "client_details" : initAfterConnectionQueryReceive(sep);
case "client_details" : initAfterConnectionQueryReceive(sep);
getProfilesFromClient();
getProfilesFromClient();
getThemesFromClient();
getThemesFromClient();
break;
break;
case "profiles" : registerProfilesFromClient(sep);
case "profiles" : registerProfilesFromClient(sep);
break;
break;
case "profile_details" : registerProfileDetailsFromClient(sep);
case "profile_details" : registerProfileDetailsFromClient(sep);
break;
break;
case "action_details" : registerActionToProfile(sep);
case "action_details" : registerActionToProfile(sep);
break;
break;
case "themes": registerThemes(sep);
case "themes": registerThemes(sep);
break;
break;
case "action_clicked": actionClicked(sep[1], sep[2]);
case "action_clicked": actionClicked(sep[1], sep[2]);
break;
break;
default: logger.warning("Command '"+command+"' does not match records. Make sure client and server versions are equal.");
default: logger.warning("Command '"+command+"' does not match records. Make sure client and server versions are equal.");
}
}
}
}
}
}
catch (StreamPiException e)
catch (StreamPiException e)
{
{
e.printStackTrace();
e.printStackTrace();
if(e instanceof MinorException)
if(e instanceof MinorException)
exceptionAndAlertHandler.handleMinorException((MinorException) e);
exceptionAndAlertHandler.handleMinorException((MinorException) e);
else if (e instanceof SevereException)
else if (e instanceof SevereException)
exceptionAndAlertHandler.handleSevereException((SevereException) e);
exceptionAndAlertHandler.handleSevereException((SevereException) e);
}
}
}
}
// commands
// commands
public void initAfterConnectionQuerySend() throws SevereException
public void initAfterConnectionQuerySend() throws SevereException
{
{
logger.info("Asking client details ...");
logger.info("Asking client details ...");
writeToStream("get_client_details::");
writeToStream("get_client_details::");
}
}
public void disconnect() throws SevereException {
public void disconnect() throws SevereException {
disconnect("");
disconnect("");
}
}
public void disconnect(String message) throws SevereException {
public void disconnect(String message) throws SevereException {
if(stop.get())
if(stop.get())
return;
return;
stop.set(true);
stop.set(true);
logger.info("Sending client disconnect message ...");
logger.info("Sending client disconnect message ...");
writeToStream("disconnect::"+message+"::");
writeToStream("disconnect::"+message+"::");
try
try
{
{
if(!socket.isClosed())
if(!socket.isClosed())
socket.close();
socket.close();
}
}
catch (IOException e)
catch (IOException e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Unable to close socket");
throw new SevereException("Unable to close socket");
}
}
}
}
public void clientDisconnected(String message)
public void clientDisconnected(String message)
{
{
stop.set(true);
stop.set(true);
String txt = "Disconnected!";
String txt = "Disconnected!";
if(!message.equals("disconnect::::"))
if(!message.equals("disconnect::::"))
txt = "Message : "+message.split("::")[1];
txt = "Message : "+message.split("::")[1];
new StreamPiAlert("Disconnected from "+getClient().getNickName()+".", txt, StreamPiAlertType.WARNING).show();;
new StreamPiAlert("Disconnected from "+getClient().getNickName()+".", txt, StreamPiAlertType.WARNING).show();;
exitAndRemove();
exitAndRemove();
}
}
public void getProfilesFromClient() throws StreamPiException
public void getProfilesFromClient() throws StreamPiException
{
{
logger.info("Asking client to send profiles ...");
logger.info("Asking client to send profiles ...");
writeToStream("get_profiles::");
writeToStream("get_profiles::");
}
}
public void getThemesFromClient() throws StreamPiException
public void getThemesFromClient() throws StreamPiException
{
{
logger.info("Asking clients to send themes ...");
logger.info("Asking clients to send themes ...");
writeToStream("get_themes::");
writeToStream("get_themes::");
}
}
public void registerThemes(String[] sep)
public void registerThemes(String[] sep)
{
{
for(int i =1; i<sep.length;i++)
for(int i =1; i<sep.length;i++)
{
{
String[] internal = sep[i].split("__");
String[] internal = sep[i].split("__");
ClientTheme clientTheme = new ClientTheme(
ClientTheme clientTheme = new ClientTheme(
internal[0],
internal[0],
internal[1],
internal[1],
internal[2],
internal[2],
internal[3]
internal[3]
);
);
try
try
{
{
getClient().addTheme(clientTheme);
getClient().addTheme(clientTheme);
}
}
catch (CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
{
logger.log(Level.SEVERE, e.getMessage());
logger.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
e.printStackTrace();
}
}
}
}
}
}
public void registerProfilesFromClient(String[] sep) throws StreamPiException
public void registerProfilesFromClient(String[] sep) throws StreamPiException
{
{
logger.info("Registering profiles ...");
logger.info("Registering profiles ...");
int noOfProfiles = Integer.parseInt(sep[1]);
int noOfProfiles = Integer.parseInt(sep[1]);
for(int i = 2; i<(noOfProfiles + 2); i++)
for(int i = 2; i<(noOfProfiles + 2); i++)
{
{
String profileID = sep[i];
String profileID = sep[i];
getProfileDetailsFromClient(profileID);
getProfileDetailsFromClient(profileID);
}
}
}
}
public void getProfileDetailsFromClient(String ID) throws StreamPiException
public void getProfileDetailsFromClient(String ID) throws StreamPiException
{
{
logger.info("Asking client to send details of profile : "+ID);
logger.info("Asking client to send details of profile : "+ID);
writeToStream("get_profile_details::"+ID+"::");
writeToStream("get_profile_details::"+ID+"::");
}
}
public void registerProfileDetailsFromClient(String[] sep)
public void registerProfileDetailsFromClient(String[] sep)
{
{
String ID = sep[1];
String ID = sep[1];
logger.info("Registering details for profile : "+ID);
logger.info("Registering details for profile : "+ID);
String name = sep[2];
String name = sep[2];
int rows = Integer.parseInt(sep[3]);
int rows = Integer.parseInt(sep[3]);
int cols = Integer.parseInt(sep[4]);
int cols = Integer.parseInt(sep[4]);
int actionSize = Integer.parseInt(sep[5]);
int actionSize = Integer.parseInt(sep[5]);
int actionGap = Integer.parseInt(sep[6]);
int actionGap = Integer.parseInt(sep[6]);
ClientProfile clientProfile = new ClientProfile(name, ID, rows, cols, actionSize, actionGap);
ClientProfile clientProfile = new ClientProfile(name, ID, rows, cols, actionSize, actionGap);
logger.info("Added client profile "+clientProfile.getName());
logger.info("Added client profile "+clientProfile.getName());
try
try
{
{
getClient().addProfile(clientProfile);
getClient().addProfile(clientProfile);
}
}
catch (CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
e.printStackTrace();
e.printStackTrace();
}
}
serverListener.clearTemp();
serverListener.clearTemp();
}
}
/*public void getActionIcon(String profileID, String actionID) throws StreamPiException
/*public void getActionIcon(String profileID, String actionID) throws StreamPiException
{
{
System.out.println("getting action icon from "+profileID+", "+actionID);
System.out.println("getting action icon from "+profileID+", "+actionID);
writeToStream("get_action_icon::"+profileID+"::"+actionID);
writeToStream("get_action_icon::"+profileID+"::"+actionID);
}*/
}*/
public synchronized void registerActionToProfile(String[] sep) throws StreamPiException
public synchronized void registerActionToProfile(String[] sep) throws StreamPiException
{
{
String profileID = sep[1];
String profileID = sep[1];
String ID = sep[2];
String ID = sep[2];
ActionType actionType = ActionType.valueOf(sep[3]);
ActionType actionType = ActionType.valueOf(sep[3]);
//4 - Version
//4 - Version
//5 - ModuleName
//5 - ModuleName
//display
//display
String bgColorHex = sep[6];
String bgColorHex = sep[6];
//icon
//icon
boolean isHasIcon = sep[7].equals("true");
boolean isHasIcon = sep[7].equals("true");
boolean isShowIcon = sep[8].equals("true");
boolean isShowIcon = sep[8].equals("true");
//text
//text
boolean isShowDisplayText = sep[9].equals("true");
boolean isShowDisplayText = sep[9].equals("true");
String displayFontColor = sep[10];
String displayFontColor = sep[10];
String displayText = sep[11];
String displayText = sep[11];
DisplayTextAlignment displayTextAlignment = DisplayTextAlignment.valueOf(sep[12]);
DisplayTextAlignment displayTextAlignment = DisplayTextAlignment.valueOf(sep[12]);
//location
//location
String row = sep[13];
String row = sep[13];
String col = sep[14];
String col = sep[14];
Location location = new Location(Integer.parseInt(row), Integer.parseInt(col));
Location location = new Location(Integer.parseInt(row), Integer.parseInt(col));
Action action = new Action(ID, actionType);
Action action = new Action(ID, actionType);
action.setBgColourHex(bgColorHex);
action.setBgColourHex(bgColorHex);
action.setShowIcon(isShowIcon);
action.setShowIcon(isShowIcon);
action.setHasIcon(isHasIcon);
action.setHasIcon(isHasIcon);
action.setShowDisplayText(isShowDisplayText);
action.setShowDisplayText(isShowDisplayText);
action.setDisplayTextFontColourHex(displayFontColor);
action.setDisplayTextFontColourHex(displayFontColor);
action.setDisplayText(displayText);
action.setDisplayText(displayText);
action.setDisplayTextAlignment(displayTextAlignment);
action.setDisplayTextAlignment(displayTextAlignment);
action.setLocation(location);
action.setLocation(location);
//client properties
//client properties
int clientPropertiesSize = Integer.parseInt(sep[15]);
int clientPropertiesSize = Integer.parseInt(sep[15]);
String root = sep[17];
String root = sep[17];
action.setParent(root);
action.setParent(root);
String[] clientPropertiesRaw = sep[16].split("!!");
String[] clientPropertiesRaw = sep[16].split("!!");
ClientProperties clientProperties = new ClientProperties();
ClientProperties clientProperties = new ClientProperties();
if(actionType == ActionType.FOLDER)
if(actionType == ActionType.FOLDER)
clientProperties.setDuplicatePropertyAllowed(true);
clientProperties.setDuplicatePropertyAllowed(true);
for(int i = 0;i<clientPropertiesSize; i++)
for(int i = 0;i<clientPropertiesSize; i++)
{
{
String[] clientPraw = clientPropertiesRaw[i].split("__");
String[] clientPraw = clientPropertiesRaw[i].split("__");
Property property = new Property(clientPraw[0], Type.STRING);
Property property = new Property(clientPraw[0], Type.STRING);
if(clientPraw.length > 1)
if(clientPraw.length > 1)
property.setRawValue(clientPraw[1]);
property.setRawValue(clientPraw[1]);
clientProperties.addProperty(property);
clientProperties.addProperty(property);
}
}
action.setClientProperties(clientProperties);
action.setClientProperties(clientProperties);
action.setModuleName(sep[5]);
action.setModuleName(sep[5]);
//set up action
//set up action
//action toBeAdded = null;
//action toBeAdded = null;
if(actionType == ActionType.NORMAL)
if(actionType == ActionType.NORMAL)
{
{
NormalAction actionCopy = NormalActionPlugins.getInstance().getPluginByModuleName(sep[5]);
NormalAction actionCopy = NormalActionPlugins.getInstance().getPluginByModuleName(sep[5]);
if(actionCopy == null)
if(actionCopy == null)
{
{
action.setInvalid(true);
action.setInvalid(true);
}
}
else
else
{
{
action.setVersion(new Version(sep[4]));
action.setVersion(new Version(sep[4]));
//action.setHelpLink(actionCopy.getHelpLink());
//action.setHelpLink(actionCopy.getHelpLink());
if(actionCopy.getVersion().getMajor() != action.getVersion().getMajor())
if(actionCopy.getVersion().getMajor() != action.getVersion().getMajor())
{
{
action.setInvalid(true);
action.setInvalid(true);
}
}
else
else
{
{
action.setName(actionCopy.getName());
action.setName(actionCopy.getName());
ClientProperties finalClientProperties = new ClientProperties();
ClientProperties finalClientProperties = new ClientProperties();
for(Property property : actionCopy.getClientProperties().get())
for(Property property : actionCopy.getClientProperties().get())
{
{
for(int i = 0;i<action.getClientProperties().getSize();i++)
for(int i = 0;i<action.getClientProperties().getSize();i++)
{
{
Property property1 = action.getClientProperties().get().get(i);
Property property1 = action.getClientProperties().get().get(i);
if (property.getName().equals(property1.getName()))
if (property.getName().equals(property1.getName()))
{
{
property.setRawValue(property1.getRawValue());
property.setRawValue(property1.getRawValue());
finalClientProperties.addProperty(property);
finalClientProperties.addProperty(property);
}
}
}
}
}
}
action.setClientProperties(finalClientProperties);
action.setClientProperties(finalClientProperties);
}
}
}
}
}
}
try
try
{
{
for(Property prop : action.getClientProperties().get())
for(Property prop : action.getClientProperties().get())
{
{
logger.info("G@@@@@ : "+prop.getRawValue());
logger.info("G@@@@@ : "+prop.getRawValue());
}
}
getClient().getProfileByID(profileID).addAction(action);
getClient().getProfileByID(profileID).addAction(action);
for(String action1x : getClient().getProfileByID(profileID).getActionsKeySet())
for(String action1x : getClient().getProfileByID(profileID).getActionsKeySet())
{
{
Action action1 = getClient().getProfileByID(profileID).getActionByID(action1x);
Action action1 = getClient().getProfileByID(profileID).getActionByID(action1x);
logger.info("231cc : "+action1.getID());
logger.info("231cc : "+action1.getID());
for(Property prop : action1.getClientProperties().get())
for(Property prop : action1.getClientProperties().get())
{
{
logger.info("G@VVVV@@@ : "+prop.getRawValue());
logger.info("G@VVVV@@@ : "+prop.getRawValue());
}
}
}
}
}
}
catch (CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException("action", "Unable to clone"));
exceptionAndAlertHandler.handleMinorException(new MinorException("action", "Unable to clone"));
}
}
}
}
public void saveActionDetails(String profileID, Action action) throws SevereException
public void saveActionDetails(String profileID, Action action) throws SevereException
{
{
StringBuilder finalQuery = new StringBuilder("save_action_details::");
StringBuilder finalQuery = new StringBuilder("save_action_details::");
//failsafes
//failsafes
if(action.getDisplayText().endsWith(":"))
if(action.getDisplayText().endsWith(":"))
action.setDisplayText(action.getDisplayText()+" ");
action.setDisplayText(action.getDisplayText()+" ");
finalQuery.append(profileID)
finalQuery.append(profileID)
.append("::")
.append("::")
.append(action.getID())
.append(action.getID())
.append("::")
.append("::")
.append(action.getActionType())
.append(action.getActionType())
.append("::");
.append("::");
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
{
{
finalQuery.append(action.getVersion().getText());
finalQuery.append(action.getVersion().getText());
System.out.println("VERSION :sdd "+action.getVersion().getText());
System.out.println("VERSION :sdd "+action.getVersion().getText());
}
}
finalQuery.append("::");
finalQuery.append("::");
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
finalQuery.append(action.getModuleName());
finalQuery.append(action.getModuleName());
finalQuery.append("::");
finalQuery.append("::");
//display
//display
finalQuery.append(action.getBgColourHex())
finalQuery.append(action.getBgColourHex())
.append("::");
.append("::");
//icon
//icon
finalQuery.append(action.isHasIcon())
finalQuery.append(action.isHasIcon())
.append("::")
.append("::")
.append(action.isShowIcon())
.append(action.isShowIcon())
.append("::");
.append("::");
//text
//text
finalQuery.append(action.isShowDisplayText())
finalQuery.append(action.isShowDisplayText())
.append("::")
.append("::")
.append(action.getDisplayTextFontColourHex())
.append(action.getDisplayTextFontColourHex())
.append("::")
.append("::")
.append(action.getDisplayText())
.append(action.getDisplayText())
.append("::")
.append("::")
.append(action.getDisplayTextAlignment())
.append(action.getDisplayTextAlignment())
.append("::");
.append("::");
//location
//location
if(action.getLocation() == null)
if(action.getLocation() == null)
finalQuery.append("-1::-1::");
finalQuery.append("-1::-1::");
else
else
finalQuery.append(action.getLocation().getRow())
finalQuery.append(action.getLocation().getRow())
.append("::")
.append("::")
.append(action.getLocation().getCol())
.append(action.getLocation().getCol())
.append("::");
.append("::");
//client properties
//client properties
ClientProperties clientProperties = action.getClientProperties();
ClientProperties clientProperties = action.getClientProperties();
finalQuery.append(clientProperties.getSize())
finalQuery.append(clientProperties.getSize())
.append("::");
.append("::");
for(Property property : clientProperties.get())
for(Property property : clientProperties.get())
{
{
finalQuery.append(property.getName())
finalQuery.append(property.getName())
.append("__")
.append("__")
.append(property.getRawValue())
.append(property.getRawValue())
.append("__");
.append("__");
finalQuery.append("!!");
finalQuery.append("!!");
}
}
finalQuery.append("::")
finalQuery.append("::")
.append(action.getParent())
.append(action.getParent())
.append("::");
.append("::");
writeToStream(finalQuery.toString());
writeToStream(finalQuery.toString());
}
}
public void deleteAction(String profileID, String actionID) throws SevereException
public void deleteAction(String profileID, String actionID) throws SevereException
{
{
writeToStream("delete_action::"+profileID+"::"+actionID);
writeToStream("delete_action::"+profileID+"::"+actionID);
}
}
public void saveClientDetails(String clientNickname, String screenWidth, String screenHeight, String defaultProfileID,
public void saveClientDetails(String clientNickname, String screenWidth, String screenHeight, String defaultProfileID,
String defaultThemeFullName) throws SevereException
String defaultThemeFullName) throws SevereException
{
{
writeToStream("save_client_details::"+
writeToStream("save_client_details::"+
clientNickname+"::"+
clientNickname+"::"+
screenWidth+"::"+
screenWidth+"::"+
screenHeight+"::"+
screenHeight+"::"+
defaultProfileID+"::"+
defaultProfileID+"::"+
defaultThemeFullName+"::");
defaultThemeFullName+"::");
client.setNickName(clientNickname);
client.setNickName(clientNickname);
client.setStartupDisplayWidth(Double.parseDouble(screenWidth));
client.setStartupDisplayWidth(Double.parseDouble(screenWidth));
client.setStartupDisplayHeight(Double.parseDouble(screenHeight));
client.setStartupDisplayHeight(Double.parseDouble(screenHeight));
client.setDefaultProfileID(defaultProfileID);
client.setDefaultProfileID(defaultProfileID);
client.setDefaultThemeFullName(defaultThemeFullName);
client.setDefaultThemeFullName(defaultThemeFullName);
}
}
public void saveProfileDetails(ClientProfile clientProfile) throws SevereException, CloneNotSupportedException {
public void saveProfileDetails(ClientProfile clientProfile) throws SevereException, CloneNotSupportedException {
if(client.getProfileByID(clientProfile.getID()) !=null)
if(client.getProfileByID(clientProfile.getID()) !=null)
{
{
client.getProfileByID(clientProfile.getID()).setName(clientProfile.getName());
client.getProfileByID(clientProfile.getID()).setName(clientProfile.getName());
client.getProfileByID(clientProfile.getID()).setRows(clientProfile.getRows());
client.getProfileByID(clientProfile.getID()).setRows(clientProfile.getRows());
client.getProfileByID(clientProfile.getID()).setCols(clientProfile.getCols());
client.getProfileByID(clientProfile.getID()).setCols(clientProfile.getCols());
client.getProfileByID(clientProfile.getID()).setActionSize(clientProfile.getActionSize());
client.getProfileByID(clientProfile.getID()).setActionSize(clientProfile.getActionSize());
client.getProfileByID(clientProfile.getID()).setActionGap(clientProfile.getActionGap());
client.getProfileByID(clientProfile.getID()).setActionGap(clientProfile.getActionGap());
}
}
else
else
client.addProfile(clientProfile);
client.addProfile(clientProfile);
writeToStream("save_client_profile::"+
writeToStream("save_client_profile::"+
clientProfile.getID()+"::"+
clientProfile.getID()+"::"+
clientProfile.getName()+"::"+
clientProfile.getName()+"::"+
clientProfile.getRows()+"::"+
clientProfile.getRows()+"::"+
clientProfile.getCols()+"::"+
clientProfile.getCols()+"::"+
clientProfile.getActionSize()+"::"+
clientProfile.getActionSize()+"::"+
clientProfile.getActionGap()+"::");
clientProfile.getActionGap()+"::");
}
}
public void deleteProfile(String ID) throws SevereException
public void deleteProfile(String ID) throws SevereException
{
{
writeToStream("delete_profile::"+ID+"::");
writeToStream("delete_profile::"+ID+"::");
}
}
public void actionClicked(String profileID, String actionID) {
public void actionClicked(String profileID, String actionID) {
try
try
{
{
Action action = client.getProfileByID(profileID).getActionByID(actionID);
Action action = client.getProfileByID(profileID).getActionByID(actionID);
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
{
{
NormalAction original = NormalActionPlugins.getInstance().getPluginByModuleName(
NormalAction original = NormalActionPlugins.getInstance().getPluginByModuleName(
action.getModuleName()
action.getModuleName()
);
);
if(original == null)
if(original == null)
{
{
throw new MinorException(
throw new MinorException(
"The action isn't installed on the server."
"The action isn't installed on the server."
);
);
}
}
NormalAction normalAction = original.clone();
NormalAction normalAction = original.clone();
normalAction.setLocation(action.getLocation());
normalAction.setLocation(action.getLocation());
normalAction.setDisplayText(action.getDisplayText());
normalAction.setDisplayText(action.getDisplayText());
normalAction.setID(actionID);
normalAction.setID(actionID);
normalAction.setClientProperties(action.getClientProperties());
normalAction.setClientProperties(action.getClientProperties());
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
boolean result = serverListener.onNormalActionClicked(normalAction);
boolean result = serverListener.onNormalActionClicked(normalAction);
if(!result)
if(!result)
{
{
sendActionFailed(profileID, actionID);
sendActionFailed(profileID, actionID);
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
return null;
return null;
}
}
}).start();
}).start();
}
}
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
}
}
public void sendActionFailed(String profileID, String actionID) throws SevereException {
public void sendActionFailed(String profileID, String actionID) throws SevereException {
logger.info("Sending failed status ...");
logger.info("Sending failed status ...");
writeToStream("action_failed::"+
writeToStream("action_failed::"+
profileID+"::"+
profileID+"::"+
actionID+"::");
actionID+"::");
}
}
}
}
/*package com.StreamPi.Server.connection;
import com.StreamPi.ActionAPI.action.action;
import com.StreamPi.ActionAPI.action.ActionType;
import com.StreamPi.ActionAPI.action.Location;
import com.StreamPi.ActionAPI.ActionProperty.ClientProperties;
import com.StreamPi.ActionAPI.NormalAction.NormalAction;
import com.StreamPi.CommAPI.ConnectionGrpc;
import com.StreamPi.CommAPI.ServerGRPC;
import NormalActionPlugins;
import client;
import ClientProfile;
import ServerInfo;
import com.StreamPi.Util.Exception.MinorException;
import com.StreamPi.Util.Exception.SevereException;
import com.StreamPi.Util.Exception.StreamPiException;
import com.StreamPi.Util.Platform.Platform;
import com.StreamPi.Util.Version.Version;
import io.grpc.stub.StreamObserver;
import javafx.concurrent.Task;
import javafx.scene.control.Alert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ConnectionService extends ConnectionGrpc.ConnectionImplBase {
private client client = null;
private Logger logger;
ServerListener serverListener;
final HashMap<String, Boolean> actionStatuses;
public ConnectionService(ServerListener serverListener)
{
super();
isDisconnect = false;
disconnectMessage = "";
logger = LoggerFactory.getLogger(ConnectionService.class);
actionStatuses = new HashMap<>();
this.serverListener = serverListener;
}
boolean isDisconnect;
String disconnectMessage;
public void disconnect()
{
disconnect("");
}
public void disconnect(String message)
{
if(!isDisconnect)
{
this.isDisconnect = true;
this.disconnectMessage = message;
}
}
@Override
public void sendClientDetails(ServerGRPC.ClientDetails request, StreamObserver<ServerGRPC.Status> responseObserver) {
Version clientVersion;
Version commsAPIVersion;
Version themeAPIVersion;
try
{
clientVersion = new Version(request.getClientVersion());
commsAPIVersion = new Version(request.getCommAPIVersion());
themeAPIVersion = new Version(request.getThemeAPIVersion());
}
catch (MinorException e)
{
e.printStackTrace();
serverListener.onRPCError(new MinorException("versions invalid. Check stacktrace"));
disconnect();
return;
}
String nickName = request.getNickName();
Platform platform = Platform.valueOf(request.getPlatform().toString());
client = new client(clientVersion, commsAPIVersion, themeAPIVersion, nickName, platform, null);
boolean sendActions = true;
if(!commsAPIVersion.isEqual(ServerInfo.getInstance().getCommAPIVersion()))
{
sendActions = false;
disconnect("client CommAPI and Server CommAPI do not match!");
}
responseObserver.onNext(ServerGRPC.Status.newBuilder().setSendActions(sendActions).build());
responseObserver.onCompleted();
}
@Override
public StreamObserver<ServerGRPC.ClientProfile> sendClientProfiles(StreamObserver<ServerGRPC.Empty> responseObserver) {
client.getProfiles().clear();
ArrayList<String> notFoundActions = new ArrayList<>();
return new StreamObserver<ServerGRPC.ClientProfile>() {
@Override
public void onNext(ServerGRPC.ClientProfile clientProfile) {
String name = clientProfile.getName();
String id = clientProfile.getId();
int rows = clientProfile.getRows();
int cols = clientProfile.getCols();
int actionSize = clientProfile.getActionSize();
int actionGap = clientProfile.getActionGap();
ClientProfile finalClientProfile = new ClientProfile(name, id, rows, cols, actionSize, actionGap);
ArrayList<action> actions = new ArrayList<>();
List<ServerGRPC.ClientAction> clientActions = clientProfile.getActionsList();
for(ServerGRPC.ClientAction clientAction : clientActions)
{
String actionID = clientAction.getId();
String actionName = clientAction.getActionName();
boolean hasIcon = clientAction.getHasIcon();
ActionType actionType = ActionType.valueOf(clientAction.getActionType().toString());
action action = new action(actionID, actionType);
action.setActionName(actionName);
action.setHasIcon(hasIcon);
int locationX = clientAction.getLocationX();
int locationY = clientAction.getLocationY();
action.setLocation(new Location(locationX, locationY));
if(actionType == ActionType.NORMAL)
{
action.setModuleName(clientAction.getModuleName());
ClientProperties properties = new ClientProperties();
List<ServerGRPC.ClientProperty> clientProperties = clientAction.getClientPropertiesList();
for(ServerGRPC.ClientProperty clientProperty : clientProperties)
{
String propertyName = clientProperty.getName();
String propertyValue = clientProperty.getValue();
properties.addProperty(propertyName, propertyValue);
}
action.setClientProperties(properties);
boolean isFound = false;
for(NormalAction normalAction : NormalActionPlugins.getInstance().getPlugins())
{
if(normalAction.getModuleName().equals(action.getModuleName()))
{
isFound = true;
normalAction.setClientProperties(action.getClientProperties());
normalAction.setActionName(action.getActionName());
normalAction.setHasIcon(action.isHasIcon());
normalAction.setID(action.getID());
normalAction.setLocation(action.getLocation());
normalAction.setInvalid(false);
actions.add(normalAction);
break;
}
}
if(!isFound)
{
String aName = action.getModuleName();
action.setInvalid(true);
logger.warn("action "+aName+" not found!");
if(!notFoundActions.contains(aName))
notFoundActions.add(aName);
actions.add(action);
}
}
}
finalClientProfile.setActions(actions);
client.addProfile(finalClientProfile);
}
@Override
public void onError(Throwable throwable) {
serverListener.onRPCError(new SevereException(throwable.getMessage()));
}
@Override
public void onCompleted() {
if(!notFoundActions.isEmpty())
{
StringBuilder all = new StringBuilder("Some actions cannot be edited/used because they are not installed on the server : ");
for(String each : notFoundActions)
{
all.append("\n * ").append(each);
}
serverListener.onAlert("Warning",all.toString(), Alert.AlertType.WARNING);
}
responseObserver.onNext(ServerGRPC.Empty.newBuilder().build());
responseObserver.onCompleted();
}
};
}
@Override
public void actionClicked(ServerGRPC.ClickedActionID request, StreamObserver<ServerGRPC.Empty> responseObserver) {
try
{
action actionClicked = client.getProfileByID(request.getProfileID()).getActionByID(request.getId());
new Thread(new Task<Void>() {
@Override
protected Void call()
{
try
{
synchronized (actionStatuses)
{
actionStatuses.put(request.getId(), serverListener.onActionClicked(actionClicked));
}
}
catch (MinorException e)
{
serverListener.onRPCError(e);
}
return null;
}
}).start();
}
catch (MinorException e)
{
e.printStackTrace();
}
finally {
responseObserver.onNext(ServerGRPC.Empty.newBuilder().build());
responseObserver.onCompleted();
}
}
@Override
public StreamObserver<ServerGRPC.Empty> actionClickedStatus(StreamObserver<ServerGRPC.ActionStatus> responseObserver) {
return new StreamObserver<ServerGRPC.Empty>() {
@Override
public void onNext(ServerGRPC.Empty empty) {
}
@Override
public void onError(Throwable throwable) {
serverListener.onRPCError(new StreamPiException(throwable.getMessage()));
}
@Override
public void onCompleted() {
String id = null;
boolean success = false;
synchronized (actionStatuses)
{
if(!actionStatuses.isEmpty())
{
for(String key : actionStatuses.keySet())
{
id = key;
success = actionStatuses.get(id);
System.out.println("SDSDSDASDASDXZXCZXCZXC");
break;
}
}
}
if(id==null)
{
responseObserver.onNext(ServerGRPC.ActionStatus.newBuilder().build());
}
else
responseObserver.onNext(ServerGRPC.ActionStatus.newBuilder()
.setId(id)
.setIsSuccess(success)
.build());
responseObserver.onCompleted();
}
};
}
@Override
public StreamObserver<ServerGRPC.DisconnectMessage> disconnect(StreamObserver<ServerGRPC.DisconnectMessage> responseObserver) {
return new StreamObserver<ServerGRPC.DisconnectMessage>() {
@Override
public void onNext(ServerGRPC.DisconnectMessage disconnectMessage) {
if(disconnectMessage.getIsDisconnect())
disconnect(disconnectMessage.getMessage());
}
@Override
public void onError(Throwable throwable) {
serverListener.onRPCError(new StreamPiException(throwable.getMessage()));
}
@Override
public void onCompleted() {
responseObserver.onNext(ServerGRPC.DisconnectMessage.newBuilder()
.setIsDisconnect(isDisconnect)
.setMessage(disconnectMessage)
.build());
responseObserver.onCompleted();
}
};
}
}
*/
package com.stream_pi.server.connection;
package com.stream_pi.server.connection;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import java.io.IOException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class MainServer extends Thread{
public class MainServer extends Thread{
private ServerListener serverListener;
private ServerListener serverListener;
private Logger logger = Logger.getLogger(MainServer.class.getName());
private Logger logger = Logger.getLogger(MainServer.class.getName());
private int port;
private int port;
private ServerSocket serverSocket = null;
private ServerSocket serverSocket = null;
//private Server server;
//private Server server;
private AtomicBoolean stop = new AtomicBoolean(false);
private AtomicBoolean stop = new AtomicBoolean(false);
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
public MainServer(ServerListener serverListener, ExceptionAndAlertHandler exceptionAndAlertHandler)
public MainServer(ServerListener serverListener, ExceptionAndAlertHandler exceptionAndAlertHandler)
{
{
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.port = port;
this.port = port;
this.serverListener = serverListener;
this.serverListener = serverListener;
}
}
public void setPort(int port) {
public void setPort(int port) {
this.port = port;
this.port = port;
}
}
@Override
@Override
public synchronized void start() {
public synchronized void start() {
stop.set(false);
stop.set(false);
super.start();
super.start();
}
}
public void stopListeningForConnections()
public void stopListeningForConnections()
{
{
/*if(server !=null)
/*if(server !=null)
{
{
if(!server.isShutdown())
if(!server.isShutdown())
server.shutdown();
server.shutdown();
}*/
}*/
try
try
{
{
logger.info("Stopping listening for connections ...");
logger.info("Stopping listening for connections ...");
if(serverSocket!=null)
if(serverSocket!=null)
if(!serverSocket.isClosed())
if(!serverSocket.isClosed())
serverSocket.close();
serverSocket.close();
} catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
}
}
finally {
finally {
logger.info("... Done!");
logger.info("... Done!");
}
}
stop.set(true);
stop.set(true);
}
}
@Override
@Override
public void run() {
public void run() {
logger.warning("Starting main server on port "+port+" ...");
logger.warning("Starting main server on port "+port+" ...");
try {
try {
logger.info("Starting server on port "+port+" ...");
logger.info("Starting server on port "+port+" ...");
/*Server server = ServerBuilder.forPort(port)
/*Server server = ServerBuilder.forPort(port)
.addService(new ConnectionService(serverListener))
.addService(new ConnectionService(serverListener))
.build();
.build();
server.start();
server.start();
logger.info("... Done!");*/
logger.info("... Done!");*/
serverSocket = new ServerSocket(port);
serverSocket = new ServerSocket(port);
while(!stop.get())
while(!stop.get())
{
{
Socket s = serverSocket.accept();
Socket s = serverSocket.accept();
ClientConnections.getInstance().addConnection(new ClientConnection(s, serverListener, exceptionAndAlertHandler));
ClientConnections.getInstance().addConnection(new ClientConnection(s, serverListener, exceptionAndAlertHandler));
logger.info("New client connected ("+s.getRemoteSocketAddress()+") !");
logger.info("New client connected ("+s.getRemoteSocketAddress()+") !");
}
}
}
}
catch (SocketException e)
catch (SocketException e)
{
{
logger.info("Main Server stopped accepting calls ...");
logger.info("Main Server stopped accepting calls ...");
e.printStackTrace(); //more likely stopped listening;
e.printStackTrace(); //more likely stopped listening;
} catch (IOException e) {
} catch (IOException e) {
exceptionAndAlertHandler.handleSevereException(new SevereException("MainServer io Exception occurred!"));
exceptionAndAlertHandler.handleSevereException(new SevereException("MainServer io Exception occurred!"));
e.printStackTrace();
e.printStackTrace();
}
}
}
}
}
}
package com.stream_pi.server.connection;
package com.stream_pi.server.connection;
import com.stream_pi.actionapi.normalaction.NormalAction;
import com.stream_pi.action_api.normalaction.NormalAction;
public interface ServerListener {
public interface ServerListener {
boolean onNormalActionClicked(NormalAction action);
boolean onNormalActionClicked(NormalAction action);
void clearTemp();
void clearTemp();
void init();
void init();
void othInit();
void othInit();
}
}
package com.stream_pi.server.controller;
package com.stream_pi.server.controller;
import com.stream_pi.actionapi.action.ServerConnection;
import com.stream_pi.action_api.action.ServerConnection;
import com.stream_pi.actionapi.action.PropertySaver;
import com.stream_pi.action_api.action.PropertySaver;
import com.stream_pi.actionapi.normalaction.NormalAction;
import com.stream_pi.action_api.normalaction.NormalAction;
import com.stream_pi.server.Main;
import com.stream_pi.server.Main;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.MainServer;
import com.stream_pi.server.connection.MainServer;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.window.Base;
import com.stream_pi.server.window.Base;
import com.stream_pi.server.window.dashboard.DonatePopupContent;
import com.stream_pi.server.window.dashboard.DonatePopupContent;
import com.stream_pi.server.window.firsttimeuse.FirstTimeUse;
import com.stream_pi.server.window.firsttimeuse.FirstTimeUse;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlertListener;
import com.stream_pi.util.alert.StreamPiAlertListener;
import com.stream_pi.util.alert.StreamPiAlertType;
import com.stream_pi.util.alert.StreamPiAlertType;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.iohelper.IOHelper;
import com.stream_pi.util.iohelper.IOHelper;
import javafx.animation.Interpolator;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.stage.WindowEvent;
import java.awt.SystemTray;
import java.awt.SystemTray;
import javafx.util.Duration;
import javafx.util.Duration;
import java.awt.Toolkit;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.TrayIcon;
import java.awt.PopupMenu;
import java.awt.PopupMenu;
import java.awt.MenuItem;
import java.awt.MenuItem;
import java.io.File;
import java.io.File;
import java.net.InetAddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Level;
public class Controller extends Base implements PropertySaver, ServerConnection
public class Controller extends Base implements PropertySaver, ServerConnection
{
{
MainServer mainServer;
MainServer mainServer;
final SystemTray systemTray;
final SystemTray systemTray;
public void setupDashWindow() throws SevereException
public void setupDashWindow() throws SevereException
{
{
try
try
{
{
getStage().setTitle("Stream-Pi Server - "+InetAddress.getLocalHost().getCanonicalHostName()+":"+ Config.getInstance().getPort()); //Sets title
getStage().setTitle("Stream-Pi Server - "+InetAddress.getLocalHost().getCanonicalHostName()+":"+ Config.getInstance().getPort()); //Sets title
getStage().setOnCloseRequest(this::onCloseRequest);
getStage().setOnCloseRequest(this::onCloseRequest);
}
}
catch (UnknownHostException e)
catch (UnknownHostException e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}
}
private void checkPrePathDirectory() throws SevereException
private void checkPrePathDirectory() throws SevereException
{
{
try {
try {
File filex = new File(ServerInfo.getInstance().getPrePath());
File filex = new File(ServerInfo.getInstance().getPrePath());
if(!filex.exists())
if(!filex.exists())
{
{
filex.mkdirs();
filex.mkdirs();
IOHelper.unzip(Main.class.getResourceAsStream("Default.obj"), ServerInfo.getInstance().getPrePath());
IOHelper.unzip(Main.class.getResourceAsStream("Default.obj"), ServerInfo.getInstance().getPrePath());
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}
}
@Override
@Override
public void init()
public void init()
{
{
try {
try {
checkPrePathDirectory();
checkPrePathDirectory();
initBase();
initBase();
setupDashWindow();
setupDashWindow();
setupSettingsWindowsAnimations();
setupSettingsWindowsAnimations();
NormalActionPlugins.getInstance().setPropertySaver(this);
NormalActionPlugins.getInstance().setPropertySaver(this);
NormalActionPlugins.getInstance().setServerConnection(this);
NormalActionPlugins.getInstance().setServerConnection(this);
getDashboardPane().getPluginsPane().getSettingsButton().setOnAction(event -> {
getDashboardPane().getPluginsPane().getSettingsButton().setOnAction(event -> {
openSettingsTimeLine.play();
openSettingsTimeLine.play();
});
});
getSettingsPane().getCloseButton().setOnAction(event -> {
getSettingsPane().getCloseButton().setOnAction(event -> {
closeSettingsTimeLine.play();
closeSettingsTimeLine.play();
});
});
getSettingsPane().getThemesSettings().setController(this);
getSettingsPane().getThemesSettings().setController(this);
mainServer = new MainServer(this, this);
mainServer = new MainServer(this, this);
if(getConfig().isFirstTimeUse())
if(getConfig().isFirstTimeUse())
{
{
Stage stage = new Stage();
Stage stage = new Stage();
Scene s = new Scene(new FirstTimeUse(this, this), 512, 300);
Scene s = new Scene(new FirstTimeUse(this, this), 512, 300);
stage.setResizable(false);
stage.setResizable(false);
stage.setScene(s);
stage.setScene(s);
stage.setTitle("Stream-Pi Server Setup");
stage.setTitle("Stream-Pi Server Setup");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setOnCloseRequest(event->Platform.exit());
stage.setOnCloseRequest(event->Platform.exit());
stage.show();
stage.show();
}
}
else
else
{
{
if(getConfig().isAllowDonatePopup())
if(getConfig().isAllowDonatePopup())
{
{
if(new Random().nextInt(5) == 3)
if(new Random().nextInt(5) == 3)
new DonatePopupContent(getHostServices(), this).show();
new DonatePopupContent(getHostServices(), this).show();
}
}
othInit();
othInit();
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
}
}
@Override
@Override
public void othInit()
public void othInit()
{
{
try
try
{
{
if(ServerInfo.getInstance().isStartMinimised())
if(ServerInfo.getInstance().isStartMinimised())
minimiseApp();
minimiseApp();
else
else
getStage().show();
getStage().show();
}
}
catch(MinorException e)
catch(MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
getSettingsPane().getGeneralSettings().loadDataFromConfig();
getSettingsPane().getGeneralSettings().loadDataFromConfig();
//themes
//themes
getSettingsPane().getThemesSettings().setThemes(getThemes());
getSettingsPane().getThemesSettings().setThemes(getThemes());
getSettingsPane().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsPane().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsPane().getThemesSettings().loadThemes();
getSettingsPane().getThemesSettings().loadThemes();
//clients
//clients
getSettingsPane().getClientsSettings().loadData();
getSettingsPane().getClientsSettings().loadData();
try
try
{
{
//Plugins
//Plugins
Platform.runLater(()->{
Platform.runLater(()->{
getDashboardPane().getPluginsPane().clearData();
getDashboardPane().getPluginsPane().clearData();
getDashboardPane().getPluginsPane().loadOtherActions();
getDashboardPane().getPluginsPane().loadOtherActions();
});
});
NormalActionPlugins.setPluginsLocation(getConfig().getPluginsPath());
NormalActionPlugins.setPluginsLocation(getConfig().getPluginsPath());
NormalActionPlugins.getInstance().init();
NormalActionPlugins.getInstance().init();
Platform.runLater(()->getDashboardPane().getPluginsPane().loadData());
Platform.runLater(()->getDashboardPane().getPluginsPane().loadData());
getSettingsPane().getPluginsSettings().loadPlugins();
getSettingsPane().getPluginsSettings().loadPlugins();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
getSettingsPane().getPluginsSettings().showPluginInitError();
getSettingsPane().getPluginsSettings().showPluginInitError();
handleMinorException(e);
handleMinorException(e);
}
}
//Server
//Server
mainServer.setPort(getConfig().getPort());
mainServer.setPort(getConfig().getPort());
mainServer.start();
mainServer.start();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
return null;
return null;
}
}
}).start();
}).start();
}
}
private void setupSettingsWindowsAnimations()
private void setupSettingsWindowsAnimations()
{
{
Node settingsNode = getSettingsPane();
Node settingsNode = getSettingsPane();
Node dashboardNode = getDashboardPane();
Node dashboardNode = getDashboardPane();
openSettingsTimeLine = new Timeline();
openSettingsTimeLine = new Timeline();
openSettingsTimeLine.setCycleCount(1);
openSettingsTimeLine.setCycleCount(1);
openSettingsTimeLine.getKeyFrames().addAll(
openSettingsTimeLine.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.EASE_IN),
0.0D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.1D, Interpolator.EASE_IN),
1.1D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.1D, Interpolator.EASE_IN),
1.1D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.1D, Interpolator.EASE_IN)),
1.1D, Interpolator.EASE_IN)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
0.9D, Interpolator.LINEAR))
0.9D, Interpolator.LINEAR))
);
);
openSettingsTimeLine.setOnFinished(event1 -> {
openSettingsTimeLine.setOnFinished(event1 -> {
settingsNode.toFront();
settingsNode.toFront();
});
});
closeSettingsTimeLine = new Timeline();
closeSettingsTimeLine = new Timeline();
closeSettingsTimeLine.setCycleCount(1);
closeSettingsTimeLine.setCycleCount(1);
closeSettingsTimeLine.getKeyFrames().addAll(
closeSettingsTimeLine.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.1D, Interpolator.LINEAR),
1.1D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.1D, Interpolator.LINEAR),
1.1D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.1D, Interpolator.LINEAR)),
1.1D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
0.9D, Interpolator.LINEAR)),
0.9D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
1.0D, Interpolator.LINEAR))
1.0D, Interpolator.LINEAR))
);
);
closeSettingsTimeLine.setOnFinished(event1 -> {
closeSettingsTimeLine.setOnFinished(event1 -> {
dashboardNode.toFront();
dashboardNode.toFront();
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call() {
protected Void call() {
try {
try {
getSettingsPane().getClientsSettings().loadData();
getSettingsPane().getClientsSettings().loadData();
getSettingsPane().getGeneralSettings().loadDataFromConfig();
getSettingsPane().getGeneralSettings().loadDataFromConfig();
getSettingsPane().getPluginsSettings().loadPlugins();
getSettingsPane().getPluginsSettings().loadPlugins();
getSettingsPane().getThemesSettings().setThemes(getThemes());
getSettingsPane().getThemesSettings().setThemes(getThemes());
getSettingsPane().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsPane().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsPane().getThemesSettings().loadThemes();
getSettingsPane().getThemesSettings().loadThemes();
getSettingsPane().setDefaultTabToGeneral();
getSettingsPane().setDefaultTabToGeneral();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
return null;
return null;
}
}
}).start();
}).start();
});
});
}
}
private Timeline openSettingsTimeLine;
private Timeline openSettingsTimeLine;
private Timeline closeSettingsTimeLine;
private Timeline closeSettingsTimeLine;
public Controller(){
public Controller(){
systemTray = SystemTray.getSystemTray();
systemTray = SystemTray.getSystemTray();
mainServer = null;
mainServer = null;
}
}
public void onCloseRequest(WindowEvent event)
public void onCloseRequest(WindowEvent event)
{
{
try
try
{
{
if(Config.getInstance().getCloseOnX())
if(Config.getInstance().getCloseOnX())
{
{
getConfig().setStartupWindowSize(
getConfig().setStartupWindowSize(
getWidth(),
getWidth(),
getHeight()
getHeight()
);
);
getConfig().save();
getConfig().save();
onQuitApp();
onQuitApp();
NormalActionPlugins.getInstance().shutDownActions();
NormalActionPlugins.getInstance().shutDownActions();
Platform.exit();
Platform.exit();
}
}
else
else
{
{
minimiseApp();
minimiseApp();
event.consume();
event.consume();
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
finally
finally
{
{
closeLogger();
closeLogger();
}
}
}
}
public void onQuitApp()
public void onQuitApp()
{
{
if(mainServer!=null)
if(mainServer!=null)
mainServer.stopListeningForConnections();
mainServer.stopListeningForConnections();
ClientConnections.getInstance().disconnectAll();
ClientConnections.getInstance().disconnectAll();
getLogger().info("Shutting down ...");
getLogger().info("Shutting down ...");
}
}
public void minimiseApp() throws MinorException
public void minimiseApp() throws MinorException
{
{
try
try
{
{
if(SystemTray.isSupported())
if(SystemTray.isSupported())
{
{
if(getTrayIcon() == null)
if(getTrayIcon() == null)
initIconTray();
initIconTray();
systemTray.add(getTrayIcon());
systemTray.add(getTrayIcon());
//getStage().setIconified(true);
//getStage().setIconified(true);
getStage().hide();
getStage().hide();
}
}
else
else
{
{
new StreamPiAlert("System Tray Error", "Your System does not support System Tray", StreamPiAlertType.ERROR).show();
new StreamPiAlert("System Tray Error", "Your System does not support System Tray", StreamPiAlertType.ERROR).show();
}
}
}
}
catch(Exception e)
catch(Exception e)
{
{
throw new MinorException(e.getMessage());
throw new MinorException(e.getMessage());
}
}
}
}
public void initIconTray()
public void initIconTray()
{
{
Platform.setImplicitExit(false);
Platform.setImplicitExit(false);
PopupMenu popup = new PopupMenu();
PopupMenu popup = new PopupMenu();
MenuItem showItem = new MenuItem("Show");
MenuItem showItem = new MenuItem("Show");
showItem.addActionListener(l->{
showItem.addActionListener(l->{
systemTray.remove(getTrayIcon());
systemTray.remove(getTrayIcon());
Platform.runLater(()->{
Platform.runLater(()->{
//getStage().setIconified(false);
//getStage().setIconified(false);
getStage().show();
getStage().show();
});
});
});
});
MenuItem exitItem = new MenuItem("Exit");
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(l->{
exitItem.addActionListener(l->{
systemTray.remove(getTrayIcon());
systemTray.remove(getTrayIcon());
onQuitApp();
onQuitApp();
Platform.exit();
Platform.exit();
});
});
popup.add(showItem);
popup.add(showItem);
popup.addSeparator();
popup.addSeparator();
popup.add(exitItem);
popup.add(exitItem);
TrayIcon trayIcon = new TrayIcon(
TrayIcon trayIcon = new TrayIcon(
Toolkit.getDefaultToolkit().getImage(Main.class.getResource("app_icon.png")),
Toolkit.getDefaultToolkit().getImage(Main.class.getResource("app_icon.png")),
"Stream-Pi Server",
"Stream-Pi Server",
popup
popup
);
);
trayIcon.setImageAutoSize(true);
trayIcon.setImageAutoSize(true);
this.trayIcon = trayIcon;
this.trayIcon = trayIcon;
}
}
private TrayIcon trayIcon = null;
private TrayIcon trayIcon = null;
public TrayIcon getTrayIcon()
public TrayIcon getTrayIcon()
{
{
return trayIcon;
return trayIcon;
}
}
@Override
@Override
public void handleMinorException(MinorException e) {
public void handleMinorException(MinorException e) {
getLogger().log(Level.SEVERE, e.getMessage());
getLogger().log(Level.SEVERE, e.getMessage());
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()-> new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
Platform.runLater(()-> new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
}
}
@Override
@Override
public void handleSevereException(SevereException e) {
public void handleSevereException(SevereException e) {
getLogger().log(Level.SEVERE, e.getMessage());
getLogger().log(Level.SEVERE, e.getMessage());
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()->{
Platform.runLater(()->{
StreamPiAlert alert = new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
StreamPiAlert alert = new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
alert.setOnClicked(new StreamPiAlertListener()
alert.setOnClicked(new StreamPiAlertListener()
{
{
@Override
@Override
public void onClick(String txt)
public void onClick(String txt)
{
{
onQuitApp();
onQuitApp();
Platform.exit();
Platform.exit();
}
}
});
});
alert.show();
alert.show();
});
});
}
}
@Override
@Override
public synchronized boolean onNormalActionClicked(NormalAction action) {
public synchronized boolean onNormalActionClicked(NormalAction action) {
try{
try{
getLogger().info("action "+action.getID()+" clicked!");
getLogger().info("action "+action.getID()+" clicked!");
action.onActionClicked();
action.onActionClicked();
return true;
return true;
}
}
catch (Exception e)
catch (Exception e)
{
{
//check if its windows UAC related
//check if its windows UAC related
if(e.getMessage().contains("operation requires elevation"))
if(e.getMessage().contains("operation requires elevation"))
{
{
handleMinorException(new MinorException(
handleMinorException(new MinorException(
"Action Execution Failed!",
"Action Execution Failed!",
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"This action requires higher UAC privileges. Re-launch Stream-Pi Server with 'Administrator Privileges' in order to run this command.")
"This action requires higher UAC privileges. Re-launch Stream-Pi Server with 'Administrator Privileges' in order to run this command.")
);
);
}
}
else
else
{
{
handleMinorException(new MinorException(
handleMinorException(new MinorException(
"Action Execution Failed!",
"Action Execution Failed!",
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Check stacktrace/log to know what exactly happened\n\nMessage : \n"+e.getMessage() )
"Check stacktrace/log to know what exactly happened\n\nMessage : \n"+e.getMessage() )
);
);
}
}
return false;
return false;
}
}
}
}
@Override
@Override
public void clearTemp() {
public void clearTemp() {
Platform.runLater(() -> {
Platform.runLater(() -> {
getDashboardPane().getClientDetailsPane().refresh();
getDashboardPane().getClientDetailsPane().refresh();
getDashboardPane().getActionGridPane().clear();
getDashboardPane().getActionGridPane().clear();
getDashboardPane().getActionDetailsPane().clear();
getDashboardPane().getActionDetailsPane().clear();
getSettingsPane().getClientsSettings().loadData();
getSettingsPane().getClientsSettings().loadData();
});
});
}
}
@Override
@Override
public void saveServerProperties() {
public void saveServerProperties() {
try {
try {
NormalActionPlugins.getInstance().saveServerSettings();
NormalActionPlugins.getInstance().saveServerSettings();
getSettingsPane().getPluginsSettings().loadPlugins();
getSettingsPane().getPluginsSettings().loadPlugins();
} catch (MinorException e) {
} catch (MinorException e) {
e.printStackTrace();
e.printStackTrace();
handleMinorException(e);
handleMinorException(e);
}
}
}
}
@Override
@Override
public com.stream_pi.util.platform.Platform getPlatform() {
public com.stream_pi.util.platform.Platform getPlatform() {
return ServerInfo.getInstance().getPlatformType();
return ServerInfo.getInstance().getPlatformType();
}
}
}
}
package com.stream_pi.server.uipropertybox;
package com.stream_pi.server.uipropertybox;
import com.stream_pi.actionapi.actionproperty.property.ControlType;
import com.stream_pi.action_api.actionproperty.property.ControlType;
import com.stream_pi.actionapi.actionproperty.property.Type;
import com.stream_pi.action_api.actionproperty.property.Type;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Slider;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleButton;
public class UIPropertyBox
public class UIPropertyBox
{
{
private Node controlNode;
private Node controlNode;
private boolean canBeBlank;
private boolean canBeBlank;
private String displayName;
private String displayName;
public String getDisplayName() {
public String getDisplayName() {
return displayName;
return displayName;
}
}
public boolean isCanBeBlank() {
public boolean isCanBeBlank() {
return canBeBlank;
return canBeBlank;
}
}
private int index;
private int index;
private ControlType controlType;
private ControlType controlType;
private Type type;
private Type type;
public UIPropertyBox(int index, String displayName, Node controlNode, ControlType controlType, Type type, boolean canBeBlank)
public UIPropertyBox(int index, String displayName, Node controlNode, ControlType controlType, Type type, boolean canBeBlank)
{
{
this.index = index;
this.index = index;
this.displayName = displayName;
this.displayName = displayName;
this.controlNode = controlNode;
this.controlNode = controlNode;
this.controlType = controlType;
this.controlType = controlType;
this.type = type;
this.type = type;
this.canBeBlank = canBeBlank;
this.canBeBlank = canBeBlank;
}
}
public ControlType getControlType()
public ControlType getControlType()
{
{
return controlType;
return controlType;
}
}
public Node getControlNode()
public Node getControlNode()
{
{
return controlNode;
return controlNode;
}
}
public int getIndex() {
public int getIndex() {
return index;
return index;
}
}
public Type getType()
public Type getType()
{
{
return type;
return type;
}
}
public String getRawValue()
public String getRawValue()
{
{
String rawValue = null;
String rawValue = null;
if (controlType == ControlType.TEXT_FIELD)
if (controlType == ControlType.TEXT_FIELD)
rawValue = ((TextField) controlNode).getText();
rawValue = ((TextField) controlNode).getText();
else if (controlType == ControlType.COMBO_BOX)
else if (controlType == ControlType.COMBO_BOX)
rawValue = ((ComboBox<String>) controlNode).getSelectionModel().getSelectedIndex() + "";
rawValue = ((ComboBox<String>) controlNode).getSelectionModel().getSelectedIndex() + "";
else if (controlType == ControlType.SLIDER_DOUBLE)
else if (controlType == ControlType.SLIDER_DOUBLE)
rawValue = ((Slider) controlNode).getValue() + "";
rawValue = ((Slider) controlNode).getValue() + "";
else if (controlType == ControlType.SLIDER_INTEGER)
else if (controlType == ControlType.SLIDER_INTEGER)
rawValue = Math.round(((Slider) controlNode).getValue()) + "";
rawValue = Math.round(((Slider) controlNode).getValue()) + "";
else if (controlType == ControlType.TOGGLE) {
else if (controlType == ControlType.TOGGLE) {
ToggleButton toggleButton = ((ToggleButton) controlNode);
ToggleButton toggleButton = ((ToggleButton) controlNode);
if (toggleButton.isSelected())
if (toggleButton.isSelected())
rawValue = "true";
rawValue = "true";
else
else
rawValue = "false";
rawValue = "false";
}
}
return rawValue;
return rawValue;
}
}
}
}
package com.stream_pi.server.window;
package com.stream_pi.server.window;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.Main;
import com.stream_pi.server.Main;
import com.stream_pi.server.window.dashboard.DashboardBase;
import com.stream_pi.server.window.dashboard.DashboardBase;
import com.stream_pi.server.window.settings.SettingsBase;
import com.stream_pi.server.window.settings.SettingsBase;
import com.stream_pi.themeapi.Theme;
import com.stream_pi.theme_api.Theme;
import com.stream_pi.themeapi.Themes;
import com.stream_pi.theme_api.Themes;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.loggerhelper.StreamPiLogFileHandler;
import com.stream_pi.util.loggerhelper.StreamPiLogFileHandler;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.scene.image.Image;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.Stage;
import java.util.logging.Logger;
import java.util.logging.Logger;
public abstract class Base extends StackPane implements ExceptionAndAlertHandler, ServerListener {
public abstract class Base extends StackPane implements ExceptionAndAlertHandler, ServerListener {
private Config config;
private Config config;
private ServerInfo serverInfo;
private ServerInfo serverInfo;
private Stage stage;
private Stage stage;
private HostServices hostServices;
private HostServices hostServices;
public Logger getLogger(){
public Logger getLogger(){
return logger;
return logger;
}
}
private SettingsBase settingsBase;
private SettingsBase settingsBase;
private DashboardBase dashboardBase;
private DashboardBase dashboardBase;
private StackPane alertStackPane;
private StackPane alertStackPane;
public void setHostServices(HostServices hostServices)
public void setHostServices(HostServices hostServices)
{
{
this.hostServices = hostServices;
this.hostServices = hostServices;
}
}
public HostServices getHostServices()
public HostServices getHostServices()
{
{
return hostServices;
return hostServices;
}
}
private Logger logger = null;
private Logger logger = null;
private StreamPiLogFileHandler logFileHandler = null;
private StreamPiLogFileHandler logFileHandler = null;
public void initLogger() throws SevereException
public void initLogger() throws SevereException
{
{
try
try
{
{
if(logger != null)
if(logger != null)
return;
return;
logger = Logger.getLogger("");
logger = Logger.getLogger("");
logFileHandler = new StreamPiLogFileHandler(ServerInfo.getInstance().getPrePath()+"../streampi.log");
logFileHandler = new StreamPiLogFileHandler(ServerInfo.getInstance().getPrePath()+"../streampi.log");
logger.addHandler(logFileHandler);
logger.addHandler(logFileHandler);
}
}
catch(Exception e)
catch(Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Cant get logger started!");
throw new SevereException("Cant get logger started!");
}
}
}
}
public void closeLogger()
public void closeLogger()
{
{
if(logFileHandler != null)
if(logFileHandler != null)
logFileHandler.close();
logFileHandler.close();
}
}
public void initBase() throws SevereException {
public void initBase() throws SevereException {
initLogger();
initLogger();
getChildren().clear();
getChildren().clear();
stage = (Stage) getScene().getWindow();
stage = (Stage) getScene().getWindow();
getStage().getIcons().add(new Image(Main.class.getResourceAsStream("app_icon.png")));
getStage().getIcons().add(new Image(Main.class.getResourceAsStream("app_icon.png")));
getStage().setMinWidth(500);
getStage().setMinWidth(500);
getStage().setMinHeight(500);
getStage().setMinHeight(500);
config = Config.getInstance();
config = Config.getInstance();
stage.setWidth(config.getStartupWindowWidth());
stage.setWidth(config.getStartupWindowWidth());
stage.setHeight(config.getStartupWindowHeight());
stage.setHeight(config.getStartupWindowHeight());
stage.centerOnScreen();
stage.centerOnScreen();
serverInfo = ServerInfo.getInstance();
serverInfo = ServerInfo.getInstance();
initThemes();
initThemes();
settingsBase = new SettingsBase(getHostServices(), this, this);
settingsBase = new SettingsBase(getHostServices(), this, this);
settingsBase.prefWidthProperty().bind(widthProperty());
settingsBase.prefWidthProperty().bind(widthProperty());
settingsBase.prefHeightProperty().bind(heightProperty());
settingsBase.prefHeightProperty().bind(heightProperty());
dashboardBase = new DashboardBase(this, getHostServices());
dashboardBase = new DashboardBase(this, getHostServices());
dashboardBase.prefWidthProperty().bind(widthProperty());
dashboardBase.prefWidthProperty().bind(widthProperty());
dashboardBase.prefHeightProperty().bind(heightProperty());
dashboardBase.prefHeightProperty().bind(heightProperty());
alertStackPane = new StackPane();
alertStackPane = new StackPane();
alertStackPane.setVisible(false);
alertStackPane.setVisible(false);
StreamPiAlert.setParent(alertStackPane);
StreamPiAlert.setParent(alertStackPane);
getChildren().addAll(settingsBase, dashboardBase, alertStackPane);
getChildren().addAll(settingsBase, dashboardBase, alertStackPane);
dashboardBase.toFront();
dashboardBase.toFront();
}
}
public void initThemes() throws SevereException {
public void initThemes() throws SevereException {
clearStylesheets();
clearStylesheets();
registerThemes();
registerThemes();
applyDefaultTheme();
applyDefaultTheme();
applyDefaultStylesheet();
applyDefaultStylesheet();
}
}
public Stage getStage()
public Stage getStage()
{
{
return stage;
return stage;
}
}
public void applyDefaultStylesheet()
public void applyDefaultStylesheet()
{
{
logger.info("Applying default stylesheet ...");
logger.info("Applying default stylesheet ...");
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
getStylesheets().add(Main.class.getResource("style.css").toExternalForm());
getStylesheets().add(Main.class.getResource("style.css").toExternalForm());
logger.info("... Done!");
logger.info("... Done!");
}
}
public DashboardBase getDashboardPane()
public DashboardBase getDashboardPane()
{
{
return dashboardBase;
return dashboardBase;
}
}
public SettingsBase getSettingsPane()
public SettingsBase getSettingsPane()
{
{
return settingsBase;
return settingsBase;
}
}
public Config getConfig()
public Config getConfig()
{
{
return config;
return config;
}
}
public ServerInfo getServerInfo()
public ServerInfo getServerInfo()
{
{
return serverInfo;
return serverInfo;
}
}
private Theme currentTheme;
private Theme currentTheme;
public Theme getCurrentTheme()
public Theme getCurrentTheme()
{
{
return currentTheme;
return currentTheme;
}
}
public void applyTheme(Theme t)
public void applyTheme(Theme t)
{
{
logger.info("Applying theme '"+t.getFullName()+"' ...");
logger.info("Applying theme '"+t.getFullName()+"' ...");
if(t.getFonts() != null)
if(t.getFonts() != null)
{
{
for(String fontFile : t.getFonts())
for(String fontFile : t.getFonts())
{
{
Font.loadFont(fontFile.replace("%20",""), 13);
Font.loadFont(fontFile.replace("%20",""), 13);
}
}
}
}
currentTheme = t;
currentTheme = t;
getStylesheets().addAll(t.getStylesheets());
getStylesheets().addAll(t.getStylesheets());
logger.info("... Done!");
logger.info("... Done!");
}
}
public void clearStylesheets()
public void clearStylesheets()
{
{
getStylesheets().clear();
getStylesheets().clear();
}
}
Themes themes;
Themes themes;
public void registerThemes() throws SevereException
public void registerThemes() throws SevereException
{
{
logger.info("Loading themes ...");
logger.info("Loading themes ...");
themes = new Themes(getConfig().getThemesPath(), getConfig().getCurrentThemeFullName(), serverInfo.getMinThemeSupportVersion());
themes = new Themes(getConfig().getThemesPath(), getConfig().getCurrentThemeFullName(), serverInfo.getMinThemeSupportVersion());
if(themes.getErrors().size()>0)
if(themes.getErrors().size()>0)
{
{
StringBuilder themeErrors = new StringBuilder();
StringBuilder themeErrors = new StringBuilder();
for(MinorException eachException : themes.getErrors())
for(MinorException eachException : themes.getErrors())
{
{
themeErrors.append("\n * ").append(eachException.getShortMessage());
themeErrors.append("\n * ").append(eachException.getShortMessage());
}
}
if(themes.getIsBadThemeTheCurrentOne())
if(themes.getIsBadThemeTheCurrentOne())
{
{
themeErrors.append("\n\nReverted to default theme! (").append(getConfig().getDefaultCurrentThemeFullName()).append(")");
themeErrors.append("\n\nReverted to default theme! (").append(getConfig().getDefaultCurrentThemeFullName()).append(")");
getConfig().setCurrentThemeFullName(getConfig().getDefaultCurrentThemeFullName());
getConfig().setCurrentThemeFullName(getConfig().getDefaultCurrentThemeFullName());
getConfig().save();
getConfig().save();
}
}
handleMinorException(new MinorException("Theme Loading issues", themeErrors.toString()));
handleMinorException(new MinorException("Theme Loading issues", themeErrors.toString()));
}
}
logger.info("... Done!");
logger.info("... Done!");
}
}
public Themes getThemes()
public Themes getThemes()
{
{
return themes;
return themes;
}
}
public void applyDefaultTheme()
public void applyDefaultTheme()
{
{
logger.info("Applying default theme ...");
logger.info("Applying default theme ...");
boolean foundTheme = false;
boolean foundTheme = false;
for(Theme t: themes.getThemeList())
for(Theme t: themes.getThemeList())
{
{
if(t.getFullName().equals(config.getCurrentThemeFullName()))
if(t.getFullName().equals(config.getCurrentThemeFullName()))
{
{
foundTheme = true;
foundTheme = true;
applyTheme(t);
applyTheme(t);
break;
break;
}
}
}
}
if(foundTheme)
if(foundTheme)
logger.info("... Done!");
logger.info("... Done!");
else
else
{
{
logger.info("Theme not found. reverting to light theme ...");
logger.info("Theme not found. reverting to light theme ...");
try {
try {
Config.getInstance().setCurrentThemeFullName("com.streampi.DefaultLight");
Config.getInstance().setCurrentThemeFullName("com.streampi.DefaultLight");
Config.getInstance().save();
Config.getInstance().save();
applyDefaultTheme();
applyDefaultTheme();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
}
}
}
}
}
}
package com.stream_pi.server.window.dashboard;
package com.stream_pi.server.window.dashboard;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.actionapi.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.actionapi.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.actionapi.actionproperty.property.Type;
import com.stream_pi.action_api.actionproperty.property.Type;
import com.stream_pi.actionapi.normalaction.NormalAction;
import com.stream_pi.action_api.normalaction.NormalAction;
import com.stream_pi.actionapi.otheractions.CombineAction;
import com.stream_pi.action_api.otheractions.CombineAction;
import com.stream_pi.actionapi.otheractions.FolderAction;
import com.stream_pi.action_api.otheractions.FolderAction;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.CacheHint;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.image.ImageView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.*;
import javafx.scene.layout.*;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashMap;
public class PluginsPane extends VBox {
public class PluginsPane extends VBox {
private Button settingsButton;
private Button settingsButton;
public PluginsPane(HostServices hostServices)
public PluginsPane(HostServices hostServices)
{
{
setMinWidth(250);
setMinWidth(250);
getStyleClass().add("plugins_pane");
getStyleClass().add("plugins_pane");
setPadding(new Insets(10));
setPadding(new Insets(10));
this.hostServices = hostServices;
this.hostServices = hostServices;
initUI();
initUI();
}
}
private Accordion pluginsAccordion;
private Accordion pluginsAccordion;
public void initUI()
public void initUI()
{
{
pluginsAccordion = new Accordion();
pluginsAccordion = new Accordion();
pluginsAccordion.getStyleClass().add("plugins_pane_accordion");
pluginsAccordion.getStyleClass().add("plugins_pane_accordion");
pluginsAccordion.setCache(true);
pluginsAccordion.setCache(true);
settingsButton = new Button();
settingsButton = new Button();
settingsButton.getStyleClass().add("plugins_pane_settings_button");
settingsButton.getStyleClass().add("plugins_pane_settings_button");
FontIcon cog = new FontIcon("fas-cog");
FontIcon cog = new FontIcon("fas-cog");
settingsButton.setGraphic(cog);
settingsButton.setGraphic(cog);
HBox settingsHBox = new HBox(settingsButton);
HBox settingsHBox = new HBox(settingsButton);
settingsHBox.getStyleClass().add("plugins_pane_settings_button_parent");
settingsHBox.getStyleClass().add("plugins_pane_settings_button_parent");
settingsHBox.setAlignment(Pos.CENTER_RIGHT);
settingsHBox.setAlignment(Pos.CENTER_RIGHT);
Label pluginsLabel = new Label("Plugins");
Label pluginsLabel = new Label("Plugins");
pluginsLabel.getStyleClass().add("plugins_pane_top_label");
pluginsLabel.getStyleClass().add("plugins_pane_top_label");
getChildren().addAll(pluginsLabel, pluginsAccordion, new SpaceFiller(SpaceFiller.FillerType.VBox), settingsHBox);
getChildren().addAll(pluginsLabel, pluginsAccordion, SpaceFiller.vertical(), settingsHBox);
}
}
public Button getSettingsButton()
public Button getSettingsButton()
{
{
return settingsButton;
return settingsButton;
}
}
public void clearData()
public void clearData()
{
{
pluginsAccordion.getPanes().clear();
pluginsAccordion.getPanes().clear();
}
}
public void loadData()
public void loadData()
{
{
HashMap<String, ArrayList<NormalAction>> sortedPlugins = NormalActionPlugins.getInstance().getSortedPlugins();
HashMap<String, ArrayList<NormalAction>> sortedPlugins = NormalActionPlugins.getInstance().getSortedPlugins();
for(String eachCategory : sortedPlugins.keySet())
for(String eachCategory : sortedPlugins.keySet())
{
{
VBox vBox = new VBox();
VBox vBox = new VBox();
vBox.getStyleClass().add("plugins_pane_each_plugin_box_parent");
vBox.getStyleClass().add("plugins_pane_each_plugin_box_parent");
TitledPane pane = new TitledPane(eachCategory, vBox);
TitledPane pane = new TitledPane(eachCategory, vBox);
pane.getStyleClass().add("plugins_pane_each_plugin_category_titled_pane");
pane.getStyleClass().add("plugins_pane_each_plugin_category_titled_pane");
for(NormalAction eachAction : sortedPlugins.get(eachCategory))
for(NormalAction eachAction : sortedPlugins.get(eachCategory))
{
{
if(!eachAction.isVisibleInPluginsPane())
if(!eachAction.isVisibleInPluginsPane())
continue;
continue;
Button eachNormalActionPluginButton = new Button();
Button eachNormalActionPluginButton = new Button();
eachNormalActionPluginButton.getStyleClass().add("plugins_pane_each_plugin_button");
eachNormalActionPluginButton.getStyleClass().add("plugins_pane_each_plugin_button");
HBox.setHgrow(eachNormalActionPluginButton, Priority.ALWAYS);
HBox.setHgrow(eachNormalActionPluginButton, Priority.ALWAYS);
eachNormalActionPluginButton.setMaxWidth(Double.MAX_VALUE);
eachNormalActionPluginButton.setMaxWidth(Double.MAX_VALUE);
eachNormalActionPluginButton.setAlignment(Pos.CENTER_LEFT);
eachNormalActionPluginButton.setAlignment(Pos.CENTER_LEFT);
Node graphic = eachAction.getServerButtonGraphic();
Node graphic = eachAction.getServerButtonGraphic();
if(graphic == null)
if(graphic == null)
{
{
FontIcon cogs = new FontIcon("fas-cogs");
FontIcon cogs = new FontIcon("fas-cogs");
cogs.getStyleClass().add("plugins_pane_each_plugin_button_icon");
cogs.getStyleClass().add("plugins_pane_each_plugin_button_icon");
eachNormalActionPluginButton.setGraphic(cogs);
eachNormalActionPluginButton.setGraphic(cogs);
}
}
else
else
{
{
if(graphic instanceof FontIcon)
if(graphic instanceof FontIcon)
{
{
FontIcon fi = (FontIcon) graphic;
FontIcon fi = (FontIcon) graphic;
fi.getStyleClass().add("plugins_pane_each_plugin_button_icon");
fi.getStyleClass().add("plugins_pane_each_plugin_button_icon");
eachNormalActionPluginButton.setGraphic(fi);
eachNormalActionPluginButton.setGraphic(fi);
}
}
else if(graphic instanceof ImageView)
else if(graphic instanceof ImageView)
{
{
ImageView iv = (ImageView) graphic;
ImageView iv = (ImageView) graphic;
iv.getStyleClass().add("plugins_pane_each_plugin_button_imageview");
iv.getStyleClass().add("plugins_pane_each_plugin_button_imageview");
iv.setPreserveRatio(false);
iv.setPreserveRatio(false);
eachNormalActionPluginButton.setGraphic(iv);
eachNormalActionPluginButton.setGraphic(iv);
}
}
}
}
eachNormalActionPluginButton.setText(eachAction.getName());
eachNormalActionPluginButton.setText(eachAction.getName());
eachNormalActionPluginButton.setOnDragDetected(mouseEvent -> {
eachNormalActionPluginButton.setOnDragDetected(mouseEvent -> {
Dragboard db = eachNormalActionPluginButton.startDragAndDrop(TransferMode.ANY);
Dragboard db = eachNormalActionPluginButton.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
ClipboardContent content = new ClipboardContent();
content.put(Action.getDataFormat(), createFakeAction(eachAction, "Untitled action"));
content.put(Action.getDataFormat(), createFakeAction(eachAction, "Untitled action"));
db.setContent(content);
db.setContent(content);
mouseEvent.consume();
mouseEvent.consume();
});
});
HBox hBox = new HBox(eachNormalActionPluginButton);
HBox hBox = new HBox(eachNormalActionPluginButton);
hBox.getStyleClass().add("plugins_pane_each_plugin_box");
hBox.getStyleClass().add("plugins_pane_each_plugin_box");
hBox.setAlignment(Pos.TOP_LEFT);
hBox.setAlignment(Pos.TOP_LEFT);
HBox.setHgrow(eachNormalActionPluginButton, Priority.ALWAYS);
HBox.setHgrow(eachNormalActionPluginButton, Priority.ALWAYS);
if(eachAction.getHelpLink() != null) {
if(eachAction.getHelpLink() != null) {
Button helpButton = new Button();
Button helpButton = new Button();
helpButton.getStyleClass().add("plugins_pane_each_plugin_button_help_icon");
helpButton.getStyleClass().add("plugins_pane_each_plugin_button_help_icon");
FontIcon questionIcon = new FontIcon("fas-question");
FontIcon questionIcon = new FontIcon("fas-question");
questionIcon.getStyleClass().add("plugins_pane_each_plugin_button_help_button_icon");
questionIcon.getStyleClass().add("plugins_pane_each_plugin_button_help_button_icon");
helpButton.setGraphic(questionIcon);
helpButton.setGraphic(questionIcon);
helpButton.setOnAction(event -> hostServices.showDocument(eachAction.getHelpLink()));
helpButton.setOnAction(event -> hostServices.showDocument(eachAction.getHelpLink()));
hBox.getChildren().add(helpButton);
hBox.getChildren().add(helpButton);
}
}
vBox.getChildren().add(hBox);
vBox.getChildren().add(hBox);
}
}
if(vBox.getChildren().size() > 0)
if(vBox.getChildren().size() > 0)
pluginsAccordion.getPanes().add(pane);
pluginsAccordion.getPanes().add(pane);
}
}
}
}
private HostServices hostServices;
private HostServices hostServices;
public Action createFakeAction(Action action, String displayText)
public Action createFakeAction(Action action, String displayText)
{
{
Action newAction = new Action(action.getActionType());
Action newAction = new Action(action.getActionType());
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
{
{
newAction.setModuleName(action.getModuleName());
newAction.setModuleName(action.getModuleName());
newAction.setVersion(action.getVersion());
newAction.setVersion(action.getVersion());
newAction.setName(action.getName());
newAction.setName(action.getName());
}
}
newAction.setClientProperties(action.getClientProperties());
newAction.setClientProperties(action.getClientProperties());
for(Property property : newAction.getClientProperties().get())
for(Property property : newAction.getClientProperties().get())
{
{
if(property.getType() == Type.STRING || property.getType() == Type.INTEGER || property.getType() == Type.DOUBLE)
if(property.getType() == Type.STRING || property.getType() == Type.INTEGER || property.getType() == Type.DOUBLE)
property.setRawValue(property.getDefaultRawValue());
property.setRawValue(property.getDefaultRawValue());
}
}
// newAction.setLocation(location);
// newAction.setLocation(location);
newAction.setIDRandom();
newAction.setIDRandom();
newAction.setShowDisplayText(true);
newAction.setShowDisplayText(true);
newAction.setDisplayText(displayText);
newAction.setDisplayText(displayText);
newAction.setDisplayTextAlignment(DisplayTextAlignment.CENTER);
newAction.setDisplayTextAlignment(DisplayTextAlignment.CENTER);
newAction.setShowIcon(false);
newAction.setShowIcon(false);
newAction.setHasIcon(false);
newAction.setHasIcon(false);
//action.setParent(root);
//action.setParent(root);
newAction.setBgColourHex("");
newAction.setBgColourHex("");
newAction.setDisplayTextFontColourHex("");
newAction.setDisplayTextFontColourHex("");
return newAction;
return newAction;
}
}
public void loadOtherActions()
public void loadOtherActions()
{
{
VBox vBox = new VBox();
VBox vBox = new VBox();
vBox.getStyleClass().add("plugins_pane_each_plugin_box_parent");
vBox.getStyleClass().add("plugins_pane_each_plugin_box_parent");
Button folderActionButton = new Button("Folder");
Button folderActionButton = new Button("Folder");
folderActionButton.getStyleClass().add("plugins_pane_each_plugin_button");
folderActionButton.getStyleClass().add("plugins_pane_each_plugin_button");
folderActionButton.setMaxWidth(Double.MAX_VALUE);
folderActionButton.setMaxWidth(Double.MAX_VALUE);
folderActionButton.setAlignment(Pos.CENTER_LEFT);
folderActionButton.setAlignment(Pos.CENTER_LEFT);
FontIcon folder = new FontIcon("fas-folder");
FontIcon folder = new FontIcon("fas-folder");
folderActionButton.setGraphic(folder);
folderActionButton.setGraphic(folder);
folderActionButton.setOnDragDetected(mouseEvent -> {
folderActionButton.setOnDragDetected(mouseEvent -> {
Dragboard db = folderActionButton.startDragAndDrop(TransferMode.ANY);
Dragboard db = folderActionButton.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
ClipboardContent content = new ClipboardContent();
content.put(Action.getDataFormat(), createFakeAction(new FolderAction(), "Untitled Folder"));
content.put(Action.getDataFormat(), createFakeAction(new FolderAction(), "Untitled Folder"));
db.setContent(content);
db.setContent(content);
mouseEvent.consume();
mouseEvent.consume();
});
});
Button combineActionButton = new Button("Combine");
Button combineActionButton = new Button("Combine");
combineActionButton.getStyleClass().add("plugins_pane_each_plugin_button");
combineActionButton.getStyleClass().add("plugins_pane_each_plugin_button");
combineActionButton.setMaxWidth(Double.MAX_VALUE);
combineActionButton.setMaxWidth(Double.MAX_VALUE);
combineActionButton.setAlignment(Pos.CENTER_LEFT);
combineActionButton.setAlignment(Pos.CENTER_LEFT);
FontIcon list = new FontIcon("fas-list");
FontIcon list = new FontIcon("fas-list");
combineActionButton.setGraphic(list);
combineActionButton.setGraphic(list);
combineActionButton.setOnDragDetected(mouseEvent -> {
combineActionButton.setOnDragDetected(mouseEvent -> {
Dragboard db = combineActionButton.startDragAndDrop(TransferMode.ANY);
Dragboard db = combineActionButton.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
ClipboardContent content = new ClipboardContent();
content.put(Action.getDataFormat(), createFakeAction(new CombineAction(), "Untitled Combine"));
content.put(Action.getDataFormat(), createFakeAction(new CombineAction(), "Untitled Combine"));
db.setContent(content);
db.setContent(content);
mouseEvent.consume();
mouseEvent.consume();
});
});
HBox.setHgrow(folderActionButton, Priority.ALWAYS);
HBox.setHgrow(folderActionButton, Priority.ALWAYS);
HBox h1 = new HBox(folderActionButton);
HBox h1 = new HBox(folderActionButton);
h1.getStyleClass().add("plugins_pane_each_plugin_box");
h1.getStyleClass().add("plugins_pane_each_plugin_box");
HBox.setHgrow(combineActionButton, Priority.ALWAYS);
HBox.setHgrow(combineActionButton, Priority.ALWAYS);
HBox h2 = new HBox(combineActionButton);
HBox h2 = new HBox(combineActionButton);
h2.getStyleClass().add("plugins_pane_each_plugin_box");
h2.getStyleClass().add("plugins_pane_each_plugin_box");
vBox.getChildren().addAll(h1, h2);
vBox.getChildren().addAll(h1, h2);
TitledPane pane = new TitledPane("StreamPi", vBox);
TitledPane pane = new TitledPane("StreamPi", vBox);
pane.getStyleClass().add("plugins_pane_each_plugin_category_titled_pane");
pane.getStyleClass().add("plugins_pane_each_plugin_category_titled_pane");
pluginsAccordion.getPanes().add(pane);
pluginsAccordion.getPanes().add(pane);
pluginsAccordion.setCache(true);
pluginsAccordion.setCache(true);
pluginsAccordion.setCacheHint(CacheHint.SPEED);
pluginsAccordion.setCacheHint(CacheHint.SPEED);
}
}
}
}
M
src/main/java/com/stream_pi/server/window/dashboard/actiondetailpane/ActionDetailsPane.java
+11
−11
package com.stream_pi.server.window.dashboard.actiondetailpane;
package com.stream_pi.server.window.dashboard.actiondetailpane;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.actionapi.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.actionapi.action.Location;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.actionapi.actionproperty.property.ControlType;
import com.stream_pi.action_api.actionproperty.property.ControlType;
import com.stream_pi.actionapi.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.actionapi.actionproperty.property.Type;
import com.stream_pi.action_api.actionproperty.property.Type;
import com.stream_pi.actionapi.otheractions.CombineAction;
import com.stream_pi.action_api.otheractions.CombineAction;
import com.stream_pi.actionapi.otheractions.FolderAction;
import com.stream_pi.action_api.otheractions.FolderAction;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBoxWithFileChooser;
import com.stream_pi.util.uihelper.HBoxInputBoxWithFileChooser;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.collections.FXCollections;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.input.TransferMode;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.paint.Paint;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import javafx.stage.Window;
import javafx.util.Callback;
import javafx.util.Callback;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import java.io.File;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class ActionDetailsPane extends VBox implements ActionDetailsPaneListener {
public class ActionDetailsPane extends VBox implements ActionDetailsPaneListener {
private ScrollPane scrollPane;
private ScrollPane scrollPane;
private VBox vbox;
private VBox vbox;
private VBox clientPropertiesVBox;
private VBox clientPropertiesVBox;
private Button saveButton;
private Button saveButton;
private Button deleteButton;
private Button deleteButton;
private Button openFolderButton;
private Button openFolderButton;
private HBox buttonBar;
private HBox buttonBar;
private Label actionHeadingLabel;
private Label actionHeadingLabel;
private Logger logger;
private Logger logger;
private Button returnButtonForCombineActionChild;
private Button returnButtonForCombineActionChild;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private HostServices hostServices;
private HostServices hostServices;
public ActionDetailsPane(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices) {
public ActionDetailsPane(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices) {
this.hostServices = hostServices;
this.hostServices = hostServices;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
logger = Logger.getLogger(ActionDetailsPane.class.getName());
logger = Logger.getLogger(ActionDetailsPane.class.getName());
setSpacing(10.0);
setSpacing(10.0);
clientPropertiesVBox = new VBox();
clientPropertiesVBox = new VBox();
clientPropertiesVBox.setSpacing(10.0);
clientPropertiesVBox.setSpacing(10.0);
vbox = new VBox();
vbox = new VBox();
vbox.setPadding(new Insets(0, 25, 0, 5));
vbox.setPadding(new Insets(0, 25, 0, 5));
vbox.getStyleClass().add("action_details_pane_vbox");
vbox.getStyleClass().add("action_details_pane_vbox");
vbox.setSpacing(10.0);
vbox.setSpacing(10.0);
getStyleClass().add("action_details_pane");
getStyleClass().add("action_details_pane");
scrollPane = new ScrollPane();
scrollPane = new ScrollPane();
VBox.setMargin(scrollPane, new Insets(0, 0, 0, 10));
VBox.setMargin(scrollPane, new Insets(0, 0, 0, 10));
scrollPane.getStyleClass().add("action_details_pane_scroll_pane");
scrollPane.getStyleClass().add("action_details_pane_scroll_pane");
setMinHeight(310);
setMinHeight(310);
scrollPane.setContent(vbox);
scrollPane.setContent(vbox);
vbox.prefWidthProperty().bind(scrollPane.widthProperty());
vbox.prefWidthProperty().bind(scrollPane.widthProperty());
scrollPane.prefWidthProperty().bind(widthProperty());
scrollPane.prefWidthProperty().bind(widthProperty());
VBox.setVgrow(scrollPane, Priority.ALWAYS);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
openFolderButton = new Button("Open Folder");
openFolderButton = new Button("Open Folder");
FontIcon folderOpenIcon = new FontIcon("far-folder-open");
FontIcon folderOpenIcon = new FontIcon("far-folder-open");
openFolderButton.setGraphic(folderOpenIcon);
openFolderButton.setGraphic(folderOpenIcon);
openFolderButton.setOnAction(event -> onOpenFolderButtonClicked());
openFolderButton.setOnAction(event -> onOpenFolderButtonClicked());
saveButton = new Button("Apply Changes");
saveButton = new Button("Apply Changes");
FontIcon syncIcon = new FontIcon("fas-sync-alt");
FontIcon syncIcon = new FontIcon("fas-sync-alt");
saveButton.setGraphic(syncIcon);
saveButton.setGraphic(syncIcon);
saveButton.setOnAction(event -> onSaveButtonClicked());
saveButton.setOnAction(event -> onSaveButtonClicked());
deleteButton = new Button("Delete action");
deleteButton = new Button("Delete action");
deleteButton.getStyleClass().add("action_details_pane_delete_button");
deleteButton.getStyleClass().add("action_details_pane_delete_button");
FontIcon deleteIcon = new FontIcon("fas-trash");
FontIcon deleteIcon = new FontIcon("fas-trash");
deleteIcon.getStyleClass().add("action_details_pane_delete_button_icon");
deleteIcon.getStyleClass().add("action_details_pane_delete_button_icon");
deleteButton.setGraphic(deleteIcon);
deleteButton.setGraphic(deleteIcon);
deleteButton.setOnAction(event -> onDeleteButtonClicked());
deleteButton.setOnAction(event -> onDeleteButtonClicked());
returnButtonForCombineActionChild = new Button("Return");
returnButtonForCombineActionChild = new Button("Return");
returnButtonForCombineActionChild.setGraphic(new FontIcon("fas-caret-left"));
returnButtonForCombineActionChild.setGraphic(new FontIcon("fas-caret-left"));
returnButtonForCombineActionChild.managedProperty().bind(returnButtonForCombineActionChild.visibleProperty());
returnButtonForCombineActionChild.managedProperty().bind(returnButtonForCombineActionChild.visibleProperty());
returnButtonForCombineActionChild.setOnAction(event -> {
returnButtonForCombineActionChild.setOnAction(event -> {
try {
try {
logger.info("@@## : " + action.getParent());
logger.info("@@## : " + action.getParent());
onActionClicked(getClientProfile().getActionByID(action.getParent()), getActionBox());
onActionClicked(getClientProfile().getActionByID(action.getParent()), getActionBox());
} catch (MinorException e) {
} catch (MinorException e) {
e.printStackTrace();
e.printStackTrace();
}
}
});
});
buttonBar = new HBox(openFolderButton, returnButtonForCombineActionChild, saveButton, deleteButton);
buttonBar = new HBox(openFolderButton, returnButtonForCombineActionChild, saveButton, deleteButton);
buttonBar.getStyleClass().add("action_details_pane_button_bar");
buttonBar.getStyleClass().add("action_details_pane_button_bar");
buttonBar.setPadding(new Insets(10, 10, 10, 0));
buttonBar.setPadding(new Insets(10, 10, 10, 0));
buttonBar.setAlignment(Pos.CENTER_RIGHT);
buttonBar.setAlignment(Pos.CENTER_RIGHT);
buttonBar.setVisible(false);
buttonBar.setVisible(false);
buttonBar.setSpacing(10.0);
buttonBar.setSpacing(10.0);
actionHeadingLabel = new Label();
actionHeadingLabel = new Label();
actionHeadingLabel.getStyleClass().add("action_details_pane_heading_label");
actionHeadingLabel.getStyleClass().add("action_details_pane_heading_label");
HBox headingHBox = new HBox(actionHeadingLabel);
HBox headingHBox = new HBox(actionHeadingLabel);
headingHBox.getStyleClass().add("action_details_pane_heading_box");
headingHBox.getStyleClass().add("action_details_pane_heading_box");
headingHBox.setPadding(new Insets(5, 10, 0, 10));
headingHBox.setPadding(new Insets(5, 10, 0, 10));
getChildren().addAll(headingHBox, scrollPane, buttonBar);
getChildren().addAll(headingHBox, scrollPane, buttonBar);
displayTextAlignmentComboBox = new ComboBox<>(FXCollections.observableArrayList(DisplayTextAlignment.TOP,
displayTextAlignmentComboBox = new ComboBox<>(FXCollections.observableArrayList(DisplayTextAlignment.TOP,
DisplayTextAlignment.CENTER, DisplayTextAlignment.BOTTOM));
DisplayTextAlignment.CENTER, DisplayTextAlignment.BOTTOM));
displayTextAlignmentComboBox.managedProperty().bind(displayTextAlignmentComboBox.visibleProperty());
displayTextAlignmentComboBox.managedProperty().bind(displayTextAlignmentComboBox.visibleProperty());
Callback<ListView<DisplayTextAlignment>, ListCell<DisplayTextAlignment>> displayTextAlignmentComboBoxFactory = new Callback<>() {
Callback<ListView<DisplayTextAlignment>, ListCell<DisplayTextAlignment>> displayTextAlignmentComboBoxFactory = new Callback<>() {
@Override
@Override
public ListCell<DisplayTextAlignment> call(ListView<DisplayTextAlignment> displayTextAlignment) {
public ListCell<DisplayTextAlignment> call(ListView<DisplayTextAlignment> displayTextAlignment) {
return new ListCell<>() {
return new ListCell<>() {
@Override
@Override
protected void updateItem(DisplayTextAlignment displayTextAlignment, boolean b) {
protected void updateItem(DisplayTextAlignment displayTextAlignment, boolean b) {
super.updateItem(displayTextAlignment, b);
super.updateItem(displayTextAlignment, b);
if (displayTextAlignment != null) {
if (displayTextAlignment != null) {
setText(displayTextAlignment.getUIName());
setText(displayTextAlignment.getUIName());
}
}
}
}
};
};
}
}
};
};
displayTextAlignmentComboBox.setCellFactory(displayTextAlignmentComboBoxFactory);
displayTextAlignmentComboBox.setCellFactory(displayTextAlignmentComboBoxFactory);
displayTextAlignmentComboBox.setButtonCell(displayTextAlignmentComboBoxFactory.call(null));
displayTextAlignmentComboBox.setButtonCell(displayTextAlignmentComboBoxFactory.call(null));
actionClientProperties = new ArrayList<>();
actionClientProperties = new ArrayList<>();
displayNameTextField = new TextField();
displayNameTextField = new TextField();
displayNameTextField.managedProperty().bind(displayNameTextField.visibleProperty());
displayNameTextField.managedProperty().bind(displayNameTextField.visibleProperty());
iconFileTextField = new TextField();
iconFileTextField = new TextField();
iconFileTextField.managedProperty().bind(iconFileTextField.visibleProperty());
iconFileTextField.managedProperty().bind(iconFileTextField.visibleProperty());
iconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
iconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
try {
try {
if (!s.equals(t1) && t1.length() > 0) {
if (!s.equals(t1) && t1.length() > 0) {
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
hideIconCheckBox.setDisable(false);
hideIconCheckBox.setDisable(false);
hideIconCheckBox.setSelected(false);
hideIconCheckBox.setSelected(false);
clearIconButton.setDisable(false);
clearIconButton.setDisable(false);
System.out.println("ABABABABABBABABBABABABCCCCCCCCCCCCCCCCCC");
System.out.println("ABABABABABBABABBABABABCCCCCCCCCCCCCCCCCC");
action.setIcon(iconFileByteArray);
action.setIcon(iconFileByteArray);
setSendIcon(true);
setSendIcon(true);
System.out.println(action.getIconAsByteArray().length);
System.out.println(action.getIconAsByteArray().length);
}
}
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
});
});
clearIconButton = new Button("Clear Icon");
clearIconButton = new Button("Clear Icon");
clearIconButton.managedProperty().bind(clearIconButton.visibleProperty());
clearIconButton.managedProperty().bind(clearIconButton.visibleProperty());
clearIconButton.setOnAction(event -> {
clearIconButton.setOnAction(event -> {
hideIconCheckBox.setDisable(true);
hideIconCheckBox.setDisable(true);
hideIconCheckBox.setSelected(false);
hideIconCheckBox.setSelected(false);
clearIconButton.setDisable(true);
clearIconButton.setDisable(true);
iconFileTextField.clear();
iconFileTextField.clear();
});
});
hideDisplayTextCheckBox = new CheckBox("Hide");
hideDisplayTextCheckBox = new CheckBox("Hide");
hideDisplayTextCheckBox.managedProperty().bind(hideDisplayTextCheckBox.visibleProperty());
hideDisplayTextCheckBox.managedProperty().bind(hideDisplayTextCheckBox.visibleProperty());
hideIconCheckBox = new CheckBox("Hide");
hideIconCheckBox = new CheckBox("Hide");
hideIconCheckBox.managedProperty().bind(hideIconCheckBox.visibleProperty());
hideIconCheckBox.managedProperty().bind(hideIconCheckBox.visibleProperty());
actionBackgroundColourPicker = new ColorPicker();
actionBackgroundColourPicker = new ColorPicker();
actionBackgroundColourPicker.managedProperty().bind(actionBackgroundColourPicker.visibleProperty());
actionBackgroundColourPicker.managedProperty().bind(actionBackgroundColourPicker.visibleProperty());
displayTextColourPicker = new ColorPicker();
displayTextColourPicker = new ColorPicker();
displayTextColourPicker.managedProperty().bind(displayTextColourPicker.visibleProperty());
displayTextColourPicker.managedProperty().bind(displayTextColourPicker.visibleProperty());
actionBackgroundColourTransparentCheckBox = new CheckBox("Default");
actionBackgroundColourTransparentCheckBox = new CheckBox("Default");
actionBackgroundColourPicker.disableProperty()
actionBackgroundColourPicker.disableProperty()
.bind(actionBackgroundColourTransparentCheckBox.selectedProperty());
.bind(actionBackgroundColourTransparentCheckBox.selectedProperty());
HBox.setMargin(actionBackgroundColourTransparentCheckBox, new Insets(0, 0, 0, 10));
HBox.setMargin(actionBackgroundColourTransparentCheckBox, new Insets(0, 0, 0, 10));
displayTextColourDefaultCheckBox = new CheckBox("Default");
displayTextColourDefaultCheckBox = new CheckBox("Default");
displayTextColourPicker.disableProperty()
displayTextColourPicker.disableProperty()
.bind(displayTextColourDefaultCheckBox.selectedProperty());
.bind(displayTextColourDefaultCheckBox.selectedProperty());
HBox.setMargin(displayTextColourDefaultCheckBox, new Insets(0, 0, 0, 10));
HBox.setMargin(displayTextColourDefaultCheckBox, new Insets(0, 0, 0, 10));
Region r = new Region();
Region r = new Region();
HBox.setHgrow(r, Priority.ALWAYS);
HBox.setHgrow(r, Priority.ALWAYS);
Region r1 = new Region();
Region r1 = new Region();
HBox.setHgrow(r1, Priority.ALWAYS);
HBox.setHgrow(r1, Priority.ALWAYS);
HBox displayTextColourHBox = new HBox(new Label("Display Text Colour"), r1, displayTextColourPicker,
HBox displayTextColourHBox = new HBox(new Label("Display Text Colour"), r1, displayTextColourPicker,
displayTextColourDefaultCheckBox);
displayTextColourDefaultCheckBox);
displayTextColourHBox.setAlignment(Pos.CENTER);
displayTextColourHBox.setAlignment(Pos.CENTER);
displayTextColourHBox.setSpacing(5.0);
displayTextColourHBox.setSpacing(5.0);
HBox bgColourHBox = new HBox(new Label("Background Colour"), r, actionBackgroundColourPicker,
HBox bgColourHBox = new HBox(new Label("Background Colour"), r, actionBackgroundColourPicker,
actionBackgroundColourTransparentCheckBox);
actionBackgroundColourTransparentCheckBox);
bgColourHBox.setAlignment(Pos.CENTER);
bgColourHBox.setAlignment(Pos.CENTER);
bgColourHBox.setSpacing(5.0);
bgColourHBox.setSpacing(5.0);
HBox clearIconHBox = new HBox(clearIconButton);
HBox clearIconHBox = new HBox(clearIconButton);
clearIconHBox.setAlignment(Pos.CENTER_RIGHT);
clearIconHBox.setAlignment(Pos.CENTER_RIGHT);
displayTextFieldHBox = new HBoxInputBox("Display Name", displayNameTextField, hideDisplayTextCheckBox);
displayTextFieldHBox = new HBoxInputBox("Display Name", displayNameTextField, hideDisplayTextCheckBox);
normalActionsPropsVBox = new VBox(displayTextColourHBox,
normalActionsPropsVBox = new VBox(displayTextColourHBox,
new HBox(new Label("Alignment"), new SpaceFiller(SpaceFiller.FillerType.HBox),
new HBox(new Label("Alignment"), SpaceFiller.horizontal(),
displayTextAlignmentComboBox),
displayTextAlignmentComboBox),
new HBoxInputBoxWithFileChooser("Icon", iconFileTextField, hideIconCheckBox,
new HBoxInputBoxWithFileChooser("Icon", iconFileTextField, hideIconCheckBox,
new FileChooser.ExtensionFilter("Images", "*.jpeg", "*.jpg", "*.png", "*.gif")),
new FileChooser.ExtensionFilter("Images", "*.jpeg", "*.jpg", "*.png", "*.gif")),
clearIconHBox, bgColourHBox);
clearIconHBox, bgColourHBox);
normalActionsPropsVBox.managedProperty().bind(normalActionsPropsVBox.visibleProperty());
normalActionsPropsVBox.managedProperty().bind(normalActionsPropsVBox.visibleProperty());
normalActionsPropsVBox.setSpacing(10.0);
normalActionsPropsVBox.setSpacing(10.0);
vbox.getChildren().addAll(displayTextFieldHBox, normalActionsPropsVBox, clientPropertiesVBox);
vbox.getChildren().addAll(displayTextFieldHBox, normalActionsPropsVBox, clientPropertiesVBox);
vbox.setVisible(false);
vbox.setVisible(false);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
setOnDragOver(dragEvent -> {
setOnDragOver(dragEvent -> {
if (dragEvent.getDragboard().hasContent(Action.getDataFormat()) && action != null) {
if (dragEvent.getDragboard().hasContent(Action.getDataFormat()) && action != null) {
if (action.getActionType() == ActionType.COMBINE) {
if (action.getActionType() == ActionType.COMBINE) {
dragEvent.acceptTransferModes(TransferMode.ANY);
dragEvent.acceptTransferModes(TransferMode.ANY);
dragEvent.consume();
dragEvent.consume();
}
}
}
}
});
});
setOnDragDropped(dragEvent -> {
setOnDragDropped(dragEvent -> {
try {
try {
Action newAction = (Action) dragEvent.getDragboard().getContent(Action.getDataFormat());
Action newAction = (Action) dragEvent.getDragboard().getContent(Action.getDataFormat());
if (newAction.getActionType() == ActionType.NORMAL) {
if (newAction.getActionType() == ActionType.NORMAL) {
newAction.setLocation(new Location(-1, -1));
newAction.setLocation(new Location(-1, -1));
newAction.setParent(this.action.getID());
newAction.setParent(this.action.getID());
combineActionPropertiesPane.getCombineAction().addChild(newAction.getID());
combineActionPropertiesPane.getCombineAction().addChild(newAction.getID());
addActionToCurrentClientProfile(newAction);
addActionToCurrentClientProfile(newAction);
ClientConnection connection = ClientConnections.getInstance()
ClientConnection connection = ClientConnections.getInstance()
.getClientConnectionBySocketAddress(getClient().getRemoteSocketAddress());
.getClientConnectionBySocketAddress(getClient().getRemoteSocketAddress());
connection.saveActionDetails(getClientProfile().getID(), newAction);
connection.saveActionDetails(getClientProfile().getID(), newAction);
combineActionPropertiesPane.renderProps();
combineActionPropertiesPane.renderProps();
saveAction();
saveAction();
}
}
} catch (MinorException e) {
} catch (MinorException e) {
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
e.printStackTrace();
e.printStackTrace();
} catch (SevereException e) {
} catch (SevereException e) {
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
e.printStackTrace();
e.printStackTrace();
} catch (CloneNotSupportedException e) {
} catch (CloneNotSupportedException e) {
e.printStackTrace();
e.printStackTrace();
}
}
});
});
}
}
private VBox normalActionsPropsVBox;
private VBox normalActionsPropsVBox;
private HBox displayTextFieldHBox;
private HBox displayTextFieldHBox;
private Client client;
private Client client;
private ClientProfile clientProfile;
private ClientProfile clientProfile;
public void setClient(Client client) {
public void setClient(Client client) {
this.client = client;
this.client = client;
}
}
public Client getClient() {
public Client getClient() {
return client;
return client;
}
}
public void setClientProfile(ClientProfile clientProfile) {
public void setClientProfile(ClientProfile clientProfile) {
this.clientProfile = clientProfile;
this.clientProfile = clientProfile;
}
}
public ClientProfile getClientProfile() {
public ClientProfile getClientProfile() {
return clientProfile;
return clientProfile;
}
}
public void setActionHeadingLabelText(String text) {
public void setActionHeadingLabelText(String text) {
actionHeadingLabel.setText(text);
actionHeadingLabel.setText(text);
}
}
private Action action;
private Action action;
public Action getAction() {
public Action getAction() {
return action;
return action;
}
}
private ActionBox actionBox;
private ActionBox actionBox;
public ActionBox getActionBox() {
public ActionBox getActionBox() {
return actionBox;
return actionBox;
}
}
@Override
@Override
public void onActionClicked(Action action, ActionBox actionBox) throws MinorException {
public void onActionClicked(Action action, ActionBox actionBox) throws MinorException {
this.action = action;
this.action = action;
this.actionBox = actionBox;
this.actionBox = actionBox;
logger.info("action Display text : "+action.getDisplayText());
logger.info("action Display text : "+action.getDisplayText());
clear();
clear();
renderActionProperties();
renderActionProperties();
}
}
private TextField displayNameTextField;
private TextField displayNameTextField;
private CheckBox hideDisplayTextCheckBox;
private CheckBox hideDisplayTextCheckBox;
private CheckBox hideIconCheckBox;
private CheckBox hideIconCheckBox;
private TextField iconFileTextField;
private TextField iconFileTextField;
private Button clearIconButton;
private Button clearIconButton;
private ColorPicker actionBackgroundColourPicker;
private ColorPicker actionBackgroundColourPicker;
private ColorPicker displayTextColourPicker;
private ColorPicker displayTextColourPicker;
private CheckBox actionBackgroundColourTransparentCheckBox;
private CheckBox actionBackgroundColourTransparentCheckBox;
private CheckBox displayTextColourDefaultCheckBox;
private CheckBox displayTextColourDefaultCheckBox;
private ComboBox<DisplayTextAlignment> displayTextAlignmentComboBox;
private ComboBox<DisplayTextAlignment> displayTextAlignmentComboBox;
public void clear()
public void clear()
{
{
sendIcon = false;
sendIcon = false;
actionClientProperties.clear();
actionClientProperties.clear();
displayNameTextField.clear();
displayNameTextField.clear();
iconFileTextField.clear();
iconFileTextField.clear();
clientPropertiesVBox.getChildren().clear();
clientPropertiesVBox.getChildren().clear();
vbox.setVisible(false);
vbox.setVisible(false);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
buttonBar.setVisible(false);
buttonBar.setVisible(false);
setActionHeadingLabelText("");
setActionHeadingLabelText("");
actionBackgroundColourPicker.setValue(Color.WHITE);
actionBackgroundColourPicker.setValue(Color.WHITE);
displayTextColourPicker.setValue(Color.WHITE);
displayTextColourPicker.setValue(Color.WHITE);
}
}
boolean isCombineChild = false;
boolean isCombineChild = false;
public boolean isCombineChild() {
public boolean isCombineChild() {
return isCombineChild;
return isCombineChild;
}
}
public void renderActionProperties() throws MinorException
public void renderActionProperties() throws MinorException
{
{
//Combine Child action
//Combine Child action
isCombineChild = action.getLocation().getCol() == -1;
isCombineChild = action.getLocation().getCol() == -1;
displayNameTextField.setText(action.getDisplayText());
displayNameTextField.setText(action.getDisplayText());
if(isCombineChild)
if(isCombineChild)
{
{
setReturnButtonForCombineActionChildVisible(true);
setReturnButtonForCombineActionChildVisible(true);
normalActionsPropsVBox.setVisible(false);
normalActionsPropsVBox.setVisible(false);
hideDisplayTextCheckBox.setSelected(false);
hideDisplayTextCheckBox.setSelected(false);
hideDisplayTextCheckBox.setVisible(false);
hideDisplayTextCheckBox.setVisible(false);
}
}
else
else
{
{
normalActionsPropsVBox.setVisible(true);
normalActionsPropsVBox.setVisible(true);
setReturnButtonForCombineActionChildVisible(false);
setReturnButtonForCombineActionChildVisible(false);
hideDisplayTextCheckBox.setVisible(true);
hideDisplayTextCheckBox.setVisible(true);
setFolderButtonVisible(action.getActionType().equals(ActionType.FOLDER));
setFolderButtonVisible(action.getActionType().equals(ActionType.FOLDER));
displayTextAlignmentComboBox.getSelectionModel().select(action.getDisplayTextAlignment());
displayTextAlignmentComboBox.getSelectionModel().select(action.getDisplayTextAlignment());
if(!action.getBgColourHex().isEmpty())
if(!action.getBgColourHex().isEmpty())
actionBackgroundColourPicker.setValue(Color.valueOf(action.getBgColourHex()));
actionBackgroundColourPicker.setValue(Color.valueOf(action.getBgColourHex()));
else
else
actionBackgroundColourTransparentCheckBox.setSelected(true);
actionBackgroundColourTransparentCheckBox.setSelected(true);
if(!action.getDisplayTextFontColourHex().isEmpty())
if(!action.getDisplayTextFontColourHex().isEmpty())
displayTextColourPicker.setValue(Color.valueOf(action.getDisplayTextFontColourHex()));
displayTextColourPicker.setValue(Color.valueOf(action.getDisplayTextFontColourHex()));
else
else
displayTextColourDefaultCheckBox.setSelected(true);
displayTextColourDefaultCheckBox.setSelected(true);
hideDisplayTextCheckBox.setSelected(!action.isShowDisplayText());
hideDisplayTextCheckBox.setSelected(!action.isShowDisplayText());
hideIconCheckBox.setDisable(!action.isHasIcon());
hideIconCheckBox.setDisable(!action.isHasIcon());
hideIconCheckBox.setSelected(!action.isShowIcon());
hideIconCheckBox.setSelected(!action.isShowIcon());
if(!action.isHasIcon())
if(!action.isHasIcon())
{
{
hideIconCheckBox.setSelected(false);
hideIconCheckBox.setSelected(false);
}
}
clearIconButton.setDisable(!action.isHasIcon());
clearIconButton.setDisable(!action.isHasIcon());
}
}
buttonBar.setVisible(true);
buttonBar.setVisible(true);
vbox.setVisible(true);
vbox.setVisible(true);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
{
{
if(action.isInvalid())
if(action.isInvalid())
setActionHeadingLabelText("Invalid action ("+action.getModuleName()+")");
setActionHeadingLabelText("Invalid action ("+action.getModuleName()+")");
else
else
setActionHeadingLabelText(action.getName());
setActionHeadingLabelText(action.getName());
}
}
else if(action.getActionType() == ActionType.COMBINE)
else if(action.getActionType() == ActionType.COMBINE)
setActionHeadingLabelText("Combine action");
setActionHeadingLabelText("Combine action");
else if(action.getActionType() == ActionType.FOLDER)
else if(action.getActionType() == ActionType.FOLDER)
setActionHeadingLabelText("Folder action");
setActionHeadingLabelText("Folder action");
if(!action.isInvalid())
if(!action.isInvalid())
{
{
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
renderClientProperties();
renderClientProperties();
else if(action.getActionType() == ActionType.COMBINE)
else if(action.getActionType() == ActionType.COMBINE)
renderCombineActionProperties();
renderCombineActionProperties();
}
}
}
}
private CombineActionPropertiesPane combineActionPropertiesPane;
private CombineActionPropertiesPane combineActionPropertiesPane;
public CombineActionPropertiesPane getCombineActionPropertiesPane() {
public CombineActionPropertiesPane getCombineActionPropertiesPane() {
return combineActionPropertiesPane;
return combineActionPropertiesPane;
}
}
public void setReturnButtonForCombineActionChildVisible(boolean visible)
public void setReturnButtonForCombineActionChildVisible(boolean visible)
{
{
returnButtonForCombineActionChild.setVisible(visible);
returnButtonForCombineActionChild.setVisible(visible);
}
}
public void renderCombineActionProperties()
public void renderCombineActionProperties()
{
{
try
try
{
{
combineActionPropertiesPane = new CombineActionPropertiesPane(getActionAsCombineAction(action),
combineActionPropertiesPane = new CombineActionPropertiesPane(getActionAsCombineAction(action),
getClientProfile(),
getClientProfile(),
this
this
);
);
clientPropertiesVBox.getChildren().add(combineActionPropertiesPane);
clientPropertiesVBox.getChildren().add(combineActionPropertiesPane);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
public void setAction(Action action) {
public void setAction(Action action) {
this.action = action;
this.action = action;
}
}
public FolderAction getActionAsFolderAction(Action action)
public FolderAction getActionAsFolderAction(Action action)
{
{
FolderAction folderAction = new FolderAction();
FolderAction folderAction = new FolderAction();
folderAction.setDisplayText(action.getDisplayText());
folderAction.setDisplayText(action.getDisplayText());
folderAction.setName(action.getName());
folderAction.setName(action.getName());
folderAction.setID(action.getID());
folderAction.setID(action.getID());
folderAction.setLocation(action.getLocation());
folderAction.setLocation(action.getLocation());
folderAction.setBgColourHex(action.getBgColourHex());
folderAction.setBgColourHex(action.getBgColourHex());
folderAction.setParent(action.getParent());
folderAction.setParent(action.getParent());
folderAction.getClientProperties().set(action.getClientProperties());
folderAction.getClientProperties().set(action.getClientProperties());
folderAction.setDisplayTextAlignment(action.getDisplayTextAlignment());
folderAction.setDisplayTextAlignment(action.getDisplayTextAlignment());
folderAction.setShowIcon(action.isShowIcon());
folderAction.setShowIcon(action.isShowIcon());
folderAction.setHasIcon(action.isHasIcon());
folderAction.setHasIcon(action.isHasIcon());
if(folderAction.isHasIcon())
if(folderAction.isHasIcon())
folderAction.setIcon(action.getIconAsByteArray());
folderAction.setIcon(action.getIconAsByteArray());
folderAction.setDisplayTextFontColourHex(action.getDisplayTextFontColourHex());
folderAction.setDisplayTextFontColourHex(action.getDisplayTextFontColourHex());
return folderAction;
return folderAction;
}
}
public CombineAction getActionAsCombineAction(Action action)
public CombineAction getActionAsCombineAction(Action action)
{
{
CombineAction combineAction = new CombineAction();
CombineAction combineAction = new CombineAction();
combineAction.setDisplayText(action.getDisplayText());
combineAction.setDisplayText(action.getDisplayText());
combineAction.setName(action.getName());
combineAction.setName(action.getName());
combineAction.setID(action.getID());
combineAction.setID(action.getID());
combineAction.setLocation(action.getLocation());
combineAction.setLocation(action.getLocation());
combineAction.setBgColourHex(action.getBgColourHex());
combineAction.setBgColourHex(action.getBgColourHex());
combineAction.setParent(action.getParent());
combineAction.setParent(action.getParent());
combineAction.getClientProperties().set(action.getClientProperties());
combineAction.getClientProperties().set(action.getClientProperties());
combineAction.setDisplayTextAlignment(action.getDisplayTextAlignment());
combineAction.setDisplayTextAlignment(action.getDisplayTextAlignment());
combineAction.setShowIcon(action.isShowIcon());
combineAction.setShowIcon(action.isShowIcon());
combineAction.setHasIcon(action.isHasIcon());
combineAction.setHasIcon(action.isHasIcon());
if(combineAction.isHasIcon())
if(combineAction.isHasIcon())
combineAction.setIcon(action.getIconAsByteArray());
combineAction.setIcon(action.getIconAsByteArray());
combineAction.setDisplayTextFontColourHex(action.getDisplayTextFontColourHex());
combineAction.setDisplayTextFontColourHex(action.getDisplayTextFontColourHex());
for(Property prop : combineAction.getClientProperties().get())
for(Property prop : combineAction.getClientProperties().get())
{
{
System.out.println("PROP : "+prop.getName()+","+prop.getRawValue());
System.out.println("PROP : "+prop.getName()+","+prop.getRawValue());
}
}
return combineAction;
return combineAction;
}
}
public void onOpenFolderButtonClicked()
public void onOpenFolderButtonClicked()
{
{
FolderAction folderAction = getActionAsFolderAction(action);
FolderAction folderAction = getActionAsFolderAction(action);
actionBox.getActionGridPaneListener().renderFolder(folderAction);
actionBox.getActionGridPaneListener().renderFolder(folderAction);
clear();
clear();
}
}
@Override
@Override
public Window getCurrentWindow() {
public Window getCurrentWindow() {
return getScene().getWindow();
return getScene().getWindow();
}
}
private ArrayList<UIPropertyBox> actionClientProperties;
private ArrayList<UIPropertyBox> actionClientProperties;
public void renderClientProperties() throws MinorException
public void renderClientProperties() throws MinorException
{
{
for(int i =0;i< action.getClientProperties().getSize(); i++)
for(int i =0;i< action.getClientProperties().getSize(); i++)
{
{
Property eachProperty = action.getClientProperties().get().get(i);
Property eachProperty = action.getClientProperties().get().get(i);
if(!eachProperty.isVisible())
if(!eachProperty.isVisible())
continue;
continue;
Label label = new Label(eachProperty.getDisplayName());
Label label = new Label(eachProperty.getDisplayName());
HBox hBox = new HBox(label);
HBox hBox = new HBox(label);
hBox.setSpacing(5.0);
hBox.setSpacing(5.0);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.setAlignment(Pos.CENTER_LEFT);
Node controlNode = null;
Node controlNode = null;
if(eachProperty.getHelpLink() != null)
if(eachProperty.getHelpLink() != null)
{
{
Button helpButton = new Button();
Button helpButton = new Button();
FontIcon questionIcon = new FontIcon("fas-question");
FontIcon questionIcon = new FontIcon("fas-question");
helpButton.setGraphic(questionIcon);
helpButton.setGraphic(questionIcon);
helpButton.setOnAction(event -> {
helpButton.setOnAction(event -> {
hostServices.showDocument(eachProperty.getHelpLink());
hostServices.showDocument(eachProperty.getHelpLink());
});
});
hBox.getChildren().add(helpButton);
hBox.getChildren().add(helpButton);
}
}
hBox.getChildren().add(new SpaceFiller(SpaceFiller.FillerType.HBox));
hBox.getChildren().add(SpaceFiller.horizontal());
if(eachProperty.getControlType() == ControlType.COMBO_BOX)
if(eachProperty.getControlType() == ControlType.COMBO_BOX)
{
{
ComboBox<String> comboBox = new ComboBox<>();
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll(eachProperty.getListValue());
comboBox.getItems().addAll(eachProperty.getListValue());
comboBox.getSelectionModel().select(eachProperty.getSelectedIndex());
comboBox.getSelectionModel().select(eachProperty.getSelectedIndex());
controlNode = comboBox;
controlNode = comboBox;
}
}
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD)
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD)
{
{
TextField textField = new TextField(eachProperty.getRawValue());
TextField textField = new TextField(eachProperty.getRawValue());
controlNode= textField;
controlNode= textField;
}
}
else if(eachProperty.getControlType() == ControlType.TOGGLE)
else if(eachProperty.getControlType() == ControlType.TOGGLE)
{
{
ToggleButton toggleButton = new ToggleButton();
ToggleButton toggleButton = new ToggleButton();
toggleButton.setSelected(eachProperty.getBoolValue());
toggleButton.setSelected(eachProperty.getBoolValue());
if(eachProperty.getBoolValue())
if(eachProperty.getBoolValue())
toggleButton.setText("ON");
toggleButton.setText("ON");
else
else
toggleButton.setText("OFF");
toggleButton.setText("OFF");
toggleButton.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
toggleButton.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
if(t1)
if(t1)
toggleButton.setText("ON");
toggleButton.setText("ON");
else
else
toggleButton.setText("OFF");
toggleButton.setText("OFF");
});
});
controlNode = toggleButton;
controlNode = toggleButton;
}
}
else if(eachProperty.getControlType() == ControlType.SLIDER_DOUBLE)
else if(eachProperty.getControlType() == ControlType.SLIDER_DOUBLE)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(eachProperty.getDoubleValue());
slider.setValue(eachProperty.getDoubleValue());
slider.setMax(eachProperty.getMaxDoubleValue());
slider.setMax(eachProperty.getMaxDoubleValue());
slider.setMin(eachProperty.getMinDoubleValue());
slider.setMin(eachProperty.getMinDoubleValue());
controlNode = slider;
controlNode = slider;
}
}
else if(eachProperty.getControlType() == ControlType.SLIDER_INTEGER)
else if(eachProperty.getControlType() == ControlType.SLIDER_INTEGER)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(eachProperty.getIntValue());
slider.setValue(eachProperty.getIntValue());
slider.setMax(eachProperty.getMaxIntValue());
slider.setMax(eachProperty.getMaxIntValue());
slider.setMin(eachProperty.getMinIntValue());
slider.setMin(eachProperty.getMinIntValue());
slider.setBlockIncrement(1.0);
slider.setBlockIncrement(1.0);
slider.setSnapToTicks(true);
slider.setSnapToTicks(true);
controlNode = slider;
controlNode = slider;
}
}
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
UIPropertyBox clientProperty = new UIPropertyBox(i, eachProperty.getDisplayName(), controlNode,
UIPropertyBox clientProperty = new UIPropertyBox(i, eachProperty.getDisplayName(), controlNode,
eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
actionClientProperties.add(clientProperty);
actionClientProperties.add(clientProperty);
clientPropertiesVBox.getChildren().add(hBox);
clientPropertiesVBox.getChildren().add(hBox);
}
}
}
}
public void onSaveButtonClicked()
public void onSaveButtonClicked()
{
{
try {
try {
// saveButton.setDisable(true);
// saveButton.setDisable(true);
// deleteButton.setDisable(true);
// deleteButton.setDisable(true);
validateForm();
validateForm();
saveAction();
saveAction();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
private boolean sendIcon = false;
private boolean sendIcon = false;
@Override
@Override
public void setSendIcon(boolean sendIcon)
public void setSendIcon(boolean sendIcon)
{
{
this.sendIcon = sendIcon;
this.sendIcon = sendIcon;
}
}
public void addActionToCurrentClientProfile(Action newAction) throws CloneNotSupportedException {
public void addActionToCurrentClientProfile(Action newAction) throws CloneNotSupportedException {
getClientProfile().addAction(newAction);
getClientProfile().addAction(newAction);
}
}
@Override
@Override
public void saveAction(Action action, boolean runAsync)
public void saveAction(Action action, boolean runAsync)
{
{
new OnSaveActionTask(
new OnSaveActionTask(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
getClient().getRemoteSocketAddress()
getClient().getRemoteSocketAddress()
),
),
action,
action,
displayNameTextField.getText(),
displayNameTextField.getText(),
isCombineChild(),
isCombineChild(),
!hideDisplayTextCheckBox.isSelected(),
!hideDisplayTextCheckBox.isSelected(),
displayTextColourDefaultCheckBox.isSelected(),
displayTextColourDefaultCheckBox.isSelected(),
"#" + displayTextColourPicker.getValue().toString().substring(2),
"#" + displayTextColourPicker.getValue().toString().substring(2),
clearIconButton.isDisable(),
clearIconButton.isDisable(),
!hideIconCheckBox.isSelected(),
!hideIconCheckBox.isSelected(),
displayTextAlignmentComboBox.getSelectionModel().getSelectedItem(),
displayTextAlignmentComboBox.getSelectionModel().getSelectedItem(),
actionBackgroundColourTransparentCheckBox.isSelected(),
actionBackgroundColourTransparentCheckBox.isSelected(),
"#" + actionBackgroundColourPicker.getValue().toString().substring(2),
"#" + actionBackgroundColourPicker.getValue().toString().substring(2),
getCombineActionPropertiesPane(),
getCombineActionPropertiesPane(),
clientProfile, sendIcon, actionBox, actionClientProperties, exceptionAndAlertHandler,
clientProfile, sendIcon, actionBox, actionClientProperties, exceptionAndAlertHandler,
saveButton, deleteButton, runAsync
saveButton, deleteButton, runAsync
);
);
}
}
@Override
@Override
public void saveAction()
public void saveAction()
{
{
saveAction(action, true);
saveAction(action, true);
}
}
public void setFolderButtonVisible(boolean visible)
public void setFolderButtonVisible(boolean visible)
{
{
openFolderButton.setVisible(visible);
openFolderButton.setVisible(visible);
}
}
public void validateForm() throws MinorException
public void validateForm() throws MinorException
{
{
String displayNameStr = displayNameTextField.getText();
String displayNameStr = displayNameTextField.getText();
StringBuilder finalErrors = new StringBuilder();
StringBuilder finalErrors = new StringBuilder();
if(displayNameStr.isBlank())
if(displayNameStr.isBlank())
{
{
finalErrors.append(" * Display Name cannot be blank\n");
finalErrors.append(" * Display Name cannot be blank\n");
}
}
if(!isCombineChild())
if(!isCombineChild())
{
{
if(action.isHasIcon())
if(action.isHasIcon())
{
{
if(hideDisplayTextCheckBox.isSelected() && hideIconCheckBox.isSelected())
if(hideDisplayTextCheckBox.isSelected() && hideIconCheckBox.isSelected())
finalErrors.append(" * Both Icon and display text check box cannot be hidden.\n");
finalErrors.append(" * Both Icon and display text check box cannot be hidden.\n");
}
}
else
else
{
{
if(hideDisplayTextCheckBox.isSelected())
if(hideDisplayTextCheckBox.isSelected())
finalErrors.append(" * Display Text cannot be hidden, since there is also no icon.\n");
finalErrors.append(" * Display Text cannot be hidden, since there is also no icon.\n");
}
}
}
}
for (UIPropertyBox clientProperty : actionClientProperties) {
for (UIPropertyBox clientProperty : actionClientProperties) {
Node controlNode = clientProperty.getControlNode();
Node controlNode = clientProperty.getControlNode();
if (clientProperty.getControlType() == ControlType.TEXT_FIELD)
if (clientProperty.getControlType() == ControlType.TEXT_FIELD)
{
{
String value = ((TextField) controlNode).getText();
String value = ((TextField) controlNode).getText();
if(clientProperty.getType() == Type.INTEGER)
if(clientProperty.getType() == Type.INTEGER)
{
{
try
try
{
{
Integer.parseInt(value);
Integer.parseInt(value);
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" must be integer.\n");
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" must be integer.\n");
}
}
}
}
else
else
{
{
if(value.isBlank() && !clientProperty.isCanBeBlank())
if(value.isBlank() && !clientProperty.isCanBeBlank())
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" cannot be blank.\n");
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" cannot be blank.\n");
}
}
}
}
}
}
if(!finalErrors.toString().isEmpty())
if(!finalErrors.toString().isEmpty())
{
{
throw new MinorException("You made mistakes",
throw new MinorException("You made mistakes",
finalErrors.toString());
finalErrors.toString());
}
}
}
}
public void onDeleteButtonClicked()
public void onDeleteButtonClicked()
{
{
new OnDeleteActionTask(
new OnDeleteActionTask(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
getClient().getRemoteSocketAddress()
getClient().getRemoteSocketAddress()
),
),
action,
action,
isCombineChild(),
isCombineChild(),
getCombineActionPropertiesPane(),
getCombineActionPropertiesPane(),
clientProfile, actionBox, this, exceptionAndAlertHandler,
clientProfile, actionBox, this, exceptionAndAlertHandler,
!isCombineChild
!isCombineChild
);
);
}
}
}
}
M
src/main/java/com/stream_pi/server/window/dashboard/actiondetailpane/ActionDetailsPaneListener.java
+1
−1
package com.stream_pi.server.window.dashboard.actiondetailpane;
package com.stream_pi.server.window.dashboard.actiondetailpane;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import javafx.stage.Window;
import javafx.stage.Window;
public interface ActionDetailsPaneListener {
public interface ActionDetailsPaneListener {
void onActionClicked(Action action, ActionBox actionBox) throws MinorException;
void onActionClicked(Action action, ActionBox actionBox) throws MinorException;
void saveAction();
void saveAction();
void saveAction(Action action, boolean runAsync);
void saveAction(Action action, boolean runAsync);
void clear();
void clear();
void setSendIcon(boolean sendIcon);
void setSendIcon(boolean sendIcon);
void onOpenFolderButtonClicked();
void onOpenFolderButtonClicked();
Window getCurrentWindow();
Window getCurrentWindow();
}
}
package com.stream_pi.server.window.dashboard.actiondetailpane;
package com.stream_pi.server.window.dashboard.actiondetailpane;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.actionapi.otheractions.CombineAction;
import com.stream_pi.action_api.otheractions.CombineAction;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import javafx.event.ActionEvent;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
public class CombineActionPropertiesPane extends VBox {
public class CombineActionPropertiesPane extends VBox {
private CombineAction combineAction;
private CombineAction combineAction;
private ClientProfile clientProfile;
private ClientProfile clientProfile;
private ActionDetailsPane actionDetailsPane;
private ActionDetailsPane actionDetailsPane;
public CombineAction getCombineAction() {
public CombineAction getCombineAction() {
return combineAction;
return combineAction;
}
}
public CombineActionPropertiesPane(CombineAction combineAction, ClientProfile clientProfile, ActionDetailsPane actionDetailsPane) throws MinorException {
public CombineActionPropertiesPane(CombineAction combineAction, ClientProfile clientProfile, ActionDetailsPane actionDetailsPane) throws MinorException {
this.combineAction = combineAction;
this.combineAction = combineAction;
this.clientProfile = clientProfile;
this.clientProfile = clientProfile;
this.actionDetailsPane = actionDetailsPane;
this.actionDetailsPane = actionDetailsPane;
setSpacing(10.0);
setSpacing(10.0);
setPadding(new Insets(0,0,10,0));
setPadding(new Insets(0,0,10,0));
renderProps();
renderProps();
}
}
public void renderProps() throws MinorException {
public void renderProps() throws MinorException {
getChildren().clear();
getChildren().clear();
int i = 0;
int i = 0;
for(String actionID : combineAction.getChildrenIDSequential())
for(String actionID : combineAction.getChildrenIDSequential())
{
{
Action action = clientProfile.getActionByID(actionID);
Action action = clientProfile.getActionByID(actionID);
System.out.println("232323xxxxxxxxxxxx : "+action.getID());
System.out.println("232323xxxxxxxxxxxx : "+action.getID());
Button settingsButton = new Button();
Button settingsButton = new Button();
FontIcon settingsFontIcon = new FontIcon("fas-cog");
FontIcon settingsFontIcon = new FontIcon("fas-cog");
settingsButton.setGraphic(settingsFontIcon);
settingsButton.setGraphic(settingsFontIcon);
settingsButton.setOnAction(event -> onSettingsButtonClicked(action));
settingsButton.setOnAction(event -> onSettingsButtonClicked(action));
Button upButton = new Button();
Button upButton = new Button();
FontIcon upButtonFontIcon = new FontIcon("fas-chevron-up");
FontIcon upButtonFontIcon = new FontIcon("fas-chevron-up");
upButton.setGraphic(upButtonFontIcon);
upButton.setGraphic(upButtonFontIcon);
Button downButton = new Button();
Button downButton = new Button();
FontIcon downButtonFontIcon = new FontIcon("fas-chevron-down");
FontIcon downButtonFontIcon = new FontIcon("fas-chevron-down");
downButton.setGraphic(downButtonFontIcon);
downButton.setGraphic(downButtonFontIcon);
Label displayTextLabel = new Label(action.getDisplayText());
Label displayTextLabel = new Label(action.getDisplayText());
displayTextLabel.setId(action.getID());
displayTextLabel.setId(action.getID());
Region r = new Region();
Region r = new Region();
HBox.setHgrow(r, Priority.ALWAYS);
HBox.setHgrow(r, Priority.ALWAYS);
HBox actionHBox = new HBox(displayTextLabel, r, settingsButton, upButton, downButton);
HBox actionHBox = new HBox(displayTextLabel, r, settingsButton, upButton, downButton);
actionHBox.setSpacing(5.0);
actionHBox.setSpacing(5.0);
upButton.setUserData(i);
upButton.setUserData(i);
downButton.setUserData(i);
downButton.setUserData(i);
upButton.setOnAction(this::onUpButtonClicked);
upButton.setOnAction(this::onUpButtonClicked);
downButton.setOnAction(this::onDownButtonClicked);
downButton.setOnAction(this::onDownButtonClicked);
getChildren().add(actionHBox);
getChildren().add(actionHBox);
i++;
i++;
}
}
}
}
public void onSettingsButtonClicked(Action action)
public void onSettingsButtonClicked(Action action)
{
{
actionDetailsPane.clear();
actionDetailsPane.clear();
actionDetailsPane.setAction(action);
actionDetailsPane.setAction(action);
try {
try {
actionDetailsPane.renderActionProperties();
actionDetailsPane.renderActionProperties();
} catch (MinorException e) {
} catch (MinorException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
public void onUpButtonClicked(ActionEvent event) {
public void onUpButtonClicked(ActionEvent event) {
try {
try {
Node node = (Node) event.getSource();
Node node = (Node) event.getSource();
int currentIndex = (int) node.getUserData();
int currentIndex = (int) node.getUserData();
if(currentIndex > 0)
if(currentIndex > 0)
{
{
Property current = combineAction.getClientProperties().getSingleProperty(currentIndex+"");
Property current = combineAction.getClientProperties().getSingleProperty(currentIndex+"");
Property aboveOne = combineAction.getClientProperties().getSingleProperty((currentIndex-1)+"");
Property aboveOne = combineAction.getClientProperties().getSingleProperty((currentIndex-1)+"");
combineAction.addChild(current.getRawValue(), currentIndex-1);
combineAction.addChild(current.getRawValue(), currentIndex-1);
combineAction.addChild(aboveOne.getRawValue(), currentIndex);
combineAction.addChild(aboveOne.getRawValue(), currentIndex);
actionDetailsPane.saveAction();
actionDetailsPane.saveAction();
renderProps();
renderProps();
}
}
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
public void onDownButtonClicked(ActionEvent event)
public void onDownButtonClicked(ActionEvent event)
{
{
try {
try {
Node node = (Node) event.getSource();
Node node = (Node) event.getSource();
int currentIndex = (int) node.getUserData();
int currentIndex = (int) node.getUserData();
if(currentIndex < getChildren().size() - 1)
if(currentIndex < getChildren().size() - 1)
{
{
Property current = combineAction.getClientProperties().getSingleProperty(currentIndex+"");
Property current = combineAction.getClientProperties().getSingleProperty(currentIndex+"");
Property belowOne = combineAction.getClientProperties().getSingleProperty((currentIndex+1)+"");
Property belowOne = combineAction.getClientProperties().getSingleProperty((currentIndex+1)+"");
combineAction.addChild(current.getRawValue(), currentIndex+1);
combineAction.addChild(current.getRawValue(), currentIndex+1);
combineAction.addChild(belowOne.getRawValue(), currentIndex);
combineAction.addChild(belowOne.getRawValue(), currentIndex);
actionDetailsPane.saveAction();
actionDetailsPane.saveAction();
renderProps();
renderProps();
}
}
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
public List<String> getFinalChildren()
public List<String> getFinalChildren()
{
{
ArrayList<String> children = new ArrayList<>();
ArrayList<String> children = new ArrayList<>();
for(int i = 0;i<getChildren().size();i++)
for(int i = 0;i<getChildren().size();i++)
{
{
HBox hBox = (HBox) getChildren().get(i);
HBox hBox = (HBox) getChildren().get(i);
Label label = (Label) hBox.getChildren().get(0);
Label label = (Label) hBox.getChildren().get(0);
children.add(label.getId());
children.add(label.getId());
}
}
return children;
return children;
}
}
}
}
M
src/main/java/com/stream_pi/server/window/dashboard/actiondetailpane/OnDeleteActionTask.java
+1
−1
package com.stream_pi.server.window.dashboard.actiondetailpane;
package com.stream_pi.server.window.dashboard.actiondetailpane;
import java.util.logging.Logger;
import java.util.logging.Logger;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
public class OnDeleteActionTask extends Task<Void>
public class OnDeleteActionTask extends Task<Void>
{
{
private Logger logger;
private Logger logger;
public OnDeleteActionTask(ClientConnection connection, Action action, boolean isCombineChild,
public OnDeleteActionTask(ClientConnection connection, Action action, boolean isCombineChild,
CombineActionPropertiesPane combineActionPropertiesPane, ClientProfile clientProfile, ActionBox actionBox,
CombineActionPropertiesPane combineActionPropertiesPane, ClientProfile clientProfile, ActionBox actionBox,
ActionDetailsPane actionDetailsPane,
ActionDetailsPane actionDetailsPane,
ExceptionAndAlertHandler exceptionAndAlertHandler, boolean runAsync)
ExceptionAndAlertHandler exceptionAndAlertHandler, boolean runAsync)
{
{
this.connection = connection;
this.connection = connection;
this.action = action;
this.action = action;
this.isCombineChild = isCombineChild;
this.isCombineChild = isCombineChild;
this.combineActionPropertiesPane = combineActionPropertiesPane;
this.combineActionPropertiesPane = combineActionPropertiesPane;
this.clientProfile = clientProfile;
this.clientProfile = clientProfile;
this.actionBox = actionBox;
this.actionBox = actionBox;
this.actionDetailsPane = actionDetailsPane;
this.actionDetailsPane = actionDetailsPane;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
logger = Logger.getLogger(getClass().getName());
logger = Logger.getLogger(getClass().getName());
if(runAsync)
if(runAsync)
new Thread(this).start();
new Thread(this).start();
else
else
runTask();
runTask();
}
}
private ClientConnection connection;
private ClientConnection connection;
private Action action;
private Action action;
private ActionBox actionBox;
private ActionBox actionBox;
private ActionDetailsPane actionDetailsPane;
private ActionDetailsPane actionDetailsPane;
private boolean isCombineChild;
private boolean isCombineChild;
private ClientProfile clientProfile;
private ClientProfile clientProfile;
private CombineActionPropertiesPane combineActionPropertiesPane;
private CombineActionPropertiesPane combineActionPropertiesPane;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private void runTask()
private void runTask()
{
{
try {
try {
connection.deleteAction(clientProfile.getID(), action.getID());
connection.deleteAction(clientProfile.getID(), action.getID());
clientProfile.removeActionByID(action.getID());
clientProfile.removeActionByID(action.getID());
if(isCombineChild)
if(isCombineChild)
{
{
System.out.println("ACTION ID TO BE REMOVED : "+action.getID());
System.out.println("ACTION ID TO BE REMOVED : "+action.getID());
combineActionPropertiesPane.getCombineAction().removeChild(action.getID());
combineActionPropertiesPane.getCombineAction().removeChild(action.getID());
System.out.println("222155 "+combineActionPropertiesPane.getCombineAction().getClientProperties().getSize());
System.out.println("222155 "+combineActionPropertiesPane.getCombineAction().getClientProperties().getSize());
combineActionPropertiesPane.renderProps();
combineActionPropertiesPane.renderProps();
try {
try {
actionDetailsPane.saveAction(combineActionPropertiesPane.getCombineAction(), false);
actionDetailsPane.saveAction(combineActionPropertiesPane.getCombineAction(), false);
System.out.println(combineActionPropertiesPane.getCombineAction().getDisplayText()+"@#@#@#@#@#@#");
System.out.println(combineActionPropertiesPane.getCombineAction().getDisplayText()+"@#@#@#@#@#@#");
actionDetailsPane.onActionClicked(
actionDetailsPane.onActionClicked(
combineActionPropertiesPane.getCombineAction(),
combineActionPropertiesPane.getCombineAction(),
actionBox
actionBox
);
);
} catch (MinorException e) {
} catch (MinorException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
else
else
{
{
Platform.runLater(()->{
Platform.runLater(()->{
actionBox.clear();
actionBox.clear();
actionDetailsPane.clear();
actionDetailsPane.clear();
});
});
}
}
// Platform.runLater(()->{
// Platform.runLater(()->{
// saveButton.setDisable(false);
// saveButton.setDisable(false);
// deleteButton.setDisable(false);
// deleteButton.setDisable(false);
// });
// });
}
}
catch (SevereException e)
catch (SevereException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
@Override
@Override
protected Void call() throws Exception
protected Void call() throws Exception
{
{
runTask();
runTask();
return null;
return null;
}
}
}
}
package com.stream_pi.server.window.dashboard.actiondetailpane;
package com.stream_pi.server.window.dashboard.actiondetailpane;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Logger;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.actionapi.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.actionapi.actionproperty.ClientProperties;
import com.stream_pi.action_api.actionproperty.ClientProperties;
import com.stream_pi.actionapi.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.actionapi.actionproperty.property.Type;
import com.stream_pi.action_api.actionproperty.property.Type;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
import javafx.scene.control.Button;
import javafx.scene.control.Button;
public class OnSaveActionTask extends Task<Void>
public class OnSaveActionTask extends Task<Void>
{
{
private Logger logger;
private Logger logger;
public OnSaveActionTask(ClientConnection connection, Action action, String displayNameText, boolean isCombineChild,
public OnSaveActionTask(ClientConnection connection, Action action, String displayNameText, boolean isCombineChild,
boolean isShowDisplayText, boolean isDefaultDisplayTextColour, String displayTextFontColour, boolean isClearIcon,
boolean isShowDisplayText, boolean isDefaultDisplayTextColour, String displayTextFontColour, boolean isClearIcon,
boolean isHideIcon, DisplayTextAlignment displayTextAlignment, boolean isTransparentBackground, String backgroundColour,
boolean isHideIcon, DisplayTextAlignment displayTextAlignment, boolean isTransparentBackground, String backgroundColour,
CombineActionPropertiesPane combineActionPropertiesPane, ClientProfile clientProfile, boolean sendIcon, ActionBox actionBox,
CombineActionPropertiesPane combineActionPropertiesPane, ClientProfile clientProfile, boolean sendIcon, ActionBox actionBox,
ArrayList<UIPropertyBox> actionClientProperties, ExceptionAndAlertHandler exceptionAndAlertHandler, Button saveButton, Button deleteButton,
ArrayList<UIPropertyBox> actionClientProperties, ExceptionAndAlertHandler exceptionAndAlertHandler, Button saveButton, Button deleteButton,
boolean runAsync)
boolean runAsync)
{
{
this.saveButton = saveButton;
this.saveButton = saveButton;
this.deleteButton = deleteButton;
this.deleteButton = deleteButton;
this.connection = connection;
this.connection = connection;
this.action = action;
this.action = action;
this.displayNameText = displayNameText;
this.displayNameText = displayNameText;
this.isCombineChild = isCombineChild;
this.isCombineChild = isCombineChild;
this.isShowDisplayText = isShowDisplayText;
this.isShowDisplayText = isShowDisplayText;
this.isDefaultDisplayTextColour = isDefaultDisplayTextColour;
this.isDefaultDisplayTextColour = isDefaultDisplayTextColour;
this.displayTextFontColour = displayTextFontColour;
this.displayTextFontColour = displayTextFontColour;
this.isClearIcon = isClearIcon;
this.isClearIcon = isClearIcon;
this.isHideIcon = isHideIcon;
this.isHideIcon = isHideIcon;
this.displayTextAlignment = displayTextAlignment;
this.displayTextAlignment = displayTextAlignment;
this.isTransparentBackground = isTransparentBackground;
this.isTransparentBackground = isTransparentBackground;
this.combineActionPropertiesPane = combineActionPropertiesPane;
this.combineActionPropertiesPane = combineActionPropertiesPane;
this.clientProfile = clientProfile;
this.clientProfile = clientProfile;
this.sendIcon = sendIcon;
this.sendIcon = sendIcon;
this.actionBox = actionBox;
this.actionBox = actionBox;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.backgroundColour = backgroundColour;
this.backgroundColour = backgroundColour;
this.actionClientProperties = actionClientProperties;
this.actionClientProperties = actionClientProperties;
logger = Logger.getLogger(getClass().getName());
logger = Logger.getLogger(getClass().getName());
if(runAsync)
if(runAsync)
new Thread(this).start();
new Thread(this).start();
else
else
runTask();
runTask();
}
}
private Button saveButton;
private Button saveButton;
private Button deleteButton;
private Button deleteButton;
private boolean isShowDisplayText;
private boolean isShowDisplayText;
private boolean isCombineChild;
private boolean isCombineChild;
private String displayNameText;
private String displayNameText;
private boolean isDefaultDisplayTextColour;
private boolean isDefaultDisplayTextColour;
private ArrayList<UIPropertyBox> actionClientProperties;
private ArrayList<UIPropertyBox> actionClientProperties;
private String displayTextFontColour;
private String displayTextFontColour;
private boolean isClearIcon;
private boolean isClearIcon;
private boolean isHideIcon;
private boolean isHideIcon;
private DisplayTextAlignment displayTextAlignment;
private DisplayTextAlignment displayTextAlignment;
private boolean isTransparentBackground;
private boolean isTransparentBackground;
private String backgroundColour;
private String backgroundColour;
private CombineActionPropertiesPane combineActionPropertiesPane;
private CombineActionPropertiesPane combineActionPropertiesPane;
private ClientProfile clientProfile;
private ClientProfile clientProfile;
private boolean sendIcon;
private boolean sendIcon;
private ActionBox actionBox;
private ActionBox actionBox;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private Action action;
private Action action;
private ClientConnection connection;
private ClientConnection connection;
private void setSaveDeleteButtonState(boolean state)
private void setSaveDeleteButtonState(boolean state)
{
{
Platform.runLater(()->{
Platform.runLater(()->{
saveButton.setDisable(state);
saveButton.setDisable(state);
deleteButton.setDisable(state);
deleteButton.setDisable(state);
});
});
}
}
private void runTask()
private void runTask()
{
{
action.setDisplayText(displayNameText);
action.setDisplayText(displayNameText);
if(!isCombineChild)
if(!isCombineChild)
{
{
setSaveDeleteButtonState(true);
setSaveDeleteButtonState(true);
action.setShowDisplayText(isShowDisplayText);
action.setShowDisplayText(isShowDisplayText);
if(isDefaultDisplayTextColour)
if(isDefaultDisplayTextColour)
action.setDisplayTextFontColourHex("");
action.setDisplayTextFontColourHex("");
else
else
{
{
action.setDisplayTextFontColourHex(displayTextFontColour);
action.setDisplayTextFontColourHex(displayTextFontColour);
//String fontColour = "#" + displayTextColourPicker.getValue().toString().substring(2);
//String fontColour = "#" + displayTextColourPicker.getValue().toString().substring(2);
//action.setDisplayTextFontColourHex(fontColour);
//action.setDisplayTextFontColourHex(fontColour);
}
}
if(isClearIcon)
if(isClearIcon)
{
{
action.setIcon(null);
action.setIcon(null);
action.setHasIcon(false);
action.setHasIcon(false);
action.setShowIcon(false);
action.setShowIcon(false);
}
}
if(action.isHasIcon())
if(action.isHasIcon())
action.setShowIcon(isHideIcon);
action.setShowIcon(isHideIcon);
action.setDisplayTextAlignment(displayTextAlignment);
action.setDisplayTextAlignment(displayTextAlignment);
logger.info("BBBGGG : "+backgroundColour);
logger.info("BBBGGG : "+backgroundColour);
if(isTransparentBackground)
if(isTransparentBackground)
action.setBgColourHex("");
action.setBgColourHex("");
else
else
{
{
//String bgColour = "#" + actionBackgroundColourPicker.getValue().toString().substring(2);
//String bgColour = "#" + actionBackgroundColourPicker.getValue().toString().substring(2);
action.setBgColourHex(backgroundColour);
action.setBgColourHex(backgroundColour);
}
}
}
}
System.out.println("parent : "+action.getParent());
System.out.println("parent : "+action.getParent());
if(action.getActionType() == ActionType.COMBINE)
if(action.getActionType() == ActionType.COMBINE)
{
{
List<String> finalChildren = combineActionPropertiesPane.getFinalChildren();
List<String> finalChildren = combineActionPropertiesPane.getFinalChildren();
System.out.println("2334 "+finalChildren.size());
System.out.println("2334 "+finalChildren.size());
ClientProperties clientProperties = new ClientProperties();
ClientProperties clientProperties = new ClientProperties();
for(int i = 0;i<finalChildren.size();i++)
for(int i = 0;i<finalChildren.size();i++)
{
{
Property property = new Property(i+"", Type.STRING);
Property property = new Property(i+"", Type.STRING);
property.setRawValue(finalChildren.get(i));
property.setRawValue(finalChildren.get(i));
clientProperties.addProperty(property);
clientProperties.addProperty(property);
}
}
action.getClientProperties().set(clientProperties);
action.getClientProperties().set(clientProperties);
}
}
else
else
{
{
//properties
//properties
for (UIPropertyBox clientProperty : actionClientProperties) {
for (UIPropertyBox clientProperty : actionClientProperties) {
action.getClientProperties().get().get(clientProperty.getIndex()).setRawValue(clientProperty.getRawValue());
action.getClientProperties().get().get(clientProperty.getIndex()).setRawValue(clientProperty.getRawValue());
}
}
}
}
try
try
{
{
logger.info("Saving action ... "+action.isHasIcon()+"+"+sendIcon);
logger.info("Saving action ... "+action.isHasIcon()+"+"+sendIcon);
/*if(action.isHasIcon())
/*if(action.isHasIcon())
{
{
if(clientProfile.getActionByID(action.getID()).getIconAsByteArray() == null)
if(clientProfile.getActionByID(action.getID()).getIconAsByteArray() == null)
{
{
sendIcon = true;
sendIcon = true;
}
}
else
else
{
{
if(!Arrays.equals(action.getIconAsByteArray(), clientProfile.getActionByID(action.getID()).getIconAsByteArray()))
if(!Arrays.equals(action.getIconAsByteArray(), clientProfile.getActionByID(action.getID()).getIconAsByteArray()))
{
{
logger.info("Sending ...");
logger.info("Sending ...");
sendIcon = true;
sendIcon = true;
}
}
}
}
}*/
}*/
connection.saveActionDetails(clientProfile.getID(), action);
connection.saveActionDetails(clientProfile.getID(), action);
if(sendIcon)
if(sendIcon)
{
{
connection.sendIcon(clientProfile.getID(), action.getID(), action.getIconAsByteArray());
connection.sendIcon(clientProfile.getID(), action.getID(), action.getIconAsByteArray());
}
}
if(!isCombineChild)
if(!isCombineChild)
{
{
Platform.runLater(()->{
Platform.runLater(()->{
actionBox.clear();
actionBox.clear();
actionBox.setAction(action);
actionBox.setAction(action);
actionBox.baseInit();
actionBox.baseInit();
actionBox.init();
actionBox.init();
});
});
setSaveDeleteButtonState(false);
setSaveDeleteButtonState(false);
}
}
clientProfile.removeActionByID(action.getID());
clientProfile.removeActionByID(action.getID());
clientProfile.addAction(action);
clientProfile.addAction(action);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
catch (CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
@Override
@Override
protected Void call() throws Exception
protected Void call() throws Exception
{
{
runTask();
runTask();
return null;
return null;
}
}
}
}
package com.stream_pi.server.window.dashboard.actiongridpane;
package com.stream_pi.server.window.dashboard.actiongridpane;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.actionapi.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.actionapi.action.Location;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.dashboard.actiondetailpane.ActionDetailsPaneListener;
import com.stream_pi.server.window.dashboard.actiondetailpane.ActionDetailsPaneListener;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.CacheHint;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.Image;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseButton;
import javafx.scene.input.TransferMode;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.Background;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextAlignment;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectInputStream;
import java.nio.ByteBuffer;
import java.nio.ByteBuffer;
public class ActionBox extends StackPane{
public class ActionBox extends StackPane{
private Label displayTextLabel;
private Label displayTextLabel;
private int row;
private int row;
private int col;
private int col;
public void setRow(int row) {
public void setRow(int row) {
this.row = row;
this.row = row;
}
}
public void setCol(int col) {
public void setCol(int col) {
this.col = col;
this.col = col;
}
}
public int getRow() {
public int getRow() {
return row;
return row;
}
}
public int getCol() {
public int getCol() {
return col;
return col;
}
}
private ActionDetailsPaneListener actionDetailsPaneListener;
private ActionDetailsPaneListener actionDetailsPaneListener;
public void clear()
public void clear()
{
{
setAction(null);
setAction(null);
setInvalid(false);
setInvalid(false);
setBackground(Background.EMPTY);
setBackground(Background.EMPTY);
setStyle(null);
setStyle(null);
getChildren().clear();
getChildren().clear();
}
}
public void baseInit()
public void baseInit()
{
{
displayTextLabel = new Label();
displayTextLabel = new Label();
displayTextLabel.setWrapText(true);
displayTextLabel.setWrapText(true);
displayTextLabel.setTextAlignment(TextAlignment.CENTER);
displayTextLabel.setTextAlignment(TextAlignment.CENTER);
displayTextLabel.getStyleClass().add("action_box_display_text_label");
displayTextLabel.getStyleClass().add("action_box_display_text_label");
displayTextLabel.prefHeightProperty().bind(heightProperty());
displayTextLabel.prefHeightProperty().bind(heightProperty());
displayTextLabel.prefWidthProperty().bind(widthProperty());
displayTextLabel.prefWidthProperty().bind(widthProperty());
getChildren().addAll(displayTextLabel);
getChildren().addAll(displayTextLabel);
setMinSize(size, size);
setMinSize(size, size);
setMaxSize(size, size);
setMaxSize(size, size);
getStyleClass().add("action_box");
getStyleClass().add("action_box");
getStyleClass().add("action_box_icon_not_present");
getStyleClass().add("action_box_icon_not_present");
getStyleClass().add("action_box_valid");
getStyleClass().add("action_box_valid");
setOnDragOver(dragEvent ->
setOnDragOver(dragEvent ->
{
{
if(dragEvent.getDragboard().hasContent(Action.getDataFormat()))
if(dragEvent.getDragboard().hasContent(Action.getDataFormat()))
{
{
dragEvent.acceptTransferModes(TransferMode.ANY);
dragEvent.acceptTransferModes(TransferMode.ANY);
dragEvent.consume();
dragEvent.consume();
}
}
});
});
setOnDragDropped(dragEvent ->
setOnDragDropped(dragEvent ->
{
{
try
try
{
{
if(action == null)
if(action == null)
{
{
Action action = (Action) dragEvent.getDragboard().getContent(Action.getDataFormat());
Action action = (Action) dragEvent.getDragboard().getContent(Action.getDataFormat());
action.setLocation(new Location(getRow(),
action.setLocation(new Location(getRow(),
getCol()));
getCol()));
action.setParent(getStreamPiParent());
action.setParent(getStreamPiParent());
action.setIDRandom();
action.setIDRandom();
actionGridPaneListener.addActionToCurrentClientProfile(action);
actionGridPaneListener.addActionToCurrentClientProfile(action);
setAction(action);
setAction(action);
init();
init();
actionDetailsPaneListener.onActionClicked(action, this);
actionDetailsPaneListener.onActionClicked(action, this);
if(action.isHasIcon())
if(action.isHasIcon())
actionDetailsPaneListener.setSendIcon(true);
actionDetailsPaneListener.setSendIcon(true);
actionDetailsPaneListener.saveAction();
actionDetailsPaneListener.saveAction();
}
}
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
e.printStackTrace();
e.printStackTrace();
}
}
});
});
setOnDragDetected(mouseEvent -> {
setOnDragDetected(mouseEvent -> {
try {
try {
if(action!=null)
if(action!=null)
{
{
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
{
{
Dragboard db = startDragAndDrop(TransferMode.ANY);
Dragboard db = startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
ClipboardContent content = new ClipboardContent();
Action newAction = (Action) action.clone();
Action newAction = (Action) action.clone();
newAction.setIDRandom();
newAction.setIDRandom();
newAction.setParent(getStreamPiParent());
newAction.setParent(getStreamPiParent());
content.put(Action.getDataFormat(), newAction);
content.put(Action.getDataFormat(), newAction);
db.setContent(content);
db.setContent(content);
mouseEvent.consume();
mouseEvent.consume();
}
}
}
}
}
}
catch (CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
});
});
setOnMouseClicked(mouseEvent -> {
setOnMouseClicked(mouseEvent -> {
if(action != null && mouseEvent.getButton().equals(MouseButton.PRIMARY))
if(action != null && mouseEvent.getButton().equals(MouseButton.PRIMARY))
{
{
if(mouseEvent.getClickCount() == 2 && action.getActionType() == ActionType.FOLDER)
if(mouseEvent.getClickCount() == 2 && action.getActionType() == ActionType.FOLDER)
{
{
getActionDetailsPaneListener().onOpenFolderButtonClicked();
getActionDetailsPaneListener().onOpenFolderButtonClicked();
}
}
else
else
{
{
try
try
{
{
actionDetailsPaneListener.onActionClicked(action, this);
actionDetailsPaneListener.onActionClicked(action, this);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
e.printStackTrace();
e.printStackTrace();
}
}
}
}
}
}
});
});
setCache(true);
setCache(true);
setCacheHint(CacheHint.SPEED);
setCacheHint(CacheHint.SPEED);
}
}
public void setInvalid(boolean invalid)
public void setInvalid(boolean invalid)
{
{
if(invalid)
if(invalid)
{
{
getStyleClass().remove("action_box_valid");
getStyleClass().remove("action_box_valid");
getStyleClass().add("action_box_invalid");
getStyleClass().add("action_box_invalid");
}
}
else
else
{
{
getStyleClass().remove("action_box_invalid");
getStyleClass().remove("action_box_invalid");
getStyleClass().add("action_box_valid");
getStyleClass().add("action_box_valid");
}
}
}
}
public ActionDetailsPaneListener getActionDetailsPaneListener() {
public ActionDetailsPaneListener getActionDetailsPaneListener() {
return actionDetailsPaneListener;
return actionDetailsPaneListener;
}
}
public ActionGridPaneListener getActionGridPaneListener() {
public ActionGridPaneListener getActionGridPaneListener() {
return actionGridPaneListener;
return actionGridPaneListener;
}
}
private int size;
private int size;
private ActionGridPaneListener actionGridPaneListener;
private ActionGridPaneListener actionGridPaneListener;
public ActionBox(int size, ActionDetailsPaneListener actionDetailsPaneListener, ActionGridPaneListener actionGridPaneListener)
public ActionBox(int size, ActionDetailsPaneListener actionDetailsPaneListener, ActionGridPaneListener actionGridPaneListener)
{
{
this.actionGridPaneListener = actionGridPaneListener;
this.actionGridPaneListener = actionGridPaneListener;
this.actionDetailsPaneListener = actionDetailsPaneListener;
this.actionDetailsPaneListener = actionDetailsPaneListener;
this.size = size;
this.size = size;
baseInit();
baseInit();
}
}
public static Action deserialize(ByteBuffer buffer) {
public static Action deserialize(ByteBuffer buffer) {
try {
try {
ByteArrayInputStream is = new ByteArrayInputStream(buffer.array());
ByteArrayInputStream is = new ByteArrayInputStream(buffer.array());
ObjectInputStream ois = new ObjectInputStream(is);
ObjectInputStream ois = new ObjectInputStream(is);
Action obj = (Action) ois.readObject();
Action obj = (Action) ois.readObject();
return obj;
return obj;
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
throw new RuntimeException(e);
throw new RuntimeException(e);
}
}
}
}
public void setIcon(byte[] iconByteArray)
public void setIcon(byte[] iconByteArray)
{
{
if(iconByteArray == null)
if(iconByteArray == null)
{
{
getStyleClass().remove("action_box_icon_present");
getStyleClass().remove("action_box_icon_present");
getStyleClass().add("action_box_icon_not_present");
getStyleClass().add("action_box_icon_not_present");
setBackground(null);
setBackground(null);
return;
return;
}
}
else
else
{
{
getStyleClass().add("action_box_icon_present");
getStyleClass().add("action_box_icon_present");
getStyleClass().remove("action_box_icon_not_present");
getStyleClass().remove("action_box_icon_not_present");
setBackground(
setBackground(
new Background(
new Background(
new BackgroundImage(new Image(
new BackgroundImage(new Image(
new ByteArrayInputStream(iconByteArray), size, size, false, true
new ByteArrayInputStream(iconByteArray), size, size, false, true
), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
new BackgroundSize(100, 100, true, true, true, false))
new BackgroundSize(100, 100, true, true, true, false))
)
)
);
);
}
}
}
}
private Action action;
private Action action;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private String parent;
private String parent;
public String getStreamPiParent() {
public String getStreamPiParent() {
return parent;
return parent;
}
}
public void setStreamPiParent(String parent) {
public void setStreamPiParent(String parent) {
this.parent = parent;
this.parent = parent;
}
}
public ActionBox(int size, Action action, ActionDetailsPaneListener actionDetailsPaneListener, ExceptionAndAlertHandler exceptionAndAlertHandler, ActionGridPaneListener actionGridPaneListener)
public ActionBox(int size, Action action, ActionDetailsPaneListener actionDetailsPaneListener, ExceptionAndAlertHandler exceptionAndAlertHandler, ActionGridPaneListener actionGridPaneListener)
{
{
this.actionGridPaneListener = actionGridPaneListener;
this.actionGridPaneListener = actionGridPaneListener;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.action = action;
this.action = action;
this.actionDetailsPaneListener = actionDetailsPaneListener;
this.actionDetailsPaneListener = actionDetailsPaneListener;
this.size = size;
this.size = size;
baseInit();
baseInit();
init();
init();
}
}
public void setAction(Action action)
public void setAction(Action action)
{
{
this.action = action;
this.action = action;
}
}
public void init()
public void init()
{
{
if(action.isShowDisplayText())
if(action.isShowDisplayText())
setDisplayTextLabel(action.getDisplayText());
setDisplayTextLabel(action.getDisplayText());
else
else
setDisplayTextLabel("");
setDisplayTextLabel("");
setDisplayTextAlignment(action.getDisplayTextAlignment());
setDisplayTextAlignment(action.getDisplayTextAlignment());
setBackgroundColour(action.getBgColourHex());
setBackgroundColour(action.getBgColourHex());
setDisplayTextFontColour(action.getDisplayTextFontColourHex());
setDisplayTextFontColour(action.getDisplayTextFontColourHex());
setInvalid(action.isInvalid());
setInvalid(action.isInvalid());
Platform.runLater(()->{
Platform.runLater(()->{
if(action.isHasIcon() && action.isShowIcon())
if(action.isHasIcon() && action.isShowIcon())
{
{
setIcon(action.getIconAsByteArray());
setIcon(action.getIconAsByteArray());
}
}
else
else
{
{
setIcon(null);
setIcon(null);
}
}
});
});
}
}
public void setDisplayTextLabel(String text)
public void setDisplayTextLabel(String text)
{
{
displayTextLabel.setText(text);
displayTextLabel.setText(text);
}
}
public void setDisplayTextAlignment(DisplayTextAlignment displayTextAlignment)
public void setDisplayTextAlignment(DisplayTextAlignment displayTextAlignment)
{
{
if(displayTextAlignment == DisplayTextAlignment.CENTER)
if(displayTextAlignment == DisplayTextAlignment.CENTER)
displayTextLabel.setAlignment(Pos.CENTER);
displayTextLabel.setAlignment(Pos.CENTER);
else if (displayTextAlignment == DisplayTextAlignment.BOTTOM)
else if (displayTextAlignment == DisplayTextAlignment.BOTTOM)
displayTextLabel.setAlignment(Pos.BOTTOM_CENTER);
displayTextLabel.setAlignment(Pos.BOTTOM_CENTER);
else if (displayTextAlignment == DisplayTextAlignment.TOP)
else if (displayTextAlignment == DisplayTextAlignment.TOP)
displayTextLabel.setAlignment(Pos.TOP_CENTER);
displayTextLabel.setAlignment(Pos.TOP_CENTER);
}
}
public void setDisplayTextFontColour(String colour)
public void setDisplayTextFontColour(String colour)
{
{
System.out.println("COLOr : "+colour);
System.out.println("COLOr : "+colour);
if(!colour.isEmpty())
if(!colour.isEmpty())
displayTextLabel.setStyle("-fx-text-fill : "+colour+";");
displayTextLabel.setStyle("-fx-text-fill : "+colour+";");
}
}
public void setBackgroundColour(String colour)
public void setBackgroundColour(String colour)
{
{
System.out.println("COLOr : "+colour);
System.out.println("COLOr : "+colour);
if(!colour.isEmpty() && action.getIconAsByteArray() == null)
if(!colour.isEmpty() && action.getIconAsByteArray() == null)
setStyle("-fx-background-color : "+colour);
setStyle("-fx-background-color : "+colour);
}
}
}
}
package com.stream_pi.server.window.dashboard.actiongridpane;
package com.stream_pi.server.window.dashboard.actiongridpane;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.action.Location;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.actionapi.otheractions.FolderAction;
import com.stream_pi.action_api.otheractions.FolderAction;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.dashboard.actiondetailpane.ActionDetailsPaneListener;
import com.stream_pi.server.window.dashboard.actiondetailpane.ActionDetailsPaneListener;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.*;
import javafx.scene.layout.*;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class ActionGridPane extends ScrollPane implements ActionGridPaneListener {
public class ActionGridPane extends ScrollPane implements ActionGridPaneListener {
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ActionDetailsPaneListener actionDetailsPaneListener;
private ActionDetailsPaneListener actionDetailsPaneListener;
public ActionGridPane(ExceptionAndAlertHandler exceptionAndAlertHandler)
public ActionGridPane(ExceptionAndAlertHandler exceptionAndAlertHandler)
{
{
logger = Logger.getLogger(ActionGridPane.class.getName());
logger = Logger.getLogger(ActionGridPane.class.getName());
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
getStyleClass().add("action_grid_pane_parent");
getStyleClass().add("action_grid_pane_parent");
VBox.setVgrow(this, Priority.ALWAYS);
VBox.setVgrow(this, Priority.ALWAYS);
actionsGridPane = new GridPane();
actionsGridPane = new GridPane();
actionsGridPane.setPadding(new Insets(5.0));
actionsGridPane.setPadding(new Insets(5.0));
actionsGridPane.getStyleClass().add("action_grid_pane");
actionsGridPane.getStyleClass().add("action_grid_pane");
actionsGridPane.setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
actionsGridPane.setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
setContent(actionsGridPane);
setContent(actionsGridPane);
}
}
public void setActionDetailsPaneListener(ActionDetailsPaneListener actionDetailsPaneListener) {
public void setActionDetailsPaneListener(ActionDetailsPaneListener actionDetailsPaneListener) {
this.actionDetailsPaneListener = actionDetailsPaneListener;
this.actionDetailsPaneListener = actionDetailsPaneListener;
}
}
private String currentParent;
private String currentParent;
public void setCurrentParent(String currentParent) {
public void setCurrentParent(String currentParent) {
this.currentParent = currentParent;
this.currentParent = currentParent;
}
}
public ClientProfile getClientProfile() {
public ClientProfile getClientProfile() {
return clientProfile;
return clientProfile;
}
}
private Client client;
private Client client;
public void setClient(Client client) {
public void setClient(Client client) {
this.client = client;
this.client = client;
}
}
public Client getClient() {
public Client getClient() {
return client;
return client;
}
}
private int rows, cols;
private int rows, cols;
private GridPane actionsGridPane;
private GridPane actionsGridPane;
private ClientProfile clientProfile;
private ClientProfile clientProfile;
public void setClientProfile(ClientProfile clientProfile)
public void setClientProfile(ClientProfile clientProfile)
{
{
this.clientProfile = clientProfile;
this.clientProfile = clientProfile;
setCurrentParent("root");
setCurrentParent("root");
setRows(clientProfile.getRows());
setRows(clientProfile.getRows());
setCols(clientProfile.getCols());
setCols(clientProfile.getCols());
}
}
public String getCurrentParent() {
public String getCurrentParent() {
return currentParent;
return currentParent;
}
}
public StackPane getFolderBackButton() throws SevereException
public StackPane getFolderBackButton() throws SevereException
{
{
StackPane stackPane = new StackPane();
StackPane stackPane = new StackPane();
stackPane.getStyleClass().add("action_box");
stackPane.getStyleClass().add("action_box");
stackPane.getStyleClass().add("action_box_valid");
stackPane.getStyleClass().add("action_box_valid");
stackPane.setPrefSize(
stackPane.setPrefSize(
Config.getInstance().getActionGridActionSize(),
Config.getInstance().getActionGridActionSize(),
Config.getInstance().getActionGridActionSize()
Config.getInstance().getActionGridActionSize()
);
);
FontIcon fontIcon = new FontIcon("fas-chevron-left");
FontIcon fontIcon = new FontIcon("fas-chevron-left");
fontIcon.getStyleClass().add("folder_action_back_button_icon");
fontIcon.getStyleClass().add("folder_action_back_button_icon");
fontIcon.setIconSize(Config.getInstance().getActionGridActionSize() - 30);
fontIcon.setIconSize(Config.getInstance().getActionGridActionSize() - 30);
stackPane.setAlignment(Pos.CENTER);
stackPane.setAlignment(Pos.CENTER);
stackPane.getChildren().add(fontIcon);
stackPane.getChildren().add(fontIcon);
stackPane.setOnMouseClicked(e->returnToPreviousParent());
stackPane.setOnMouseClicked(e->returnToPreviousParent());
return stackPane;
return stackPane;
}
}
public void renderGrid() throws SevereException {
public void renderGrid() throws SevereException {
clear();
clear();
actionsGridPane.setHgap(Config.getInstance().getActionGridActionGap());
actionsGridPane.setHgap(Config.getInstance().getActionGridActionGap());
actionsGridPane.setVgap(Config.getInstance().getActionGridActionGap());
actionsGridPane.setVgap(Config.getInstance().getActionGridActionGap());
boolean isFolder = false;
boolean isFolder = false;
if(!getCurrentParent().equals("root"))
if(!getCurrentParent().equals("root"))
{
{
isFolder = true;
isFolder = true;
actionsGridPane.add(getFolderBackButton(), 0,0);
actionsGridPane.add(getFolderBackButton(), 0,0);
}
}
for(int row = 0; row<rows; row++)
for(int row = 0; row<rows; row++)
{
{
for(int col = 0; col<cols; col++)
for(int col = 0; col<cols; col++)
{
{
if(row == 0 && col == 0 && isFolder)
if(row == 0 && col == 0 && isFolder)
continue;
continue;
ActionBox actionBox = new ActionBox(Config.getInstance().getActionGridActionSize(), actionDetailsPaneListener, this);
ActionBox actionBox = new ActionBox(Config.getInstance().getActionGridActionSize(), actionDetailsPaneListener, this);
actionBox.setStreamPiParent(currentParent);
actionBox.setStreamPiParent(currentParent);
actionBox.setRow(row);
actionBox.setRow(row);
actionBox.setCol(col);
actionBox.setCol(col);
actionsGridPane.add(actionBox, row, col);
actionsGridPane.add(actionBox, row, col);
}
}
}
}
}
}
public void renderActions()
public void renderActions()
{
{
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
for(String action1x : getClientProfile().getActionsKeySet())
for(String action1x : getClientProfile().getActionsKeySet())
{
{
Action eachAction = getClientProfile().getActionByID(action1x);
Action eachAction = getClientProfile().getActionByID(action1x);
logger.info("action ID : "+eachAction.getID()+
logger.info("action ID : "+eachAction.getID()+
"\nInvalid : "+eachAction.isInvalid());
"\nInvalid : "+eachAction.isInvalid());
try {
try {
renderAction(eachAction);
renderAction(eachAction);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
errors.append("*").append(e.getShortMessage()).append("\n");
errors.append("*").append(e.getShortMessage()).append("\n");
}
}
}
}
if(!errors.toString().isEmpty())
if(!errors.toString().isEmpty())
{
{
exceptionAndAlertHandler.handleMinorException(new MinorException("Error while rendering following actions", errors.toString()));
exceptionAndAlertHandler.handleMinorException(new MinorException("Error while rendering following actions", errors.toString()));
}
}
}
}
public void clear()
public void clear()
{
{
actionsGridPane.getChildren().clear();
actionsGridPane.getChildren().clear();
}
}
private Logger logger;
private Logger logger;
public void renderAction(Action action) throws SevereException, MinorException
public void renderAction(Action action) throws SevereException, MinorException
{
{
if(!action.getParent().equals(currentParent))
if(!action.getParent().equals(currentParent))
{
{
logger.info("Skipping action "+action.getID()+", not current parent!");
logger.info("Skipping action "+action.getID()+", not current parent!");
return;
return;
}
}
if(action.getLocation().getRow()==-1)
if(action.getLocation().getRow()==-1)
{
{
logger.info("action has -1 rowIndex. Probably Combine action. Skipping ...");
logger.info("action has -1 rowIndex. Probably Combine action. Skipping ...");
return;
return;
}
}
if(action.getLocation().getRow() >= rows || action.getLocation().getCol() >= cols)
if(action.getLocation().getRow() >= rows || action.getLocation().getCol() >= cols)
{
{
throw new MinorException("action "+action.getDisplayText()+" ("+action.getID()+") falls outside bounds.\n" +
throw new MinorException("action "+action.getDisplayText()+" ("+action.getID()+") falls outside bounds.\n" +
" Consider increasing rows/cols from client settings and relocating/deleting it.");
" Consider increasing rows/cols from client settings and relocating/deleting it.");
}
}
ActionBox actionBox = new ActionBox(Config.getInstance().getActionGridActionSize(), action, actionDetailsPaneListener, exceptionAndAlertHandler, this);
ActionBox actionBox = new ActionBox(Config.getInstance().getActionGridActionSize(), action, actionDetailsPaneListener, exceptionAndAlertHandler, this);
Location location = action.getLocation();
Location location = action.getLocation();
actionBox.setStreamPiParent(currentParent);
actionBox.setStreamPiParent(currentParent);
actionBox.setRow(location.getRow());
actionBox.setRow(location.getRow());
actionBox.setCol(location.getCol());
actionBox.setCol(location.getCol());
for(Node node : actionsGridPane.getChildren())
for(Node node : actionsGridPane.getChildren())
{
{
if(GridPane.getColumnIndex(node) == location.getRow() &&
if(GridPane.getColumnIndex(node) == location.getRow() &&
GridPane.getRowIndex(node) == location.getCol())
GridPane.getRowIndex(node) == location.getCol())
{
{
actionsGridPane.getChildren().remove(node);
actionsGridPane.getChildren().remove(node);
break;
break;
}
}
}
}
System.out.println(location.getCol()+","+location.getRow());
System.out.println(location.getCol()+","+location.getRow());
actionsGridPane.add(actionBox, location.getRow(), location.getCol());
actionsGridPane.add(actionBox, location.getRow(), location.getCol());
}
}
public void setRows(int rows)
public void setRows(int rows)
{
{
this.rows = rows;
this.rows = rows;
}
}
public void setCols(int cols)
public void setCols(int cols)
{
{
this.cols = cols;
this.cols = cols;
}
}
public int getRows()
public int getRows()
{
{
return rows;
return rows;
}
}
public int getCols()
public int getCols()
{
{
return cols;
return cols;
}
}
@Override
@Override
public void addActionToCurrentClientProfile(Action newAction) {
public void addActionToCurrentClientProfile(Action newAction) {
try {
try {
getClientProfile().addAction(newAction);
getClientProfile().addAction(newAction);
} catch (CloneNotSupportedException e) {
} catch (CloneNotSupportedException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
private String previousParent;
private String previousParent;
public void setPreviousParent(String previousParent) {
public void setPreviousParent(String previousParent) {
this.previousParent = previousParent;
this.previousParent = previousParent;
}
}
public String getPreviousParent() {
public String getPreviousParent() {
return previousParent;
return previousParent;
}
}
@Override
@Override
public void renderFolder(FolderAction action) {
public void renderFolder(FolderAction action) {
setCurrentParent(action.getID());
setCurrentParent(action.getID());
setPreviousParent(action.getParent());
setPreviousParent(action.getParent());
try {
try {
renderGrid();
renderGrid();
renderActions();
renderActions();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
public void returnToPreviousParent()
public void returnToPreviousParent()
{
{
setCurrentParent(getPreviousParent());
setCurrentParent(getPreviousParent());
if(!getPreviousParent().equals("root"))
if(!getPreviousParent().equals("root"))
{
{
System.out.println("parent : "+getPreviousParent());
System.out.println("parent : "+getPreviousParent());
setPreviousParent(getClientProfile().getActionByID(
setPreviousParent(getClientProfile().getActionByID(
getPreviousParent()
getPreviousParent()
).getParent());
).getParent());
}
}
try {
try {
renderGrid();
renderGrid();
renderActions();
renderActions();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
}
}
M
src/main/java/com/stream_pi/server/window/dashboard/actiongridpane/ActionGridPaneListener.java
+2
−2
package com.stream_pi.server.window.dashboard.actiongridpane;
package com.stream_pi.server.window.dashboard.actiongridpane;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.actionapi.otheractions.FolderAction;
import com.stream_pi.action_api.otheractions.FolderAction;
public interface ActionGridPaneListener {
public interface ActionGridPaneListener {
void addActionToCurrentClientProfile(Action newAction);
void addActionToCurrentClientProfile(Action newAction);
void renderFolder(FolderAction action);
void renderFolder(FolderAction action);
}
}
package com.stream_pi.server.window.firsttimeuse;
package com.stream_pi.server.window.firsttimeuse;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller.FillerType;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Stage;
public class FinalConfigPane extends VBox
public class FinalConfigPane extends VBox
{
{
private TextField serverNicknameTextField;
private TextField serverNicknameTextField;
private TextField serverPortTextField;
private TextField serverPortTextField;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ServerListener serverListener;
private ServerListener serverListener;
public FinalConfigPane(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener)
public FinalConfigPane(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener)
{
{
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.serverListener = serverListener;
this.serverListener = serverListener;
getStyleClass().add("first_time_use_pane_final_config");
getStyleClass().add("first_time_use_pane_final_config");
Label label = new Label("Thats it. Now just name your Stream-Pi Server, and the port where the server will run on!\n" +
Label label = new Label("Thats it. Now just name your Stream-Pi Server, and the port where the server will run on!\n" +
"You can leave the default value of the port as it is.");
"You can leave the default value of the port as it is.");
label.setWrapText(true);
label.setWrapText(true);
label.getStyleClass().add("first_time_use_pane_final_config_label");
label.getStyleClass().add("first_time_use_pane_final_config_label");
serverNicknameTextField = new TextField();
serverNicknameTextField = new TextField();
serverPortTextField = new TextField("2004");
serverPortTextField = new TextField("2004");
HBoxInputBox serverNickNameInputBox = new HBoxInputBox("Server Nickname", serverNicknameTextField, 200);
HBoxInputBox serverNickNameInputBox = new HBoxInputBox("Server Nickname", serverNicknameTextField, 200);
HBoxInputBox serverPortInputBox = new HBoxInputBox("Server Port", serverPortTextField);
HBoxInputBox serverPortInputBox = new HBoxInputBox("Server Port", serverPortTextField);
Button confirmButton = new Button("Confirm");
Button confirmButton = new Button("Confirm");
confirmButton.setOnAction(event -> onConfirmButtonClicked());
confirmButton.setOnAction(event -> onConfirmButtonClicked());
HBox bBar = new HBox(confirmButton);
HBox bBar = new HBox(confirmButton);
bBar.setAlignment(Pos.CENTER_RIGHT);
bBar.setAlignment(Pos.CENTER_RIGHT);
getChildren().addAll(label, serverNickNameInputBox, serverPortInputBox, new SpaceFiller(FillerType.VBox), bBar);
getChildren().addAll(label, serverNickNameInputBox, serverPortInputBox, SpaceFiller.vertical(), bBar);
setSpacing(10.0);
setSpacing(10.0);
setVisible(false);
setVisible(false);
}
}
private void onConfirmButtonClicked()
private void onConfirmButtonClicked()
{
{
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
String serverNameStr = serverNicknameTextField.getText();
String serverNameStr = serverNicknameTextField.getText();
String serverPortStr = serverPortTextField.getText();
String serverPortStr = serverPortTextField.getText();
if(serverNameStr.isBlank() || serverNameStr.isEmpty())
if(serverNameStr.isBlank() || serverNameStr.isEmpty())
{
{
errors.append("* Server Name cannot be blank.\n");
errors.append("* Server Name cannot be blank.\n");
}
}
int serverPort=-1;
int serverPort=-1;
try {
try {
serverPort = Integer.parseInt(serverPortStr);
serverPort = Integer.parseInt(serverPortStr);
if (serverPort < 1024)
if (serverPort < 1024)
errors.append("* Server Port must be more than 1024");
errors.append("* Server Port must be more than 1024");
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append("* Server Port must be integer.\n");
errors.append("* Server Port must be integer.\n");
}
}
if(errors.toString().isEmpty())
if(errors.toString().isEmpty())
{
{
try
try
{
{
Config.getInstance().setServerName(serverNameStr);
Config.getInstance().setServerName(serverNameStr);
Config.getInstance().setServerPort(serverPort);
Config.getInstance().setServerPort(serverPort);
Config.getInstance().setFirstTimeUse(false);
Config.getInstance().setFirstTimeUse(false);
Config.getInstance().save();
Config.getInstance().save();
serverListener.othInit();
serverListener.othInit();
((Stage) getScene().getWindow()).close();
((Stage) getScene().getWindow()).close();
}
}
catch(SevereException e)
catch(SevereException e)
{
{
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
}
}
else
else
{
{
Alert alert = new Alert(AlertType.ERROR);
Alert alert = new Alert(AlertType.ERROR);
alert.setResizable(false);
alert.setResizable(false);
alert.getDialogPane().setPrefHeight(250);
alert.getDialogPane().setPrefHeight(250);
alert.setContentText("Please rectify the following errors and try again:\n"+errors.toString());
alert.setContentText("Please rectify the following errors and try again:\n"+errors.toString());
alert.show();
alert.show();
}
}
}
}
}
}
package com.stream_pi.server.window.firsttimeuse;
package com.stream_pi.server.window.firsttimeuse;
import com.stream_pi.server.Main;
import com.stream_pi.server.Main;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller.FillerType;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Font;
public class FirstTimeUse extends VBox{
public class FirstTimeUse extends VBox{
public FirstTimeUse(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener)
public FirstTimeUse(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener)
{
{
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
getStylesheets().add(Main.class.getResource("style.css").toExternalForm());
getStylesheets().add(Main.class.getResource("style.css").toExternalForm());
getStyleClass().add("first_time_use_pane");
getStyleClass().add("first_time_use_pane");
setSpacing(10.0);
setSpacing(10.0);
setPadding(new Insets(5));
setPadding(new Insets(5));
headingLabel = new Label();
headingLabel = new Label();
headingLabel.getStyleClass().add("first_time_use_pane_heading_label");
headingLabel.getStyleClass().add("first_time_use_pane_heading_label");
StackPane stackPane = new StackPane();
StackPane stackPane = new StackPane();
stackPane.getStyleClass().add("first_time_use_pane_stackpane");
stackPane.getStyleClass().add("first_time_use_pane_stackpane");
VBox.setVgrow(stackPane, Priority.ALWAYS);
VBox.setVgrow(stackPane, Priority.ALWAYS);
welcomePane = new WelcomePane();
welcomePane = new WelcomePane();
licensePane = new LicensePane();
licensePane = new LicensePane();
finalConfigPane = new FinalConfigPane(exceptionAndAlertHandler, serverListener);
finalConfigPane = new FinalConfigPane(exceptionAndAlertHandler, serverListener);
stackPane.getChildren().addAll(
stackPane.getChildren().addAll(
welcomePane,
welcomePane,
licensePane,
licensePane,
finalConfigPane
finalConfigPane
);
);
nextButton = new Button("Next");
nextButton = new Button("Next");
nextButton.setOnAction(event-> onNextButtonClicked());
nextButton.setOnAction(event-> onNextButtonClicked());
previousButton = new Button("Previous");
previousButton = new Button("Previous");
previousButton.setOnAction(event-> onPreviousButtonClicked());
previousButton.setOnAction(event-> onPreviousButtonClicked());
HBox buttonBar = new HBox(previousButton, new SpaceFiller(FillerType.HBox), nextButton);
HBox buttonBar = new HBox(previousButton, SpaceFiller.horizontal(), nextButton);
buttonBar.setSpacing(10.0);
buttonBar.setSpacing(10.0);
getChildren().addAll(headingLabel, stackPane, buttonBar);
getChildren().addAll(headingLabel, stackPane, buttonBar);
setWindow(WindowName.WELCOME);
setWindow(WindowName.WELCOME);
}
}
private Label headingLabel;
private Label headingLabel;
private Button nextButton;
private Button nextButton;
private Button previousButton;
private Button previousButton;
private WelcomePane welcomePane;
private WelcomePane welcomePane;
private LicensePane licensePane;
private LicensePane licensePane;
private FinalConfigPane finalConfigPane;
private FinalConfigPane finalConfigPane;
private WindowName windowName;
private WindowName windowName;
private void onNextButtonClicked()
private void onNextButtonClicked()
{
{
if(windowName == WindowName.WELCOME)
if(windowName == WindowName.WELCOME)
{
{
setWindow(WindowName.LICENSE);
setWindow(WindowName.LICENSE);
}
}
else if(windowName == WindowName.LICENSE)
else if(windowName == WindowName.LICENSE)
{
{
setWindow(WindowName.FINAL);
setWindow(WindowName.FINAL);
}
}
}
}
private void onPreviousButtonClicked()
private void onPreviousButtonClicked()
{
{
if(windowName == WindowName.FINAL)
if(windowName == WindowName.FINAL)
{
{
setWindow(WindowName.LICENSE);
setWindow(WindowName.LICENSE);
}
}
else if(windowName == WindowName.LICENSE)
else if(windowName == WindowName.LICENSE)
{
{
setWindow(WindowName.WELCOME);
setWindow(WindowName.WELCOME);
}
}
}
}
private void setWindow(WindowName windowName)
private void setWindow(WindowName windowName)
{
{
if (windowName == WindowName.WELCOME)
if (windowName == WindowName.WELCOME)
{
{
this.windowName = WindowName.WELCOME;
this.windowName = WindowName.WELCOME;
welcomePane.toFront();
welcomePane.toFront();
welcomePane.setVisible(true);
welcomePane.setVisible(true);
licensePane.setVisible(false);
licensePane.setVisible(false);
finalConfigPane.setVisible(false);
finalConfigPane.setVisible(false);
headingLabel.setText("");
headingLabel.setText("");
nextButton.setDisable(false);
nextButton.setDisable(false);
previousButton.setDisable(true);
previousButton.setDisable(true);
}
}
else if (windowName == WindowName.LICENSE)
else if (windowName == WindowName.LICENSE)
{
{
this.windowName = WindowName.LICENSE;
this.windowName = WindowName.LICENSE;
licensePane.toFront();
licensePane.toFront();
welcomePane.setVisible(false);
welcomePane.setVisible(false);
licensePane.setVisible(true);
licensePane.setVisible(true);
finalConfigPane.setVisible(false);
finalConfigPane.setVisible(false);
headingLabel.setText("License Agreement");
headingLabel.setText("License Agreement");
nextButton.setDisable(false);
nextButton.setDisable(false);
previousButton.setDisable(false);
previousButton.setDisable(false);
}
}
else if (windowName == WindowName.FINAL)
else if (windowName == WindowName.FINAL)
{
{
this.windowName = WindowName.FINAL;
this.windowName = WindowName.FINAL;
finalConfigPane.toFront();
finalConfigPane.toFront();
welcomePane.setVisible(false);
welcomePane.setVisible(false);
licensePane.setVisible(false);
licensePane.setVisible(false);
finalConfigPane.setVisible(true);
finalConfigPane.setVisible(true);
headingLabel.setText("Finishing up ...");
headingLabel.setText("Finishing up ...");
nextButton.setDisable(true);
nextButton.setDisable(true);
previousButton.setDisable(false);
previousButton.setDisable(false);
}
}
}
}
}
}
package com.stream_pi.server.window.settings;
package com.stream_pi.server.window.settings;
import com.stream_pi.actionapi.ActionAPI;
import com.stream_pi.action_api.ActionAPI;
import com.stream_pi.server.info.License;
import com.stream_pi.server.info.License;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.Main;
import com.stream_pi.server.Main;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
public class About extends VBox{
public class About extends VBox{
private HostServices hostServices;
private HostServices hostServices;
public About(HostServices hostServices)
public About(HostServices hostServices)
{
{
getStyleClass().add("about");
getStyleClass().add("about");
this.hostServices = hostServices;
this.hostServices = hostServices;
setAlignment(Pos.TOP_CENTER);
setAlignment(Pos.TOP_CENTER);
Image appIcon = new Image(Main.class.getResourceAsStream("app_icon.png"));
Image appIcon = new Image(Main.class.getResourceAsStream("app_icon.png"));
ImageView appIconImageView = new ImageView(appIcon);
ImageView appIconImageView = new ImageView(appIcon);
appIconImageView.setFitHeight(196);
appIconImageView.setFitHeight(196);
appIconImageView.setFitWidth(182);
appIconImageView.setFitWidth(182);
Label licenseLabel = new Label("License");
Label licenseLabel = new Label("License");
licenseLabel.getStyleClass().add("about_license_label");
licenseLabel.getStyleClass().add("about_license_label");
VBox.setMargin(licenseLabel, new Insets(20, 0 , 10 ,0));
VBox.setMargin(licenseLabel, new Insets(20, 0 , 10 ,0));
TextArea licenseTextArea = new TextArea(License.getLicense());
TextArea licenseTextArea = new TextArea(License.getLicense());
licenseTextArea.getStyleClass().add("about_license_text_area");
licenseTextArea.getStyleClass().add("about_license_text_area");
licenseTextArea.setWrapText(false);
licenseTextArea.setWrapText(false);
licenseTextArea.setEditable(false);
licenseTextArea.setEditable(false);
licenseTextArea.setMaxWidth(600);
licenseTextArea.setMaxWidth(600);
VBox.setVgrow(licenseTextArea, Priority.ALWAYS);
VBox.setVgrow(licenseTextArea, Priority.ALWAYS);
HBox links = new HBox();
HBox links = new HBox();
links.getStyleClass().add("about_links_box");
links.getStyleClass().add("about_links_box");
Hyperlink github = new Hyperlink("GitHub");
Hyperlink github = new Hyperlink("GitHub");
github.setOnAction(event -> openWebpage("https://github.com/Stream-Pi"));
github.setOnAction(event -> openWebpage("https://github.com/Stream-Pi"));
Hyperlink discord = new Hyperlink("Discord");
Hyperlink discord = new Hyperlink("Discord");
discord.setOnAction(event -> openWebpage("https://discord.gg/BExqGmk"));
discord.setOnAction(event -> openWebpage("https://discord.gg/BExqGmk"));
Hyperlink website = new Hyperlink("Website");
Hyperlink website = new Hyperlink("Website");
website.setOnAction(event -> openWebpage("https://stream-pi.com"));
website.setOnAction(event -> openWebpage("https://stream-pi.com"));
Hyperlink twitter = new Hyperlink("Twitter");
Hyperlink twitter = new Hyperlink("Twitter");
twitter.setOnAction(event -> openWebpage("https://twitter.com/Stream_Pi"));
twitter.setOnAction(event -> openWebpage("https://twitter.com/Stream_Pi"));
Hyperlink matrix = new Hyperlink("Matrix");
Hyperlink matrix = new Hyperlink("Matrix");
matrix.setOnAction(event -> openWebpage("https://matrix.to/#/#stream-pi_general:matrix.org"));
matrix.setOnAction(event -> openWebpage("https://matrix.to/#/#stream-pi_general:matrix.org"));
links.setAlignment(Pos.CENTER);
links.setAlignment(Pos.CENTER);
links.getChildren().addAll(github, matrix, discord, website, twitter);
links.getChildren().addAll(github, matrix, discord, website, twitter);
Hyperlink donateButton = new Hyperlink("DONATE");
Hyperlink donateButton = new Hyperlink("DONATE");
donateButton.setOnAction(event -> {
donateButton.setOnAction(event -> {
openWebpage("https://www.patreon.com/streampi");
openWebpage("https://www.patreon.com/streampi");
});
});
donateButton.getStyleClass().add("about_donate_hyperlink");
donateButton.getStyleClass().add("about_donate_hyperlink");
ServerInfo serverInfo = ServerInfo.getInstance();
ServerInfo serverInfo = ServerInfo.getInstance();
Label versionText = new Label(serverInfo.getVersion().getText() + " - "+ serverInfo.getPlatformType().getUIName() + " - "+ serverInfo.getReleaseStatus().getUIName());
Label versionText = new Label(serverInfo.getVersion().getText() + " - "+ serverInfo.getPlatformType().getUIName() + " - "+ serverInfo.getReleaseStatus().getUIName());
versionText.getStyleClass().add("about_version_label");
versionText.getStyleClass().add("about_version_label");
Label commStandardLabel = new Label("Comm Standard "+serverInfo.getCommStandardVersion().getText());
Label commStandardLabel = new Label("Comm Standard "+serverInfo.getCommStandardVersion().getText());
commStandardLabel.getStyleClass().add("about_comm_standard_label");
commStandardLabel.getStyleClass().add("about_comm_standard_label");
Label minThemeAPILabel = new Label("Min ThemeAPI "+serverInfo.getMinThemeSupportVersion().getText());
Label minThemeAPILabel = new Label("Min ThemeAPI "+serverInfo.getMinThemeSupportVersion().getText());
minThemeAPILabel.getStyleClass().add("about_min_theme_api_label");
minThemeAPILabel.getStyleClass().add("about_min_theme_api_label");
Label minActionAPILabel = new Label("Min ActionAPI "+serverInfo.getMinPluginSupportVersion().getText());
Label minActionAPILabel = new Label("Min ActionAPI "+serverInfo.getMinPluginSupportVersion().getText());
minActionAPILabel.getStyleClass().add("about_min_action_api_label");
minActionAPILabel.getStyleClass().add("about_min_action_api_label");
Label currentActionAPILabel = new Label("ActionAPI "+ ActionAPI.API_VERSION.getText());
Label currentActionAPILabel = new Label("ActionAPI "+ ActionAPI.API_VERSION.getText());
currentActionAPILabel.getStyleClass().add("about_current_action_api_label");
currentActionAPILabel.getStyleClass().add("about_current_action_api_label");
getChildren().addAll(appIconImageView, licenseLabel, licenseTextArea, links, donateButton, versionText, commStandardLabel, minThemeAPILabel, minActionAPILabel, currentActionAPILabel);
getChildren().addAll(appIconImageView, licenseLabel, licenseTextArea, links, donateButton, versionText, commStandardLabel, minThemeAPILabel, minActionAPILabel, currentActionAPILabel);
}
}
public void openWebpage(String url) {
public void openWebpage(String url) {
hostServices.showDocument(url);
hostServices.showDocument(url);
}
}
}
}
package com.stream_pi.server.window.settings;
package com.stream_pi.server.window.settings;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientTheme;
import com.stream_pi.server.client.ClientTheme;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.platform.ReleaseStatus;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.FXCollections;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.CacheHint;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import javafx.util.Callback;
import javafx.util.Callback;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class ClientsSettings extends VBox {
public class ClientsSettings extends VBox {
private VBox clientsSettingsVBox;
private VBox clientsSettingsVBox;
private Button saveButton;
private Button saveButton;
private ServerListener serverListener;
private ServerListener serverListener;
private Logger logger;
private Logger logger;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
public ClientsSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener)
public ClientsSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener)
{
{
getStyleClass().add("clients_settings");
getStyleClass().add("clients_settings");
this.serverListener = serverListener;
this.serverListener = serverListener;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
clientSettingsVBoxArrayList = new ArrayList<>();
clientSettingsVBoxArrayList = new ArrayList<>();
logger = Logger.getLogger(ClientsSettings.class.getName());
logger = Logger.getLogger(ClientsSettings.class.getName());
clientsSettingsVBox = new VBox();
clientsSettingsVBox = new VBox();
clientsSettingsVBox.getStyleClass().add("clients_settings_vbox");
clientsSettingsVBox.getStyleClass().add("clients_settings_vbox");
clientsSettingsVBox.setAlignment(Pos.TOP_CENTER);
clientsSettingsVBox.setAlignment(Pos.TOP_CENTER);
setAlignment(Pos.TOP_CENTER);
setAlignment(Pos.TOP_CENTER);
ScrollPane scrollPane = new ScrollPane();
ScrollPane scrollPane = new ScrollPane();
scrollPane.getStyleClass().add("clients_settings_scroll_pane");
scrollPane.getStyleClass().add("clients_settings_scroll_pane");
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
clientsSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
clientsSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
scrollPane.setContent(clientsSettingsVBox);
scrollPane.setContent(clientsSettingsVBox);
saveButton = new Button("Save");
saveButton = new Button("Save");
saveButton.setOnAction(event -> onSaveButtonClicked());
saveButton.setOnAction(event -> onSaveButtonClicked());
HBox hBox = new HBox(saveButton);
HBox hBox = new HBox(saveButton);
hBox.setAlignment(Pos.CENTER_RIGHT);
hBox.setAlignment(Pos.CENTER_RIGHT);
getChildren().addAll(scrollPane, hBox);
getChildren().addAll(scrollPane, hBox);
setCache(true);
setCache(true);
setCacheHint(CacheHint.SPEED);
setCacheHint(CacheHint.SPEED);
}
}
public void onSaveButtonClicked()
public void onSaveButtonClicked()
{
{
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
Platform.runLater(()->saveButton.setDisable(true));
Platform.runLater(()->saveButton.setDisable(true));
StringBuilder finalErrors = new StringBuilder();
StringBuilder finalErrors = new StringBuilder();
for(ClientSettingsVBox clientSettingsVBox : clientSettingsVBoxArrayList)
for(ClientSettingsVBox clientSettingsVBox : clientSettingsVBoxArrayList)
{
{
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
if(clientSettingsVBox.getNickname().isBlank())
if(clientSettingsVBox.getNickname().isBlank())
errors.append(" Cannot have blank nickname. \n");
errors.append(" Cannot have blank nickname. \n");
try {
try {
Double.parseDouble(clientSettingsVBox.getStartupWindowHeight());
Double.parseDouble(clientSettingsVBox.getStartupWindowHeight());
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append(" Must have integer display height. \n");
errors.append(" Must have integer display height. \n");
}
}
try {
try {
Double.parseDouble(clientSettingsVBox.getStartupWindowWidth());
Double.parseDouble(clientSettingsVBox.getStartupWindowWidth());
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append(" Must have integer display width. \n");
errors.append(" Must have integer display width. \n");
}
}
for(ClientProfileVBox clientProfileVBox : clientSettingsVBox.getClientProfileVBoxes())
for(ClientProfileVBox clientProfileVBox : clientSettingsVBox.getClientProfileVBoxes())
{
{
StringBuilder errors2 = new StringBuilder();
StringBuilder errors2 = new StringBuilder();
if(clientProfileVBox.getName().isBlank())
if(clientProfileVBox.getName().isBlank())
errors2.append(" cannot have blank nickname. \n");
errors2.append(" cannot have blank nickname. \n");
try {
try {
Integer.parseInt(clientProfileVBox.getActionSize());
Integer.parseInt(clientProfileVBox.getActionSize());
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors2.append(" Must have integer action Size. \n");
errors2.append(" Must have integer action Size. \n");
}
}
try {
try {
Integer.parseInt(clientProfileVBox.getActionGap());
Integer.parseInt(clientProfileVBox.getActionGap());
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors2.append(" Must have integer action Gap. \n");
errors2.append(" Must have integer action Gap. \n");
}
}
try {
try {
int rows = Integer.parseInt(clientProfileVBox.getRows());
int rows = Integer.parseInt(clientProfileVBox.getRows());
int actionsSize = Integer.parseInt(clientProfileVBox.getActionSize());
int actionsSize = Integer.parseInt(clientProfileVBox.getActionSize());
double startupWidth = Double.parseDouble(clientSettingsVBox.getStartupWindowWidth());
double startupWidth = Double.parseDouble(clientSettingsVBox.getStartupWindowWidth());
if((rows*actionsSize) > (startupWidth - 25) && clientSettingsVBox.getPlatform()!= com.stream_pi.util.platform.Platform.ANDROID)
if((rows*actionsSize) > (startupWidth - 25) && clientSettingsVBox.getPlatform()!= com.stream_pi.util.platform.Platform.ANDROID)
{
{
errors2.append(" Rows out of bounds of screen size. \n"+startupWidth);
errors2.append(" Rows out of bounds of screen size. \n"+startupWidth);
}
}
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors2.append(" Must have integer Rows. \n");
errors2.append(" Must have integer Rows. \n");
}
}
try {
try {
int cols = Integer.parseInt(clientProfileVBox.getCols());
int cols = Integer.parseInt(clientProfileVBox.getCols());
int actionsSize = Integer.parseInt(clientProfileVBox.getActionSize());
int actionsSize = Integer.parseInt(clientProfileVBox.getActionSize());
double startupHeight = Double.parseDouble(clientSettingsVBox.getStartupWindowHeight());
double startupHeight = Double.parseDouble(clientSettingsVBox.getStartupWindowHeight());
if((cols*actionsSize) > (startupHeight - 25) && clientSettingsVBox.getPlatform()!= com.stream_pi.util.platform.Platform.ANDROID)
if((cols*actionsSize) > (startupHeight - 25) && clientSettingsVBox.getPlatform()!= com.stream_pi.util.platform.Platform.ANDROID)
{
{
errors2.append(" Cols out of bounds of screen size. \n"+startupHeight);
errors2.append(" Cols out of bounds of screen size. \n"+startupHeight);
}
}
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors2.append(" Must have integer Columns. \n");
errors2.append(" Must have integer Columns. \n");
}
}
if(!errors2.toString().isEmpty())
if(!errors2.toString().isEmpty())
{
{
errors.append(" ")
errors.append(" ")
.append(clientProfileVBox.getRealName())
.append(clientProfileVBox.getRealName())
.append("\n")
.append("\n")
.append(errors2.toString())
.append(errors2.toString())
.append("\n");
.append("\n");
}
}
}
}
if(!errors.toString().isEmpty())
if(!errors.toString().isEmpty())
{
{
finalErrors.append("* ")
finalErrors.append("* ")
.append(clientSettingsVBox.getRealNickName())
.append(clientSettingsVBox.getRealNickName())
.append("\n")
.append("\n")
.append(errors.toString())
.append(errors.toString())
.append("\n");
.append("\n");
}
}
}
}
if(!finalErrors.toString().isEmpty())
if(!finalErrors.toString().isEmpty())
throw new MinorException("You made form mistakes",
throw new MinorException("You made form mistakes",
"Please fix the following issues : \n"+finalErrors.toString());
"Please fix the following issues : \n"+finalErrors.toString());
//save details and values
//save details and values
for(ClientSettingsVBox clientSettingsVBox : clientSettingsVBoxArrayList)
for(ClientSettingsVBox clientSettingsVBox : clientSettingsVBoxArrayList)
{
{
clientSettingsVBox.saveClientAndProfileDetails();
clientSettingsVBox.saveClientAndProfileDetails();
}
}
loadData();
loadData();
serverListener.clearTemp();
serverListener.clearTemp();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
catch (CloneNotSupportedException e)
catch (CloneNotSupportedException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(new SevereException(
exceptionAndAlertHandler.handleSevereException(new SevereException(
e.getMessage()
e.getMessage()
));
));
}
}
finally
finally
{
{
Platform.runLater(()->saveButton.setDisable(false));
Platform.runLater(()->saveButton.setDisable(false));
}
}
return null;
return null;
}
}
}).start();
}).start();
}
}
private ArrayList<ClientSettingsVBox> clientSettingsVBoxArrayList;
private ArrayList<ClientSettingsVBox> clientSettingsVBoxArrayList;
public void loadData()
public void loadData()
{
{
logger.info("Loading client data into ClientsSettings ...");
logger.info("Loading client data into ClientsSettings ...");
Platform.runLater(()-> clientsSettingsVBox.getChildren().clear());
Platform.runLater(()-> clientsSettingsVBox.getChildren().clear());
clientSettingsVBoxArrayList.clear();
clientSettingsVBoxArrayList.clear();
List<ClientConnection> clientConnections = ClientConnections.getInstance().getConnections();
List<ClientConnection> clientConnections = ClientConnections.getInstance().getConnections();
if(clientConnections.size() == 0)
if(clientConnections.size() == 0)
{
{
Platform.runLater(()->{
Platform.runLater(()->{
clientsSettingsVBox.getChildren().add(new Label("No Clients Connected."));
clientsSettingsVBox.getChildren().add(new Label("No Clients Connected."));
saveButton.setVisible(false);
saveButton.setVisible(false);
});
});
}
}
else
else
{
{
Platform.runLater(()->saveButton.setVisible(true));
Platform.runLater(()->saveButton.setVisible(true));
for (ClientConnection clientConnection : clientConnections) {
for (ClientConnection clientConnection : clientConnections) {
ClientSettingsVBox clientSettingsVBox = new ClientSettingsVBox(clientConnection);
ClientSettingsVBox clientSettingsVBox = new ClientSettingsVBox(clientConnection);
clientSettingsVBoxArrayList.add(clientSettingsVBox);
clientSettingsVBoxArrayList.add(clientSettingsVBox);
Platform.runLater(()->clientsSettingsVBox.getChildren().add(clientSettingsVBox));
Platform.runLater(()->clientsSettingsVBox.getChildren().add(clientSettingsVBox));
}
}
}
}
logger.info("... Done!");
logger.info("... Done!");
}
}
public class ClientSettingsVBox extends VBox
public class ClientSettingsVBox extends VBox
{
{
private ComboBox<ClientProfile> profilesComboBox;
private ComboBox<ClientProfile> profilesComboBox;
private ComboBox<ClientTheme> themesComboBox;
private ComboBox<ClientTheme> themesComboBox;
private TextField startupWindowHeightTextField;
private TextField startupWindowHeightTextField;
public String getStartupWindowHeight() {
public String getStartupWindowHeight() {
return startupWindowHeightTextField.getText();
return startupWindowHeightTextField.getText();
}
}
private TextField startupWindowWidthTextField;
private TextField startupWindowWidthTextField;
public String getStartupWindowWidth() {
public String getStartupWindowWidth() {
return startupWindowWidthTextField.getText();
return startupWindowWidthTextField.getText();
}
}
private TextField nicknameTextField;
private TextField nicknameTextField;
public String getNickname() {
public String getNickname() {
return nicknameTextField.getText();
return nicknameTextField.getText();
}
}
private Label nickNameLabel;
private Label nickNameLabel;
private Label versionLabel;
private Label versionLabel;
public String getRealNickName()
public String getRealNickName()
{
{
return nickNameLabel.getText();
return nickNameLabel.getText();
}
}
private com.stream_pi.util.platform.Platform platform;
private com.stream_pi.util.platform.Platform platform;
public com.stream_pi.util.platform.Platform getPlatform() {
public com.stream_pi.util.platform.Platform getPlatform() {
return platform;
return platform;
}
}
private Label socketConnectionLabel;
private Label socketConnectionLabel;
private ClientConnection connection;
private ClientConnection connection;
private Accordion profilesAccordion;
private Accordion profilesAccordion;
private ArrayList<ClientProfileVBox> clientProfileVBoxes;
private ArrayList<ClientProfileVBox> clientProfileVBoxes;
private Label platformLabel;
private Label platformLabel;
private HBoxInputBox startupWindowHeightInputBox, startupWindowWidthInputBox;
private HBoxInputBox startupWindowHeightInputBox, startupWindowWidthInputBox;
public ArrayList<ClientProfileVBox> getClientProfileVBoxes() {
public ArrayList<ClientProfileVBox> getClientProfileVBoxes() {
return clientProfileVBoxes;
return clientProfileVBoxes;
}
}
public ClientSettingsVBox(ClientConnection connection)
public ClientSettingsVBox(ClientConnection connection)
{
{
this.connection = connection;
this.connection = connection;
this.platform = connection.getClient().getPlatform();
this.platform = connection.getClient().getPlatform();
clientProfileVBoxes = new ArrayList<>();
clientProfileVBoxes = new ArrayList<>();
getStyleClass().add("clients_settings_each_client_box");
getStyleClass().add("clients_settings_each_client_box");
initUI();
initUI();
loadValues();
loadValues();
}
}
public ClientConnection getConnection()
public ClientConnection getConnection()
{
{
return connection;
return connection;
}
}
public void saveClientAndProfileDetails() throws SevereException, CloneNotSupportedException, MinorException {
public void saveClientAndProfileDetails() throws SevereException, CloneNotSupportedException, MinorException {
System.out.println("IIN");
System.out.println("IIN");
getConnection().saveClientDetails(
getConnection().saveClientDetails(
nicknameTextField.getText(),
nicknameTextField.getText(),
startupWindowWidthTextField.getText(),
startupWindowWidthTextField.getText(),
startupWindowHeightTextField.getText(),
startupWindowHeightTextField.getText(),
profilesComboBox.getSelectionModel().getSelectedItem().getID(),
profilesComboBox.getSelectionModel().getSelectedItem().getID(),
themesComboBox.getSelectionModel().getSelectedItem().getThemeFullName()
themesComboBox.getSelectionModel().getSelectedItem().getThemeFullName()
);
);
System.out.println("OUT");
System.out.println("OUT");
logger.info("Profiles : ");
logger.info("Profiles : ");
for(ClientProfileVBox clientProfileVBox : clientProfileVBoxes)
for(ClientProfileVBox clientProfileVBox : clientProfileVBoxes)
{
{
logger.info("Name : "+clientProfileVBox.getClientProfile().getName());
logger.info("Name : "+clientProfileVBox.getClientProfile().getName());
getConnection().saveProfileDetails(clientProfileVBox.getClientProfile());
getConnection().saveProfileDetails(clientProfileVBox.getClientProfile());
}
}
//remove deleted client profiles
//remove deleted client profiles
for(ClientProfile clientProfile : connection.getClient().getAllClientProfiles())
for(ClientProfile clientProfile : connection.getClient().getAllClientProfiles())
{
{
boolean found = false;
boolean found = false;
for(ClientProfileVBox clientProfileVBox : clientProfileVBoxes)
for(ClientProfileVBox clientProfileVBox : clientProfileVBoxes)
{
{
if(clientProfileVBox.getClientProfile().getID().equals(clientProfile.getID()))
if(clientProfileVBox.getClientProfile().getID().equals(clientProfile.getID()))
{
{
found = true;
found = true;
break;
break;
}
}
}
}
if(!found)
if(!found)
{
{
connection.getClient().removeProfileFromID(clientProfile.getID());
connection.getClient().removeProfileFromID(clientProfile.getID());
connection.deleteProfile(clientProfile.getID());
connection.deleteProfile(clientProfile.getID());
}
}
}
}
}
}
public void initUI()
public void initUI()
{
{
profilesComboBox = new ComboBox<>();
profilesComboBox = new ComboBox<>();
Callback<ListView<ClientProfile>, ListCell<ClientProfile>> profilesComboBoxFactory = new Callback<>() {
Callback<ListView<ClientProfile>, ListCell<ClientProfile>> profilesComboBoxFactory = new Callback<>() {
@Override
@Override
public ListCell<ClientProfile> call(ListView<ClientProfile> clientConnectionListView) {
public ListCell<ClientProfile> call(ListView<ClientProfile> clientConnectionListView) {
return new ListCell<>() {
return new ListCell<>() {
@Override
@Override
protected void updateItem(ClientProfile clientProfile, boolean b) {
protected void updateItem(ClientProfile clientProfile, boolean b) {
super.updateItem(clientProfile, b);
super.updateItem(clientProfile, b);
if(clientProfile == null)
if(clientProfile == null)
{
{
setText(null);
setText(null);
}
}
else
else
{
{
setText(clientProfile.getName());
setText(clientProfile.getName());
}
}
}
}
};
};
}
}
};
};
profilesComboBox.setCellFactory(profilesComboBoxFactory);
profilesComboBox.setCellFactory(profilesComboBoxFactory);
profilesComboBox.setButtonCell(profilesComboBoxFactory.call(null));
profilesComboBox.setButtonCell(profilesComboBoxFactory.call(null));
themesComboBox = new ComboBox<>();
themesComboBox = new ComboBox<>();
Callback<ListView<ClientTheme>, ListCell<ClientTheme>> themesComboBoxFactory = new Callback<>() {
Callback<ListView<ClientTheme>, ListCell<ClientTheme>> themesComboBoxFactory = new Callback<>() {
@Override
@Override
public ListCell<ClientTheme> call(ListView<ClientTheme> clientConnectionListView) {
public ListCell<ClientTheme> call(ListView<ClientTheme> clientConnectionListView) {
return new ListCell<>() {
return new ListCell<>() {
@Override
@Override
protected void updateItem(ClientTheme clientTheme, boolean b) {
protected void updateItem(ClientTheme clientTheme, boolean b) {
super.updateItem(clientTheme, b);
super.updateItem(clientTheme, b);
if(clientTheme == null)
if(clientTheme == null)
{
{
setText(null);
setText(null);
}
}
else
else
{
{
setText(clientTheme.getShortName());
setText(clientTheme.getShortName());
}
}
}
}
};
};
}
}
};
};
themesComboBox.setCellFactory(themesComboBoxFactory);
themesComboBox.setCellFactory(themesComboBoxFactory);
themesComboBox.setButtonCell(themesComboBoxFactory.call(null));
themesComboBox.setButtonCell(themesComboBoxFactory.call(null));
startupWindowHeightTextField = new TextField();
startupWindowHeightTextField = new TextField();
startupWindowWidthTextField = new TextField();
startupWindowWidthTextField = new TextField();
platformLabel = new Label();
platformLabel = new Label();
platformLabel.getStyleClass().add("client_settings_each_client_platform_label");
platformLabel.getStyleClass().add("client_settings_each_client_platform_label");
socketConnectionLabel = new Label();
socketConnectionLabel = new Label();
socketConnectionLabel.getStyleClass().add("client_settings_each_client_socket_connection_label");
socketConnectionLabel.getStyleClass().add("client_settings_each_client_socket_connection_label");
nicknameTextField = new TextField();
nicknameTextField = new TextField();
nickNameLabel = new Label();
nickNameLabel = new Label();
nickNameLabel.getStyleClass().add("client_settings_each_client_nick_name_label");
nickNameLabel.getStyleClass().add("client_settings_each_client_nick_name_label");
versionLabel = new Label();
versionLabel = new Label();
versionLabel.getStyleClass().add("client_settings_each_client_version_label");
versionLabel.getStyleClass().add("client_settings_each_client_version_label");
profilesAccordion = new Accordion();
profilesAccordion = new Accordion();
profilesAccordion.getStyleClass().add("client_settings_each_client_profiles_accordion");
profilesAccordion.getStyleClass().add("client_settings_each_client_profiles_accordion");
VBox.setMargin(profilesAccordion, new Insets(0,0,20,0));
VBox.setMargin(profilesAccordion, new Insets(0,0,20,0));
Button addNewProfileButton = new Button("Add new Profile");
Button addNewProfileButton = new Button("Add new Profile");
addNewProfileButton.setOnAction(event -> onNewProfileButtonClicked());
addNewProfileButton.setOnAction(event -> onNewProfileButtonClicked());
setSpacing(10.0);
setSpacing(10.0);
getStyleClass().add("settings_clients_each_client");
getStyleClass().add("settings_clients_each_client");
startupWindowHeightInputBox = new HBoxInputBox("Startup window Height", startupWindowHeightTextField);
startupWindowHeightInputBox = new HBoxInputBox("Startup window Height", startupWindowHeightTextField);
startupWindowHeightInputBox.managedProperty().bind(startupWindowHeightInputBox.visibleProperty());
startupWindowHeightInputBox.managedProperty().bind(startupWindowHeightInputBox.visibleProperty());
startupWindowWidthInputBox = new HBoxInputBox("Startup window Width", startupWindowWidthTextField);
startupWindowWidthInputBox = new HBoxInputBox("Startup window Width", startupWindowWidthTextField);
startupWindowWidthInputBox.managedProperty().bind(startupWindowWidthInputBox.visibleProperty());
startupWindowWidthInputBox.managedProperty().bind(startupWindowWidthInputBox.visibleProperty());
this.getChildren().addAll(
this.getChildren().addAll(
nickNameLabel,
nickNameLabel,
socketConnectionLabel,
socketConnectionLabel,
platformLabel,
platformLabel,
versionLabel,
versionLabel,
new HBoxInputBox("Nickname",nicknameTextField),
new HBoxInputBox("Nickname",nicknameTextField),
new HBox(
new HBox(
new Label("Theme"),
new Label("Theme"),
new SpaceFiller(SpaceFiller.FillerType.HBox),
SpaceFiller.horizontal(),
themesComboBox
themesComboBox
),
),
startupWindowHeightInputBox,
startupWindowHeightInputBox,
startupWindowWidthInputBox,
startupWindowWidthInputBox,
new HBox(new Label("Startup Profile"),
new HBox(new Label("Startup Profile"),
new SpaceFiller(SpaceFiller.FillerType.HBox),
SpaceFiller.horizontal(),
profilesComboBox),
profilesComboBox),
addNewProfileButton,
addNewProfileButton,
profilesAccordion);
profilesAccordion);
}
}
public void loadValues()
public void loadValues()
{
{
Client client = connection.getClient();
Client client = connection.getClient();
profilesComboBox.setItems(FXCollections.observableList(client.getAllClientProfiles()));
profilesComboBox.setItems(FXCollections.observableList(client.getAllClientProfiles()));
profilesComboBox.getSelectionModel().select(
profilesComboBox.getSelectionModel().select(
client.getProfileByID(client.getDefaultProfileID())
client.getProfileByID(client.getDefaultProfileID())
);
);
themesComboBox.setItems(FXCollections.observableList(client.getThemes()));
themesComboBox.setItems(FXCollections.observableList(client.getThemes()));
themesComboBox.getSelectionModel().select(
themesComboBox.getSelectionModel().select(
client.getThemeByFullName(
client.getThemeByFullName(
client.getDefaultThemeFullName()
client.getDefaultThemeFullName()
)
)
);
);
nicknameTextField.setText(client.getNickName());
nicknameTextField.setText(client.getNickName());
if(client.getPlatform() == com.stream_pi.util.platform.Platform.ANDROID)
if(client.getPlatform() == com.stream_pi.util.platform.Platform.ANDROID)
{
{
startupWindowHeightInputBox.setVisible(false);
startupWindowHeightInputBox.setVisible(false);
startupWindowWidthInputBox.setVisible(false);
startupWindowWidthInputBox.setVisible(false);
}
}
platformLabel.setText("Platform : "+client.getPlatform().getUIName());
platformLabel.setText("Platform : "+client.getPlatform().getUIName());
startupWindowWidthTextField.setText(client.getStartupDisplayWidth()+"");
startupWindowWidthTextField.setText(client.getStartupDisplayWidth()+"");
startupWindowHeightTextField.setText(client.getStartupDisplayHeight()+"");
startupWindowHeightTextField.setText(client.getStartupDisplayHeight()+"");
socketConnectionLabel.setText(client.getRemoteSocketAddress().toString().substring(1)); //substring removes the `/`
socketConnectionLabel.setText(client.getRemoteSocketAddress().toString().substring(1)); //substring removes the `/`
nickNameLabel.setText(client.getNickName());
nickNameLabel.setText(client.getNickName());
versionLabel.setText(client.getReleaseStatus().getUIName()+" "+client.getVersion().getText());
versionLabel.setText(client.getReleaseStatus().getUIName()+" "+client.getVersion().getText());
//add profiles
//add profiles
for(ClientProfile clientProfile : client.getAllClientProfiles())
for(ClientProfile clientProfile : client.getAllClientProfiles())
{
{
TitledPane titledPane = new TitledPane();
TitledPane titledPane = new TitledPane();
titledPane.getStyleClass().add("client_settings_each_client_accordion_each_titled_pane");
titledPane.getStyleClass().add("client_settings_each_client_accordion_each_titled_pane");
titledPane.setText(clientProfile.getName());
titledPane.setText(clientProfile.getName());
ClientProfileVBox clientProfileVBox = new ClientProfileVBox(clientProfile);
ClientProfileVBox clientProfileVBox = new ClientProfileVBox(clientProfile);
clientProfileVBox.getRemoveButton().setOnAction(event -> onProfileDeleteButtonClicked(clientProfileVBox, titledPane));
clientProfileVBox.getRemoveButton().setOnAction(event -> onProfileDeleteButtonClicked(clientProfileVBox, titledPane));
titledPane.setContent(clientProfileVBox);
titledPane.setContent(clientProfileVBox);
clientProfileVBoxes.add(clientProfileVBox);
clientProfileVBoxes.add(clientProfileVBox);
profilesAccordion.getPanes().add(titledPane);
profilesAccordion.getPanes().add(titledPane);
}
}
}
}
public void onNewProfileButtonClicked()
public void onNewProfileButtonClicked()
{
{
ClientProfile clientProfile = new ClientProfile(
ClientProfile clientProfile = new ClientProfile(
"Untitled Profile",
"Untitled Profile",
3,
3,
3,
3,
100,
100,
5
5
);
);
ClientProfileVBox clientProfileVBox = new ClientProfileVBox(clientProfile);
ClientProfileVBox clientProfileVBox = new ClientProfileVBox(clientProfile);
TitledPane titledPane = new TitledPane();
TitledPane titledPane = new TitledPane();
titledPane.setContent(clientProfileVBox);
titledPane.setContent(clientProfileVBox);
titledPane.setText(clientProfile.getName());
titledPane.setText(clientProfile.getName());
clientProfileVBox.getRemoveButton().setOnAction(event -> onProfileDeleteButtonClicked(clientProfileVBox, titledPane));
clientProfileVBox.getRemoveButton().setOnAction(event -> onProfileDeleteButtonClicked(clientProfileVBox, titledPane));
clientProfileVBoxes.add(clientProfileVBox);
clientProfileVBoxes.add(clientProfileVBox);
profilesAccordion.getPanes().add(titledPane);
profilesAccordion.getPanes().add(titledPane);
}
}
public void onProfileDeleteButtonClicked(ClientProfileVBox clientProfileVBox, TitledPane titledPane)
public void onProfileDeleteButtonClicked(ClientProfileVBox clientProfileVBox, TitledPane titledPane)
{
{
if(clientProfileVBoxes.size() == 1)
if(clientProfileVBoxes.size() == 1)
{
{
exceptionAndAlertHandler.handleMinorException(new MinorException("Only one",
exceptionAndAlertHandler.handleMinorException(new MinorException("Only one",
"You cannot delete all profiles"));
"You cannot delete all profiles"));
}
}
else
else
{
{
if(profilesComboBox.getSelectionModel().getSelectedItem().getID().equals(clientProfileVBox.getClientProfile().getID()))
if(profilesComboBox.getSelectionModel().getSelectedItem().getID().equals(clientProfileVBox.getClientProfile().getID()))
{
{
exceptionAndAlertHandler.handleMinorException(new MinorException("Default",
exceptionAndAlertHandler.handleMinorException(new MinorException("Default",
"You cannot delete default profile. Change to another one to delete this."));
"You cannot delete default profile. Change to another one to delete this."));
}
}
else
else
{
{
clientProfileVBoxes.remove(clientProfileVBox);
clientProfileVBoxes.remove(clientProfileVBox);
profilesComboBox.getItems().remove(clientProfileVBox.getClientProfile());
profilesComboBox.getItems().remove(clientProfileVBox.getClientProfile());
profilesAccordion.getPanes().remove(titledPane);
profilesAccordion.getPanes().remove(titledPane);
}
}
}
}
}
}
}
}
public class ClientProfileVBox extends VBox
public class ClientProfileVBox extends VBox
{
{
private TextField nameTextField;
private TextField nameTextField;
public String getName()
public String getName()
{
{
return nameTextField.getText();
return nameTextField.getText();
}
}
private TextField rowsTextField;
private TextField rowsTextField;
public String getRows()
public String getRows()
{
{
return rowsTextField.getText();
return rowsTextField.getText();
}
}
private TextField colsTextField;
private TextField colsTextField;
public String getCols()
public String getCols()
{
{
return colsTextField.getText();
return colsTextField.getText();
}
}
private TextField actionSizeTextField;
private TextField actionSizeTextField;
public String getActionSize()
public String getActionSize()
{
{
return actionSizeTextField.getText();
return actionSizeTextField.getText();
}
}
private TextField actionGapTextField;
private TextField actionGapTextField;
public String getActionGap()
public String getActionGap()
{
{
return actionGapTextField.getText();
return actionGapTextField.getText();
}
}
private Button removeButton;
private Button removeButton;
private ClientProfile clientProfile;
private ClientProfile clientProfile;
public String getRealName()
public String getRealName()
{
{
return clientProfile.getName();
return clientProfile.getName();
}
}
public ClientProfileVBox(ClientProfile clientProfile)
public ClientProfileVBox(ClientProfile clientProfile)
{
{
this.clientProfile = clientProfile;
this.clientProfile = clientProfile;
getStyleClass().add("client_settings_each_client_accordion_each_profile_box");
getStyleClass().add("client_settings_each_client_accordion_each_profile_box");
initUI();
initUI();
loadValues(clientProfile);
loadValues(clientProfile);
}
}
public void initUI()
public void initUI()
{
{
setPadding(new Insets(5.0));
setPadding(new Insets(5.0));
setSpacing(10.0);
setSpacing(10.0);
nameTextField = new TextField();
nameTextField = new TextField();
rowsTextField = new TextField();
rowsTextField = new TextField();
colsTextField = new TextField();
colsTextField = new TextField();
actionSizeTextField = new TextField();
actionSizeTextField = new TextField();
actionGapTextField = new TextField();
actionGapTextField = new TextField();
removeButton = new Button("Remove");
removeButton = new Button("Remove");
HBox hBox = new HBox(removeButton);
HBox hBox = new HBox(removeButton);
hBox.setAlignment(Pos.CENTER_RIGHT);
hBox.setAlignment(Pos.CENTER_RIGHT);
getChildren().addAll(
getChildren().addAll(
new HBoxInputBox("Name ", nameTextField),
new HBoxInputBox("Name ", nameTextField),
new HBoxInputBox("Columns", rowsTextField),
new HBoxInputBox("Columns", rowsTextField),
new HBoxInputBox("Rows", colsTextField),
new HBoxInputBox("Rows", colsTextField),
new HBoxInputBox("action Size", actionSizeTextField),
new HBoxInputBox("action Size", actionSizeTextField),
new HBoxInputBox("action Gap", actionGapTextField),
new HBoxInputBox("action Gap", actionGapTextField),
hBox
hBox
);
);
}
}
public Button getRemoveButton()
public Button getRemoveButton()
{
{
return removeButton;
return removeButton;
}
}
public void loadValues(ClientProfile clientProfile)
public void loadValues(ClientProfile clientProfile)
{
{
nameTextField.setText(clientProfile.getName());
nameTextField.setText(clientProfile.getName());
rowsTextField.setText(clientProfile.getRows()+"");
rowsTextField.setText(clientProfile.getRows()+"");
colsTextField.setText(clientProfile.getCols()+"");
colsTextField.setText(clientProfile.getCols()+"");
actionSizeTextField.setText(clientProfile.getActionSize()+"");
actionSizeTextField.setText(clientProfile.getActionSize()+"");
actionGapTextField.setText(clientProfile.getActionGap()+"");
actionGapTextField.setText(clientProfile.getActionGap()+"");
}
}
public ClientProfile getClientProfile()
public ClientProfile getClientProfile()
{
{
clientProfile.setActionGap(Integer.parseInt(actionGapTextField.getText()));
clientProfile.setActionGap(Integer.parseInt(actionGapTextField.getText()));
clientProfile.setActionSize(Integer.parseInt(actionSizeTextField.getText()));
clientProfile.setActionSize(Integer.parseInt(actionSizeTextField.getText()));
clientProfile.setRows(Integer.parseInt(rowsTextField.getText()));
clientProfile.setRows(Integer.parseInt(rowsTextField.getText()));
clientProfile.setCols(Integer.parseInt(colsTextField.getText()));
clientProfile.setCols(Integer.parseInt(colsTextField.getText()));
clientProfile.setName(nameTextField.getText());
clientProfile.setName(nameTextField.getText());
return clientProfile;
return clientProfile;
}
}
}
}
}
}
package com.stream_pi.server.window.settings;
package com.stream_pi.server.window.settings;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.actionapi.actionproperty.property.ControlType;
import com.stream_pi.action_api.actionproperty.property.ControlType;
import com.stream_pi.actionapi.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.actionapi.actionproperty.property.Type;
import com.stream_pi.action_api.actionproperty.property.Type;
import com.stream_pi.actionapi.normalaction.NormalAction;
import com.stream_pi.action_api.normalaction.NormalAction;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.server.action.NormalActionPlugins;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller.FillerType;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class PluginsSettings extends VBox {
public class PluginsSettings extends VBox {
private VBox pluginsSettingsVBox;
private VBox pluginsSettingsVBox;
private ServerListener serverListener;
private ServerListener serverListener;
private Logger logger;
private Logger logger;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private HostServices hostServices;
private HostServices hostServices;
public PluginsSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices)
public PluginsSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices)
{
{
getStyleClass().add("plugins_settings");
getStyleClass().add("plugins_settings");
this.hostServices = hostServices;
this.hostServices = hostServices;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
pluginProperties = new ArrayList<>();
pluginProperties = new ArrayList<>();
logger = Logger.getLogger(PluginsSettings.class.getName());
logger = Logger.getLogger(PluginsSettings.class.getName());
pluginsSettingsVBox = new VBox();
pluginsSettingsVBox = new VBox();
pluginsSettingsVBox.getStyleClass().add("plugins_settings_vbox");
pluginsSettingsVBox.getStyleClass().add("plugins_settings_vbox");
pluginsSettingsVBox.setAlignment(Pos.TOP_CENTER);
pluginsSettingsVBox.setAlignment(Pos.TOP_CENTER);
ScrollPane scrollPane = new ScrollPane();
ScrollPane scrollPane = new ScrollPane();
scrollPane.getStyleClass().add("plugins_settings_scroll_pane");
scrollPane.getStyleClass().add("plugins_settings_scroll_pane");
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
pluginsSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
pluginsSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
scrollPane.setContent(pluginsSettingsVBox);
scrollPane.setContent(pluginsSettingsVBox);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
setAlignment(Pos.TOP_CENTER);
setAlignment(Pos.TOP_CENTER);
saveButton = new Button("Save");
saveButton = new Button("Save");
saveButton.setOnAction(event -> onSaveButtonClicked());
saveButton.setOnAction(event -> onSaveButtonClicked());
HBox hBox = new HBox(saveButton);
HBox hBox = new HBox(saveButton);
hBox.setAlignment(Pos.CENTER_RIGHT);
hBox.setAlignment(Pos.CENTER_RIGHT);
getChildren().addAll(scrollPane, hBox);
getChildren().addAll(scrollPane, hBox);
}
}
private Button saveButton;
private Button saveButton;
public void onSaveButtonClicked()
public void onSaveButtonClicked()
{
{
try {
try {
//form validation
//form validation
StringBuilder finalErrors = new StringBuilder();
StringBuilder finalErrors = new StringBuilder();
for (PluginProperties p : pluginProperties)
for (PluginProperties p : pluginProperties)
{
{
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
for(int j = 0; j < p.getServerPropertyUIBox().size(); j++)
for(int j = 0; j < p.getServerPropertyUIBox().size(); j++)
{
{
UIPropertyBox serverProperty = p.getServerPropertyUIBox().get(j);
UIPropertyBox serverProperty = p.getServerPropertyUIBox().get(j);
Node controlNode = serverProperty.getControlNode();
Node controlNode = serverProperty.getControlNode();
if (serverProperty.getControlType() == ControlType.TEXT_FIELD)
if (serverProperty.getControlType() == ControlType.TEXT_FIELD)
{
{
String value = ((TextField) controlNode).getText();
String value = ((TextField) controlNode).getText();
if(serverProperty.getType() == Type.INTEGER)
if(serverProperty.getType() == Type.INTEGER)
{
{
try
try
{
{
Integer.parseInt(value);
Integer.parseInt(value);
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" must be integer.\n");
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" must be integer.\n");
}
}
}
}
else
else
{
{
if(value.isBlank() && !serverProperty.isCanBeBlank())
if(value.isBlank() && !serverProperty.isCanBeBlank())
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" cannot be blank.\n");
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" cannot be blank.\n");
}
}
}
}
}
}
if(!errors.toString().isBlank())
if(!errors.toString().isBlank())
{
{
finalErrors.append(" * ").append(p.getName()).append("\n").append(errors.toString()).append("\n");
finalErrors.append(" * ").append(p.getName()).append("\n").append(errors.toString()).append("\n");
}
}
}
}
if(!finalErrors.toString().isEmpty())
if(!finalErrors.toString().isEmpty())
{
{
throw new MinorException("Form Validation Errors",
throw new MinorException("Form Validation Errors",
"Please rectify the following errors and try again \n"+finalErrors.toString());
"Please rectify the following errors and try again \n"+finalErrors.toString());
}
}
//save
//save
for (PluginProperties pp : pluginProperties) {
for (PluginProperties pp : pluginProperties) {
for (int j = 0; j < pp.getServerPropertyUIBox().size(); j++) {
for (int j = 0; j < pp.getServerPropertyUIBox().size(); j++) {
UIPropertyBox serverProperty = pp.getServerPropertyUIBox().get(j);
UIPropertyBox serverProperty = pp.getServerPropertyUIBox().get(j);
String rawValue = serverProperty.getRawValue();
String rawValue = serverProperty.getRawValue();
NormalActionPlugins.getInstance().getActionFromIndex(pp.getIndex())
NormalActionPlugins.getInstance().getActionFromIndex(pp.getIndex())
.getServerProperties().get()
.getServerProperties().get()
.get(serverProperty.getIndex()).setRawValue(rawValue);
.get(serverProperty.getIndex()).setRawValue(rawValue);
}
}
}
}
NormalActionPlugins.getInstance().saveServerSettings();
NormalActionPlugins.getInstance().saveServerSettings();
NormalActionPlugins.getInstance().initPlugins();
NormalActionPlugins.getInstance().initPlugins();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
private ArrayList<PluginProperties> pluginProperties;
private ArrayList<PluginProperties> pluginProperties;
public void showPluginInitError()
public void showPluginInitError()
{
{
Platform.runLater(()->{
Platform.runLater(()->{
pluginsSettingsVBox.getChildren().add(new Label("Plugin init error. Resolve issues and restart."));
pluginsSettingsVBox.getChildren().add(new Label("Plugin init error. Resolve issues and restart."));
saveButton.setVisible(false);
saveButton.setVisible(false);
});
});
}
}
public void loadPlugins() throws MinorException {
public void loadPlugins() throws MinorException {
pluginProperties.clear();
pluginProperties.clear();
List<NormalAction> actions = NormalActionPlugins.getInstance().getPlugins();
List<NormalAction> actions = NormalActionPlugins.getInstance().getPlugins();
Platform.runLater(()-> pluginsSettingsVBox.getChildren().clear());
Platform.runLater(()-> pluginsSettingsVBox.getChildren().clear());
if(actions.size() == 0)
if(actions.size() == 0)
{
{
Platform.runLater(()->{
Platform.runLater(()->{
Label l = new Label("No Plugins Installed.");
Label l = new Label("No Plugins Installed.");
l.getStyleClass().add("plugins_pane_no_plugins_installed_label");
l.getStyleClass().add("plugins_pane_no_plugins_installed_label");
pluginsSettingsVBox.getChildren().add(l);
pluginsSettingsVBox.getChildren().add(l);
saveButton.setVisible(false);
saveButton.setVisible(false);
});
});
return;
return;
}
}
else
else
{
{
Platform.runLater(()->saveButton.setVisible(true));
Platform.runLater(()->saveButton.setVisible(true));
}
}
for(int i = 0; i<actions.size(); i++)
for(int i = 0; i<actions.size(); i++)
{
{
NormalAction action = actions.get(i);
NormalAction action = actions.get(i);
if(!action.isVisibleInServerSettingsPane())
if(!action.isVisibleInServerSettingsPane())
continue;
continue;
Label headingLabel = new Label(action.getName());
Label headingLabel = new Label(action.getName());
headingLabel.getStyleClass().add("plugins_settings_each_plugin_heading_label");
headingLabel.getStyleClass().add("plugins_settings_each_plugin_heading_label");
HBox headerHBox = new HBox(headingLabel);
HBox headerHBox = new HBox(headingLabel);
headerHBox.getStyleClass().add("plugins_settings_each_plugin_header");
headerHBox.getStyleClass().add("plugins_settings_each_plugin_header");
if (action.getHelpLink()!=null)
if (action.getHelpLink()!=null)
{
{
Button helpButton = new Button();
Button helpButton = new Button();
helpButton.getStyleClass().add("plugins_settings_each_plugin_help_button");
helpButton.getStyleClass().add("plugins_settings_each_plugin_help_button");
FontIcon questionIcon = new FontIcon("fas-question");
FontIcon questionIcon = new FontIcon("fas-question");
questionIcon.getStyleClass().add("plugins_settings_each_plugin_help_icon");
questionIcon.getStyleClass().add("plugins_settings_each_plugin_help_icon");
helpButton.setGraphic(questionIcon);
helpButton.setGraphic(questionIcon);
helpButton.setOnAction(event -> hostServices.showDocument(action.getHelpLink()));
helpButton.setOnAction(event -> hostServices.showDocument(action.getHelpLink()));
headerHBox.getChildren().addAll(new SpaceFiller(FillerType.HBox),helpButton);
headerHBox.getChildren().addAll(SpaceFiller.horizontal() ,helpButton);
}
}
Label authorLabel = new Label(action.getAuthor());
Label authorLabel = new Label(action.getAuthor());
authorLabel.getStyleClass().add("plugins_settings_each_plugin_author_label");
authorLabel.getStyleClass().add("plugins_settings_each_plugin_author_label");
Label moduleLabel = new Label(action.getModuleName());
Label moduleLabel = new Label(action.getModuleName());
moduleLabel.getStyleClass().add("plugins_settings_each_plugin_module_label");
moduleLabel.getStyleClass().add("plugins_settings_each_plugin_module_label");
Label versionLabel = new Label("Version : "+action.getVersion().getText());
Label versionLabel = new Label("Version : "+action.getVersion().getText());
versionLabel.getStyleClass().add("plugins_settings_each_plugin_version_label");
versionLabel.getStyleClass().add("plugins_settings_each_plugin_version_label");
VBox serverPropertiesVBox = new VBox();
VBox serverPropertiesVBox = new VBox();
serverPropertiesVBox.getStyleClass().add("plugins_settings_each_plugin_server_properties_box");
serverPropertiesVBox.getStyleClass().add("plugins_settings_each_plugin_server_properties_box");
serverPropertiesVBox.setSpacing(10.0);
serverPropertiesVBox.setSpacing(10.0);
List<Property> serverProperties = action.getServerProperties().get();
List<Property> serverProperties = action.getServerProperties().get();
ArrayList<UIPropertyBox> serverPropertyArrayList = new ArrayList<>();
ArrayList<UIPropertyBox> serverPropertyArrayList = new ArrayList<>();
for(int j =0; j<serverProperties.size(); j++)
for(int j =0; j<serverProperties.size(); j++)
{
{
Property eachProperty = serverProperties.get(j);
Property eachProperty = serverProperties.get(j);
if(!eachProperty.isVisible())
if(!eachProperty.isVisible())
continue;
continue;
Label label = new Label(eachProperty.getDisplayName());
Label label = new Label(eachProperty.getDisplayName());
Region region = new Region();
Region region = new Region();
HBox.setHgrow(region, Priority.ALWAYS);
HBox.setHgrow(region, Priority.ALWAYS);
HBox hBox = new HBox(label, new SpaceFiller(SpaceFiller.FillerType.HBox));
HBox hBox = new HBox(label, SpaceFiller.horizontal());
//hBox.setId(j+"");
//hBox.setId(j+"");
Node controlNode = null;
Node controlNode = null;
if(eachProperty.getControlType() == ControlType.COMBO_BOX)
if(eachProperty.getControlType() == ControlType.COMBO_BOX)
{
{
ComboBox<String> comboBox = new ComboBox<>();
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll(eachProperty.getListValue());
comboBox.getItems().addAll(eachProperty.getListValue());
comboBox.getSelectionModel().select(eachProperty.getSelectedIndex());
comboBox.getSelectionModel().select(eachProperty.getSelectedIndex());
hBox.getChildren().add(comboBox);
hBox.getChildren().add(comboBox);
controlNode = comboBox;
controlNode = comboBox;
}
}
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD)
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD)
{
{
TextField textField = new TextField(eachProperty.getRawValue());
TextField textField = new TextField(eachProperty.getRawValue());
hBox.getChildren().add(textField);
hBox.getChildren().add(textField);
controlNode = textField;
controlNode = textField;
}
}
else if(eachProperty.getControlType() == ControlType.TOGGLE)
else if(eachProperty.getControlType() == ControlType.TOGGLE)
{
{
ToggleButton toggleButton = new ToggleButton();
ToggleButton toggleButton = new ToggleButton();
toggleButton.setSelected(eachProperty.getBoolValue());
toggleButton.setSelected(eachProperty.getBoolValue());
if(eachProperty.getBoolValue())
if(eachProperty.getBoolValue())
toggleButton.setText("ON");
toggleButton.setText("ON");
else
else
toggleButton.setText("OFF");
toggleButton.setText("OFF");
toggleButton.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
toggleButton.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
if(t1)
if(t1)
toggleButton.setText("ON");
toggleButton.setText("ON");
else
else
toggleButton.setText("OFF");
toggleButton.setText("OFF");
});
});
hBox.getChildren().add(toggleButton);
hBox.getChildren().add(toggleButton);
controlNode = toggleButton;
controlNode = toggleButton;
}
}
else if(eachProperty.getControlType() == ControlType.SLIDER_DOUBLE)
else if(eachProperty.getControlType() == ControlType.SLIDER_DOUBLE)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(eachProperty.getDoubleValue());
slider.setValue(eachProperty.getDoubleValue());
slider.setMax(eachProperty.getMaxDoubleValue());
slider.setMax(eachProperty.getMaxDoubleValue());
slider.setMin(eachProperty.getMinDoubleValue());
slider.setMin(eachProperty.getMinDoubleValue());
hBox.getChildren().add(slider);
hBox.getChildren().add(slider);
controlNode = slider;
controlNode = slider;
}
}
else if(eachProperty.getControlType() == ControlType.SLIDER_INTEGER)
else if(eachProperty.getControlType() == ControlType.SLIDER_INTEGER)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(eachProperty.getIntValue());
slider.setValue(eachProperty.getIntValue());
slider.setMax(eachProperty.getMaxIntValue());
slider.setMax(eachProperty.getMaxIntValue());
slider.setMin(eachProperty.getMinIntValue());
slider.setMin(eachProperty.getMinIntValue());
slider.setBlockIncrement(1.0);
slider.setBlockIncrement(1.0);
slider.setSnapToTicks(true);
slider.setSnapToTicks(true);
hBox.getChildren().add(slider);
hBox.getChildren().add(slider);
controlNode = slider;
controlNode = slider;
}
}
UIPropertyBox serverProperty = new UIPropertyBox(j, eachProperty.getDisplayName(), controlNode, eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
UIPropertyBox serverProperty = new UIPropertyBox(j, eachProperty.getDisplayName(), controlNode, eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
serverPropertyArrayList.add(serverProperty);
serverPropertyArrayList.add(serverProperty);
serverPropertiesVBox.getChildren().add(hBox);
serverPropertiesVBox.getChildren().add(hBox);
}
}
PluginProperties pp = new PluginProperties(i, serverPropertyArrayList, action.getName());
PluginProperties pp = new PluginProperties(i, serverPropertyArrayList, action.getName());
pluginProperties.add(pp);
pluginProperties.add(pp);
Platform.runLater(()->{
Platform.runLater(()->{
VBox vBox = new VBox();
VBox vBox = new VBox();
vBox.getStyleClass().add("plugins_settings_each_plugin_box");
vBox.getStyleClass().add("plugins_settings_each_plugin_box");
vBox.setSpacing(5.0);
vBox.setSpacing(5.0);
vBox.getChildren().addAll(headerHBox, authorLabel, moduleLabel, versionLabel, serverPropertiesVBox);
vBox.getChildren().addAll(headerHBox, authorLabel, moduleLabel, versionLabel, serverPropertiesVBox);
if(action.getButtonBar()!=null)
if(action.getButtonBar()!=null)
{
{
HBox buttonBarHBox = new HBox(new SpaceFiller(SpaceFiller.FillerType.HBox), action.getButtonBar());
HBox buttonBarHBox = new HBox(SpaceFiller.horizontal(), action.getButtonBar());
buttonBarHBox.getStyleClass().add("plugins_settings_each_plugin_button_bar");
buttonBarHBox.getStyleClass().add("plugins_settings_each_plugin_button_bar");
vBox.getChildren().add(buttonBarHBox);
vBox.getChildren().add(buttonBarHBox);
}
}
pluginsSettingsVBox.getChildren().add(vBox);
pluginsSettingsVBox.getChildren().add(vBox);
});
});
}
}
}
}
public class PluginProperties
public class PluginProperties
{
{
private int index;
private int index;
private ArrayList<UIPropertyBox> serverProperty;
private ArrayList<UIPropertyBox> serverProperty;
private String name;
private String name;
public PluginProperties(int index, ArrayList<UIPropertyBox> serverProperty, String name)
public PluginProperties(int index, ArrayList<UIPropertyBox> serverProperty, String name)
{
{
this.index = index;
this.index = index;
this.serverProperty = serverProperty;
this.serverProperty = serverProperty;
this.name = name;
this.name = name;
}
}
public String getName()
public String getName()
{
{
return name;
return name;
}
}
public int getIndex() {
public int getIndex() {
return index;
return index;
}
}
public ArrayList<UIPropertyBox> getServerPropertyUIBox() {
public ArrayList<UIPropertyBox> getServerPropertyUIBox() {
return serverProperty;
return serverProperty;
}
}
}
}
}
}
package com.stream_pi.server.window.settings;
package com.stream_pi.server.window.settings;
import com.stream_pi.server.controller.Controller;
import com.stream_pi.server.controller.Controller;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.themeapi.Theme;
import com.stream_pi.theme_api.Theme;
import com.stream_pi.themeapi.Themes;
import com.stream_pi.theme_api.Themes;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class ThemesSettings extends VBox
public class ThemesSettings extends VBox
{
{
private VBox themesSettingsVBox;
private VBox themesSettingsVBox;
private Controller controller;
private Controller controller;
private Logger logger;
private Logger logger;
private HostServices hostServices;
private HostServices hostServices;
public ThemesSettings(HostServices hostServices)
public ThemesSettings(HostServices hostServices)
{
{
this.hostServices = hostServices;
this.hostServices = hostServices;
getStyleClass().add("themes_settings");
getStyleClass().add("themes_settings");
logger = Logger.getLogger(ThemesSettings.class.getName());
logger = Logger.getLogger(ThemesSettings.class.getName());
themesSettingsVBox = new VBox();
themesSettingsVBox = new VBox();
themesSettingsVBox.getStyleClass().add("themes_settings_vbox");
themesSettingsVBox.getStyleClass().add("themes_settings_vbox");
themesSettingsVBox.setAlignment(Pos.TOP_CENTER);
themesSettingsVBox.setAlignment(Pos.TOP_CENTER);
ScrollPane scrollPane = new ScrollPane();
ScrollPane scrollPane = new ScrollPane();
scrollPane.getStyleClass().add("themes_settings_scroll_pane");
scrollPane.getStyleClass().add("themes_settings_scroll_pane");
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
themesSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(10));
themesSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(10));
scrollPane.setContent(themesSettingsVBox);
scrollPane.setContent(themesSettingsVBox);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
setAlignment(Pos.TOP_CENTER);
setAlignment(Pos.TOP_CENTER);
getChildren().addAll(scrollPane);
getChildren().addAll(scrollPane);
toggleButtons = new ArrayList<>();
toggleButtons = new ArrayList<>();
}
}
public void setController(Controller controller)
public void setController(Controller controller)
{
{
this.controller = controller;
this.controller = controller;
}
}
private Themes themes;
private Themes themes;
private String currentThemeFullName;
private String currentThemeFullName;
public void setThemes(Themes themes)
public void setThemes(Themes themes)
{
{
this.themes = themes;
this.themes = themes;
}
}
public void setCurrentThemeFullName(String currentThemeFullName)
public void setCurrentThemeFullName(String currentThemeFullName)
{
{
this.currentThemeFullName = currentThemeFullName;
this.currentThemeFullName = currentThemeFullName;
}
}
private ArrayList<ToggleButton> toggleButtons;
private ArrayList<ToggleButton> toggleButtons;
public void loadThemes()
public void loadThemes()
{
{
toggleButtons.clear();
toggleButtons.clear();
Platform.runLater(()-> themesSettingsVBox.getChildren().clear());
Platform.runLater(()-> themesSettingsVBox.getChildren().clear());
for(int i = 0; i<themes.getThemeList().size(); i++)
for(int i = 0; i<themes.getThemeList().size(); i++)
{
{
Theme theme = themes.getThemeList().get(i);
Theme theme = themes.getThemeList().get(i);
Label shortNameLabel = new Label(theme.getShortName());
Label shortNameLabel = new Label(theme.getShortName());
shortNameLabel.getStyleClass().add("themes_settings_each_theme_heading");
shortNameLabel.getStyleClass().add("themes_settings_each_theme_heading");
Label authorLabel = new Label(theme.getAuthor());
Label authorLabel = new Label(theme.getAuthor());
authorLabel.getStyleClass().add("themes_settings_each_theme_author_label");
authorLabel.getStyleClass().add("themes_settings_each_theme_author_label");
Label fullNameLabel = new Label(theme.getFullName());
Label fullNameLabel = new Label(theme.getFullName());
fullNameLabel.getStyleClass().add("themes_settings_each_theme_full_name_label");
fullNameLabel.getStyleClass().add("themes_settings_each_theme_full_name_label");
HBox topRowHBox = new HBox(shortNameLabel);
HBox topRowHBox = new HBox(shortNameLabel);
topRowHBox.getStyleClass().add("themes_settings_each_theme_header");
topRowHBox.getStyleClass().add("themes_settings_each_theme_header");
Label versionLabel = new Label("Version : "+theme.getVersion().getText());
Label versionLabel = new Label("Version : "+theme.getVersion().getText());
versionLabel.getStyleClass().add("themes_settings_each_theme_version_label");
versionLabel.getStyleClass().add("themes_settings_each_theme_version_label");
if(theme.getWebsite() != null)
if(theme.getWebsite() != null)
{
{
Button helpButton = new Button();
Button helpButton = new Button();
helpButton.getStyleClass().add("themes_settings_each_theme_help_button");
helpButton.getStyleClass().add("themes_settings_each_theme_help_button");
FontIcon questionIcon = new FontIcon("fas-question");
FontIcon questionIcon = new FontIcon("fas-question");
questionIcon.getStyleClass().add("themes_settings_each_theme_help_icon");
questionIcon.getStyleClass().add("themes_settings_each_theme_help_icon");
helpButton.setGraphic(questionIcon);
helpButton.setGraphic(questionIcon);
helpButton.setOnAction(event -> hostServices.showDocument(theme.getWebsite()));
helpButton.setOnAction(event -> hostServices.showDocument(theme.getWebsite()));
topRowHBox.getChildren().addAll(new SpaceFiller(SpaceFiller.FillerType.HBox), helpButton);
topRowHBox.getChildren().addAll(SpaceFiller.horizontal(), helpButton);
}
}
ToggleButton toggleButton = new ToggleButton();
ToggleButton toggleButton = new ToggleButton();
toggleButton.getStyleClass().add("themes_settings_each_theme_toggle_button");
toggleButton.getStyleClass().add("themes_settings_each_theme_toggle_button");
toggleButton.setSelected(theme.getFullName().equals(currentThemeFullName));
toggleButton.setSelected(theme.getFullName().equals(currentThemeFullName));
toggleButton.setId(theme.getFullName());
toggleButton.setId(theme.getFullName());
if(theme.getFullName().equals(currentThemeFullName))
if(theme.getFullName().equals(currentThemeFullName))
{
{
toggleButton.setText("ON");
toggleButton.setText("ON");
toggleButton.setSelected(true);
toggleButton.setSelected(true);
toggleButton.setDisable(true);
toggleButton.setDisable(true);
}
}
else
else
{
{
toggleButton.setText("OFF");
toggleButton.setText("OFF");
}
}
toggleButton.setOnAction(event -> {
toggleButton.setOnAction(event -> {
ToggleButton toggleButton1 = (ToggleButton) event.getSource();
ToggleButton toggleButton1 = (ToggleButton) event.getSource();
toggleButton.setText("ON");
toggleButton.setText("ON");
try {
try {
Config.getInstance().setCurrentThemeFullName(toggleButton1.getId());
Config.getInstance().setCurrentThemeFullName(toggleButton1.getId());
Config.getInstance().save();
Config.getInstance().save();
for(ToggleButton toggleButton2 : toggleButtons)
for(ToggleButton toggleButton2 : toggleButtons)
{
{
if(toggleButton2.getId().equals(Config.getInstance().getCurrentThemeFullName()))
if(toggleButton2.getId().equals(Config.getInstance().getCurrentThemeFullName()))
{
{
toggleButton2.setDisable(true);
toggleButton2.setDisable(true);
toggleButton2.setText("ON");
toggleButton2.setText("ON");
toggleButton2.setSelected(true);
toggleButton2.setSelected(true);
}
}
else
else
{
{
toggleButton2.setDisable(false);
toggleButton2.setDisable(false);
toggleButton2.setText("OFF");
toggleButton2.setText("OFF");
toggleButton2.setSelected(false);
toggleButton2.setSelected(false);
}
}
}
}
controller.initThemes();
controller.initThemes();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
controller.handleSevereException(e);
controller.handleSevereException(e);
}
}
});
});
HBox hBox = new HBox(toggleButton);
HBox hBox = new HBox(toggleButton);
hBox.getStyleClass().add("themes_settings_each_theme_toggle_button_parent");
hBox.getStyleClass().add("themes_settings_each_theme_toggle_button_parent");
hBox.setAlignment(Pos.TOP_RIGHT);
hBox.setAlignment(Pos.TOP_RIGHT);
VBox vBox = new VBox(topRowHBox, authorLabel, fullNameLabel, versionLabel, hBox);
VBox vBox = new VBox(topRowHBox, authorLabel, fullNameLabel, versionLabel, hBox);
vBox.getStyleClass().add("theme_settings_each_theme_box");
vBox.getStyleClass().add("theme_settings_each_theme_box");
Platform.runLater(()->themesSettingsVBox.getChildren().add(vBox));
Platform.runLater(()->themesSettingsVBox.getChildren().add(vBox));
toggleButtons.add(toggleButton);
toggleButtons.add(toggleButton);
}
}
}
}
}
}
module com.stream_pi.server {
module com.stream_pi.server {
uses com.stream_pi.actionapi.action.Action;
uses com.stream_pi.action_api.action.Action;
uses com.stream_pi.actionapi.normalaction.NormalAction;
uses com.stream_pi.action_api.normalaction.NormalAction;
requires com.stream_pi.actionapi;
requires com.stream_pi.action_api;
requires com.stream_pi.util;
requires com.stream_pi.util;
requires com.stream_pi.themeapi;
requires com.stream_pi.theme_api;
requires org.kordamp.ikonli.javafx;
requires org.kordamp.ikonli.javafx;
requires java.xml;
requires java.xml;
requires javafx.base;
requires javafx.base;
requires javafx.graphics;
requires javafx.graphics;
requires javafx.controls;
requires javafx.controls;
requires javafx.media;
requires javafx.media;
requires java.desktop;
requires java.desktop;
requires java.sql;
requires java.sql;
requires org.json;
requires org.json;
exports com.stream_pi.server;
exports com.stream_pi.server;
}
}