client
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>client</artifactId>
<artifactId>client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<version>1.0.0-SNAPSHOT</version>
<url>https://stream-pi.com/</url>
<url>https://stream-pi.com/</url>
<properties>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.release>11</maven.compiler.release>
<javafx.version>16-ea+6</javafx.version>
<javafx.version>16-ea+6</javafx.version>
<client.plugin.version>0.1.36</client.plugin.version>
<client.plugin.version>0.1.36</client.plugin.version>
<ikonli.version>11.5.0</ikonli.version>
<ikonli.version>11.5.0</ikonli.version>
<action.api.version>1.0.0-SNAPSHOT</action.api.version>
<action.api.version>1.0.0-SNAPSHOT</action.api.version>
<util.version>1.0.0-SNAPSHOT</util.version>
<util.version>1.0.0-SNAPSHOT</util.version>
<theme.api.version>1.0.0-SNAPSHOT</theme.api.version>
<theme.api.version>1.0.0-SNAPSHOT</theme.api.version>
<main.class.name>com.StreamPi.Client.Main</main.class.name>
<main.class.name>com.StreamPi.Client.Main</main.class.name>
<JavaFXSDK>/path/to/sdk</JavaFXSDK>
<JavaFXSDK>/path/to/sdk</JavaFXSDK>
</properties>
</properties>
<dependencies>
<dependencies>
<dependency>
<dependency>
<groupId>org.openjfx</groupId>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
<version>${javafx.version}</version>
<!--<systemPath>${JavaFXSDK}/lib/javafx.controls.jar</systemPath>-->
<!--<systemPath>${JavaFXSDK}/lib/javafx.controls.jar</systemPath>-->
</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>${ikonli.version}</version>
<version>${ikonli.version}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>org.kordamp.ikonli</groupId>
<groupId>org.kordamp.ikonli</groupId>
<artifactId>ikonli-javafx</artifactId>
<artifactId>ikonli-javafx</artifactId>
<version>${ikonli.version}</version>
<version>${ikonli.version}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.stream-pi</groupId>
<groupId>com.stream-pi</groupId>
<artifactId>action-api</artifactId>
<artifactId>action-api</artifactId>
<version>${action.api.version}</version>
<version>${action.api.version}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.stream-pi</groupId>
<groupId>com.stream-pi</groupId>
<artifactId>theme-api</artifactId>
<artifactId>theme-api</artifactId>
<version>${theme.api.version}</version>
<version>${theme.api.version}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.stream_pi</groupId>
<groupId>com.stream-pi</groupId>
<artifactId>util</artifactId>
<artifactId>util</artifactId>
<version>${util.version}</version>
<version>${util.version}</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.gluonhq.attach</groupId>
<groupId>com.gluonhq.attach</groupId>
<artifactId>lifecycle</artifactId>
<artifactId>lifecycle</artifactId>
<version>4.0.10</version>
<version>4.0.10</version>
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>com.gluonhq.attach</groupId>
<groupId>com.gluonhq.attach</groupId>
<artifactId>util</artifactId>
<artifactId>util</artifactId>
<version>4.0.10</version>
<version>4.0.10</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>
</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>
<stripDebug>true</stripDebug>
<stripDebug>true</stripDebug>
<compress>2</compress>
<compress>2</compress>
<noHeaderFiles>true</noHeaderFiles>
<noHeaderFiles>true</noHeaderFiles>
<noManPages>true</noManPages>
<noManPages>true</noManPages>
<mainClass>${main.class.name}</mainClass>
<mainClass>${main.class.name}</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>
<target>${clientTarget}</target>
<target>${clientTarget}</target>
<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>${additionalArgs}</list>
<list>${additionalArgs}</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>
<attachList>
<attachList>
<list>lifecycle</list>
<list>lifecycle</list>
</attachList>
</attachList>
<reflectionList>
<reflectionList>
<list>java.util.logging.FileHandler</list>
<list>java.util.logging.FileHandler</list>
</reflectionList>
</reflectionList>
<mainClass>${main.class.name}</mainClass>
<mainClass>${main.class.name}</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>
<profiles>
<profiles>
<profile>
<profile>
<id>android</id>
<id>android</id>
<properties>
<properties>
<clientTarget>android</clientTarget>
<clientTarget>android</clientTarget>
<additionalArgs>-Dsvm.targetName=android</additionalArgs>
<additionalArgs>-Dsvm.targetName=android</additionalArgs>
</properties>
</properties>
</profile>
</profile>
<profile>
<profile>
<id>rpi</id>
<id>rpi</id>
<properties>
<properties>
<clientTarget>linux-aarch64</clientTarget>
<clientTarget>linux-aarch64</clientTarget>
<additionalArgs>-Dsvm.targetName=linux_raspberrypi</additionalArgs>
<additionalArgs>-Dsvm.targetName=linux_raspberrypi</additionalArgs>
</properties>
</properties>
</profile>
</profile>
<profile>
<profile>
<id>windows64</id>
<id>windows64</id>
<properties>
<properties>
<clientTarget>windows</clientTarget>
<clientTarget>windows</clientTarget>
<additionalArgs>-Dsvm.targetName=windows</additionalArgs>
<additionalArgs>-Dsvm.targetName=windows</additionalArgs>
</properties>
</properties>
</profile>
</profile>
<profile>
<profile>
<id>linux64</id>
<id>linux64</id>
<properties>
<properties>
<additionalArgs>-Dsvm.targetName=linux</additionalArgs>
<additionalArgs>-Dsvm.targetName=linux</additionalArgs>
</properties>
</properties>
</profile>
</profile>
</profiles>
</profiles>
<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>
package com.stream_pi.client.connection;
package com.stream_pi.client.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.client.io.Config;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.themeapi.Theme;
import com.stream_pi.theme_api.Theme;
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.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.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class Client extends Thread{
public class Client extends Thread{
private Socket socket;
private Socket socket;
//private Logger logger;
//private Logger logger;
private DataOutputStream dos;
private DataOutputStream dos;
private DataInputStream dis;
private DataInputStream dis;
private AtomicBoolean stop = new AtomicBoolean(false);
private AtomicBoolean stop = new AtomicBoolean(false);
private ClientListener clientListener;
private ClientListener clientListener;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ClientInfo clientInfo;
private ClientInfo clientInfo;
private String serverIP;
private String serverIP;
private int serverPort;
private int serverPort;
private Logger logger;
private Logger logger;
public Client(String serverIP, int serverPort, ClientListener clientListener, ExceptionAndAlertHandler exceptionAndAlertHandler)
public Client(String serverIP, int serverPort, ClientListener clientListener, ExceptionAndAlertHandler exceptionAndAlertHandler)
{
{
this.serverIP = serverIP;
this.serverIP = serverIP;
this.serverPort = serverPort;
this.serverPort = serverPort;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.clientInfo = ClientInfo.getInstance();
this.clientInfo = ClientInfo.getInstance();
this.clientListener = clientListener;
this.clientListener = clientListener;
logger = Logger.getLogger(Client.class.getName());
logger = Logger.getLogger(Client.class.getName());
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
try {
try {
logger.info("Trying to connect to server at "+serverIP+":"+serverPort);
logger.info("Trying to connect to server at "+serverIP+":"+serverPort);
socket = new Socket();
socket = new Socket();
socket.connect(new InetSocketAddress(serverIP, serverPort), 5000);
socket.connect(new InetSocketAddress(serverIP, serverPort), 5000);
clientListener.setConnected(true);
clientListener.setConnected(true);
clientListener.updateSettingsConnectDisconnectButton();
clientListener.updateSettingsConnectDisconnectButton();
logger.info("Connected to "+socket.getRemoteSocketAddress()+" !");
logger.info("Connected to "+socket.getRemoteSocketAddress()+" !");
} catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
clientListener.setConnected(false);
clientListener.setConnected(false);
clientListener.updateSettingsConnectDisconnectButton();
clientListener.updateSettingsConnectDisconnectButton();
throw new MinorException("connection Error", "Unable to connect to server. Please check settings and connection and try again.");
throw new MinorException("connection Error", "Unable to connect to server. Please check settings and connection and try again.");
}
}
try
try
{
{
dos = new DataOutputStream(socket.getOutputStream());
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dis = new DataInputStream(socket.getInputStream());
}
}
catch (IOException e)
catch (IOException e)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
e.printStackTrace();
e.printStackTrace();
throw new MinorException("Unable to set up io Streams to server. Check connection and try again.");
throw new MinorException("Unable to set up io Streams to server. Check connection and try again.");
}
}
start();
start();
} catch (MinorException e)
} catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
return null;
return null;
}
}
}).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)
{
{
disconnect();
disconnect();
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
e.printStackTrace();
e.printStackTrace();
}
}
}
}
public void writeToStream(String text) throws SevereException
public void writeToStream(String text) throws SevereException
{
{
/*try
/*try
{
{
logger.debug(text);
logger.debug(text);
dos.writeUTF(text);
dos.writeUTF(text);
dos.flush();
dos.flush();
}
}
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!");
}*/
}*/
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 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)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Unable to write to io Stream!");
throw new SevereException("Unable to write to io Stream!");
}
}
}
}
@Override
@Override
public void run() {
public void run() {
try
try
{
{
while(!stop.get())
while(!stop.get())
{
{
String msg = "";
String msg = "";
try
try
{
{
String raw = dis.readUTF();
String raw = dis.readUTF();
System.out.println("AAAAAAAAAAAAAAAAAA : "+raw);
System.out.println("AAAAAAAAAAAAAAAAAA : "+raw);
int length = dis.readInt();
int length = dis.readInt();
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);
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);
}
}
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"))
{
{
System.out.println("asdsdsxxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("asdsdsxxxxxxxxxxxxxxxxxxxxxxxxxxx");
String[] secondArgSep = secondArg.split("!!");
String[] secondArgSep = secondArg.split("!!");
String profileID = secondArgSep[0];
String profileID = secondArgSep[0];
String actionID = secondArgSep[1];
String actionID = secondArgSep[1];
clientListener.getClientProfiles().getProfileFromID(profileID).saveActionIcon(actionID, bArr);
clientListener.getClientProfiles().getProfileFromID(profileID).saveActionIcon(actionID, bArr);
Action a = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
Action a = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
clientListener.clearActionBox(a.getLocation().getCol(), a.getLocation().getRow());
clientListener.clearActionBox(a.getLocation().getCol(), a.getLocation().getRow());
clientListener.renderAction(profileID, a);
clientListener.renderAction(profileID, a);
continue;
continue;
}
}
}
}
catch (IOException e)
catch (IOException e)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
e.printStackTrace();
e.printStackTrace();
clientListener.setConnected(false);
clientListener.setConnected(false);
clientListener.updateSettingsConnectDisconnectButton();
clientListener.updateSettingsConnectDisconnectButton();
if(!stop.get())
if(!stop.get())
{
{
//isDisconnect.set(true); //Prevent running disconnect
//isDisconnect.set(true); //Prevent running disconnect
throw new MinorException("Accidentally disconnected from Server! (Failed at readUTF)");
throw new MinorException("Accidentally disconnected from Server! (Failed at readUTF)");
}
}
exit();
exit();
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" : serverDisconnected(msg);
case "disconnect" : serverDisconnected(msg);
break;
break;
case "get_client_details" : sendClientDetails();
case "get_client_details" : sendClientDetails();
break;
break;
case "get_profiles" : sendProfileNamesToServer();
case "get_profiles" : sendProfileNamesToServer();
break;
break;
case "get_profile_details": sendProfileDetailsToServer(sep[1]);
case "get_profile_details": sendProfileDetailsToServer(sep[1]);
break;
break;
case "save_action_details": saveActionDetails(sep);
case "save_action_details": saveActionDetails(sep);
break;
break;
case "delete_action": deleteAction(sep[1], sep[2]);
case "delete_action": deleteAction(sep[1], sep[2]);
break;
break;
case "get_themes": sendThemesToServer();
case "get_themes": sendThemesToServer();
break;
break;
case "save_client_details": saveClientDetails(sep);
case "save_client_details": saveClientDetails(sep);
break;
break;
case "save_client_profile": saveProfileDetails(sep);
case "save_client_profile": saveProfileDetails(sep);
break;
break;
case "delete_profile": deleteProfile(sep[1]);
case "delete_profile": deleteProfile(sep[1]);
break;
break;
case "action_failed": actionFailed(sep[1], sep[2]);
case "action_failed": actionFailed(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 (SevereException e)
catch (SevereException e)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
//commands
//commands
/*public void receiveActionIcon(String[] sep) throws MinorException {
/*public void receiveActionIcon(String[] sep) throws MinorException {
String profileID = sep[1];
String profileID = sep[1];
String actionID = sep[2];
String actionID = sep[2];
int bytesToRead = Integer.parseInt(sep[3]);
int bytesToRead = Integer.parseInt(sep[3]);
int port = Integer.parseInt(sep[4]);
int port = Integer.parseInt(sep[4]);
try
try
{
{
Socket tempSocket = new Socket(socket.getInetAddress(), port);
Socket tempSocket = new Socket(socket.getInetAddress(), port);
tempSocket.setReceiveBufferSize(bytesToRead);
tempSocket.setReceiveBufferSize(bytesToRead);
tempSocket.setSoTimeout(10000);
tempSocket.setSoTimeout(10000);
DataInputStream dataInputStream = new DataInputStream(tempSocket.getInputStream());
DataInputStream dataInputStream = new DataInputStream(tempSocket.getInputStream());
byte[] dataIcon = new byte[bytesToRead];
byte[] dataIcon = new byte[bytesToRead];
dataInputStream.read(dataIcon);
dataInputStream.read(dataIcon);
clientProfiles.getProfileFromID(profileID).getActionFromID(actionID).setIcon(dataIcon);
clientProfiles.getProfileFromID(profileID).getActionFromID(actionID).setIcon(dataIcon);
dataInputStream.close();
dataInputStream.close();
tempSocket.close();
tempSocket.close();
}
}
catch (IOException e)
catch (IOException e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new MinorException("Unable to Receive icon");
throw new MinorException("Unable to Receive icon");
}
}
}*/
}*/
public void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
public void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
{
{
try
try
{
{
Thread.sleep(50);
Thread.sleep(50);
dos.writeUTF("action_icon::"+profileID+"!!"+actionID+"!!::"+icon.length);
dos.writeUTF("action_icon::"+profileID+"!!"+actionID+"!!::"+icon.length);
dos.flush();
dos.flush();
dos.writeInt(icon.length);
dos.writeInt(icon.length);
dos.flush();
dos.flush();
write(icon);
write(icon);
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 void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
/*public void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
{
{
try
try
{
{
ServerSocket tmpServer = new ServerSocket(0);
ServerSocket tmpServer = new ServerSocket(0);
dos.writeUTF("action_icon::"+
dos.writeUTF("action_icon::"+
profileID+"::"+
profileID+"::"+
actionID+"::"+
actionID+"::"+
icon.length+"::"+
icon.length+"::"+
tmpServer.getLocalPort()+"::");
tmpServer.getLocalPort()+"::");
Socket socket = tmpServer.accept();
Socket socket = tmpServer.accept();
socket.setSendBufferSize(icon.length);
socket.setSendBufferSize(icon.length);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.write(icon);
dataOutputStream.write(icon);
dataOutputStream.close();
dataOutputStream.close();
tmpServer.close();
tmpServer.close();
}
}
catch (IOException e)
catch (IOException e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}*/
}*/
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 server disconnect message ...");
logger.info("Sending server disconnect message ...");
writeToStream("disconnect::"+message+"::");
writeToStream("disconnect::"+message+"::");
try
try
{
{
if(!socket.isClosed())
if(!socket.isClosed())
socket.close();
socket.close();
clientListener.setConnected(false);
clientListener.setConnected(false);
clientListener.updateSettingsConnectDisconnectButton();
clientListener.updateSettingsConnectDisconnectButton();
}
}
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 sendThemesToServer() throws SevereException
public void sendThemesToServer() throws SevereException
{
{
StringBuilder finalQuery = new StringBuilder("themes::");
StringBuilder finalQuery = new StringBuilder("themes::");
for(Theme theme : clientListener.getThemes().getThemeList())
for(Theme theme : clientListener.getThemes().getThemeList())
{
{
finalQuery.append(theme.getFullName())
finalQuery.append(theme.getFullName())
.append("__")
.append("__")
.append(theme.getShortName())
.append(theme.getShortName())
.append("__")
.append("__")
.append(theme.getAuthor())
.append(theme.getAuthor())
.append("__")
.append("__")
.append(theme.getVersion().getText())
.append(theme.getVersion().getText())
.append("__::");
.append("__::");
}
}
writeToStream(finalQuery.toString());
writeToStream(finalQuery.toString());
}
}
public void sendActionIcon(String clientProfileID, String actionID) throws SevereException
public void sendActionIcon(String clientProfileID, String actionID) throws SevereException
{
{
System.out.println("sending action icon "+clientProfileID+", "+actionID);
System.out.println("sending action icon "+clientProfileID+", "+actionID);
sendIcon(clientProfileID, actionID, clientListener.getClientProfiles().getProfileFromID(clientProfileID).getActionFromID(actionID).getIconAsByteArray());
sendIcon(clientProfileID, actionID, clientListener.getClientProfiles().getProfileFromID(clientProfileID).getActionFromID(actionID).getIconAsByteArray());
}
}
public void serverDisconnected(String message)
public void serverDisconnected(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];
exceptionAndAlertHandler.onAlert("Disconnected from Server", txt, StreamPiAlertType.WARNING);
exceptionAndAlertHandler.onAlert("Disconnected from Server", txt, StreamPiAlertType.WARNING);
if(!socket.isClosed()) {
if(!socket.isClosed()) {
try {
try {
socket.close();
socket.close();
} catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
clientListener.setConnected(false);
clientListener.setConnected(false);
clientListener.updateSettingsConnectDisconnectButton();
clientListener.updateSettingsConnectDisconnectButton();
}
}
public void sendClientDetails() throws SevereException
public void sendClientDetails() throws SevereException
{
{
Version clientVersion = clientInfo.getVersion();
Version clientVersion = clientInfo.getVersion();
ReleaseStatus releaseStatus = clientInfo.getReleaseStatus();
ReleaseStatus releaseStatus = clientInfo.getReleaseStatus();
Version clientCommsStandard = clientInfo.getCommsStandardVersion();
Version clientCommsStandard = clientInfo.getCommsStandardVersion();
Version clientMinThemeStandard = clientInfo.getMinThemeSupportVersion();
Version clientMinThemeStandard = clientInfo.getMinThemeSupportVersion();
String clientNickname = Config.getInstance().getClientNickName();
String clientNickname = Config.getInstance().getClientNickName();
double screenWidth = Config.getInstance().getStartupWindowWidth();
double screenWidth = Config.getInstance().getStartupWindowWidth();
double screenHeight = Config.getInstance().getStartupWindowHeight();
double screenHeight = Config.getInstance().getStartupWindowHeight();
Platform OS = clientInfo.getPlatformType();
Platform OS = clientInfo.getPlatformType();
String defaultProfileID = Config.getInstance().getStartupProfileID();
String defaultProfileID = Config.getInstance().getStartupProfileID();
writeToStream("client_details::"+
writeToStream("client_details::"+
clientVersion.getText()+"::"+
clientVersion.getText()+"::"+
releaseStatus+"::"+
releaseStatus+"::"+
clientCommsStandard.getText()+"::"+
clientCommsStandard.getText()+"::"+
clientMinThemeStandard.getText()+"::"+
clientMinThemeStandard.getText()+"::"+
clientNickname+"::"+
clientNickname+"::"+
screenWidth+"::"+
screenWidth+"::"+
screenHeight+"::"+
screenHeight+"::"+
OS+"::" +
OS+"::" +
defaultProfileID+"::"+
defaultProfileID+"::"+
clientListener.getDefaultThemeFullName()+"::");
clientListener.getDefaultThemeFullName()+"::");
}
}
public void sendProfileNamesToServer() throws SevereException
public void sendProfileNamesToServer() throws SevereException
{
{
StringBuilder finalQuery = new StringBuilder("profiles::");
StringBuilder finalQuery = new StringBuilder("profiles::");
finalQuery.append(clientListener.getClientProfiles().getClientProfiles().size()).append("::");
finalQuery.append(clientListener.getClientProfiles().getClientProfiles().size()).append("::");
for(ClientProfile clientProfile : clientListener.getClientProfiles().getClientProfiles())
for(ClientProfile clientProfile : clientListener.getClientProfiles().getClientProfiles())
{
{
finalQuery.append(clientProfile.getID()).append("::");
finalQuery.append(clientProfile.getID()).append("::");
}
}
writeToStream(finalQuery.toString());
writeToStream(finalQuery.toString());
}
}
public void sendProfileDetailsToServer(String ID) throws SevereException
public void sendProfileDetailsToServer(String ID) throws SevereException
{
{
StringBuilder finalQuery = new StringBuilder("profile_details::");
StringBuilder finalQuery = new StringBuilder("profile_details::");
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(ID);
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(ID);
finalQuery.append(ID).append("::");
finalQuery.append(ID).append("::");
finalQuery.append(clientProfile.getName())
finalQuery.append(clientProfile.getName())
.append("::")
.append("::")
.append(clientProfile.getRows())
.append(clientProfile.getRows())
.append("::")
.append("::")
.append(clientProfile.getCols())
.append(clientProfile.getCols())
.append("::")
.append("::")
.append(clientProfile.getActionSize())
.append(clientProfile.getActionSize())
.append("::")
.append("::")
.append(clientProfile.getActionGap())
.append(clientProfile.getActionGap())
.append("::");
.append("::");
writeToStream(finalQuery.toString());
writeToStream(finalQuery.toString());
for(Action action : clientProfile.getActions())
for(Action action : clientProfile.getActions())
{
{
sendActionDetails(clientProfile.getID(), action);
sendActionDetails(clientProfile.getID(), action);
}
}
for(Action action : clientProfile.getActions())
for(Action action : clientProfile.getActions())
{
{
if(action.isHasIcon())
if(action.isHasIcon())
{
{
System.out.println("23123123123 : "+action.getID() + action.isHasIcon());
System.out.println("23123123123 : "+action.getID() + action.isHasIcon());
sendActionIcon(clientProfile.getID(), action.getID());
sendActionIcon(clientProfile.getID(), action.getID());
}
}
}
}
}
}
public void sendActionDetails(String profileID, Action action) throws SevereException {
public void sendActionDetails(String profileID, Action action) throws SevereException {
if(action == null)
if(action == null)
{
{
logger.info("NO SUCH ACTION");
logger.info("NO SUCH ACTION");
return;
return;
}
}
StringBuilder finalQuery = new StringBuilder("action_details::");
StringBuilder finalQuery = new StringBuilder("action_details::");
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());
}
}
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 saveActionDetails(String[] sep)
public void saveActionDetails(String[] sep)
{
{
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);
if(actionType == ActionType.NORMAL)
if(actionType == ActionType.NORMAL)
{
{
try
try
{
{
action.setVersion(new Version(sep[4]));
action.setVersion(new Version(sep[4]));
action.setModuleName(sep[5]);
action.setModuleName(sep[5]);
}
}
catch (Exception e)
catch (Exception e)
{
{
logger.severe(e.getMessage());
logger.severe(e.getMessage());
e.printStackTrace();
e.printStackTrace();
}
}
}
}
action.setBgColourHex(bgColorHex);
action.setBgColourHex(bgColorHex);
action.setShowIcon(isShowIcon);
action.setShowIcon(isShowIcon);
action.setHasIcon(isHasIcon);
action.setHasIcon(isHasIcon);
System.out.println("IS HAS ICON : "+isHasIcon+", IS SHOW ICON :"+isShowIcon);
System.out.println("IS HAS ICON : "+isHasIcon+", IS SHOW ICON :"+isShowIcon);
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[] 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);
String parent = sep[17];
String parent = sep[17];
action.setParent(parent);
action.setParent(parent);
try
try
{
{
Action old = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(action.getID());
Action old = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(action.getID());
if(old != null)
if(old != null)
{
{
if(action.isHasIcon())
if(action.isHasIcon())
action.setIcon(clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(action.getID()).getIconAsByteArray());
action.setIcon(clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(action.getID()).getIconAsByteArray());
}
}
clientListener.getClientProfiles().getProfileFromID(profileID).addAction(action);
clientListener.getClientProfiles().getProfileFromID(profileID).addAction(action);
System.out.println("XXXXXXXXXXX " +action.isHasIcon());
System.out.println("XXXXXXXXXXX " +action.isHasIcon());
//clientListener.getClientProfiles().getProfileFromID(profileID).saveActions();
//clientListener.getClientProfiles().getProfileFromID(profileID).saveActions();
clientListener.getClientProfiles().getProfileFromID(profileID).saveAction(action);
clientListener.getClientProfiles().getProfileFromID(profileID).saveAction(action);
if(clientListener.getCurrentProfile().getID().equals(profileID) && action.getLocation().getCol()!=-1)
if(clientListener.getCurrentProfile().getID().equals(profileID) && action.getLocation().getCol()!=-1)
{
{
javafx.application.Platform.runLater(()->{
javafx.application.Platform.runLater(()->{
ActionBox box = clientListener.getActionBox(action.getLocation().getCol(), action.getLocation().getRow());
ActionBox box = clientListener.getActionBox(action.getLocation().getCol(), action.getLocation().getRow());
System.out.println(box==null);
System.out.println(box==null);
System.out.println("GATYYY : "+action.getLocation().getCol()+","+action.getLocation().getRow());
System.out.println("GATYYY : "+action.getLocation().getCol()+","+action.getLocation().getRow());
box.clear();
box.clear();
box.setAction(action);
box.setAction(action);
box.baseInit();
box.baseInit();
box.init();
box.init();
});
});
}
}
//clientListener.clearActionBox(action.getLocation().getCol(), action.getLocation().getRow());
//clientListener.clearActionBox(action.getLocation().getCol(), action.getLocation().getRow());
//clientListener.renderAction(profileID, action);
//clientListener.renderAction(profileID, action);
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
}
}
public void deleteAction(String profileID, String actionID)
public void deleteAction(String profileID, String actionID)
{
{
try
try
{
{
Action acc = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
Action acc = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
if(acc.getActionType() == ActionType.FOLDER)
if(acc.getActionType() == ActionType.FOLDER)
{
{
ArrayList<String> idsToBeRemoved = new ArrayList<>();
ArrayList<String> idsToBeRemoved = new ArrayList<>();
ArrayList<String> folders = new ArrayList<>();
ArrayList<String> folders = new ArrayList<>();
String folderToBeDeletedID = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID).getID();
String folderToBeDeletedID = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID).getID();
folders.add(folderToBeDeletedID);
folders.add(folderToBeDeletedID);
boolean startOver = true;
boolean startOver = true;
while(startOver)
while(startOver)
{
{
startOver = false;
startOver = false;
for(Action action : clientListener.getClientProfiles().getProfileFromID(profileID).getActions())
for(Action action : clientListener.getClientProfiles().getProfileFromID(profileID).getActions())
{
{
if(folders.contains(action.getParent()))
if(folders.contains(action.getParent()))
{
{
if(!idsToBeRemoved.contains(action.getID()))
if(!idsToBeRemoved.contains(action.getID()))
{
{
idsToBeRemoved.add(action.getID());
idsToBeRemoved.add(action.getID());
if(action.getActionType() == ActionType.FOLDER)
if(action.getActionType() == ActionType.FOLDER)
{
{
folders.add(action.getID());
folders.add(action.getID());
startOver = true;
startOver = true;
}
}
}
}
}
}
}
}
}
}
for(String ids : idsToBeRemoved)
for(String ids : idsToBeRemoved)
{
{
clientListener.getClientProfiles().getProfileFromID(profileID).removeAction(ids);
clientListener.getClientProfiles().getProfileFromID(profileID).removeAction(ids);
}
}
}
}
else if (acc.getActionType() == ActionType.COMBINE)
else if (acc.getActionType() == ActionType.COMBINE)
{
{
for(Property property : acc.getClientProperties().get())
for(Property property : acc.getClientProperties().get())
{
{
clientListener.getClientProfiles().getProfileFromID(profileID).removeAction(property.getRawValue());
clientListener.getClientProfiles().getProfileFromID(profileID).removeAction(property.getRawValue());
}
}
}
}
clientListener.getClientProfiles().getProfileFromID(profileID).removeAction(acc.getID());
clientListener.getClientProfiles().getProfileFromID(profileID).removeAction(acc.getID());
clientListener.getClientProfiles().getProfileFromID(profileID).saveActions();
clientListener.getClientProfiles().getProfileFromID(profileID).saveActions();
if(acc.getLocation().getCol()!=-1)
if(acc.getLocation().getCol()!=-1)
{
{
clientListener.clearActionBox(acc.getLocation().getCol(), acc.getLocation().getRow());
clientListener.clearActionBox(acc.getLocation().getCol(), acc.getLocation().getRow());
clientListener.addBlankActionBox(acc.getLocation().getCol(), acc.getLocation().getRow());
clientListener.addBlankActionBox(acc.getLocation().getCol(), acc.getLocation().getRow());
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
}
}
public void saveClientDetails(String[] sep)
public void saveClientDetails(String[] sep)
{
{
try
try
{
{
Config.getInstance().setNickName(sep[1]);
Config.getInstance().setNickName(sep[1]);
String oldWidth = Config.getInstance().getStartupWindowWidth()+"";
String oldWidth = Config.getInstance().getStartupWindowWidth()+"";
String oldHeight = Config.getInstance().getStartupWindowHeight()+"";
String oldHeight = Config.getInstance().getStartupWindowHeight()+"";
Config.getInstance().setStartupWindowSize(
Config.getInstance().setStartupWindowSize(
Double.parseDouble(sep[2]),
Double.parseDouble(sep[2]),
Double.parseDouble(sep[3])
Double.parseDouble(sep[3])
);
);
Config.getInstance().setStartupProfileID(sep[4]);
Config.getInstance().setStartupProfileID(sep[4]);
String oldThemeFullName = Config.getInstance().getCurrentThemeFullName();
String oldThemeFullName = Config.getInstance().getCurrentThemeFullName();
Config.getInstance().setCurrentThemeFullName(sep[5]);
Config.getInstance().setCurrentThemeFullName(sep[5]);
if(!oldHeight.equals(sep[3]) || !oldWidth.equals(sep[2]) || !oldThemeFullName.equals(sep[5]))
if(!oldHeight.equals(sep[3]) || !oldWidth.equals(sep[2]) || !oldThemeFullName.equals(sep[5]))
javafx.application.Platform.runLater(()-> clientListener.init());
javafx.application.Platform.runLater(()-> clientListener.init());
Config.getInstance().save();
Config.getInstance().save();
javafx.application.Platform.runLater(()->clientListener.loadSettings());
javafx.application.Platform.runLater(()->clientListener.loadSettings());
}
}
catch (SevereException e)
catch (SevereException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
}
}
public void saveProfileDetails(String[] sep) throws SevereException, MinorException
public void saveProfileDetails(String[] sep) throws SevereException, MinorException
{
{
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(sep[1]);
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(sep[1]);
if(clientProfile == null)
if(clientProfile == null)
{
{
clientProfile = new ClientProfile(new File(Config.getInstance().getProfilesPath().toString()+"/"+sep[1]+".xml"),
clientProfile = new ClientProfile(new File(Config.getInstance().getProfilesPath().toString()+"/"+sep[1]+".xml"),
Config.getInstance().getIconsPath());
Config.getInstance().getIconsPath());
}
}
clientProfile.setName(sep[2]);
clientProfile.setName(sep[2]);
clientProfile.setRows(Integer.parseInt(sep[3]));
clientProfile.setRows(Integer.parseInt(sep[3]));
clientProfile.setCols(Integer.parseInt(sep[4]));
clientProfile.setCols(Integer.parseInt(sep[4]));
clientProfile.setActionSize(Integer.parseInt(sep[5]));
clientProfile.setActionSize(Integer.parseInt(sep[5]));
clientProfile.setActionGap(Integer.parseInt(sep[6]));
clientProfile.setActionGap(Integer.parseInt(sep[6]));
try
try
{
{
clientListener.getClientProfiles().addProfile(clientProfile);
clientListener.getClientProfiles().addProfile(clientProfile);
clientProfile.saveProfileDetails();
clientProfile.saveProfileDetails();
clientListener.refreshGridIfCurrent(sep[1]);
clientListener.refreshGridIfCurrent(sep[1]);
javafx.application.Platform.runLater(()->clientListener.loadSettings());
javafx.application.Platform.runLater(()->clientListener.loadSettings());
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}
}
public void deleteProfile(String ID)
public void deleteProfile(String ID)
{
{
clientListener.getClientProfiles().deleteProfile(clientListener.getClientProfiles().getProfileFromID(ID));
clientListener.getClientProfiles().deleteProfile(clientListener.getClientProfiles().getProfileFromID(ID));
}
}
public void onActionClicked(String profileID, String actionID) throws SevereException {
public void onActionClicked(String profileID, String actionID) throws SevereException {
writeToStream("action_clicked::"+profileID+"::"+actionID+"::");
writeToStream("action_clicked::"+profileID+"::"+actionID+"::");
}
}
public void actionFailed(String profileID, String actionID)
public void actionFailed(String profileID, String actionID)
{
{
clientListener.onActionFailed(profileID, actionID);
clientListener.onActionFailed(profileID, actionID);
}
}
}
}
package com.stream_pi.client.connection;
package com.stream_pi.client.connection;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
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;
public interface ClientListener {
public interface ClientListener {
void onActionFailed(String profileID, String actionID);
void onActionFailed(String profileID, String actionID);
void onNormalActionClicked(String profileID, String actionID);
void onNormalActionClicked(String profileID, String actionID);
ClientProfiles getClientProfiles();
ClientProfiles getClientProfiles();
Themes getThemes();
Themes getThemes();
String getDefaultThemeFullName();
String getDefaultThemeFullName();
void renderRootDefaultProfile() throws SevereException;
void renderRootDefaultProfile() throws SevereException;
void setConnected(boolean isConnected);
void setConnected(boolean isConnected);
boolean isConnected();
boolean isConnected();
void renderProfile(ClientProfile clientProfile);
void renderProfile(ClientProfile clientProfile);
void clearActionBox(int col, int row);
void clearActionBox(int col, int row);
void addBlankActionBox(int col, int row);
void addBlankActionBox(int col, int row);
void renderAction(String currentProfileID, Action action);
void renderAction(String currentProfileID, Action action);
void refreshGridIfCurrent(String currentProfileID);
void refreshGridIfCurrent(String currentProfileID);
ActionBox getActionBox(int col, int row);
ActionBox getActionBox(int col, int row);
ClientProfile getCurrentProfile();
ClientProfile getCurrentProfile();
Theme getCurrentTheme();
Theme getCurrentTheme();
void init();
void init();
void disconnect(String message) throws SevereException;
void disconnect(String message) throws SevereException;
void setupClientConnection();
void setupClientConnection();
void updateSettingsConnectDisconnectButton();
void updateSettingsConnectDisconnectButton();
void onCloseRequest();
void onCloseRequest();
void loadSettings();
void loadSettings();
}
}
syntax = "proto3";
package protos;
option java_package = "com.StreamPi.Client.Connection.protos";
option java_outer_classname = "ClientConnectionProtos";
message ClientAction
{
string moduleName = 1;
string id = 2;
enum ActionType
{
FOLDER = 0;
COMBINE = 1;
NORMAL = 2;
}
ActionType actionType = 3;
int32 locationX = 4;
int32 locationY = 5;
bool hasIcon = 6;
string name = 7;
string actionName = 8;
repeated ClientProperty clientProperties = 9;
}
message ClientProperty
{
string name = 1;
string value = 2;
}
message ClientProfile
{
string name = 1;
string id = 2;
int32 rows = 3;
int32 cols = 4;
int32 actionSize = 5;
int32 actionGap = 6;
repeated ClientAction actions = 7;
}
syntax = "proto3";
package protos;
option java_package = "com.StreamPi.Client.Connection.protos";
option java_outer_classname = "ClientGRPC";
import "com/StreamPi/Client/Connection/protos/ClientConnectionProtos.proto";
service Connection
{
}
package com.stream_pi.client.controller;
package com.stream_pi.client.controller;
import com.stream_pi.actionapi.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.client.connection.Client;
import com.stream_pi.client.connection.Client;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.window.Base;
import com.stream_pi.client.window.Base;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
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.gluonhq.attach.lifecycle.LifecycleService;
import com.gluonhq.attach.lifecycle.LifecycleService;
import com.gluonhq.attach.util.Services;
import com.gluonhq.attach.util.Services;
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.scene.Node;
import javafx.scene.Node;
import javafx.util.Duration;
import javafx.util.Duration;
import java.io.*;
import java.io.*;
public class Controller extends Base
public class Controller extends Base
{
{
private Client client;
private Client client;
public Controller()
public Controller()
{
{
client = null;
client = null;
}
}
private boolean firstRun = true;
private boolean firstRun = true;
@Override
@Override
public void init()
public void init()
{
{
try
try
{
{
if(firstRun)
if(firstRun)
initBase();
initBase();
applyDefaultTheme();
applyDefaultTheme();
if(getClientInfo().getPlatformType()!= com.stream_pi.util.platform.Platform.ANDROID && getClientInfo().getPlatformType() != com.stream_pi.util.platform.Platform.IOS) {
if(getClientInfo().getPlatformType()!= com.stream_pi.util.platform.Platform.ANDROID && getClientInfo().getPlatformType() != com.stream_pi.util.platform.Platform.IOS) {
getStage().setWidth(getConfig().getStartupWindowWidth());
getStage().setWidth(getConfig().getStartupWindowWidth());
getStage().setHeight(getConfig().getStartupWindowHeight());
getStage().setHeight(getConfig().getStartupWindowHeight());
getStage().centerOnScreen();
getStage().centerOnScreen();
setupFlags();
setupFlags();
}
}
setupDashWindow();
setupDashWindow();
getStage().show();
getStage().show();
requestFocus();
requestFocus();
if(Config.getInstance().isFirstTimeUse())
if(Config.getInstance().isFirstTimeUse())
return;
return;
setupSettingsWindowsAnimations();
setupSettingsWindowsAnimations();
getDashboardPane().getSettingsButton().setOnAction(event -> {
getDashboardPane().getSettingsButton().setOnAction(event -> {
openSettingsTimeLine.play();
openSettingsTimeLine.play();
});
});
getSettingsPane().getCloseButton().setOnAction(event -> {
getSettingsPane().getCloseButton().setOnAction(event -> {
closeSettingsTimeLine.play();
closeSettingsTimeLine.play();
});
});
setClientProfiles(new ClientProfiles(new File(getConfig().getProfilesPath()), getConfig().getStartupProfileID()));
setClientProfiles(new ClientProfiles(new File(getConfig().getProfilesPath()), getConfig().getStartupProfileID()));
if(getClientProfiles().getLoadingErrors().size() > 0)
if(getClientProfiles().getLoadingErrors().size() > 0)
{
{
StringBuilder errors = new StringBuilder("Please rectify the following errors and try again");
StringBuilder errors = new StringBuilder("Please rectify the following errors and try again");
for(MinorException exception : getClientProfiles().getLoadingErrors())
for(MinorException exception : getClientProfiles().getLoadingErrors())
{
{
errors.append("\n * ")
errors.append("\n * ")
.append(exception.getMessage());
.append(exception.getMessage());
}
}
throw new MinorException("Profiles", errors.toString());
throw new MinorException("Profiles", errors.toString());
}
}
renderRootDefaultProfile();
renderRootDefaultProfile();
loadSettings();
loadSettings();
if(firstRun)
if(firstRun)
{
{
setupClientConnection();
setupClientConnection();
firstRun = false;
firstRun = false;
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
return;
return;
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
return;
return;
}
}
}
}
@Override
@Override
public void setupClientConnection()
public void setupClientConnection()
{
{
Platform.runLater(()->getSettingsPane().setDisableStatus(true));
Platform.runLater(()->getSettingsPane().setDisableStatus(true));
client = new Client(getConfig().getSavedServerHostNameOrIP(), getConfig().getSavedServerPort(), this, this);
client = new Client(getConfig().getSavedServerHostNameOrIP(), getConfig().getSavedServerPort(), this, this);
}
}
@Override
@Override
public void updateSettingsConnectDisconnectButton() {
public void updateSettingsConnectDisconnectButton() {
getSettingsPane().setConnectDisconnectButtonStatus();
getSettingsPane().setConnectDisconnectButtonStatus();
}
}
@Override
@Override
public void disconnect(String message) throws SevereException {
public void disconnect(String message) throws SevereException {
client.disconnect(message);
client.disconnect(message);
}
}
public void setupDashWindow()
public void setupDashWindow()
{
{
getStage().setTitle("Stream-Pi Client");
getStage().setTitle("Stream-Pi Client");
getStage().setOnCloseRequest(e->onCloseRequest());
getStage().setOnCloseRequest(e->onCloseRequest());
}
}
@Override
@Override
public void onCloseRequest()
public void onCloseRequest()
{
{
if(isConnected())
if(isConnected())
client.exit();
client.exit();
getLogger().info("Shut down");
getLogger().info("Shut down");
closeLogger();
closeLogger();
if (ClientInfo.getInstance().getPlatformType() == com.stream_pi.util.platform.Platform.ANDROID)
if (ClientInfo.getInstance().getPlatformType() == com.stream_pi.util.platform.Platform.ANDROID)
Services.get(LifecycleService.class).ifPresent(LifecycleService::shutdown);
Services.get(LifecycleService.class).ifPresent(LifecycleService::shutdown);
}
}
@Override
@Override
public void loadSettings() {
public void loadSettings() {
try {
try {
getSettingsPane().loadData();
getSettingsPane().loadData();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
}
}
private Timeline openSettingsTimeLine;
private Timeline openSettingsTimeLine;
private Timeline closeSettingsTimeLine;
private Timeline closeSettingsTimeLine;
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 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 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 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))
);
);
openSettingsTimeLine.setOnFinished(event1 -> settingsNode.toFront());
openSettingsTimeLine.setOnFinished(event1 -> 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 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 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 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))
);
);
closeSettingsTimeLine.setOnFinished(event1 -> {
closeSettingsTimeLine.setOnFinished(event1 -> {
dashboardNode.toFront();
dashboardNode.toFront();
Platform.runLater(()-> {
Platform.runLater(()-> {
try {
try {
getSettingsPane().loadData();
getSettingsPane().loadData();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
});
});
});
});
}
}
@Override
@Override
public void handleMinorException(MinorException e)
public void handleMinorException(MinorException e)
{
{
Platform.runLater(()-> genNewAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
Platform.runLater(()-> genNewAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
}
}
@Override
@Override
public void handleSevereException(SevereException e)
public void handleSevereException(SevereException e)
{
{
Platform.runLater(()->
Platform.runLater(()->
{
{
StreamPiAlert alert = genNewAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
StreamPiAlert alert = genNewAlert(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)
{
{
onCloseRequest();
onCloseRequest();
Platform.exit();
Platform.exit();
}
}
});
});
alert.show();
alert.show();
});
});
}
}
@Override
@Override
public void onAlert(String title, String body, StreamPiAlertType alertType) {
public void onAlert(String title, String body, StreamPiAlertType alertType) {
Platform.runLater(()-> genNewAlert(title, body, alertType).show());
Platform.runLater(()-> genNewAlert(title, body, alertType).show());
}
}
public StreamPiAlert genNewAlert(String title, String message, StreamPiAlertType alertType)
public StreamPiAlert genNewAlert(String title, String message, StreamPiAlertType alertType)
{
{
StreamPiAlert alert = new StreamPiAlert(title, message, alertType);
StreamPiAlert alert = new StreamPiAlert(title, message, alertType);
return alert;
return alert;
}
}
private boolean isConnected = false;
private boolean isConnected = false;
@Override
@Override
public void onActionFailed(String profileID, String actionID) {
public void onActionFailed(String profileID, String actionID) {
Platform.runLater(()-> getDashboardPane().getActionGridPane().actionFailed(profileID, actionID));
Platform.runLater(()-> getDashboardPane().getActionGridPane().actionFailed(profileID, actionID));
}
}
@Override
@Override
public void onNormalActionClicked(String profileID, String actionID) {
public void onNormalActionClicked(String profileID, String actionID) {
try {
try {
client.onActionClicked(profileID, actionID);
client.onActionClicked(profileID, actionID);
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
}
}
@Override
@Override
public void setConnected(boolean isConnected) {
public void setConnected(boolean isConnected) {
this.isConnected = isConnected;
this.isConnected = isConnected;
}
}
@Override
@Override
public ActionBox getActionBox(int col, int row)
public ActionBox getActionBox(int col, int row)
{
{
return getDashboardPane().getActionGridPane().getActionBox(col, row);
return getDashboardPane().getActionGridPane().getActionBox(col, row);
}
}
@Override
@Override
public boolean isConnected()
public boolean isConnected()
{
{
return isConnected;
return isConnected;
}
}
@Override
@Override
public void renderProfile(ClientProfile clientProfile) {
public void renderProfile(ClientProfile clientProfile) {
try {
try {
getDashboardPane().renderProfile(clientProfile);
getDashboardPane().renderProfile(clientProfile);
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
}
}
@Override
@Override
public void clearActionBox(int col, int row)
public void clearActionBox(int col, int row)
{
{
Platform.runLater(()->getDashboardPane().getActionGridPane().clearActionBox(col, row));
Platform.runLater(()->getDashboardPane().getActionGridPane().clearActionBox(col, row));
}
}
@Override
@Override
public void addBlankActionBox(int col, int row)
public void addBlankActionBox(int col, int row)
{
{
Platform.runLater(()->getDashboardPane().getActionGridPane().addBlankActionBox(col, row));
Platform.runLater(()->getDashboardPane().getActionGridPane().addBlankActionBox(col, row));
}
}
@Override
@Override
public void renderAction(String currentProfileID, Action action)
public void renderAction(String currentProfileID, Action action)
{
{
Platform.runLater(()->{
Platform.runLater(()->{
try {
try {
if(getDashboardPane().getActionGridPane().getCurrentParent().equals(action.getParent()) &&
if(getDashboardPane().getActionGridPane().getCurrentParent().equals(action.getParent()) &&
getDashboardPane().getActionGridPane().getClientProfile().getID().equals(currentProfileID))
getDashboardPane().getActionGridPane().getClientProfile().getID().equals(currentProfileID))
{
{
getDashboardPane().getActionGridPane().renderAction(action);
getDashboardPane().getActionGridPane().renderAction(action);
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
});
});
}
}
@Override
@Override
public void refreshGridIfCurrent(String profileID) {
public void refreshGridIfCurrent(String profileID) {
ClientProfile clientProfile = getDashboardPane().getActionGridPane().getClientProfile();
ClientProfile clientProfile = getDashboardPane().getActionGridPane().getClientProfile();
if(clientProfile.getID().equals(profileID))
if(clientProfile.getID().equals(profileID))
{
{
Platform.runLater(()->{
Platform.runLater(()->{
try {
try {
getDashboardPane().renderProfile(getClientProfiles().getProfileFromID(profileID));
getDashboardPane().renderProfile(getClientProfiles().getProfileFromID(profileID));
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
});
});
}
}
}
}
@Override
@Override
public ClientProfile getCurrentProfile() {
public ClientProfile getCurrentProfile() {
return getDashboardPane().getActionGridPane().getClientProfile();
return getDashboardPane().getActionGridPane().getClientProfile();
}
}
}
}
package com.stream_pi.client.profile;
package com.stream_pi.client.profile;
import java.io.File;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.NoSuchFileException;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.logging.Logger;
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.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.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
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.Document;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NodeList;
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 HashMap<String, Action> actions;
private HashMap<String, Action> actions;
private String iconsPath;
private String iconsPath;
private File file;
private File file;
private Logger logger;
private Logger logger;
private Document document;
private Document document;
public ClientProfile(File file, String iconsPath) throws MinorException
public ClientProfile(File file, String iconsPath) throws MinorException
{
{
this.file = file;
this.file = file;
this.iconsPath = iconsPath;
this.iconsPath = iconsPath;
actions = new HashMap<>();
actions = new HashMap<>();
logger = Logger.getLogger(ClientProfile.class.getName());
logger = Logger.getLogger(ClientProfile.class.getName());
if(!file.exists() && !file.isFile())
if(!file.exists() && !file.isFile())
createConfigFile(file);
createConfigFile(file);
try
try
{
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
document = docBuilder.parse(file);
document = docBuilder.parse(file);
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new MinorException("profile", "Unable to read profile config file.");
throw new MinorException("profile", "Unable to read profile config file.");
}
}
setID(file.getName().replace(".xml", ""));
setID(file.getName().replace(".xml", ""));
load();
load();
}
}
private Element getProfileElement()
private Element getProfileElement()
{
{
return (Element) document.getElementsByTagName("profile").item(0);
return (Element) document.getElementsByTagName("profile").item(0);
}
}
private Element getActionsElement()
private Element getActionsElement()
{
{
return (Element) document.getElementsByTagName("actions").item(0);
return (Element) document.getElementsByTagName("actions").item(0);
}
}
public void load() throws MinorException
public void load() throws MinorException
{
{
try
try
{
{
actions.clear();
actions.clear();
logger.info("Loading profile "+getID()+" ...");
logger.info("Loading profile "+getID()+" ...");
String name = XMLConfigHelper.getStringProperty(getProfileElement(), "name");
String name = XMLConfigHelper.getStringProperty(getProfileElement(), "name");
int rows = XMLConfigHelper.getIntProperty(getProfileElement(), "rows");
int rows = XMLConfigHelper.getIntProperty(getProfileElement(), "rows");
int cols = XMLConfigHelper.getIntProperty(getProfileElement(), "cols");
int cols = XMLConfigHelper.getIntProperty(getProfileElement(), "cols");
int actionSize = XMLConfigHelper.getIntProperty(getProfileElement(), "action-size");
int actionSize = XMLConfigHelper.getIntProperty(getProfileElement(), "action-size");
int actionGap = XMLConfigHelper.getIntProperty(getProfileElement(), "action-gap");
int actionGap = XMLConfigHelper.getIntProperty(getProfileElement(), "action-gap");
setName(name);
setName(name);
setRows(rows);
setRows(rows);
setCols(cols);
setCols(cols);
setActionSize(actionSize);
setActionSize(actionSize);
setActionGap(actionGap);
setActionGap(actionGap);
//Load Actions
//Load Actions
NodeList actionsNodesList = getActionsElement().getChildNodes();
NodeList actionsNodesList = getActionsElement().getChildNodes();
int actionsSize = actionsNodesList.getLength();
int actionsSize = actionsNodesList.getLength();
logger.info("Actions Size : "+actionsSize);
logger.info("Actions Size : "+actionsSize);
for(int item = 0; item<actionsSize; item++)
for(int item = 0; item<actionsSize; item++)
{
{
Node eachActionNode = actionsNodesList.item(item);
Node eachActionNode = actionsNodesList.item(item);
if(eachActionNode.getNodeType() != Node.ELEMENT_NODE)
if(eachActionNode.getNodeType() != Node.ELEMENT_NODE)
continue;
continue;
Element eachActionElement = (Element) eachActionNode;
Element eachActionElement = (Element) eachActionNode;
if(!eachActionElement.getNodeName().equals("action"))
if(!eachActionElement.getNodeName().equals("action"))
continue;
continue;
String id = XMLConfigHelper.getStringProperty(eachActionElement, "id");
String id = XMLConfigHelper.getStringProperty(eachActionElement, "id");
String parent = XMLConfigHelper.getStringProperty(eachActionElement, "parent");
String parent = XMLConfigHelper.getStringProperty(eachActionElement, "parent");
logger.info("Loading action "+id+" ...");
logger.info("Loading action "+id+" ...");
ActionType actionType = ActionType.valueOf(XMLConfigHelper.getStringProperty(eachActionElement, "action-type"));
ActionType actionType = ActionType.valueOf(XMLConfigHelper.getStringProperty(eachActionElement, "action-type"));
Action action = new Action(id, actionType);
Action action = new Action(id, actionType);
action.setParent(parent);
action.setParent(parent);
ClientProperties properties = new ClientProperties();
ClientProperties properties = new ClientProperties();
if(actionType == ActionType.FOLDER)
if(actionType == ActionType.FOLDER)
properties.setDuplicatePropertyAllowed(true);
properties.setDuplicatePropertyAllowed(true);
if(actionType == ActionType.NORMAL)
if(actionType == ActionType.NORMAL)
{
{
action.setVersion(new Version(XMLConfigHelper.getStringProperty(eachActionElement, "version")));
action.setVersion(new Version(XMLConfigHelper.getStringProperty(eachActionElement, "version")));
action.setModuleName(XMLConfigHelper.getStringProperty(eachActionElement, "module-name"));
action.setModuleName(XMLConfigHelper.getStringProperty(eachActionElement, "module-name"));
}
}
Node propertiesNode = eachActionElement.getElementsByTagName("properties").item(0);
Node propertiesNode = eachActionElement.getElementsByTagName("properties").item(0);
NodeList propertiesNodesList = propertiesNode.getChildNodes();
NodeList propertiesNodesList = propertiesNode.getChildNodes();
int propertiesSize = propertiesNodesList.getLength();
int propertiesSize = propertiesNodesList.getLength();
for(int propItem = 0; propItem < propertiesSize; propItem++)
for(int propItem = 0; propItem < propertiesSize; propItem++)
{
{
Node eachPropertyNode = propertiesNodesList.item(propItem);
Node eachPropertyNode = propertiesNodesList.item(propItem);
if(eachPropertyNode.getNodeType() != Node.ELEMENT_NODE)
if(eachPropertyNode.getNodeType() != Node.ELEMENT_NODE)
continue;
continue;
Element eachPropertyElement = (Element) eachPropertyNode;
Element eachPropertyElement = (Element) eachPropertyNode;
if(eachPropertyElement.getNodeName() != "property")
if(eachPropertyElement.getNodeName() != "property")
continue;
continue;
String propertyName = XMLConfigHelper.getStringProperty(eachPropertyElement, "name");
String propertyName = XMLConfigHelper.getStringProperty(eachPropertyElement, "name");
String propertyValue = XMLConfigHelper.getStringProperty(eachPropertyElement, "value");
String propertyValue = XMLConfigHelper.getStringProperty(eachPropertyElement, "value");
logger.info("Property Name : "+propertyName);
logger.info("Property Name : "+propertyName);
logger.info("Property Value : "+propertyValue);
logger.info("Property Value : "+propertyValue);
Property p = new Property(propertyName, Type.STRING);
Property p = new Property(propertyName, Type.STRING);
p.setRawValue(propertyValue);
p.setRawValue(propertyValue);
properties.addProperty(p);
properties.addProperty(p);
}
}
action.setClientProperties(properties);
action.setClientProperties(properties);
Element displayElement = (Element) eachActionElement.getElementsByTagName("display").item(0);
Element displayElement = (Element) eachActionElement.getElementsByTagName("display").item(0);
//display
//display
//location
//location
try
try
{
{
Element locationElement = (Element) displayElement.getElementsByTagName("location").item(0);
Element locationElement = (Element) displayElement.getElementsByTagName("location").item(0);
int row = XMLConfigHelper.getIntProperty(locationElement, "row");
int row = XMLConfigHelper.getIntProperty(locationElement, "row");
int col = XMLConfigHelper.getIntProperty(locationElement, "col");
int col = XMLConfigHelper.getIntProperty(locationElement, "col");
action.setLocation(new Location(row, col));
action.setLocation(new Location(row, col));
}
}
catch (Exception e)
catch (Exception e)
{
{
logger.info("Action has no location, most probably a combine action child");
logger.info("Action has no location, most probably a combine action child");
}
}
//background
//background
Element backgroundElement = (Element) displayElement.getElementsByTagName("background").item(0);
Element backgroundElement = (Element) displayElement.getElementsByTagName("background").item(0);
action.setBgColourHex(XMLConfigHelper.getStringProperty(backgroundElement, "colour-hex"));
action.setBgColourHex(XMLConfigHelper.getStringProperty(backgroundElement, "colour-hex"));
Element iconElement = (Element) backgroundElement.getElementsByTagName("icon").item(0);
Element iconElement = (Element) backgroundElement.getElementsByTagName("icon").item(0);
boolean showIcon = XMLConfigHelper.getBooleanProperty(iconElement, "show");
boolean showIcon = XMLConfigHelper.getBooleanProperty(iconElement, "show");
boolean hasIcon = XMLConfigHelper.getBooleanProperty(iconElement, "has");
boolean hasIcon = XMLConfigHelper.getBooleanProperty(iconElement, "has");
Element textElement = (Element) displayElement.getElementsByTagName("text").item(0);
Element textElement = (Element) displayElement.getElementsByTagName("text").item(0);
boolean showText = XMLConfigHelper.getBooleanProperty(textElement, "show");
boolean showText = XMLConfigHelper.getBooleanProperty(textElement, "show");
String displayTextFontColour = XMLConfigHelper.getStringProperty(textElement, "colour-hex");
String displayTextFontColour = XMLConfigHelper.getStringProperty(textElement, "colour-hex");
DisplayTextAlignment displayTextAlignment = DisplayTextAlignment.valueOf(XMLConfigHelper.getStringProperty(textElement, "alignment"));
DisplayTextAlignment displayTextAlignment = DisplayTextAlignment.valueOf(XMLConfigHelper.getStringProperty(textElement, "alignment"));
action.setDisplayTextAlignment(displayTextAlignment);
action.setDisplayTextAlignment(displayTextAlignment);
action.setShowIcon(showIcon);
action.setShowIcon(showIcon);
action.setHasIcon(hasIcon);
action.setHasIcon(hasIcon);
action.setShowDisplayText(showText);
action.setShowDisplayText(showText);
action.setDisplayTextFontColourHex(displayTextFontColour);
action.setDisplayTextFontColourHex(displayTextFontColour);
String displayText = XMLConfigHelper.getStringProperty(textElement, "display-text");
String displayText = XMLConfigHelper.getStringProperty(textElement, "display-text");
action.setDisplayText(displayText);
action.setDisplayText(displayText);
if(hasIcon)
if(hasIcon)
{
{
File f = new File(iconsPath+"/"+id);
File f = new File(iconsPath+"/"+id);
try
try
{
{
byte[] iconFileByteArray = Files.readAllBytes(f.toPath());
byte[] iconFileByteArray = Files.readAllBytes(f.toPath());
action.setIcon(iconFileByteArray);
action.setIcon(iconFileByteArray);
}
}
catch(NoSuchFileException e)
catch(NoSuchFileException e)
{
{
action.setIcon(null);
action.setIcon(null);
action.setHasIcon(false);
action.setHasIcon(false);
action.setShowIcon(false);
action.setShowIcon(false);
saveAction(action);
saveAction(action);
}
}
}
}
addAction(action);
addAction(action);
logger.info("... Done!");
logger.info("... Done!");
}
}
logger.info("Loaded profile "+getID()+" ("+getName()+") !");
logger.info("Loaded profile "+getID()+" ("+getName()+") !");
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new MinorException("profile", "profile is corrupt.");
throw new MinorException("profile", "profile is corrupt.");
}
}
}
}
public void addAction(Action action) throws CloneNotSupportedException {
public void addAction(Action action) throws CloneNotSupportedException {
actions.put(action.getID(), (Action) action.clone());
actions.put(action.getID(), (Action) action.clone());
}
}
private void createConfigFile(File file) throws MinorException
private void createConfigFile(File file) throws MinorException
{
{
try
try
{
{
file.createNewFile();
file.createNewFile();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document newDocument = dBuilder.newDocument();
Document newDocument = dBuilder.newDocument();
Element rootElement = newDocument.createElement("config");
Element rootElement = newDocument.createElement("config");
newDocument.appendChild(rootElement);
newDocument.appendChild(rootElement);
Element profileElement = newDocument.createElement("profile");
Element profileElement = newDocument.createElement("profile");
rootElement.appendChild(profileElement);
rootElement.appendChild(profileElement);
Element actionsElement = newDocument.createElement("actions");
Element actionsElement = newDocument.createElement("actions");
rootElement.appendChild(actionsElement);
rootElement.appendChild(actionsElement);
Element nameElement = newDocument.createElement("name");
Element nameElement = newDocument.createElement("name");
nameElement.setTextContent("Untitled profile");
nameElement.setTextContent("Untitled profile");
profileElement.appendChild(nameElement);
profileElement.appendChild(nameElement);
Element rowsElement = newDocument.createElement("rows");
Element rowsElement = newDocument.createElement("rows");
rowsElement.setTextContent("3");
rowsElement.setTextContent("3");
profileElement.appendChild(rowsElement);
profileElement.appendChild(rowsElement);
Element colsElement = newDocument.createElement("cols");
Element colsElement = newDocument.createElement("cols");
colsElement.setTextContent("3");
colsElement.setTextContent("3");
profileElement.appendChild(colsElement);
profileElement.appendChild(colsElement);
Element actionSizeElement = newDocument.createElement("action-size");
Element actionSizeElement = newDocument.createElement("action-size");
actionSizeElement.setTextContent("100");
actionSizeElement.setTextContent("100");
profileElement.appendChild(actionSizeElement);
profileElement.appendChild(actionSizeElement);
Element actionGapElement = newDocument.createElement("action-gap");
Element actionGapElement = newDocument.createElement("action-gap");
actionGapElement.setTextContent("5");
actionGapElement.setTextContent("5");
profileElement.appendChild(actionGapElement);
profileElement.appendChild(actionGapElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(newDocument);
DOMSource source = new DOMSource(newDocument);
StreamResult result = new StreamResult(file);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
transformer.transform(source, result);
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new MinorException(e.getMessage());
throw new MinorException(e.getMessage());
}
}
}
}
public void deleteProfile()
public void deleteProfile()
{
{
file.delete();
file.delete();
}
}
public void saveAction(Action action) throws Exception {
public void saveAction(Action action) throws Exception {
Element newActionElement = document.createElement("action");
Element newActionElement = document.createElement("action");
getActionsElement().appendChild(newActionElement);
getActionsElement().appendChild(newActionElement);
Element idElement = document.createElement("id");
Element idElement = document.createElement("id");
idElement.setTextContent(action.getID());
idElement.setTextContent(action.getID());
newActionElement.appendChild(idElement);
newActionElement.appendChild(idElement);
Element parentElement = document.createElement("parent");
Element parentElement = document.createElement("parent");
parentElement.setTextContent(action.getParent());
parentElement.setTextContent(action.getParent());
newActionElement.appendChild(parentElement);
newActionElement.appendChild(parentElement);
Element actionTypeElement = document.createElement("action-type");
Element actionTypeElement = document.createElement("action-type");
actionTypeElement.setTextContent(action.getActionType()+"");
actionTypeElement.setTextContent(action.getActionType()+"");
newActionElement.appendChild(actionTypeElement);
newActionElement.appendChild(actionTypeElement);
if(action.getActionType() == ActionType.NORMAL)
if(action.getActionType() == ActionType.NORMAL)
{
{
Element versionElement = document.createElement("version");
Element versionElement = document.createElement("version");
versionElement.setTextContent(action.getVersion().getText());
versionElement.setTextContent(action.getVersion().getText());
newActionElement.appendChild(versionElement);
newActionElement.appendChild(versionElement);
System.out.println(action.getModuleName());
System.out.println(action.getModuleName());
Element moduleNameElement = document.createElement("module-name");
Element moduleNameElement = document.createElement("module-name");
moduleNameElement.setTextContent(action.getModuleName());
moduleNameElement.setTextContent(action.getModuleName());
newActionElement.appendChild(moduleNameElement);
newActionElement.appendChild(moduleNameElement);
}
}
Element displayElement = document.createElement("display");
Element displayElement = document.createElement("display");
newActionElement.appendChild(displayElement);
newActionElement.appendChild(displayElement);
Element backgroundElement = document.createElement("background");
Element backgroundElement = document.createElement("background");
displayElement.appendChild(backgroundElement);
displayElement.appendChild(backgroundElement);
Element colourHexElement = document.createElement("colour-hex");
Element colourHexElement = document.createElement("colour-hex");
colourHexElement.setTextContent(action.getBgColourHex());
colourHexElement.setTextContent(action.getBgColourHex());
backgroundElement.appendChild(colourHexElement);
backgroundElement.appendChild(colourHexElement);
Element iconElement = document.createElement("icon");
Element iconElement = document.createElement("icon");
Element iconShowElement = document.createElement("show");
Element iconShowElement = document.createElement("show");
iconShowElement.setTextContent(action.isShowIcon()+"");
iconShowElement.setTextContent(action.isShowIcon()+"");
iconElement.appendChild(iconShowElement);
iconElement.appendChild(iconShowElement);
Element iconHasElement = document.createElement("has");
Element iconHasElement = document.createElement("has");
iconHasElement.setTextContent(action.isHasIcon()+"");
iconHasElement.setTextContent(action.isHasIcon()+"");
iconElement.appendChild(iconHasElement);
iconElement.appendChild(iconHasElement);
backgroundElement.appendChild(iconElement);
backgroundElement.appendChild(iconElement);
Element textElement = document.createElement("text");
Element textElement = document.createElement("text");
displayElement.appendChild(textElement);
displayElement.appendChild(textElement);
Element textTolourHexElement = document.createElement("colour-hex");
Element textTolourHexElement = document.createElement("colour-hex");
textTolourHexElement.setTextContent(action.getDisplayTextFontColourHex());
textTolourHexElement.setTextContent(action.getDisplayTextFontColourHex());
textElement.appendChild(textTolourHexElement);
textElement.appendChild(textTolourHexElement);
Element textShowElement = document.createElement("show");
Element textShowElement = document.createElement("show");
textShowElement.setTextContent(action.isShowDisplayText()+"");
textShowElement.setTextContent(action.isShowDisplayText()+"");
textElement.appendChild(textShowElement);
textElement.appendChild(textShowElement);
Element textDisplayTextElement = document.createElement("display-text");
Element textDisplayTextElement = document.createElement("display-text");
textDisplayTextElement.setTextContent(action.getDisplayText());
textDisplayTextElement.setTextContent(action.getDisplayText());
textElement.appendChild(textDisplayTextElement);
textElement.appendChild(textDisplayTextElement);
Element textAlignmentElement = document.createElement("alignment");
Element textAlignmentElement = document.createElement("alignment");
textAlignmentElement.setTextContent(action.getDisplayTextAlignment()+"");
textAlignmentElement.setTextContent(action.getDisplayTextAlignment()+"");
textElement.appendChild(textAlignmentElement);
textElement.appendChild(textAlignmentElement);
Element locationElement = document.createElement("location");
Element locationElement = document.createElement("location");
displayElement.appendChild(locationElement);
displayElement.appendChild(locationElement);
Element colElement = document.createElement("col");
Element colElement = document.createElement("col");
colElement.setTextContent(action.getLocation().getCol()+"");
colElement.setTextContent(action.getLocation().getCol()+"");
locationElement.appendChild(colElement);
locationElement.appendChild(colElement);
Element rowElement = document.createElement("row");
Element rowElement = document.createElement("row");
rowElement.setTextContent(action.getLocation().getRow()+"");
rowElement.setTextContent(action.getLocation().getRow()+"");
locationElement.appendChild(rowElement);
locationElement.appendChild(rowElement);
Element propertiesElement = document.createElement("properties");
Element propertiesElement = document.createElement("properties");
newActionElement.appendChild(propertiesElement);
newActionElement.appendChild(propertiesElement);
for(String key : action.getClientProperties().getNames())
for(String key : action.getClientProperties().getNames())
{
{
for(Property eachProperty : action.getClientProperties().getMultipleProperties(key))
for(Property eachProperty : action.getClientProperties().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 int getActionIndexInConfig(String actionID)
private int getActionIndexInConfig(String actionID)
{
{
NodeList actionsList = getActionsElement().getChildNodes();
NodeList actionsList = getActionsElement().getChildNodes();
int actionsSize = actionsList.getLength();
int actionsSize = actionsList.getLength();
int index = 0;
int index = 0;
for(int i = 0;i<actionsSize;i++)
for(int i = 0;i<actionsSize;i++)
{
{
Node eachActionNode = actionsList.item(index);
Node eachActionNode = actionsList.item(index);
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;
Element idElement = (Element) eachActionElement.getElementsByTagName("id").item(0);
Element idElement = (Element) eachActionElement.getElementsByTagName("id").item(0);
if(idElement.getTextContent().equals(actionID))
if(idElement.getTextContent().equals(actionID))
return index;
return index;
index++;
index++;
}
}
return -1;
return -1;
}
}
public void saveActionIcon(String actionID, byte[] array){
public void saveActionIcon(String actionID, byte[] array){
int index = getActionIndexInConfig(actionID);
int index = getActionIndexInConfig(actionID);
getActionFromID(actionID).setIcon(array);
getActionFromID(actionID).setIcon(array);
File iconFile = new File(iconsPath+"/"+actionID);
File iconFile = new File(iconsPath+"/"+actionID);
if(iconFile.exists())
if(iconFile.exists())
{
{
boolean result = iconFile.delete();
boolean result = iconFile.delete();
System.out.println("result : "+result);
System.out.println("result : "+result);
}
}
try
try
{
{
OutputStream outputStream = new FileOutputStream(iconFile);
OutputStream outputStream = new FileOutputStream(iconFile);
outputStream.write(array);
outputStream.write(array);
outputStream.flush();
outputStream.flush();
outputStream.close();
outputStream.close();
Element actionElement = (Element) getActionsElement().getElementsByTagName("action").item(index);
Element actionElement = (Element) getActionsElement().getElementsByTagName("action").item(index);
Element displayElement = (Element) actionElement.getElementsByTagName("display").item(0);
Element displayElement = (Element) actionElement.getElementsByTagName("display").item(0);
Element backgroundElement = (Element) displayElement.getElementsByTagName("background").item(0);
Element backgroundElement = (Element) displayElement.getElementsByTagName("background").item(0);
Element iconElement = (Element) backgroundElement.getElementsByTagName("icon").item(0);
Element iconElement = (Element) backgroundElement.getElementsByTagName("icon").item(0);
Element hasElement = (Element) iconElement.getElementsByTagName("has").item(0);
Element hasElement = (Element) iconElement.getElementsByTagName("has").item(0);
hasElement.setTextContent("true");
hasElement.setTextContent("true");
save();
save();
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
private void save() throws Exception
private void save() throws Exception
{
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(file);
Result output = new StreamResult(file);
Source input = new DOMSource(document);
Source input = new DOMSource(document);
transformer.transform(input, output);
transformer.transform(input, output);
}
}
public void saveProfileDetails() throws Exception {
public void saveProfileDetails() throws Exception {
XMLConfigHelper.removeChilds(getProfileElement());
XMLConfigHelper.removeChilds(getProfileElement());
Element nameElement = document.createElement("name");
Element nameElement = document.createElement("name");
nameElement.setTextContent(getName());
nameElement.setTextContent(getName());
getProfileElement().appendChild(nameElement);
getProfileElement().appendChild(nameElement);
Element rowsElement = document.createElement("rows");
Element rowsElement = document.createElement("rows");
rowsElement.setTextContent(getRows()+"");
rowsElement.setTextContent(getRows()+"");
getProfileElement().appendChild(rowsElement);
getProfileElement().appendChild(rowsElement);
Element colsElement = document.createElement("cols");
Element colsElement = document.createElement("cols");
colsElement.setTextContent(getCols()+"");
colsElement.setTextContent(getCols()+"");
getProfileElement().appendChild(colsElement);
getProfileElement().appendChild(colsElement);
Element actionSizeElement = document.createElement("action-size");
Element actionSizeElement = document.createElement("action-size");
actionSizeElement.setTextContent(getActionSize()+"");
actionSizeElement.setTextContent(getActionSize()+"");
getProfileElement().appendChild(actionSizeElement);
getProfileElement().appendChild(actionSizeElement);
Element actionGapElement = document.createElement("action-gap");
Element actionGapElement = document.createElement("action-gap");
actionGapElement.setTextContent(getActionGap()+"");
actionGapElement.setTextContent(getActionGap()+"");
getProfileElement().appendChild(actionGapElement);
getProfileElement().appendChild(actionGapElement);
save();
save();
}
}
public void saveActions() throws Exception
public void saveActions() throws Exception
{
{
XMLConfigHelper.removeChilds(getActionsElement());
XMLConfigHelper.removeChilds(getActionsElement());
save();
save();
for(Action action : getActions())
for(Action action : getActions())
{
{
logger.info("ACTION ID :"+action.getID());
logger.info("ACTION ID :"+action.getID());
logger.info("Action ICON : "+action.isHasIcon());
logger.info("Action ICON : "+action.isHasIcon());
saveAction(action);
saveAction(action);
}
}
}
}
public void removeAction(String ID) throws Exception {
public void removeAction(String ID) throws Exception {
int index = getActionIndexInConfig(ID);
int index = getActionIndexInConfig(ID);
if(index>-1)
if(index>-1)
{
{
Element actionElement = (Element) getActionsElement().getElementsByTagName("action").item(index);
Element actionElement = (Element) getActionsElement().getElementsByTagName("action").item(index);
Element displayElement = (Element) actionElement.getElementsByTagName("display").item(0);
Element displayElement = (Element) actionElement.getElementsByTagName("display").item(0);
Element backgroundElement = (Element) displayElement.getElementsByTagName("background").item(0);
Element backgroundElement = (Element) displayElement.getElementsByTagName("background").item(0);
Element iconElement = (Element) backgroundElement.getElementsByTagName("icon").item(0);
Element iconElement = (Element) backgroundElement.getElementsByTagName("icon").item(0);
if(XMLConfigHelper.getBooleanProperty(iconElement, "has"))
if(XMLConfigHelper.getBooleanProperty(iconElement, "has"))
{
{
File file = new File(ClientInfo.getInstance().getPrePath()+iconsPath+"/"+ID);
File file = new File(ClientInfo.getInstance().getPrePath()+iconsPath+"/"+ID);
System.out.println(file.delete());
System.out.println(file.delete());
}
}
actions.remove(ID);
actions.remove(ID);
}
}
}
}
public ArrayList<Action> getActions()
public ArrayList<Action> getActions()
{
{
ArrayList<Action> p = new ArrayList<>();
ArrayList<Action> p = new ArrayList<>();
for(String profile : actions.keySet())
for(String profile : actions.keySet())
p.add(actions.get(profile));
p.add(actions.get(profile));
return p;
return p;
}
}
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 Action getActionFromID(String ID)
public Action getActionFromID(String ID)
{
{
return actions.getOrDefault(ID, null);
return actions.getOrDefault(ID, null);
}
}
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.client.window;
package com.stream_pi.client.window;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import java.io.File;
import java.io.File;
import java.util.logging.Logger;
import java.util.logging.Logger;
import com.stream_pi.client.Main;
import com.stream_pi.client.Main;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.window.dashboard.DashboardBase;
import com.stream_pi.client.window.dashboard.DashboardBase;
import com.stream_pi.client.window.firsttimeuse.FirstTimeUse;
import com.stream_pi.client.window.firsttimeuse.FirstTimeUse;
import com.stream_pi.client.window.settings.SettingsBase;
import com.stream_pi.client.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.combobox.StreamPiComboBox;
import com.stream_pi.util.combobox.StreamPiComboBox;
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 com.stream_pi.util.loggerhelper.StreamPiLogFallbackHandler;
import com.stream_pi.util.loggerhelper.StreamPiLogFallbackHandler;
import com.stream_pi.util.loggerhelper.StreamPiLogFileHandler;
import com.stream_pi.util.loggerhelper.StreamPiLogFileHandler;
import com.stream_pi.util.platform.Platform;
import com.stream_pi.util.platform.Platform;
import javafx.scene.CacheHint;
import javafx.scene.CacheHint;
import javafx.scene.Cursor;
import javafx.scene.Cursor;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyCombination;
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;
public abstract class Base extends StackPane implements ExceptionAndAlertHandler, ClientListener {
public abstract class Base extends StackPane implements ExceptionAndAlertHandler, ClientListener {
private Config config;
private Config config;
private ClientProfiles clientProfiles;
private ClientProfiles clientProfiles;
private ClientInfo clientInfo;
private ClientInfo clientInfo;
private Stage stage;
private Stage stage;
public Stage getStage()
public Stage getStage()
{
{
return stage;
return stage;
}
}
public Logger getLogger()
public Logger getLogger()
{
{
return logger;
return logger;
}
}
private DashboardBase dashboardBase;
private DashboardBase dashboardBase;
private SettingsBase settingsBase;
private SettingsBase settingsBase;
private FirstTimeUse firstTimeUse;
private FirstTimeUse firstTimeUse;
public FirstTimeUse getFirstTimeUse() {
public FirstTimeUse getFirstTimeUse() {
return firstTimeUse;
return firstTimeUse;
}
}
private StackPane alertStackPane;
private StackPane alertStackPane;
@Override
@Override
public ClientProfiles getClientProfiles() {
public ClientProfiles getClientProfiles() {
return clientProfiles;
return clientProfiles;
}
}
public void setClientProfiles(ClientProfiles clientProfiles) {
public void setClientProfiles(ClientProfiles clientProfiles) {
this.clientProfiles = clientProfiles;
this.clientProfiles = clientProfiles;
}
}
private Logger logger = null;
private Logger logger = null;
private StreamPiLogFileHandler logFileHandler = null;
private StreamPiLogFileHandler logFileHandler = null;
private StreamPiLogFallbackHandler logFallbackHandler = null;
private StreamPiLogFallbackHandler logFallbackHandler = null;
public void initLogger()
public void initLogger()
{
{
try
try
{
{
if(logger != null || logFileHandler != null)
if(logger != null || logFileHandler != null)
return;
return;
closeLogger();
closeLogger();
logger = Logger.getLogger("");
logger = Logger.getLogger("");
if(new File(ClientInfo.getInstance().getPrePath()).getAbsoluteFile().getParentFile().canWrite())
if(new File(ClientInfo.getInstance().getPrePath()).getAbsoluteFile().getParentFile().canWrite())
{
{
String path = ClientInfo.getInstance().getPrePath()+"../streampi.log";
String path = ClientInfo.getInstance().getPrePath()+"../streampi.log";
if(ClientInfo.getInstance().getPlatformType() == Platform.ANDROID)
if(ClientInfo.getInstance().getPlatformType() == Platform.ANDROID)
path = ClientInfo.getInstance().getPrePath()+"streampi.log";
path = ClientInfo.getInstance().getPrePath()+"streampi.log";
logFileHandler = new StreamPiLogFileHandler(path);
logFileHandler = new StreamPiLogFileHandler(path);
logger.addHandler(logFileHandler);
logger.addHandler(logFileHandler);
}
}
else
else
{
{
logFallbackHandler = new StreamPiLogFallbackHandler();
logFallbackHandler = new StreamPiLogFallbackHandler();
logger.addHandler(logFallbackHandler);
logger.addHandler(logFallbackHandler);
}
}
}
}
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();
else if(logFallbackHandler != null)
else if(logFallbackHandler != null)
logFallbackHandler.close();
logFallbackHandler.close();
}
}
public void initBase() throws SevereException
public void initBase() throws SevereException
{
{
stage = (Stage) getScene().getWindow();
stage = (Stage) getScene().getWindow();
initLogger();
initLogger();
clientInfo = ClientInfo.getInstance();
clientInfo = ClientInfo.getInstance();
dashboardBase = new DashboardBase(this, this);
dashboardBase = new DashboardBase(this, this);
dashboardBase.setCache(true);
dashboardBase.setCache(true);
dashboardBase.setCacheHint(CacheHint.SPEED);
dashboardBase.setCacheHint(CacheHint.SPEED);
dashboardBase.prefWidthProperty().bind(widthProperty());
dashboardBase.prefWidthProperty().bind(widthProperty());
dashboardBase.prefHeightProperty().bind(heightProperty());
dashboardBase.prefHeightProperty().bind(heightProperty());
settingsBase = new SettingsBase(this, this);
settingsBase = new SettingsBase(this, this);
settingsBase.setCache(true);
settingsBase.setCache(true);
settingsBase.setCacheHint(CacheHint.SPEED);
settingsBase.setCacheHint(CacheHint.SPEED);
alertStackPane = new StackPane();
alertStackPane = new StackPane();
alertStackPane.setVisible(false);
alertStackPane.setVisible(false);
StreamPiAlert.setParent(alertStackPane);
StreamPiAlert.setParent(alertStackPane);
StreamPiComboBox.setParent(alertStackPane);
StreamPiComboBox.setParent(alertStackPane);
firstTimeUse = new FirstTimeUse(this, this);
firstTimeUse = new FirstTimeUse(this, this);
getChildren().clear();
getChildren().clear();
getChildren().addAll(settingsBase, dashboardBase, alertStackPane);
getChildren().addAll(settingsBase, dashboardBase, alertStackPane);
setStyle(null);
setStyle(null);
checkPrePathDirectory();
checkPrePathDirectory();
config = Config.getInstance();
config = Config.getInstance();
if(config.isFirstTimeUse())
if(config.isFirstTimeUse())
{
{
clearStylesheets();
clearStylesheets();
applyDefaultStylesheet();
applyDefaultStylesheet();
getChildren().add(firstTimeUse);
getChildren().add(firstTimeUse);
firstTimeUse.toFront();
firstTimeUse.toFront();
}
}
else
else
{
{
dashboardBase.toFront();
dashboardBase.toFront();
}
}
registerThemes();
registerThemes();
}
}
private void checkPrePathDirectory() throws SevereException
private void checkPrePathDirectory() throws SevereException
{
{
try
try
{
{
File filex = new File(ClientInfo.getInstance().getPrePath());
File filex = new File(ClientInfo.getInstance().getPrePath());
if(filex.getAbsoluteFile().getParentFile().canWrite())
if(filex.getAbsoluteFile().getParentFile().canWrite())
{
{
if(!filex.exists())
if(!filex.exists())
{
{
filex.mkdirs();
filex.mkdirs();
IOHelper.unzip(Main.class.getResourceAsStream("Default.obj"), ClientInfo.getInstance().getPrePath());
IOHelper.unzip(Main.class.getResourceAsStream("Default.obj"), ClientInfo.getInstance().getPrePath());
}
}
}
}
else
else
{
{
throw new SevereException("No storage permission. Give it!");
throw new SevereException("No storage permission. Give it!");
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}
}
public void setupFlags()
public void setupFlags()
{
{
//Full Screen
//Full Screen
if(getConfig().isFullscreen())
if(getConfig().isFullscreen())
{
{
getStage().setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
getStage().setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
getStage().setFullScreen(true);
getStage().setFullScreen(true);
}
}
else
else
{
{
getStage().setFullScreenExitKeyCombination(KeyCombination.keyCombination("Esc"));
getStage().setFullScreenExitKeyCombination(KeyCombination.keyCombination("Esc"));
getStage().setFullScreen(false);
getStage().setFullScreen(false);
}
}
//Cursor
//Cursor
if(getConfig().isShowCursor())
if(getConfig().isShowCursor())
{
{
setCursor(Cursor.DEFAULT);
setCursor(Cursor.DEFAULT);
}
}
else
else
{
{
setCursor(Cursor.NONE);
setCursor(Cursor.NONE);
}
}
}
}
public SettingsBase getSettingsPane() {
public SettingsBase getSettingsPane() {
return settingsBase;
return settingsBase;
}
}
public DashboardBase getDashboardPane() {
public DashboardBase getDashboardPane() {
return dashboardBase;
return dashboardBase;
}
}
public void renderRootDefaultProfile() throws SevereException {
public void renderRootDefaultProfile() throws SevereException {
getDashboardPane().renderProfile(getClientProfiles().getProfileFromID(
getDashboardPane().renderProfile(getClientProfiles().getProfileFromID(
Config.getInstance().getStartupProfileID()
Config.getInstance().getStartupProfileID()
));
));
}
}
public void clearStylesheets()
public void clearStylesheets()
{
{
getStylesheets().clear();
getStylesheets().clear();
}
}
public void applyDefaultStylesheet()
public void applyDefaultStylesheet()
{
{
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());
}
}
public Config getConfig()
public Config getConfig()
{
{
return config;
return config;
}
}
public ClientInfo getClientInfo()
public ClientInfo getClientInfo()
{
{
return clientInfo;
return clientInfo;
}
}
private Theme currentTheme;
private Theme currentTheme;
@Override
@Override
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;
clearStylesheets();
clearStylesheets();
getStylesheets().addAll(t.getStylesheets());
getStylesheets().addAll(t.getStylesheets());
applyDefaultStylesheet();
applyDefaultStylesheet();
logger.info("... Done!");
logger.info("... Done!");
}
}
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(), clientInfo.getMinThemeSupportVersion());
themes = new Themes(getConfig().getThemesPath(), getConfig().getCurrentThemeFullName(), clientInfo.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!");
}
}
@Override
@Override
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);
}
}
}
}
}
}
@Override
@Override
public String getDefaultThemeFullName()
public String getDefaultThemeFullName()
{
{
return config.getCurrentThemeFullName();
return config.getCurrentThemeFullName();
}
}
}
}
package com.stream_pi.client.window.dashboard.actiongridpane;
package com.stream_pi.client.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.client.window.ExceptionAndAlertHandler;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
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.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.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 javafx.util.Duration;
import javafx.util.Duration;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
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 int getRow() {
public int getRow() {
return row;
return row;
}
}
public int getCol() {
public int getCol() {
return col;
return col;
}
}
public void clear()
public void clear()
{
{
setAction(null);
setAction(null);
setBackground(Background.EMPTY);
setBackground(Background.EMPTY);
setStyle(null);
setStyle(null);
getChildren().clear();
getChildren().clear();
}
}
private FontIcon statusIcon;
private FontIcon statusIcon;
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());
statusIcon = new FontIcon();
statusIcon = new FontIcon();
statusIcon.setOpacity(0);
statusIcon.setOpacity(0);
statusIcon.setCache(true);
statusIcon.setCache(true);
statusIcon.setCacheHint(CacheHint.SPEED);
statusIcon.setCacheHint(CacheHint.SPEED);
statusIcon.setIconSize(size - 30);
statusIcon.setIconSize(size - 30);
getChildren().addAll(statusIcon, displayTextLabel);
getChildren().addAll(statusIcon, displayTextLabel);
setMinSize(size, size);
setMinSize(size, size);
setMaxSize(size, size);
setMaxSize(size, size);
getStyleClass().clear();
getStyleClass().clear();
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_"+row+"_"+col);
getStyleClass().add("action_box_"+row+"_"+col);
setOnMouseClicked(touchEvent -> actionClicked());
setOnMouseClicked(touchEvent -> actionClicked());
setOnMousePressed(TouchEvent -> {
setOnMousePressed(TouchEvent -> {
if(action != null)
if(action != null)
{
{
getStyleClass().add("action_box_onclick");
getStyleClass().add("action_box_onclick");
}
}
});
});
setOnMouseReleased(TouchEvent ->{
setOnMouseReleased(TouchEvent ->{
if(action != null)
if(action != null)
{
{
getStyleClass().remove("action_box_onclick");
getStyleClass().remove("action_box_onclick");
}
}
});
});
statusIconAnimation = new Timeline(
statusIconAnimation = new Timeline(
new KeyFrame(
new KeyFrame(
Duration.millis(0.0D),
Duration.millis(0.0D),
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_IN)),
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_IN)),
new KeyFrame(
new KeyFrame(
Duration.millis(100.0D),
Duration.millis(100.0D),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_IN)),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_IN)),
new KeyFrame(
new KeyFrame(
Duration.millis(600.0D),
Duration.millis(600.0D),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_OUT)),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_OUT)),
new KeyFrame(
new KeyFrame(
Duration.millis(700.0D),
Duration.millis(700.0D),
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_OUT))
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_OUT))
);
);
statusIconAnimation.setOnFinished(event -> {
statusIconAnimation.setOnFinished(event -> {
statusIcon.toBack();
statusIcon.toBack();
});
});
}
}
public void actionClicked()
public void actionClicked()
{
{
if(action!=null)
if(action!=null)
{
{
if(action.getActionType() == ActionType.FOLDER)
if(action.getActionType() == ActionType.FOLDER)
{
{
getActionGridPaneListener().renderFolder(action.getID());
getActionGridPaneListener().renderFolder(action.getID());
}
}
else
else
{
{
if(action.getActionType() == ActionType.COMBINE)
if(action.getActionType() == ActionType.COMBINE)
{
{
getActionGridPaneListener().combineActionClicked(action.getID());
getActionGridPaneListener().combineActionClicked(action.getID());
}
}
else if(action.getActionType() == ActionType.NORMAL)
else if(action.getActionType() == ActionType.NORMAL)
{
{
getActionGridPaneListener().normalActionClicked(action.getID());
getActionGridPaneListener().normalActionClicked(action.getID());
}
}
}
}
}
}
}
}
public FontIcon getStatusIcon() {
public FontIcon getStatusIcon() {
return statusIcon;
return statusIcon;
}
}
private Timeline statusIconAnimation;
private Timeline statusIconAnimation;
public Timeline getStatusIconAnimation() {
public Timeline getStatusIconAnimation() {
return statusIconAnimation;
return statusIconAnimation;
}
}
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, ActionGridPaneListener actionGridPaneListener, int row, int col)
public ActionBox(int size, ActionGridPaneListener actionGridPaneListener, int row, int col)
{
{
this.actionGridPaneListener = actionGridPaneListener;
this.actionGridPaneListener = actionGridPaneListener;
this.size = size;
this.size = size;
this.row = row;
this.row = row;
this.col = col;
this.col = col;
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);
return (Action) ois.readObject();
return (Action) ois.readObject();
} 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(Background.EMPTY);
setBackground(Background.EMPTY);
}
}
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;
public Action getAction() {
public Action getAction() {
return action;
return 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, ExceptionAndAlertHandler exceptionAndAlertHandler,
public ActionBox(int size, Action action, ExceptionAndAlertHandler exceptionAndAlertHandler,
ActionGridPaneListener actionGridPaneListener, int row, int col)
ActionGridPaneListener actionGridPaneListener, int row, int col)
{
{
this.actionGridPaneListener = actionGridPaneListener;
this.actionGridPaneListener = actionGridPaneListener;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.action = action;
this.action = action;
this.size = size;
this.size = size;
this.row = row;
this.row = row;
this.col = col;
this.col = col;
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()
{
{
setDisplayTextFontColour(action.getDisplayTextFontColourHex());
setDisplayTextFontColour(action.getDisplayTextFontColourHex());
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());
if(action.isHasIcon() && action.isShowIcon())
if(action.isHasIcon() && action.isShowIcon())
{
{
setIcon(action.getIconAsByteArray());
setIcon(action.getIconAsByteArray());
}
}
else
else
{
{
setIcon(null);
setIcon(null);
}
}
}
}
public void animateStatus()
public void animateStatus()
{
{
statusIcon.toFront();
statusIcon.toFront();
statusIconAnimation.play();
statusIconAnimation.play();
}
}
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("'"+colour+"'COLOR");
System.out.println("'"+colour+"'COLOR");
if(!colour.isEmpty())
if(!colour.isEmpty())
{
{
System.out.println(
System.out.println(
"putting ..." + Thread.currentThread().getName()
"putting ..." + Thread.currentThread().getName()
);
);
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.client.window.dashboard.actiongridpane;
package com.stream_pi.client.window.dashboard.actiongridpane;
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.Location;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
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 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.Node;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.GridPane;
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.paint.Color;
import javafx.scene.paint.Color;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
public class ActionGridPane extends GridPane implements ActionGridPaneListener {
public class ActionGridPane extends GridPane implements ActionGridPaneListener {
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ClientListener clientListener;
private ClientListener clientListener;
public ActionGridPane(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener)
public ActionGridPane(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener)
{
{
this.clientListener = clientListener;
this.clientListener = clientListener;
logger = Logger.getLogger(ActionGridPane.class.getName());
logger = Logger.getLogger(ActionGridPane.class.getName());
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
getStyleClass().add("action_grid_pane");
getStyleClass().add("action_grid_pane");
setPadding(new Insets(5.0));
setPadding(new Insets(5.0));
setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
VBox.setVgrow(this, Priority.ALWAYS);
VBox.setVgrow(this, Priority.ALWAYS);
}
}
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 int rows, cols;
private int rows, cols;
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 void actionFailed(String profileID, String actionID)
public void actionFailed(String profileID, String actionID)
{
{
if(getClientProfile().getID().equals(profileID))
if(getClientProfile().getID().equals(profileID))
{
{
Action action = getClientProfile().getActionFromID(actionID);
Action action = getClientProfile().getActionFromID(actionID);
if(action != null)
if(action != null)
{
{
if(currentParent.equals(action.getParent()))
if(currentParent.equals(action.getParent()))
{
{
failShow(action);
failShow(action);
}
}
else
else
{
{
if(action.getLocation().getCol() == -1)
if(action.getLocation().getCol() == -1)
{
{
failShow(getClientProfile().getActionFromID(action.getParent()));
failShow(getClientProfile().getActionFromID(action.getParent()));
}
}
}
}
}
}
}
}
}
}
public void failShow(Action action)
public void failShow(Action action)
{
{
for(Node node : getChildren())
for(Node node : getChildren())
{
{
if(GridPane.getColumnIndex(node) == action.getLocation().getRow() &&
if(GridPane.getColumnIndex(node) == action.getLocation().getRow() &&
GridPane.getRowIndex(node) == action.getLocation().getCol())
GridPane.getRowIndex(node) == action.getLocation().getCol())
{
{
ActionBox actionBox = (ActionBox) node;
ActionBox actionBox = (ActionBox) node;
actionBox.getStatusIcon().setIconLiteral("fas-exclamation-triangle");
actionBox.getStatusIcon().setIconLiteral("fas-exclamation-triangle");
actionBox.getStatusIcon().setIconColor(Color.RED);
actionBox.getStatusIcon().setIconColor(Color.RED);
actionBox.animateStatus();
actionBox.animateStatus();
break;
break;
}
}
}
}
}
}
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(
getClientProfile().getActionSize(),
getClientProfile().getActionSize(),
getClientProfile().getActionSize()
getClientProfile().getActionSize()
);
);
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(getClientProfile().getActionSize() - 30);
fontIcon.setIconSize(getClientProfile().getActionSize() - 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();
setHgap(getClientProfile().getActionGap());
setHgap(getClientProfile().getActionGap());
setVgap(getClientProfile().getActionGap());
setVgap(getClientProfile().getActionGap());
boolean isFolder = false;
boolean isFolder = false;
if(!getCurrentParent().equals("root"))
if(!getCurrentParent().equals("root"))
{
{
isFolder = true;
isFolder = true;
add(getFolderBackButton(), 0,0);
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;
addBlankActionBox(col, row);
addBlankActionBox(col, row);
}
}
}
}
}
}
public void renderActions()
public void renderActions()
{
{
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
for(Action eachAction : getClientProfile().getActions())
for(Action eachAction : getClientProfile().getActions())
{
{
logger.info("Action ID : "+eachAction.getID()+"\nInvalid : "+eachAction.isInvalid());
logger.info("Action ID : "+eachAction.getID()+"\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()
{
{
getChildren().clear();
getChildren().clear();
}
}
private Logger logger;
private Logger logger;
public void clearActionBox(int col, int row)
public void clearActionBox(int col, int row)
{
{
for(Node node : getChildren())
for(Node node : getChildren())
{
{
if(GridPane.getColumnIndex(node) == row &&
if(GridPane.getColumnIndex(node) == row &&
GridPane.getRowIndex(node) == col)
GridPane.getRowIndex(node) == col)
{
{
getChildren().remove(node);
getChildren().remove(node);
break;
break;
}
}
}
}
}
}
public ActionBox getActionBox(int col, int row)
public ActionBox getActionBox(int col, int row)
{
{
for(Node node : getChildren())
for(Node node : getChildren())
{
{
if(GridPane.getColumnIndex(node) == row &&
if(GridPane.getColumnIndex(node) == row &&
GridPane.getRowIndex(node) == col)
GridPane.getRowIndex(node) == col)
{
{
return (ActionBox) node;
return (ActionBox) node;
}
}
}
}
return null;
return null;
}
}
public void addBlankActionBox(int col, int row)
public void addBlankActionBox(int col, int row)
{
{
ActionBox actionBox = new ActionBox(getClientProfile().getActionSize(), this, row, col);
ActionBox actionBox = new ActionBox(getClientProfile().getActionSize(), this, row, col);
actionBox.setStreamPiParent(currentParent);
actionBox.setStreamPiParent(currentParent);
add(actionBox, row, col);
add(actionBox, row, col);
}
}
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.");
}
}
Location location = action.getLocation();
Location location = action.getLocation();
ActionBox actionBox = new ActionBox(getClientProfile().getActionSize(), action, exceptionAndAlertHandler, this, location.getRow(), location.getCol());
ActionBox actionBox = new ActionBox(getClientProfile().getActionSize(), action, exceptionAndAlertHandler, this, location.getRow(), location.getCol());
actionBox.setStreamPiParent(currentParent);
actionBox.setStreamPiParent(currentParent);
clearActionBox(location.getCol(), location.getRow());
clearActionBox(location.getCol(), location.getRow());
System.out.println(location.getCol()+","+location.getRow());
System.out.println(location.getCol()+","+location.getRow());
add(actionBox, location.getRow(), location.getCol());
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;
}
}
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(String actionID) {
public void renderFolder(String actionID) {
setCurrentParent(clientProfile.getActionFromID(actionID).getID());
setCurrentParent(clientProfile.getActionFromID(actionID).getID());
setPreviousParent(clientProfile.getActionFromID(actionID).getParent());
setPreviousParent(clientProfile.getActionFromID(actionID).getParent());
try {
try {
renderGrid();
renderGrid();
renderActions();
renderActions();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
@Override
@Override
public void normalActionClicked(String ID) {
public void normalActionClicked(String ID) {
if(clientListener.isConnected())
if(clientListener.isConnected())
clientListener.onNormalActionClicked(getClientProfile().getID(), ID);
clientListener.onNormalActionClicked(getClientProfile().getID(), ID);
else
else
exceptionAndAlertHandler.onAlert("Not Connected", "Not Connected to any Server", StreamPiAlertType.ERROR);
exceptionAndAlertHandler.onAlert("Not Connected", "Not Connected to any Server", StreamPiAlertType.ERROR);
}
}
@Override
@Override
public void combineActionClicked(String ID) {
public void combineActionClicked(String ID) {
if(clientListener.isConnected())
if(clientListener.isConnected())
{
{
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
Action action = getClientProfile().getActionFromID(ID);
Action action = getClientProfile().getActionFromID(ID);
for(int i = 0;i<action.getClientProperties().get().size();i++)
for(int i = 0;i<action.getClientProperties().get().size();i++)
{
{
try {
try {
logger.info("Clicking "+i+", '"+action.getClientProperties().getSingleProperty(i+"").getRawValue()+"'");
logger.info("Clicking "+i+", '"+action.getClientProperties().getSingleProperty(i+"").getRawValue()+"'");
normalActionClicked(action.getClientProperties().getSingleProperty(i+"").getRawValue());
normalActionClicked(action.getClientProperties().getSingleProperty(i+"").getRawValue());
} catch (MinorException e) {
} catch (MinorException e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
return null;
return null;
}
}
}).start();
}).start();
}
}
}
}
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().getActionFromID(
setPreviousParent(getClientProfile().getActionFromID(
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/client/window/dashboard/actiongridpane/ActionGridPaneListener.java
+2
−2
package com.stream_pi.client.window.dashboard.actiongridpane;
package com.stream_pi.client.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 renderFolder(String ID);
void renderFolder(String ID);
void normalActionClicked(String ID);
void normalActionClicked(String ID);
void combineActionClicked(String ID);
void combineActionClicked(String ID);
}
}
package com.stream_pi.client.window.firsttimeuse;
package com.stream_pi.client.window.firsttimeuse;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
import com.stream_pi.client.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.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 com.stream_pi.util.platform.Platform;
import com.stream_pi.util.platform.Platform;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.control.TextField;
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 FinalConfigPane extends VBox
public class FinalConfigPane extends VBox
{
{
private TextField clientNicknameTextField;
private TextField clientNicknameTextField;
private TextField serverIPHostNameTextField;
private TextField serverIPHostNameTextField;
private TextField serverPortTextField;
private TextField serverPortTextField;
private TextField displayWidthTextField;
private TextField displayWidthTextField;
private TextField displayHeightTextField;
private TextField displayHeightTextField;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ClientListener clientListener;
private ClientListener clientListener;
public FinalConfigPane(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener)
public FinalConfigPane(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener)
{
{
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.clientListener = clientListener;
this.clientListener = clientListener;
getStyleClass().add("first_time_use_pane_final_config");
getStyleClass().add("first_time_use_pane_final_config");
Label label = new Label("Thats it. Now just a little bit and then you're set!");
Label label = new Label("Thats it. Now just a little bit and then you're set!");
label.setWrapText(true);
label.setWrapText(true);
VBox.setVgrow(label, Priority.ALWAYS);
VBox.setVgrow(label, Priority.ALWAYS);
label.getStyleClass().add("first_time_use_pane_final_config_label");
label.getStyleClass().add("first_time_use_pane_final_config_label");
clientNicknameTextField = new TextField();
clientNicknameTextField = new TextField();
serverIPHostNameTextField = new TextField();
serverIPHostNameTextField = new TextField();
serverPortTextField = new TextField();
serverPortTextField = new TextField();
displayWidthTextField = new TextField();
displayWidthTextField = new TextField();
displayHeightTextField = new TextField();
displayHeightTextField = new TextField();
HBoxInputBox clientNickNameInputBox = new HBoxInputBox("Nickname", clientNicknameTextField);
HBoxInputBox clientNickNameInputBox = new HBoxInputBox("Nickname", clientNicknameTextField);
HBoxInputBox serverIPHostNameInputBox = new HBoxInputBox("Server IP", serverIPHostNameTextField);
HBoxInputBox serverIPHostNameInputBox = new HBoxInputBox("Server IP", serverIPHostNameTextField);
HBoxInputBox serverIPPortInputBox = new HBoxInputBox("Server Port", serverPortTextField);
HBoxInputBox serverIPPortInputBox = new HBoxInputBox("Server Port", serverPortTextField);
HBoxInputBox displayWidthInputBox = new HBoxInputBox("Display Width", displayWidthTextField);
HBoxInputBox displayWidthInputBox = new HBoxInputBox("Display Width", displayWidthTextField);
HBoxInputBox displayHeightInputBox = new HBoxInputBox("Display Height", displayHeightTextField);
HBoxInputBox displayHeightInputBox = new HBoxInputBox("Display Height", displayHeightTextField);
if(ClientInfo.getInstance().getPlatformType() == Platform.ANDROID)
if(ClientInfo.getInstance().getPlatformType() == Platform.ANDROID)
{
{
displayWidthInputBox.setVisible(false);
displayWidthInputBox.setVisible(false);
displayHeightInputBox.setVisible(false);
displayHeightInputBox.setVisible(false);
}
}
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);
VBox v = new VBox(clientNickNameInputBox, serverIPHostNameInputBox, serverIPPortInputBox,
VBox v = new VBox(clientNickNameInputBox, serverIPHostNameInputBox, serverIPPortInputBox,
displayWidthInputBox, displayHeightInputBox);
displayWidthInputBox, displayHeightInputBox);
v.setSpacing(10.0);
v.setSpacing(10.0);
ScrollPane scrollPane = new ScrollPane(v);
ScrollPane scrollPane = new ScrollPane(v);
scrollPane.getStyleClass().add("first_time_use_final_config_pane_scroll_pane");
scrollPane.getStyleClass().add("first_time_use_final_config_pane_scroll_pane");
v.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
v.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
getChildren().addAll(label, scrollPane,new SpaceFiller(FillerType.VBox), bBar);
getChildren().addAll(label, scrollPane, 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();
if(clientNicknameTextField.getText().isBlank())
if(clientNicknameTextField.getText().isBlank())
{
{
errors.append("* Nick name cannot be blank.\n");
errors.append("* Nick name cannot be blank.\n");
}
}
if(serverIPHostNameTextField.getText().isBlank())
if(serverIPHostNameTextField.getText().isBlank())
{
{
errors.append("* Server IP cannot be empty.\n");
errors.append("* Server IP cannot be empty.\n");
}
}
int port = -1;
int port = -1;
try
try
{
{
port = Integer.parseInt(serverPortTextField.getText());
port = Integer.parseInt(serverPortTextField.getText());
if(port < 1024)
if(port < 1024)
errors.append("* Server IP should be above 1024.\n");
errors.append("* Server IP should be above 1024.\n");
}
}
catch (NumberFormatException exception)
catch (NumberFormatException exception)
{
{
errors.append("* Server IP should be a number.\n");
errors.append("* Server IP should be a number.\n");
}
}
double width=-1,height=-1;
double width=-1,height=-1;
if(ClientInfo.getInstance().getPlatformType() != Platform.ANDROID)
if(ClientInfo.getInstance().getPlatformType() != Platform.ANDROID)
{
{
try
try
{
{
width = Double.parseDouble(displayWidthTextField.getText());
width = Double.parseDouble(displayWidthTextField.getText());
if(width < 0)
if(width < 0)
errors.append("* Display Width should be above 0.\n");
errors.append("* Display Width should be above 0.\n");
}
}
catch (NumberFormatException exception)
catch (NumberFormatException exception)
{
{
errors.append("* Display Width should be a number.\n");
errors.append("* Display Width should be a number.\n");
}
}
try
try
{
{
height = Double.parseDouble(displayHeightTextField.getText());
height = Double.parseDouble(displayHeightTextField.getText());
if(height < 0)
if(height < 0)
errors.append("* Display Height should be above 0.\n");
errors.append("* Display Height should be above 0.\n");
}
}
catch (NumberFormatException exception)
catch (NumberFormatException exception)
{
{
errors.append("* Display Height should be a number.\n");
errors.append("* Display Height should be a number.\n");
}
}
}
}
if(errors.toString().isEmpty())
if(errors.toString().isEmpty())
{
{
try
try
{
{
Config.getInstance().setNickName(clientNicknameTextField.getText());
Config.getInstance().setNickName(clientNicknameTextField.getText());
Config.getInstance().setServerHostNameOrIP(serverIPHostNameTextField.getText());
Config.getInstance().setServerHostNameOrIP(serverIPHostNameTextField.getText());
Config.getInstance().setServerPort(port);
Config.getInstance().setServerPort(port);
Config.getInstance().setFirstTimeUse(false);
Config.getInstance().setFirstTimeUse(false);
if(ClientInfo.getInstance().getPlatformType() != Platform.ANDROID)
if(ClientInfo.getInstance().getPlatformType() != Platform.ANDROID)
{
{
Config.getInstance().setStartupWindowSize(
Config.getInstance().setStartupWindowSize(
width, height
width, height
);
);
}
}
Config.getInstance().save();
Config.getInstance().save();
clientListener.init();
clientListener.init();
}
}
catch(SevereException e)
catch(SevereException e)
{
{
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
}
}
else
else
{
{
new StreamPiAlert("Uh Oh", "Please rectify the following errors and try again:\n"+errors.toString(), StreamPiAlertType.ERROR).show();
new StreamPiAlert("Uh Oh", "Please rectify the following errors and try again:\n"+errors.toString(), StreamPiAlertType.ERROR).show();
}
}
}
}
}
}
package com.stream_pi.client.window.firsttimeuse;
package com.stream_pi.client.window.firsttimeuse;
import com.stream_pi.client.Main;
import com.stream_pi.client.Main;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
import com.stream_pi.client.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, ClientListener clientListener)
public FirstTimeUse(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener)
{
{
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, clientListener);
finalConfigPane = new FinalConfigPane(exceptionAndAlertHandler, clientListener);
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.getStyleClass().add("first_time_use_pane_button_bar");
buttonBar.getStyleClass().add("first_time_use_pane_button_bar");
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.client.window.settings;
package com.stream_pi.client.window.settings;
import java.io.File;
import java.io.File;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.connection.ClientListener;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
import com.stream_pi.client.window.ExceptionAndAlertHandler;
import com.stream_pi.themeapi.Theme;
import com.stream_pi.theme_api.Theme;
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.combobox.StreamPiComboBox;
import com.stream_pi.util.combobox.StreamPiComboBox;
import com.stream_pi.util.combobox.StreamPiComboBoxFactory;
import com.stream_pi.util.combobox.StreamPiComboBoxFactory;
import com.stream_pi.util.combobox.StreamPiComboBoxListener;
import com.stream_pi.util.combobox.StreamPiComboBoxListener;
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.startatboot.SoftwareType;
import com.stream_pi.util.startatboot.SoftwareType;
import com.stream_pi.util.startatboot.StartAtBoot;
import com.stream_pi.util.startatboot.StartAtBoot;
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.VBox;
import javafx.scene.layout.VBox;
public class SettingsBase extends VBox {
public class SettingsBase extends VBox {
private TextField serverPortTextField;
private TextField serverPortTextField;
private TextField serverHostNameOrIPTextField;
private TextField serverHostNameOrIPTextField;
private StreamPiComboBox<ClientProfile> clientProfileComboBox;
private StreamPiComboBox<ClientProfile> clientProfileComboBox;
private StreamPiComboBox<Theme> themeComboBox;
private StreamPiComboBox<Theme> themeComboBox;
private TextField displayWidthTextField;
private TextField displayWidthTextField;
private TextField displayHeightTextField;
private TextField displayHeightTextField;
private TextField nickNameTextField;
private TextField nickNameTextField;
private Button closeButton;
private Button closeButton;
private Button saveButton;
private Button saveButton;
private Button connectDisconnectButton;
private Button connectDisconnectButton;
private Button shutdownButton;
private Button shutdownButton;
private ToggleButton startOnBootToggleButton;
private ToggleButton startOnBootToggleButton;
private ToggleButton showCursorToggleButton;
private ToggleButton showCursorToggleButton;
private ToggleButton fullScreenToggleButton;
private ToggleButton fullScreenToggleButton;
private ClientListener clientListener;
private ClientListener clientListener;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private TextField themesPathTextField;
private TextField themesPathTextField;
private TextField iconsPathTextField;
private TextField iconsPathTextField;
private TextField profilesPathTextField;
private TextField profilesPathTextField;
public SettingsBase(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener) {
public SettingsBase(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener) {
getStyleClass().add("settings_base");
getStyleClass().add("settings_base");
this.clientListener = clientListener;
this.clientListener = clientListener;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
serverPortTextField = new TextField();
serverPortTextField = new TextField();
serverHostNameOrIPTextField = new TextField();
serverHostNameOrIPTextField = new TextField();
nickNameTextField = new TextField();
nickNameTextField = new TextField();
clientProfileComboBox = new StreamPiComboBox<>();
clientProfileComboBox = new StreamPiComboBox<>();
clientProfileComboBox.setStreamPiComboBoxFactory(new StreamPiComboBoxFactory<ClientProfile>()
clientProfileComboBox.setStreamPiComboBoxFactory(new StreamPiComboBoxFactory<ClientProfile>()
{
{
@Override
@Override
public String getOptionDisplayText(ClientProfile object)
public String getOptionDisplayText(ClientProfile object)
{
{
return object.getName();
return object.getName();
}
}
});
});
clientProfileComboBox.setStreamPiComboBoxListener(new StreamPiComboBoxListener<ClientProfile>(){
clientProfileComboBox.setStreamPiComboBoxListener(new StreamPiComboBoxListener<ClientProfile>(){
@Override
@Override
public void onNewItemSelected(ClientProfile selectedItem)
public void onNewItemSelected(ClientProfile selectedItem)
{
{
clientListener.renderProfile(selectedItem);
clientListener.renderProfile(selectedItem);
}
}
});
});
themeComboBox = new StreamPiComboBox<>();
themeComboBox = new StreamPiComboBox<>();
themeComboBox.setStreamPiComboBoxFactory(new StreamPiComboBoxFactory<Theme>()
themeComboBox.setStreamPiComboBoxFactory(new StreamPiComboBoxFactory<Theme>()
{
{
@Override
@Override
public String getOptionDisplayText(Theme object)
public String getOptionDisplayText(Theme object)
{
{
return object.getShortName();
return object.getShortName();
}
}
});
});
displayHeightTextField = new TextField();
displayHeightTextField = new TextField();
displayWidthTextField = new TextField();
displayWidthTextField = new TextField();
themesPathTextField = new TextField();
themesPathTextField = new TextField();
iconsPathTextField = new TextField();
iconsPathTextField = new TextField();
profilesPathTextField = new TextField();
profilesPathTextField = new TextField();
startOnBootToggleButton = new ToggleButton("Start On Boot");
startOnBootToggleButton = new ToggleButton("Start On Boot");
startOnBootToggleButton.managedProperty().bind(startOnBootToggleButton.visibleProperty());
startOnBootToggleButton.managedProperty().bind(startOnBootToggleButton.visibleProperty());
showCursorToggleButton = new ToggleButton("Show Cursor");
showCursorToggleButton = new ToggleButton("Show Cursor");
showCursorToggleButton.managedProperty().bind(showCursorToggleButton.visibleProperty());
showCursorToggleButton.managedProperty().bind(showCursorToggleButton.visibleProperty());
fullScreenToggleButton = new ToggleButton("Full Screen");
fullScreenToggleButton = new ToggleButton("Full Screen");
fullScreenToggleButton.managedProperty().bind(fullScreenToggleButton.visibleProperty());
fullScreenToggleButton.managedProperty().bind(fullScreenToggleButton.visibleProperty());
int prefWidth = 200;
int prefWidth = 200;
Label licenseLabel = new Label("This software is licensed to GNU GPLv3. Check StreamPi Server > settings > About to see full License Statement.");
Label licenseLabel = new Label("This software is licensed to GNU GPLv3. Check StreamPi Server > settings > About to see full License Statement.");
licenseLabel.setWrapText(true);
licenseLabel.setWrapText(true);
Label versionLabel = new Label(ClientInfo.getInstance().getReleaseStatus().getUIName() +" "+ClientInfo.getInstance().getVersion().getText());
Label versionLabel = new Label(ClientInfo.getInstance().getReleaseStatus().getUIName() +" "+ClientInfo.getInstance().getVersion().getText());
HBoxInputBox themesPathInputBox = new HBoxInputBox("Themes Path", themesPathTextField, prefWidth);
HBoxInputBox themesPathInputBox = new HBoxInputBox("Themes Path", themesPathTextField, prefWidth);
themesPathInputBox.managedProperty().bind(themesPathInputBox.visibleProperty());
themesPathInputBox.managedProperty().bind(themesPathInputBox.visibleProperty());
HBoxInputBox iconsPathInputBox = new HBoxInputBox("Icons Path", iconsPathTextField, prefWidth);
HBoxInputBox iconsPathInputBox = new HBoxInputBox("Icons Path", iconsPathTextField, prefWidth);
iconsPathInputBox.managedProperty().bind(iconsPathInputBox.visibleProperty());
iconsPathInputBox.managedProperty().bind(iconsPathInputBox.visibleProperty());
HBoxInputBox profilesPathInputBox = new HBoxInputBox("Profiles Path", profilesPathTextField, prefWidth);
HBoxInputBox profilesPathInputBox = new HBoxInputBox("Profiles Path", profilesPathTextField, prefWidth);
profilesPathInputBox.managedProperty().bind(profilesPathInputBox.visibleProperty());
profilesPathInputBox.managedProperty().bind(profilesPathInputBox.visibleProperty());
HBoxInputBox screenHeightInputBox = new HBoxInputBox("Screen Height", displayHeightTextField, prefWidth);
HBoxInputBox screenHeightInputBox = new HBoxInputBox("Screen Height", displayHeightTextField, prefWidth);
screenHeightInputBox.managedProperty().bind(screenHeightInputBox.visibleProperty());
screenHeightInputBox.managedProperty().bind(screenHeightInputBox.visibleProperty());
HBoxInputBox screenWidthInputBox = new HBoxInputBox("Screen Width", displayWidthTextField, prefWidth);
HBoxInputBox screenWidthInputBox = new HBoxInputBox("Screen Width", displayWidthTextField, prefWidth);
screenWidthInputBox.managedProperty().bind(screenWidthInputBox.visibleProperty());
screenWidthInputBox.managedProperty().bind(screenWidthInputBox.visibleProperty());
if(ClientInfo.getInstance().getPlatformType() == com.stream_pi.util.platform.Platform.ANDROID)
if(ClientInfo.getInstance().getPlatformType() == com.stream_pi.util.platform.Platform.ANDROID)
{
{
themesPathInputBox.setVisible(false);
themesPathInputBox.setVisible(false);
iconsPathInputBox.setVisible(false);
iconsPathInputBox.setVisible(false);
profilesPathInputBox.setVisible(false);
profilesPathInputBox.setVisible(false);
startOnBootToggleButton.setVisible(false);
startOnBootToggleButton.setVisible(false);
showCursorToggleButton.setVisible(false);
showCursorToggleButton.setVisible(false);
fullScreenToggleButton.setVisible(false);
fullScreenToggleButton.setVisible(false);
screenHeightInputBox.setVisible(false);
screenHeightInputBox.setVisible(false);
screenWidthInputBox.setVisible(false);
screenWidthInputBox.setVisible(false);
}
}
VBox vBox = new VBox(
VBox vBox = new VBox(
new HBoxInputBox("Device Name", nickNameTextField, prefWidth),
new HBoxInputBox("Device Name", nickNameTextField, prefWidth),
new HBoxInputBox("Host Name/IP", serverHostNameOrIPTextField, prefWidth),
new HBoxInputBox("Host Name/IP", serverHostNameOrIPTextField, prefWidth),
new HBoxInputBox("Port", serverPortTextField, prefWidth),
new HBoxInputBox("Port", serverPortTextField, prefWidth),
new HBox(
new HBox(
new Label("Current profile"),
new Label("Current profile"),
new SpaceFiller(SpaceFiller.FillerType.HBox),
SpaceFiller.horizontal(),
clientProfileComboBox
clientProfileComboBox
),
),
new HBox(
new HBox(
new Label("Theme"),
new Label("Theme"),
new SpaceFiller(SpaceFiller.FillerType.HBox),
SpaceFiller.horizontal(),
themeComboBox
themeComboBox
),
),
screenHeightInputBox,
screenHeightInputBox,
screenWidthInputBox,
screenWidthInputBox,
themesPathInputBox,
themesPathInputBox,
iconsPathInputBox,
iconsPathInputBox,
profilesPathInputBox,
profilesPathInputBox,
startOnBootToggleButton,
startOnBootToggleButton,
showCursorToggleButton,
showCursorToggleButton,
fullScreenToggleButton,
fullScreenToggleButton,
licenseLabel,
licenseLabel,
versionLabel
versionLabel
);
);
vBox.getStyleClass().add("settings_base_vbox");
vBox.getStyleClass().add("settings_base_vbox");
vBox.setSpacing(5.0);
vBox.setSpacing(5.0);
vBox.setPadding(new Insets(5));
vBox.setPadding(new Insets(5));
ScrollPane scrollPane = new ScrollPane();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
scrollPane.getStyleClass().add("settings_base_scroll_pane");
scrollPane.getStyleClass().add("settings_base_scroll_pane");
scrollPane.setContent(vBox);
scrollPane.setContent(vBox);
vBox.setMinWidth(300);
vBox.setMinWidth(300);
vBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
vBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
Label settingsLabel = new Label("Settings");
Label settingsLabel = new Label("Settings");
settingsLabel.setPadding(new Insets(5,0,0,5));
settingsLabel.setPadding(new Insets(5,0,0,5));
settingsLabel.getStyleClass().add("settings_heading_label");
settingsLabel.getStyleClass().add("settings_heading_label");
saveButton = new Button("Save");
saveButton = new Button("Save");
saveButton.setOnAction(event->onSaveButtonClicked());
saveButton.setOnAction(event->onSaveButtonClicked());
closeButton = new Button("Close");
closeButton = new Button("Close");
connectDisconnectButton = new Button("Connect");
connectDisconnectButton = new Button("Connect");
connectDisconnectButton.setOnAction(event -> onConnectDisconnectButtonClicked());
connectDisconnectButton.setOnAction(event -> onConnectDisconnectButtonClicked());
shutdownButton = new Button("Shutdown");
shutdownButton = new Button("Shutdown");
shutdownButton.setOnAction(event -> onShutdownButtonClicked());
shutdownButton.setOnAction(event -> onShutdownButtonClicked());
Button exitButton = new Button("Exit");
Button exitButton = new Button("Exit");
exitButton.setOnAction(event -> onExitButtonClicked());
exitButton.setOnAction(event -> onExitButtonClicked());
HBox buttonBar = new HBox(connectDisconnectButton, saveButton, exitButton, closeButton);
HBox buttonBar = new HBox(connectDisconnectButton, saveButton, exitButton, closeButton);
buttonBar.getStyleClass().add("settings_button_bar");
buttonBar.getStyleClass().add("settings_button_bar");
if(ClientInfo.getInstance().getPlatformType() == com.stream_pi.util.platform.Platform.LINUX &&
if(ClientInfo.getInstance().getPlatformType() == com.stream_pi.util.platform.Platform.LINUX &&
ClientInfo.getInstance().isShowShutDownButton())
ClientInfo.getInstance().isShowShutDownButton())
{
{
buttonBar.getChildren().add(shutdownButton);
buttonBar.getChildren().add(shutdownButton);
}
}
buttonBar.setPadding(new Insets(0,5,5,0));
buttonBar.setPadding(new Insets(0,5,5,0));
buttonBar.setSpacing(5.0);
buttonBar.setSpacing(5.0);
buttonBar.setAlignment(Pos.CENTER_RIGHT);
buttonBar.setAlignment(Pos.CENTER_RIGHT);
setSpacing(5.0);
setSpacing(5.0);
getChildren().addAll(
getChildren().addAll(
settingsLabel,
settingsLabel,
scrollPane,
scrollPane,
buttonBar
buttonBar
);
);
}
}
public void onExitButtonClicked()
public void onExitButtonClicked()
{
{
clientListener.onCloseRequest();
clientListener.onCloseRequest();
Platform.exit();
Platform.exit();
}
}
public void setDisableStatus(boolean status)
public void setDisableStatus(boolean status)
{
{
saveButton.setDisable(status);
saveButton.setDisable(status);
connectDisconnectButton.setDisable(status);
connectDisconnectButton.setDisable(status);
}
}
public void onShutdownButtonClicked()
public void onShutdownButtonClicked()
{
{
clientListener.onCloseRequest();
clientListener.onCloseRequest();
try {
try {
Runtime.getRuntime().exec("sudo halt");
Runtime.getRuntime().exec("sudo halt");
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
public void onConnectDisconnectButtonClicked()
public void onConnectDisconnectButtonClicked()
{
{
try
try
{
{
if(clientListener.isConnected())
if(clientListener.isConnected())
clientListener.disconnect("Client disconnected from settings");
clientListener.disconnect("Client disconnected from settings");
else
else
clientListener.setupClientConnection();
clientListener.setupClientConnection();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
}
}
public void setConnectDisconnectButtonStatus()
public void setConnectDisconnectButtonStatus()
{
{
Platform.runLater(()->{
Platform.runLater(()->{
setDisableStatus(false);
setDisableStatus(false);
if(clientListener.isConnected())
if(clientListener.isConnected())
connectDisconnectButton.setText("Disconnect");
connectDisconnectButton.setText("Disconnect");
else
else
connectDisconnectButton.setText("Connect");
connectDisconnectButton.setText("Connect");
});
});
}
}
public Button getCloseButton() {
public Button getCloseButton() {
return closeButton;
return closeButton;
}
}
public void loadData() throws SevereException
public void loadData() throws SevereException
{
{
nickNameTextField.setText(Config.getInstance().getClientNickName());
nickNameTextField.setText(Config.getInstance().getClientNickName());
serverHostNameOrIPTextField.setText(Config.getInstance().getSavedServerHostNameOrIP());
serverHostNameOrIPTextField.setText(Config.getInstance().getSavedServerHostNameOrIP());
serverPortTextField.setText(Config.getInstance().getSavedServerPort()+"");
serverPortTextField.setText(Config.getInstance().getSavedServerPort()+"");
clientProfileComboBox.setOptions(clientListener.getClientProfiles().getClientProfiles());
clientProfileComboBox.setOptions(clientListener.getClientProfiles().getClientProfiles());
int ind = 0;
int ind = 0;
for(int i = 0;i<clientProfileComboBox.getOptions().size();i++)
for(int i = 0;i<clientProfileComboBox.getOptions().size();i++)
{
{
if(clientProfileComboBox.getOptions().get(i).getID().equals(clientListener.getCurrentProfile().getID()))
if(clientProfileComboBox.getOptions().get(i).getID().equals(clientListener.getCurrentProfile().getID()))
{
{
ind = i;
ind = i;
break;
break;
}
}
}
}
clientProfileComboBox.setCurrentSelectedItemIndex(ind);
clientProfileComboBox.setCurrentSelectedItemIndex(ind);
themeComboBox.setOptions(clientListener.getThemes().getThemeList());
themeComboBox.setOptions(clientListener.getThemes().getThemeList());
int ind2 = 0;
int ind2 = 0;
for(int i = 0;i<themeComboBox.getOptions().size();i++)
for(int i = 0;i<themeComboBox.getOptions().size();i++)
{
{
if(themeComboBox.getOptions().get(i).getFullName().equals(clientListener.getCurrentTheme().getFullName()))
if(themeComboBox.getOptions().get(i).getFullName().equals(clientListener.getCurrentTheme().getFullName()))
{
{
ind2 = i;
ind2 = i;
break;
break;
}
}
}
}
themeComboBox.setCurrentSelectedItemIndex(ind2);
themeComboBox.setCurrentSelectedItemIndex(ind2);
displayWidthTextField.setText(Config.getInstance().getStartupWindowWidth()+"");
displayWidthTextField.setText(Config.getInstance().getStartupWindowWidth()+"");
displayHeightTextField.setText(Config.getInstance().getStartupWindowHeight()+"");
displayHeightTextField.setText(Config.getInstance().getStartupWindowHeight()+"");
themesPathTextField.setText(Config.getInstance().getThemesPath());
themesPathTextField.setText(Config.getInstance().getThemesPath());
iconsPathTextField.setText(Config.getInstance().getIconsPath());
iconsPathTextField.setText(Config.getInstance().getIconsPath());
profilesPathTextField.setText(Config.getInstance().getProfilesPath());
profilesPathTextField.setText(Config.getInstance().getProfilesPath());
startOnBootToggleButton.setSelected(Config.getInstance().isStartOnBoot());
startOnBootToggleButton.setSelected(Config.getInstance().isStartOnBoot());
fullScreenToggleButton.setSelected(Config.getInstance().isFullscreen());
fullScreenToggleButton.setSelected(Config.getInstance().isFullscreen());
showCursorToggleButton.setSelected(Config.getInstance().isShowCursor());
showCursorToggleButton.setSelected(Config.getInstance().isShowCursor());
}
}
public void onSaveButtonClicked()
public void onSaveButtonClicked()
{
{
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
int port = -1;
int port = -1;
try
try
{
{
port = Integer.parseInt(serverPortTextField.getText());
port = Integer.parseInt(serverPortTextField.getText());
if(port < 1024)
if(port < 1024)
errors.append("* Server IP should be above 1024.\n");
errors.append("* Server IP should be above 1024.\n");
}
}
catch (NumberFormatException exception)
catch (NumberFormatException exception)
{
{
errors.append("* Server IP should be a number.\n");
errors.append("* Server IP should be a number.\n");
}
}
double width = -1;
double width = -1;
try
try
{
{
width = Double.parseDouble(displayWidthTextField.getText());
width = Double.parseDouble(displayWidthTextField.getText());
if(width < 0)
if(width < 0)
errors.append("* Display Width should be above 0.\n");
errors.append("* Display Width should be above 0.\n");
}
}
catch (NumberFormatException exception)
catch (NumberFormatException exception)
{
{
errors.append("* Display Width should be a number.\n");
errors.append("* Display Width should be a number.\n");
}
}
double height = -1;
double height = -1;
try
try
{
{
height = Double.parseDouble(displayHeightTextField.getText());
height = Double.parseDouble(displayHeightTextField.getText());
if(height < 0)
if(height < 0)
errors.append("* Display Height should be above 0.\n");
errors.append("* Display Height should be above 0.\n");
}
}
catch (NumberFormatException exception)
catch (NumberFormatException exception)
{
{
errors.append("* Display Height should be a number.\n");
errors.append("* Display Height should be a number.\n");
}
}
if(serverHostNameOrIPTextField.getText().isBlank())
if(serverHostNameOrIPTextField.getText().isBlank())
{
{
errors.append("* Server IP cannot be empty.\n");
errors.append("* Server IP cannot be empty.\n");
}
}
if(nickNameTextField.getText().isBlank())
if(nickNameTextField.getText().isBlank())
{
{
errors.append("* Nick name cannot be blank.\n");
errors.append("* Nick name cannot be blank.\n");
}
}
if(!errors.toString().isEmpty())
if(!errors.toString().isEmpty())
{
{
exceptionAndAlertHandler.handleMinorException(new MinorException(
exceptionAndAlertHandler.handleMinorException(new MinorException(
"You made mistakes",
"You made mistakes",
"Please fix the errors and try again :\n"+errors.toString()
"Please fix the errors and try again :\n"+errors.toString()
));
));
return;
return;
}
}
try {
try {
boolean toBeReloaded = false;
boolean toBeReloaded = false;
boolean breakConnection = false;
boolean breakConnection = false;
if(!Config.getInstance().getCurrentThemeFullName().equals(themeComboBox.getCurrentSelectedItem().getFullName()))
if(!Config.getInstance().getCurrentThemeFullName().equals(themeComboBox.getCurrentSelectedItem().getFullName()))
toBeReloaded = true;
toBeReloaded = true;
Config.getInstance().setCurrentThemeFullName(themeComboBox.getCurrentSelectedItem().getFullName());
Config.getInstance().setCurrentThemeFullName(themeComboBox.getCurrentSelectedItem().getFullName());
if(width != Config.getInstance().getStartupWindowWidth() || height != Config.getInstance().getStartupWindowHeight())
if(width != Config.getInstance().getStartupWindowWidth() || height != Config.getInstance().getStartupWindowHeight())
toBeReloaded = true;
toBeReloaded = true;
Config.getInstance().setStartupWindowSize(width, height);
Config.getInstance().setStartupWindowSize(width, height);
if(!Config.getInstance().getClientNickName().equals(nickNameTextField.getText()))
if(!Config.getInstance().getClientNickName().equals(nickNameTextField.getText()))
breakConnection = true;
breakConnection = true;
Config.getInstance().setNickName(nickNameTextField.getText());
Config.getInstance().setNickName(nickNameTextField.getText());
if(port != Config.getInstance().getSavedServerPort() || !serverHostNameOrIPTextField.getText().equals(Config.getInstance().getSavedServerHostNameOrIP()))
if(port != Config.getInstance().getSavedServerPort() || !serverHostNameOrIPTextField.getText().equals(Config.getInstance().getSavedServerHostNameOrIP()))
breakConnection = true;
breakConnection = true;
Config.getInstance().setServerPort(port);
Config.getInstance().setServerPort(port);
Config.getInstance().setServerHostNameOrIP(serverHostNameOrIPTextField.getText());
Config.getInstance().setServerHostNameOrIP(serverHostNameOrIPTextField.getText());
boolean startOnBoot = startOnBootToggleButton.isSelected();
boolean startOnBoot = startOnBootToggleButton.isSelected();
if(Config.getInstance().isStartOnBoot() != startOnBoot)
if(Config.getInstance().isStartOnBoot() != startOnBoot)
{
{
if(ClientInfo.getInstance().getRunnerFileName() == null)
if(ClientInfo.getInstance().getRunnerFileName() == null)
{
{
new StreamPiAlert("Uh Oh", "No Runner File Name Specified as startup arguments. Cant set run at boot.", StreamPiAlertType.ERROR).show();
new StreamPiAlert("Uh Oh", "No Runner File Name Specified as startup arguments. Cant set run at boot.", StreamPiAlertType.ERROR).show();
startOnBoot = false;
startOnBoot = false;
}
}
else
else
{
{
StartAtBoot startAtBoot = new StartAtBoot(SoftwareType.CLIENT, ClientInfo.getInstance().getPlatformType());
StartAtBoot startAtBoot = new StartAtBoot(SoftwareType.CLIENT, ClientInfo.getInstance().getPlatformType());
if(startOnBoot)
if(startOnBoot)
{
{
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()));
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()));
}
}
else
else
{
{
boolean result = startAtBoot.delete();
boolean result = startAtBoot.delete();
if(!result)
if(!result)
new StreamPiAlert("Uh Oh!", "Unable to delete starter file", StreamPiAlertType.ERROR).show();
new StreamPiAlert("Uh Oh!", "Unable to delete starter file", StreamPiAlertType.ERROR).show();
}
}
}
}
}
}
Config.getInstance().setStartOnBoot(startOnBoot);
Config.getInstance().setStartOnBoot(startOnBoot);
if(Config.getInstance().isFullscreen() != fullScreenToggleButton.isSelected() ||
if(Config.getInstance().isFullscreen() != fullScreenToggleButton.isSelected() ||
Config.getInstance().isShowCursor() != showCursorToggleButton.isSelected())
Config.getInstance().isShowCursor() != showCursorToggleButton.isSelected())
toBeReloaded = true;
toBeReloaded = true;
Config.getInstance().setFullscreen(fullScreenToggleButton.isSelected());
Config.getInstance().setFullscreen(fullScreenToggleButton.isSelected());
Config.getInstance().setShowCursor(showCursorToggleButton.isSelected());
Config.getInstance().setShowCursor(showCursorToggleButton.isSelected());
if(!Config.getInstance().getThemesPath().equals(themesPathTextField.getText()))
if(!Config.getInstance().getThemesPath().equals(themesPathTextField.getText()))
toBeReloaded = true;
toBeReloaded = true;
Config.getInstance().setThemesPath(themesPathTextField.getText());
Config.getInstance().setThemesPath(themesPathTextField.getText());
if(!Config.getInstance().getIconsPath().equals(iconsPathTextField.getText()))
if(!Config.getInstance().getIconsPath().equals(iconsPathTextField.getText()))
toBeReloaded = true;
toBeReloaded = true;
Config.getInstance().setIconsPath(iconsPathTextField.getText());
Config.getInstance().setIconsPath(iconsPathTextField.getText());
if(!Config.getInstance().getProfilesPath().equals(profilesPathTextField.getText()))
if(!Config.getInstance().getProfilesPath().equals(profilesPathTextField.getText()))
toBeReloaded = true;
toBeReloaded = true;
Config.getInstance().setProfilesPath(profilesPathTextField.getText());
Config.getInstance().setProfilesPath(profilesPathTextField.getText());
Config.getInstance().save();
Config.getInstance().save();
loadData();
loadData();
if(breakConnection)
if(breakConnection)
{
{
if(clientListener.isConnected())
if(clientListener.isConnected())
clientListener.disconnect("Client connection settings were changed.");
clientListener.disconnect("Client connection settings were changed.");
}
}
if(toBeReloaded)
if(toBeReloaded)
{
{
clientListener.init();
clientListener.init();
clientListener.renderRootDefaultProfile();
clientListener.renderRootDefaultProfile();
}
}
}
}
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);
}
}
}
}
}
}
module com.stream_pi.client {
module com.stream_pi.client {
requires javafx.base;
requires javafx.base;
requires javafx.graphics;
requires javafx.graphics;
requires javafx.controls;
requires javafx.controls;
requires org.kordamp.iconli.core;
requires org.kordamp.iconli.core;
requires org.kordamp.ikonli.javafx;
requires org.kordamp.ikonli.javafx;
requires com.gluonhq.attach.lifecycle;
requires com.gluonhq.attach.lifecycle;
requires com.gluonhq.attach.util;
requires com.gluonhq.attach.util;
requires java.xml;
requires java.xml;
requires com.stream_pi.util;
requires com.stream_pi.util;
requires com.stream_pi.actionapi;
requires com.stream_pi.theme_api;
requires com.stream_pi.themeapi;
requires com.stream_pi.action_api;
requires org.kordamp.ikonli.fontawesome5;
requires org.kordamp.ikonli.fontawesome5;
exports com.stream_pi.client;
exports com.stream_pi.client;
}
}