client

Clone or download

Modified Files

package com.stream_pi.client;
package com.stream_pi.client;
import com.stream_pi.client.controller.Controller;
import com.stream_pi.client.controller.Controller;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import javafx.application.Application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.Stage;
public class Main extends Application {
public class Main extends Application {
@Override
@Override
public void start(Stage stage)
public void start(Stage stage)
{
{
Controller d = new Controller();
Controller d = new Controller();
Scene s = new Scene(d);
Scene s = new Scene(d);
stage.setScene(s);
stage.setScene(s);
d.setHostServices(getHostServices());
d.init();
d.init();
}
}
public static void main(String[] args)
public static void main(String[] args)
{
{
for(String eachArg : args)
for(String eachArg : args)
{
{
String[] r = eachArg.split("=");
String[] r = eachArg.split("=");
String arg = r[0];
String arg = r[0];
String val = r[1];
String val = r[1];
switch (arg) {
switch (arg) {
case "-DStreamPi.startupRunnerFileName":
case "-DStreamPi.startupRunnerFileName":
ClientInfo.getInstance().setRunnerFileName(val);
ClientInfo.getInstance().setRunnerFileName(val);
break;
break;
case "-DStreamPi.showShutDownButton":
case "-DStreamPi.showShutDownButton":
ClientInfo.getInstance().setShowShutDownButton(val.equals("true"));
ClientInfo.getInstance().setShowShutDownButton(val.equals("true"));
break;
break;
case "-DStreamPi.isXMode":
case "-DStreamPi.isXMode":
ClientInfo.getInstance().setXMode(val.equals("true"));
ClientInfo.getInstance().setXMode(val.equals("true"));
break;
break;
}
}
}
}
launch(args);
launch(args);
}
}
}
}
package com.stream_pi.client.connection;
package com.stream_pi.client.connection;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.action_api.actionproperty.ClientProperties;
import com.stream_pi.action_api.actionproperty.ClientProperties;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.action_api.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.theme_api.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.comms.Message;
import com.stream_pi.util.comms.Message;
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.version.Version;
import com.stream_pi.util.version.Version;
import javafx.application.Platform;
import javafx.application.Platform;
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 ObjectOutputStream oos;
private ObjectOutputStream oos;
private ObjectInputStream ois;
private ObjectInputStream ois;
private final AtomicBoolean stop = new AtomicBoolean(false);
private final AtomicBoolean stop = new AtomicBoolean(false);
private final ClientListener clientListener;
private final ClientListener clientListener;
private final ExceptionAndAlertHandler exceptionAndAlertHandler;
private final ExceptionAndAlertHandler exceptionAndAlertHandler;
private final ClientInfo clientInfo;
private final ClientInfo clientInfo;
private final String serverIP;
private final String serverIP;
private final int serverPort;
private final int serverPort;
private final Logger logger;
private final 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
{
{
oos = new ObjectOutputStream(socket.getOutputStream());
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
ois = new ObjectInputStream(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 synchronized void sendMessage(Message message) throws SevereException
public synchronized void sendMessage(Message message) throws SevereException
{
{
try
try
{
{
oos.writeObject(message);
oos.writeObject(message);
oos.flush();
oos.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!");
}
}
}
}
@Override
@Override
public void run() {
public void run() {
try
try
{
{
while(!stop.get())
while(!stop.get())
{
{
try
try
{
{
Message message = (Message) ois.readObject();
Message message = (Message) ois.readObject();
String header = message.getHeader();
String header = message.getHeader();
logger.info("Message Received. Heading : "+header);
logger.info("Message Received. Heading : "+header);
switch (header)
switch (header)
{
{
case "action_icon" : onActionIconReceived(message);
case "action_icon" : onActionIconReceived(message);
break;
break;
case "disconnect" : serverDisconnected(message);
case "disconnect" : serverDisconnected(message);
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(message);
case "get_profile_details": sendProfileDetailsToServer(message);
break;
break;
case "save_action_details": saveActionDetails(message);
case "save_action_details": saveActionDetails(message);
break;
break;
case "delete_action": deleteAction(message);
case "delete_action": deleteAction(message);
break;
break;
case "get_themes": sendThemesToServer();
case "get_themes": sendThemesToServer();
break;
break;
case "save_client_details": saveClientDetails(message);
case "save_client_details": saveClientDetails(message);
break;
break;
case "save_client_profile": saveProfileDetails(message);
case "save_client_profile": saveProfileDetails(message);
break;
break;
case "delete_profile": deleteProfile(message);
case "delete_profile": deleteProfile(message);
break;
break;
case "action_failed": actionFailed(message);
case "action_failed": actionFailed(message);
break;
break;
default: logger.warning("Command '"+header+"' does not match records. Make sure client and server versions are equal.");
default: logger.warning("Command '"+header+"' does not match records. Make sure client and server versions are equal.");
}
}
}
}
catch (IOException | ClassNotFoundException e)
catch (IOException | ClassNotFoundException 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;
}
}
}
}
}
}
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);
}
}
}
}
private void onActionIconReceived(Message message)
private void onActionIconReceived(Message message)
{
{
String profileID = message.getStringArrValue()[0];
String profileID = message.getStringArrValue()[0];
String actionID = message.getStringArrValue()[1];
String actionID = message.getStringArrValue()[1];
clientListener.getClientProfiles().getProfileFromID(profileID).saveActionIcon(
clientListener.getClientProfiles().getProfileFromID(profileID).saveActionIcon(
actionID,
actionID,
message.getByteArrValue()
message.getByteArrValue()
);
);
Action a = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
Action a = clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
clientListener.renderAction(profileID, a);
clientListener.renderAction(profileID, a);
}
}
//commands
//commands
public synchronized void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
public synchronized void sendIcon(String profileID, String actionID, byte[] icon) throws SevereException
{
{
try
try
{
{
Thread.sleep(50);
Thread.sleep(50);
}
}
catch (InterruptedException e)
catch (InterruptedException e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
Message message = new Message("action_icon");
Message message = new Message("action_icon");
message.setStringArrValue(profileID, actionID);
message.setStringArrValue(profileID, actionID);
message.setByteArrValue(icon);
message.setByteArrValue(icon);
sendMessage(message);
sendMessage(message);
}
}
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 ...");
Message m = new Message("disconnect");
Message m = new Message("disconnect");
m.setStringValue(message);
m.setStringValue(message);
sendMessage(m);
sendMessage(m);
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
{
{
Message message = new Message("themes");
Message message = new Message("themes");
String[] arr = new String[clientListener.getThemes().getThemeList().size()*4];
String[] arr = new String[clientListener.getThemes().getThemeList().size()*4];
int x = 0;
int x = 0;
for(int i = 0;i<clientListener.getThemes().getThemeList().size();i++)
for(int i = 0;i<clientListener.getThemes().getThemeList().size();i++)
{
{
Theme theme = clientListener.getThemes().getThemeList().get(i);
Theme theme = clientListener.getThemes().getThemeList().get(i);
arr[x] = theme.getFullName();
arr[x] = theme.getFullName();
arr[x+1] = theme.getShortName();
arr[x+1] = theme.getShortName();
arr[x+2] = theme.getAuthor();
arr[x+2] = theme.getAuthor();
arr[x+3] = theme.getVersion().getText();
arr[x+3] = theme.getVersion().getText();
x+=4;
x+=4;
}
}
message.setStringArrValue(arr);
message.setStringArrValue(arr);
sendMessage(message);
sendMessage(message);
}
}
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(Message message)
public void serverDisconnected(Message message)
{
{
stop.set(true);
stop.set(true);
String txt = "Disconnected!";
String txt = "Disconnected!";
String m = message.getStringValue();
String m = message.getStringValue();
if(!m.isBlank())
if(!m.isBlank())
txt = "Message : "+m;
txt = "Message : "+m;
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
{
{
String clientVersion = clientInfo.getVersion().getText();
String clientVersion = clientInfo.getVersion().getText();
String releaseStatus = clientInfo.getReleaseStatus().toString();
String releaseStatus = clientInfo.getReleaseStatus().toString();
String clientCommsStandard = clientInfo.getCommsStandardVersion().getText();
String clientCommStandard = clientInfo.getCommStandardVersion().getText();
String clientMinThemeStandard = clientInfo.getMinThemeSupportVersion().getText();
String clientMinThemeStandard = clientInfo.getMinThemeSupportVersion().getText();
String clientNickname = Config.getInstance().getClientNickName();
String clientNickname = Config.getInstance().getClientNickName();
String screenWidth = Config.getInstance().getStartupWindowWidth()+"";
String screenWidth = Config.getInstance().getStartupWindowWidth()+"";
String screenHeight = Config.getInstance().getStartupWindowHeight()+"";
String screenHeight = Config.getInstance().getStartupWindowHeight()+"";
String OS = clientInfo.getPlatformType()+"";
String OS = clientInfo.getPlatformType()+"";
String defaultProfileID = Config.getInstance().getStartupProfileID();
String defaultProfileID = Config.getInstance().getStartupProfileID();
Message toBeSent = new Message("client_details");
Message toBeSent = new Message("client_details");
toBeSent.setStringArrValue(
toBeSent.setStringArrValue(
clientVersion,
clientVersion,
releaseStatus,
releaseStatus,
clientCommsStandard,
clientCommStandard,
clientMinThemeStandard,
clientMinThemeStandard,
clientNickname,
clientNickname,
screenWidth,
screenWidth,
screenHeight,
screenHeight,
OS,
OS,
defaultProfileID,
defaultProfileID,
clientListener.getDefaultThemeFullName()
clientListener.getDefaultThemeFullName()
);
);
sendMessage(toBeSent);
sendMessage(toBeSent);
}
}
public void sendProfileNamesToServer() throws SevereException
public void sendProfileNamesToServer() throws SevereException
{
{
Message message = new Message("profiles");
Message message = new Message("profiles");
String[] arr = new String[clientListener.getClientProfiles().getClientProfiles().size()];
String[] arr = new String[clientListener.getClientProfiles().getClientProfiles().size()];
for(int i = 0;i<arr.length;i++)
for(int i = 0;i<arr.length;i++)
{
{
ClientProfile clientProfile = clientListener.getClientProfiles().getClientProfiles().get(i);
ClientProfile clientProfile = clientListener.getClientProfiles().getClientProfiles().get(i);
arr[i] = clientProfile.getID();
arr[i] = clientProfile.getID();
}
}
message.setStringArrValue(arr);
message.setStringArrValue(arr);
sendMessage(message);
sendMessage(message);
}
}
public void sendProfileDetailsToServer(Message message) throws SevereException
public void sendProfileDetailsToServer(Message message) throws SevereException
{
{
String ID = message.getStringValue();
String ID = message.getStringValue();
Message tbs1 = new Message("profile_details");
Message tbs1 = new Message("profile_details");
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(ID);
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(ID);
String[] arr = new String[]{
String[] arr = new String[]{
ID,
ID,
clientProfile.getName(),
clientProfile.getName(),
clientProfile.getRows()+"",
clientProfile.getRows()+"",
clientProfile.getCols()+"",
clientProfile.getCols()+"",
clientProfile.getActionSize()+"",
clientProfile.getActionSize()+"",
clientProfile.getActionGap()+""
clientProfile.getActionGap()+""
};
};
tbs1.setStringArrValue(arr);
tbs1.setStringArrValue(arr);
sendMessage(tbs1);
sendMessage(tbs1);
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())
{
{
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;
}
}
ArrayList<String> a = new ArrayList<>();
ArrayList<String> a = new ArrayList<>();
a.add(profileID);
a.add(profileID);
a.add(action.getID());
a.add(action.getID());
a.add(action.getActionType()+"");
a.add(action.getActionType()+"");
if(action.getActionType() == ActionType.NORMAL) {
if(action.getActionType() == ActionType.NORMAL) {
a.add(action.getVersion().getText());
a.add(action.getVersion().getText());
}
}
else
else
{
{
a.add("no");
a.add("no");
}
}
if(action.getActionType() ==ActionType.NORMAL)
if(action.getActionType() ==ActionType.NORMAL)
{
{
a.add(action.getModuleName());
a.add(action.getModuleName());
}
}
else
else
{
{
a.add("nut");
a.add("nut");
}
}
//display
//display
a.add(action.getBgColourHex());
a.add(action.getBgColourHex());
//icon
//icon
a.add(action.isHasIcon()+"");
a.add(action.isHasIcon()+"");
a.add(action.isShowIcon()+"");
a.add(action.isShowIcon()+"");
//text
//text
a.add(action.isShowDisplayText()+"");
a.add(action.isShowDisplayText()+"");
a.add(action.getDisplayTextFontColourHex());
a.add(action.getDisplayTextFontColourHex());
a.add(action.getDisplayText());
a.add(action.getDisplayText());
a.add(action.getDisplayTextAlignment()+"");
a.add(action.getDisplayTextAlignment()+"");
//location
//location
if(action.getLocation() == null)
if(action.getLocation() == null)
{
{
a.add("-1");
a.add("-1");
a.add("-1");
a.add("-1");
}
}
else
else
{
{
a.add(action.getLocation().getRow()+"");
a.add(action.getLocation().getRow()+"");
a.add(action.getLocation().getCol()+"");
a.add(action.getLocation().getCol()+"");
}
}
a.add(action.getParent());
a.add(action.getParent());
//client properties
//client properties
ClientProperties clientProperties = action.getClientProperties();
ClientProperties clientProperties = action.getClientProperties();
a.add(clientProperties.getSize()+"");
a.add(clientProperties.getSize()+"");
for(Property property : clientProperties.get())
for(Property property : clientProperties.get())
{
{
a.add(property.getName());
a.add(property.getName());
a.add(property.getRawValue());
a.add(property.getRawValue());
}
}
Message message = new Message("action_details");
Message message = new Message("action_details");
String[] x = new String[a.size()];
String[] x = new String[a.size()];
x = a.toArray(x);
x = a.toArray(x);
message.setStringArrValue(x);
message.setStringArrValue(x);
sendMessage(message);
sendMessage(message);
}
}
public void saveActionDetails(Message message)
public void saveActionDetails(Message message)
{
{
String[] r = message.getStringArrValue();
String[] r = message.getStringArrValue();
String profileID = r[0];
String profileID = r[0];
String actionID = r[1];
String actionID = r[1];
ActionType actionType = ActionType.valueOf(r[2]);
ActionType actionType = ActionType.valueOf(r[2]);
//3 - Version
//3 - Version
//4 - ModuleName
//4 - ModuleName
//display
//display
String bgColorHex = r[5];
String bgColorHex = r[5];
//icon
//icon
boolean isHasIcon = r[6].equals("true");
boolean isHasIcon = r[6].equals("true");
boolean isShowIcon = r[7].equals("true");
boolean isShowIcon = r[7].equals("true");
//text
//text
boolean isShowDisplayText = r[8].equals("true");
boolean isShowDisplayText = r[8].equals("true");
String displayFontColor = r[9];
String displayFontColor = r[9];
String displayText = r[10];
String displayText = r[10];
DisplayTextAlignment displayTextAlignment = DisplayTextAlignment.valueOf(r[11]);
DisplayTextAlignment displayTextAlignment = DisplayTextAlignment.valueOf(r[11]);
//location
//location
String row = r[12];
String row = r[12];
String col = r[13];
String col = r[13];
Location location = new Location(Integer.parseInt(row), Integer.parseInt(col));
Location location = new Location(Integer.parseInt(row), Integer.parseInt(col));
Action action = new Action(actionID, actionType);
Action action = new Action(actionID, actionType);
if(actionType == ActionType.NORMAL)
if(actionType == ActionType.NORMAL)
{
{
try
try
{
{
action.setVersion(new Version(r[3]));
action.setVersion(new Version(r[3]));
action.setModuleName(r[4]);
action.setModuleName(r[4]);
}
}
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);
String parent = r[14];
String parent = r[14];
action.setParent(parent);
action.setParent(parent);
//client properties
//client properties
int clientPropertiesSize = Integer.parseInt(r[15]);
int clientPropertiesSize = Integer.parseInt(r[15]);
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 = 16;i<((clientPropertiesSize*2) + 16); i+=2)
for(int i = 16;i<((clientPropertiesSize*2) + 16); i+=2)
{
{
Property property = new Property(r[i], Type.STRING);
Property property = new Property(r[i], Type.STRING);
property.setRawValue(r[i+1]);
property.setRawValue(r[i+1]);
clientProperties.addProperty(property);
clientProperties.addProperty(property);
}
}
action.setClientProperties(clientProperties);
action.setClientProperties(clientProperties);
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(isHasIcon)
action.setIcon(clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(action.getID()).getIconAsByteArray());
action.setIcon(clientListener.getClientProfiles().getProfileFromID(profileID).getActionFromID(action.getID()).getIconAsByteArray());
else
{
if(old.isHasIcon())
{
new File(Config.getInstance().getIconsPath()+"/"+actionID).delete();
}
}
}
}
clientListener.getClientProfiles().getProfileFromID(profileID).addAction(action);
clientListener.getClientProfiles().getProfileFromID(profileID).addAction(action);
clientListener.getClientProfiles().getProfileFromID(profileID).saveAction(action);
clientListener.getClientProfiles().getProfileFromID(profileID).saveAction(action);
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(Message message)
public void deleteAction(Message message)
{
{
try
try
{
{
String[] arr = message.getStringArrValue();
String[] arr = message.getStringArrValue();
String profileID = arr[0];
String profileID = arr[0];
String actionID = arr[1];
String actionID = arr[1];
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)
{
{
String currentParent = clientListener.getCurrentParent();
String currentParent = clientListener.getCurrentParent();
if(acc.getParent().equals(currentParent))
if(acc.getParent().equals(currentParent))
{
{
clientListener.clearActionBox(acc.getLocation().getCol(), acc.getLocation().getRow());
clientListener.clearActionBox(acc.getLocation().getCol(), acc.getLocation().getRow());
}
}
Platform.runLater(()->{
Platform.runLater(()->{
try
try
{
{
clientListener.renderRootDefaultProfile();
clientListener.renderRootDefaultProfile();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
});
});
}
}
}
}
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(Message message)
public void saveClientDetails(Message message)
{
{
try
try
{
{
String[] sep = message.getStringArrValue();
String[] sep = message.getStringArrValue();
Config.getInstance().setNickName(sep[0]);
Config.getInstance().setNickName(sep[0]);
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[1]),
Double.parseDouble(sep[1]),
Double.parseDouble(sep[2])
Double.parseDouble(sep[2])
);
);
Config.getInstance().setStartupProfileID(sep[3]);
Config.getInstance().setStartupProfileID(sep[3]);
String oldThemeFullName = Config.getInstance().getCurrentThemeFullName();
String oldThemeFullName = Config.getInstance().getCurrentThemeFullName();
Config.getInstance().setCurrentThemeFullName(sep[4]);
Config.getInstance().setCurrentThemeFullName(sep[4]);
if(!oldHeight.equals(sep[2]) || !oldWidth.equals(sep[1]) || !oldThemeFullName.equals(sep[4]))
if(!oldHeight.equals(sep[2]) || !oldWidth.equals(sep[1]) || !oldThemeFullName.equals(sep[4]))
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(Message message) throws SevereException, MinorException
public void saveProfileDetails(Message message) throws SevereException, MinorException
{
{
String[] sep = message.getStringArrValue();
String[] sep = message.getStringArrValue();
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(sep[0]);
ClientProfile clientProfile = clientListener.getClientProfiles().getProfileFromID(sep[0]);
if(clientProfile == null)
if(clientProfile == null)
{
{
clientProfile = new ClientProfile(new File(Config.getInstance().getProfilesPath()+"/"+sep[0]+".xml"),
clientProfile = new ClientProfile(new File(Config.getInstance().getProfilesPath()+"/"+sep[0]+".xml"),
Config.getInstance().getIconsPath());
Config.getInstance().getIconsPath());
}
}
clientProfile.setName(sep[1]);
clientProfile.setName(sep[1]);
clientProfile.setRows(Integer.parseInt(sep[2]));
clientProfile.setRows(Integer.parseInt(sep[2]));
clientProfile.setCols(Integer.parseInt(sep[3]));
clientProfile.setCols(Integer.parseInt(sep[3]));
clientProfile.setActionSize(Integer.parseInt(sep[4]));
clientProfile.setActionSize(Integer.parseInt(sep[4]));
clientProfile.setActionGap(Integer.parseInt(sep[5]));
clientProfile.setActionGap(Integer.parseInt(sep[5]));
try
try
{
{
clientListener.getClientProfiles().addProfile(clientProfile);
clientListener.getClientProfiles().addProfile(clientProfile);
clientProfile.saveProfileDetails();
clientProfile.saveProfileDetails();
clientListener.refreshGridIfCurrentProfile(sep[0]);
clientListener.refreshGridIfCurrentProfile(sep[0]);
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(Message message)
public void deleteProfile(Message message)
{
{
clientListener.getClientProfiles().deleteProfile(clientListener.getClientProfiles().getProfileFromID(
clientListener.getClientProfiles().deleteProfile(clientListener.getClientProfiles().getProfileFromID(
message.getStringValue()
message.getStringValue()
));
));
}
}
public void onActionClicked(String profileID, String actionID) throws SevereException
public void onActionClicked(String profileID, String actionID) throws SevereException
{
{
Message m = new Message("action_clicked");
Message m = new Message("action_clicked");
m.setStringArrValue(profileID, actionID);
m.setStringArrValue(profileID, actionID);
sendMessage(m);
sendMessage(m);
}
}
public void actionFailed(Message message)
public void actionFailed(Message message)
{
{
String[] r = message.getStringArrValue();
String[] r = message.getStringArrValue();
String profileID = r[0];
String profileID = r[0];
String actionID = r[1];
String actionID = r[1];
clientListener.onActionFailed(profileID, actionID);
clientListener.onActionFailed(profileID, actionID);
}
}
}
}
/*
/*
ServerInfo.java
ServerInfo.java
Stores basic information about the server - name, platform type
Stores basic information about the server - name, platform type
Contributors: Debayan Sutradhar (@dubbadhar)
Contributors: Debayan Sutradhar (@dubbadhar)
*/
*/
package com.stream_pi.client.info;
package com.stream_pi.client.info;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
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 java.io.File;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileNotFoundException;
import java.util.Optional;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Function;
public class ClientInfo {
public class ClientInfo {
private Version version;
private Version version;
private final ReleaseStatus releaseStatus;
private final ReleaseStatus releaseStatus;
private Platform platformType = null;
private Platform platformType;
private String prePath;
private String prePath;
private Version minThemeSupportVersion;
private Version minThemeSupportVersion;
private Version minPluginSupportVersion;
private Version minPluginSupportVersion;
private Version commsStandardVersion;
private Version commStandardVersion;
private String runnerFileName;
private String runnerFileName;
private static ClientInfo instance = null;
private static ClientInfo instance = null;
private ClientInfo(){
private ClientInfo()
{
try {
version = new Version(1,0,0);
version = new Version("1.0.0");
minThemeSupportVersion = new Version(1,0,0);
minThemeSupportVersion = new Version("1.0.0");
minPluginSupportVersion = new Version(1,0,0);
minPluginSupportVersion = new Version("1.0.0");
commStandardVersion = new Version(1,0,0);
commsStandardVersion = new Version("1.0.0");
} catch (MinorException e) {
e.printStackTrace();
}
releaseStatus = ReleaseStatus.EA;
releaseStatus = ReleaseStatus.EA;
if(platformType == null)
String osName = System.getProperty("os.name").toLowerCase();
if(osName.contains("windows"))
{
{
String osName = System.getProperty("os.name").toLowerCase();
prePath = "data/";
platformType = Platform.WINDOWS;
if(osName.contains("windows"))
}
{
else if (osName.contains("linux"))
prePath = "data/";
{
platformType = Platform.WINDOWS;
prePath = "data/";
}
platformType = Platform.LINUX;
else if (osName.contains("linux"))
}
{
else if(osName.contains("android")) // SPECIFY -Dsvm.targetName=android WHILE BUILDING ANDROID NATIVE IMAGE
if(osName.contains("raspberrypi"))
{
{
prePath = "/sdcard/Android/data/com.stream_pi.client/";
prePath = "data/";
platformType = Platform.ANDROID;
platformType = Platform.LINUX_RPI;
}
}
else if (osName.contains("mac"))
else
{
{
prePath = "data/";
prePath = "data/";
platformType = Platform.MAC;
platformType = Platform.LINUX;
}
}
else
}
{
else if(osName.contains("android")) // SPECIFY -Dsvm.targetName=android WHILE BUILDING ANDROID NATIVE IMAGE
prePath = "data/";
{
platformType = Platform.UNKNOWN;
prePath = "/sdcard/Android/data/com.stream_pi.client/";
platformType = Platform.ANDROID;
}
else if (osName.contains("mac"))
{
prePath = "data/";
platformType = Platform.MAC;
}
else
{
prePath = "data/";
platformType = Platform.UNKNOWN;
}
}
}
}
}
public void setRunnerFileName(String runnerFileName)
public void setRunnerFileName(String runnerFileName)
{
{
this.runnerFileName = runnerFileName;
this.runnerFileName = runnerFileName;
}
}
public String getRunnerFileName()
public String getRunnerFileName()
{
{
return runnerFileName;
return runnerFileName;
}
}
public static synchronized ClientInfo getInstance(){
public static synchronized ClientInfo getInstance(){
if(instance == null)
if(instance == null)
{
{
instance = new ClientInfo();
instance = new ClientInfo();
}
}
return instance;
return instance;
}
}
private boolean isShowShutDownButton = false;
private boolean isShowShutDownButton = false;
public void setShowShutDownButton(boolean showShutDownButton) {
public void setShowShutDownButton(boolean showShutDownButton) {
isShowShutDownButton = showShutDownButton;
isShowShutDownButton = showShutDownButton;
}
}
private boolean isXMode = false;
private boolean isXMode = false;
public void setXMode(boolean isXMode)
public void setXMode(boolean isXMode)
{
{
this.isXMode = isXMode;
this.isXMode = isXMode;
}
}
public boolean isXMode() {
public boolean isXMode() {
return isXMode;
return isXMode;
}
}
public boolean isShowShutDownButton() {
public boolean isShowShutDownButton() {
return isShowShutDownButton;
return isShowShutDownButton;
}
}
public String getPrePath()
public String getPrePath()
{
{
return prePath;
return prePath;
}
}
public Platform getPlatformType()
public Platform getPlatformType()
{
{
return platformType;
return platformType;
}
}
public Version getVersion() {
public Version getVersion() {
return version;
return version;
}
}
public ReleaseStatus getReleaseStatus()
public ReleaseStatus getReleaseStatus()
{
{
return releaseStatus;
return releaseStatus;
}
}
public Version getMinThemeSupportVersion()
public Version getMinThemeSupportVersion()
{
{
return minThemeSupportVersion;
return minThemeSupportVersion;
}
}
public Version getMinPluginSupportVersion()
public Version getMinPluginSupportVersion()
{
{
return minPluginSupportVersion;
return minPluginSupportVersion;
}
}
public Version getCommsStandardVersion()
public Version getCommStandardVersion()
{
{
return commsStandardVersion;
return commStandardVersion;
}
}
}
}
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.action_api.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.action_api.action.ActionType;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.DisplayTextAlignment;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.action_api.action.Location;
import com.stream_pi.action_api.actionproperty.ClientProperties;
import com.stream_pi.action_api.actionproperty.ClientProperties;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.action_api.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);
new File(iconsPath+"/"+ID).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.theme_api.Theme;
import com.stream_pi.theme_api.Theme;
import com.stream_pi.theme_api.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.application.HostServices;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
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;
@Override
@Override
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();
logFallbackHandler = new StreamPiLogFallbackHandler();
logFallbackHandler = new StreamPiLogFallbackHandler();
logger.addHandler(logFallbackHandler);
logger.addHandler(logFallbackHandler);
}
}
}
}
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();
}
}
private HostServices hostServices;
public void setHostServices(HostServices hostServices)
{
this.hostServices = hostServices;
}
public HostServices getHostServices()
{
return hostServices;
}
public void initBase() throws SevereException
public void initBase() throws SevereException
{
{
stage = (Stage) getScene().getWindow();
stage = (Stage) getScene().getWindow();
clientInfo = ClientInfo.getInstance();
clientInfo = ClientInfo.getInstance();
dashboardBase = new DashboardBase(this, this);
dashboardBase = new DashboardBase(this, this);
dashboardBase.setCache(true);
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, getHostServices());
settingsBase.setCache(true);
settingsBase.setCacheHint(CacheHint.SPEED);
alertStackPane = new StackPane();
alertStackPane = new StackPane();
alertStackPane.setPadding(new Insets(10));
alertStackPane.setPadding(new Insets(10));
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(alertStackPane);
getChildren().addAll(alertStackPane);
initLogger();
initLogger();
checkPrePathDirectory();
checkPrePathDirectory();
getChildren().addAll(settingsBase, dashboardBase);
getChildren().addAll(settingsBase, dashboardBase);
setStyle(null);
setStyle(null);
config = Config.getInstance();
config = Config.getInstance();
if(config.isFirstTimeUse())
if(config.isFirstTimeUse())
{
{
clearStylesheets();
clearStylesheets();
applyDefaultStylesheet();
applyDefaultStylesheet();
applyDefaultIconsStylesheet();
applyDefaultIconsStylesheet();
getChildren().add(firstTimeUse);
getChildren().add(firstTimeUse);
firstTimeUse.toFront();
firstTimeUse.toFront();
}
}
else
else
{
{
dashboardBase.toFront();
dashboardBase.toFront();
}
}
initThemes();
initThemes();
}
}
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
{
{
if(getClientInfo().getPlatformType() != Platform.ANDROID)
if(getClientInfo().getPlatformType() != Platform.ANDROID)
{
{
setPrefSize(300,300);
setPrefSize(300,300);
}
}
clearStylesheets();
clearStylesheets();
applyDefaultStylesheet();
applyDefaultStylesheet();
applyDefaultIconsStylesheet();
applyDefaultIconsStylesheet();
getStage().show();
getStage().show();
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 void applyDefaultIconsStylesheet()
public void applyDefaultIconsStylesheet()
{
{
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
getStylesheets().add(Main.class.getResource("default_icons.css").toExternalForm());
getStylesheets().add(Main.class.getResource("default_icons.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();
applyDefaultStylesheet();
applyDefaultStylesheet();
getStylesheets().addAll(t.getStylesheets());
getStylesheets().addAll(t.getStylesheets());
applyDefaultIconsStylesheet();
applyDefaultIconsStylesheet();
logger.info("... Done!");
logger.info("... Done!");
}
}
Themes themes;
Themes themes;
public void initThemes() throws SevereException
public void initThemes() 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;
package com.stream_pi.client.window.dashboard;
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.client.window.dashboard.actiongridpane.ActionGridPane;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionGridPane;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.CacheHint;
import javafx.scene.control.Button;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
public class DashboardBase extends VBox {
public class DashboardBase extends VBox {
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ActionGridPane actionGridPane;
private ActionGridPane actionGridPane;
private Button settingsButton;
private Button settingsButton;
public DashboardBase(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener)
public DashboardBase(ExceptionAndAlertHandler exceptionAndAlertHandler, ClientListener clientListener)
{
{
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
actionGridPane = new ActionGridPane(exceptionAndAlertHandler, clientListener);
actionGridPane = new ActionGridPane(exceptionAndAlertHandler, clientListener);
FontIcon fontIcon = new FontIcon("fas-cog");
FontIcon fontIcon = new FontIcon("fas-cog");
fontIcon.getStyleClass().addAll("dashboard_settings_button_icon");
fontIcon.getStyleClass().addAll("dashboard_settings_button_icon");
settingsButton = new Button();
settingsButton = new Button();
settingsButton.getStyleClass().addAll("dashboard_settings_button");
settingsButton.getStyleClass().addAll("dashboard_settings_button");
settingsButton.setGraphic(fontIcon);
settingsButton.setGraphic(fontIcon);
HBox hBox = new HBox(settingsButton);
HBox hBox = new HBox(settingsButton);
hBox.getStyleClass().add("dashboard_settings_button_parent");
hBox.getStyleClass().add("dashboard_settings_button_parent");
hBox.setPadding(new Insets(0,5,5,0));
hBox.setPadding(new Insets(0,5,5,0));
hBox.setAlignment(Pos.CENTER_RIGHT);
hBox.setAlignment(Pos.CENTER_RIGHT);
getChildren().addAll(actionGridPane,hBox);
getChildren().addAll(actionGridPane,hBox);
getStyleClass().add("dashboard");
getStyleClass().add("dashboard");
setCache(true);
setCacheHint(CacheHint.SPEED);
}
}
public void renderProfile(ClientProfile clientProfile) throws SevereException
public void renderProfile(ClientProfile clientProfile) throws SevereException
{
{
renderProfile(clientProfile, "root");
renderProfile(clientProfile, "root");
}
}
public void renderProfile(ClientProfile clientProfile, String currentParent) throws SevereException
public void renderProfile(ClientProfile clientProfile, String currentParent) throws SevereException
{
{
actionGridPane.setClientProfile(clientProfile);
actionGridPane.setClientProfile(clientProfile);
actionGridPane.setCurrentParent(currentParent);
actionGridPane.setCurrentParent(currentParent);
actionGridPane.renderGrid();
actionGridPane.renderGrid();
actionGridPane.renderActions();
actionGridPane.renderActions();
}
}
public void addBlankActionBox(int col, int row)
public void addBlankActionBox(int col, int row)
{
{
actionGridPane.addBlankActionBox(col, row);
actionGridPane.addBlankActionBox(col, row);
}
}
public void clearActionBox(int col, int row)
public void clearActionBox(int col, int row)
{
{
actionGridPane.clearActionBox(col, row);
actionGridPane.clearActionBox(col, row);
}
}
public ActionGridPane getActionGridPane() {
public ActionGridPane getActionGridPane() {
return actionGridPane;
return actionGridPane;
}
}
public Button getSettingsButton() {
public Button getSettingsButton() {
return settingsButton;
return settingsButton;
}
}
}
}
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.action_api.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.action_api.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.CacheHint;
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;
private ActionBox[][] actionBoxes;
private ActionBox[][] actionBoxes;
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);
setCache(true);
setCacheHint(CacheHint.SPEED);
}
}
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.animateStatus();
actionBox.animateStatus();
break;
break;
}
}
}*/
}*/
actionBoxes[action.getLocation().getCol()][action.getLocation().getRow()].animateStatus();
actionBoxes[action.getLocation().getCol()][action.getLocation().getRow()].animateStatus();
}
}
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;
}
}
private boolean isFreshRender = true;
private boolean isFreshRender = true;
private Node folderBackButton = null;
private Node folderBackButton = null;
public void renderGrid() throws SevereException
public void renderGrid() throws SevereException
{
{
setHgap(getClientProfile().getActionGap());
setHgap(getClientProfile().getActionGap());
setVgap(getClientProfile().getActionGap());
setVgap(getClientProfile().getActionGap());
if(isFreshRender)
if(isFreshRender)
{
{
clear();
clear();
actionBoxes = new ActionBox[cols][rows];
actionBoxes = new ActionBox[cols][rows];
}
}
boolean isFolder = false;
boolean isFolder = false;
if(getCurrentParent().equals("root"))
if(getCurrentParent().equals("root"))
{
{
if(folderBackButton != null)
if(folderBackButton != null)
{
{
getChildren().remove(folderBackButton);
getChildren().remove(folderBackButton);
folderBackButton = null;
folderBackButton = null;
actionBoxes[0][0] = addBlankActionBox(0,0);
actionBoxes[0][0] = addBlankActionBox(0,0);
}
}
}
}
else
else
{
{
isFolder = true;
isFolder = true;
if(folderBackButton != null)
if(folderBackButton != null)
{
{
getChildren().remove(folderBackButton);
getChildren().remove(folderBackButton);
folderBackButton = null;
folderBackButton = null;
}
}
else
else
{
{
getChildren().remove(actionBoxes[0][0]);
getChildren().remove(actionBoxes[0][0]);
}
}
folderBackButton = getFolderBackButton();
folderBackButton = getFolderBackButton();
add(folderBackButton, 0,0);
add(folderBackButton, 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;
if(isFreshRender)
if(isFreshRender)
{
{
actionBoxes[col][row] = addBlankActionBox(col, row);
actionBoxes[col][row] = addBlankActionBox(col, row);
}
}
else
else
{
{
if(actionBoxes[col][row].getAction() != null)
if(actionBoxes[col][row].getAction() != null)
{
{
logger.info("xc234213123123");
logger.info("xc234213123123");
actionBoxes[col][row].clear();
actionBoxes[col][row].clear();
}
}
else
else
{
{
logger.info("bbbbbb " +col+","+row);
logger.info("bbbbbb " +col+","+row);
}
}
}
}
logger.info(isFreshRender+"22222222222222222xxxxxxxxxx");
}
}
}
}
isFreshRender = false;
isFreshRender = false;
}
}
public void setFreshRender(boolean isFreshRender) {
public void setFreshRender(boolean isFreshRender) {
this.isFreshRender = isFreshRender;
this.isFreshRender = isFreshRender;
}
}
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)
{
{
actionBoxes[col][row].clear();
actionBoxes[col][row].clear();
}
}
public ActionBox getActionBox(int col, int row)
public ActionBox getActionBox(int col, int row)
{
{
return actionBoxes[col][row];
return actionBoxes[col][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 ActionBox addBlankActionBox(int col, int row)
public ActionBox 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);
return actionBox;
return actionBox;
}
}
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 = actionBoxes[location.getCol()][location.getRow()];
ActionBox actionBox = actionBoxes[location.getCol()][location.getRow()];
actionBox.clear();
actionBox.clear();
actionBox.setAction(action);
actionBox.setAction(action);
actionBox.setStreamPiParent(currentParent);
actionBox.setStreamPiParent(currentParent);
actionBox.init();
actionBox.init();
/*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());
actionBoxes[location.getCol()][location.getRow()] = actionBox;*/
actionBoxes[location.getCol()][location.getRow()] = actionBox;*/
}
}
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();
}
}
}
}
}
}
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.theme_api.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.checkforupdates.CheckForUpdates;
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.platform.PlatformType;
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.StartAtBoot;
import com.stream_pi.util.startatboot.StartAtBoot;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
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) {
private final Button checkForUpdatesButton;
private HostServices hostServices;
public SettingsBase(ExceptionAndAlertHandler exceptionAndAlertHandler,
ClientListener clientListener, HostServices hostServices)
{
getStyleClass().add("settings_base");
getStyleClass().add("settings_base");
this.hostServices = hostServices;
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);
}
}
checkForUpdatesButton = new Button("Check for updates");
checkForUpdatesButton.setOnAction(event->checkForUpdates());
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"),
SpaceFiller.horizontal(),
SpaceFiller.horizontal(),
clientProfileComboBox
clientProfileComboBox
),
),
new HBox(
new HBox(
new Label("Theme"),
new Label("Theme"),
SpaceFiller.horizontal(),
SpaceFiller.horizontal(),
themeComboBox
themeComboBox
),
),
screenHeightInputBox,
screenHeightInputBox,
screenWidthInputBox,
screenWidthInputBox,
themesPathInputBox,
themesPathInputBox,
iconsPathInputBox,
iconsPathInputBox,
profilesPathInputBox,
profilesPathInputBox
);
if(ClientInfo.getInstance().getPlatformType() == com.stream_pi.util.platform.Platform.LINUX &&
ClientInfo.getInstance().isShowShutDownButton())
{
shutdownButton = new Button("Shutdown");
shutdownButton.setOnAction(event -> onShutdownButtonClicked());
vBox.getChildren().add(shutdownButton);
}
vBox.getChildren().addAll(
checkForUpdatesButton,
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.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 &&
ClientInfo.getInstance().isShowShutDownButton())
{
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
);
);
setCache(true);
setCacheHint(CacheHint.SPEED);
}
private void checkForUpdates()
{
new CheckForUpdates(checkForUpdatesButton, hostServices,
PlatformType.CLIENT, ClientInfo.getInstance().getVersion());
}
}
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()))
{
{
breakConnection = true;
breakConnection = true;
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(PlatformType.CLIENT, ClientInfo.getInstance().getPlatformType());
if(startOnBoot)
if(startOnBoot)
{
{
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()),
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()),
ClientInfo.getInstance().isXMode());
ClientInfo.getInstance().isXMode());
}
}
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. Client will reconnect again.");
clientListener.disconnect("Client connection settings were changed. Client will reconnect again.");
clientListener.setupClientConnection();
clientListener.setupClientConnection();
}
}
}
}
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);
}
}
}
}
}
}