client
Clone or download
Modified Files
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.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
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 AtomicBoolean stop = new AtomicBoolean(false);
private final ClientListener clientListener;
private ClientListener clientListener;
private final ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private final ClientInfo clientInfo;
private ClientInfo clientInfo;
private final String serverIP;
private String serverIP;
private final int serverPort;
private int serverPort;
private final Logger logger;
private Logger logger;
public Client(String serverIP, int serverPort, ClientListener clientListener, ExceptionAndAlertHandler exceptionAndAlertHandler)
private Runnable onConnectAndSetupToBeRun;
public Client(String serverIP, int serverPort, ClientListener clientListener,
ExceptionAndAlertHandler exceptionAndAlertHandler, Runnable onConnectAndSetupToBeRun)
{
{
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;
this.onConnectAndSetupToBeRun = onConnectAndSetupToBeRun;
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 "ready" : onServerReady();
break;
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_client_screen_details" : sendClientScreenDetails();
case "get_client_screen_details" : sendClientScreenDetails();
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;
case "set_toggle_status": onSetToggleStatus(message);
case "set_toggle_status": onSetToggleStatus(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();
clientListener.onDisconnect();
clientListener.onDisconnect();
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 onSetToggleStatus(Message message)
private void onSetToggleStatus(Message message)
{
{
String[] arr = message.getStringArrValue();
String[] arr = message.getStringArrValue();
String profileID = arr[0];
String profileID = arr[0];
String actionID = arr[1];
String actionID = arr[1];
boolean newStatus = arr[2].equals("true");
boolean newStatus = arr[2].equals("true");
boolean currentStatus = clientListener.getToggleStatus(profileID,actionID);
boolean currentStatus = clientListener.getToggleStatus(profileID,actionID);
if(currentStatus == newStatus)
if(currentStatus == newStatus)
{
{
return;
return;
}
}
ActionBox actionBox = clientListener.getActionBoxByProfileAndID(profileID, actionID);
ActionBox actionBox = clientListener.getActionBoxByProfileAndID(profileID, actionID);
if(actionBox!=null)
if(actionBox!=null)
{
{
actionBox.setCurrentToggleStatus(newStatus);
actionBox.setCurrentToggleStatus(newStatus);
Platform.runLater(()-> actionBox.toggle(newStatus));
Platform.runLater(()-> actionBox.toggle(newStatus));
}
}
}
}
private void onActionIconReceived(Message message) throws MinorException
private void onActionIconReceived(Message message) throws MinorException
{
{
String profileID = message.getStringArrValue()[0];
String profileID = message.getStringArrValue()[0];
String actionID = message.getStringArrValue()[1];
String actionID = message.getStringArrValue()[1];
String state = message.getStringArrValue()[2];
String state = message.getStringArrValue()[2];
clientListener.getClientProfiles().getProfileFromID(profileID).saveActionIcon(
clientListener.getClientProfiles().getProfileFromID(profileID).saveActionIcon(
actionID,
actionID,
message.getByteArrValue(),
message.getByteArrValue(),
state
state
);
);
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, String state, byte[] icon) throws SevereException
public synchronized void sendIcon(String profileID, String actionID, String state, 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, state);
message.setStringArrValue(profileID, actionID, state);
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 onServerReady()
{
if(onConnectAndSetupToBeRun!=null)
{
onConnectAndSetupToBeRun.run();
onConnectAndSetupToBeRun = null;
}
}
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, String state) throws SevereException
public void sendActionIcon(String clientProfileID, String actionID, String state) throws SevereException
{
{
sendIcon(clientProfileID,
sendIcon(clientProfileID,
actionID,
actionID,
state,
state,
clientListener.getClientProfiles()
clientListener.getClientProfiles()
.getProfileFromID(clientProfileID)
.getProfileFromID(clientProfileID)
.getActionFromID(actionID).getIcon(state));
.getActionFromID(actionID).getIcon(state));
}
}
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.onDisconnect();
clientListener.onDisconnect();
clientListener.updateSettingsConnectDisconnectButton();
clientListener.updateSettingsConnectDisconnectButton();
}
}
public void sendClientScreenDetails() throws SevereException
public void sendClientScreenDetails() throws SevereException
{
{
String screenWidth = clientListener.getStageWidth() + "";
String screenHeight = clientListener.getStageHeight() + "";
Message toBeSent = new Message("client_screen_details");
Message toBeSent = new Message("client_screen_details");
toBeSent.setStringArrValue(
screenWidth,
toBeSent.setDoubleArrValue(
screenHeight
clientListener.getStageWidth(),
clientListener.getStageHeight()
);
);
sendMessage(toBeSent);
sendMessage(toBeSent);
}
}
public void sendClientDetails() throws SevereException
public void sendClientDetails() throws SevereException
{
{
sendClientDetails("register_client_details");
sendClientDetails("register_client_details");
}
}
public void updateClientDetails() throws SevereException
public void updateClientDetails() throws SevereException
{
{
sendClientDetails("update_client_details");
sendClientDetails("update_client_details");
}
}
public void sendClientDetails(String header) throws SevereException
public void sendClientDetails(String header) throws SevereException
{
{
String clientVersion = clientInfo.getVersion().getText();
String clientVersion = clientInfo.getVersion().getText();
String releaseStatus = clientInfo.getReleaseStatus().toString();
String releaseStatus = clientInfo.getReleaseStatus().toString();
String clientCommStandard = clientInfo.getCommStandardVersion().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 = clientListener.getStageWidth()+"";
String screenWidth = clientListener.getStageWidth()+"";
String screenHeight = clientListener.getStageHeight()+"";
String screenHeight = clientListener.getStageHeight()+"";
String OS = clientInfo.getPlatform()+"";
String OS = clientInfo.getPlatform()+"";
String defaultProfileID = Config.getInstance().getStartupProfileID();
String defaultProfileID = Config.getInstance().getStartupProfileID();
Message toBeSent = new Message(header);
Message toBeSent = new Message(header);
toBeSent.setStringArrValue(
toBeSent.setStringArrValue(
clientVersion,
clientVersion,
releaseStatus,
releaseStatus,
clientCommStandard,
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()];
int totalActions = 0;
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);
totalActions += clientProfile.getActions().size();
arr[i] = clientProfile.getID();
arr[i] = clientProfile.getID();
}
}
message.setStringArrValue(arr);
message.setStringArrValue(arr);
message.setIntValue(totalActions);
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();
logger.info("IDDDD : "+ID);
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())
{
{
for(String key : action.getIcons().keySet())
for(String key : action.getIcons().keySet())
{
{
sendActionIcon(clientProfile.getID(), action.getID(), key);
sendActionIcon(clientProfile.getID(), action.getID(), key);
}
}
}
}
}
}
}
}
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 ||
action.getActionType() == ActionType.TOGGLE) {
action.getActionType() == ActionType.TOGGLE) {
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 ||
action.getActionType() == ActionType.TOGGLE)
action.getActionType() == ActionType.TOGGLE)
{
{
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
StringBuilder allIconStatesNames = new StringBuilder();
StringBuilder allIconStatesNames = new StringBuilder();
for(String eachState : action.getIcons().keySet())
for(String eachState : action.getIcons().keySet())
{
{
allIconStatesNames.append(eachState).append("::");
allIconStatesNames.append(eachState).append("::");
}
}
a.add(allIconStatesNames.toString());
a.add(allIconStatesNames.toString());
a.add(action.getCurrentIconState()+"");
a.add(action.getCurrentIconState()+"");
//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());
a.add(action.getDelayBeforeExecuting()+"");
a.add(action.getDelayBeforeExecuting()+"");
//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];
String[] iconStates = r[6].split("::");
String[] iconStates = r[6].split("::");
String currentIconState = r[7];
String currentIconState = r[7];
//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 || actionType == ActionType.TOGGLE)
if(actionType == ActionType.NORMAL || actionType == ActionType.TOGGLE)
{
{
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.setShowDisplayText(isShowDisplayText);
action.setShowDisplayText(isShowDisplayText);
action.setDisplayTextFontColourHex(displayFontColor);
action.setDisplayTextFontColourHex(displayFontColor);
action.setDisplayText(displayText);
action.setDisplayText(displayText);
action.setDisplayTextAlignment(displayTextAlignment);
action.setDisplayTextAlignment(displayTextAlignment);
action.setCurrentIconState(currentIconState);
action.setCurrentIconState(currentIconState);
action.setLocation(location);
action.setLocation(location);
String parent = r[14];
String parent = r[14];
action.setParent(parent);
action.setParent(parent);
//client properties
//client properties
action.setDelayBeforeExecuting(Integer.parseInt(r[15]));
action.setDelayBeforeExecuting(Integer.parseInt(r[15]));
int clientPropertiesSize = Integer.parseInt(r[16]);
int clientPropertiesSize = Integer.parseInt(r[16]);
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 = 17;i<((clientPropertiesSize*2) + 17); i+=2)
for(int i = 17;i<((clientPropertiesSize*2) + 17); 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);
for(String state : iconStates)
for(String state : iconStates)
{
{
action.addIcon(state, null);
action.addIcon(state, null);
}
}
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)
{
{
for(String oldState : old.getIcons().keySet())
for(String oldState : old.getIcons().keySet())
{
{
boolean isPresent = false;
boolean isPresent = false;
for(String state : iconStates)
for(String state : iconStates)
{
{
if(state.equals(oldState))
if(state.equals(oldState))
{
{
isPresent = true;
isPresent = true;
break;
break;
}
}
}
}
if(!isPresent)
if(!isPresent)
{
{
// State no longer exists. Delete.
// State no longer exists. Delete.
new File(Config.getInstance().getIconsPath()+"/"+actionID+"___"+oldState).delete();
new File(Config.getInstance().getIconsPath()+"/"+actionID+"___"+oldState).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 == null)
if(acc == null)
{
{
exceptionAndAlertHandler.handleMinorException(new MinorException("Unable to delete action "+actionID+" since it does not exist."));
exceptionAndAlertHandler.handleMinorException(new MinorException("Unable to delete action "+actionID+" since it does not exist."));
return;
return;
}
}
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);
}
}
Platform.runLater(clientListener::renderRootDefaultProfile);
Platform.runLater(clientListener::renderRootDefaultProfile);
}
}
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)
{
{
Platform.runLater(()-> {
Platform.runLater(()-> {
if (clientListener.getCurrentProfile().getID().equals(profileID)
if (clientListener.getCurrentProfile().getID().equals(profileID)
&& clientListener.getCurrentParent().equals(acc.getParent()))
&& clientListener.getCurrentParent().equals(acc.getParent()))
{
{
clientListener.clearActionBox(
clientListener.clearActionBox(
acc.getLocation().getCol(),
acc.getLocation().getCol(),
acc.getLocation().getRow()
acc.getLocation().getRow()
);
);
}
}
});
});
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
}
}
public void saveClientDetails(Message message)
public void saveClientDetails(Message message)
{
{
try
try
{
{
boolean reInit = false;
boolean reInit = false;
String[] sep = message.getStringArrValue();
String[] sep = message.getStringArrValue();
Config.getInstance().setNickName(sep[0]);
Config.getInstance().setNickName(sep[0]);
Config.getInstance().setStartupProfileID(sep[1]);
Config.getInstance().setStartupProfileID(sep[1]);
String oldThemeFullName = Config.getInstance().getCurrentThemeFullName();
String oldThemeFullName = Config.getInstance().getCurrentThemeFullName();
String newThemeFullName = sep[2];
String newThemeFullName = sep[2];
if(!oldThemeFullName.equals(newThemeFullName))
if(!oldThemeFullName.equals(newThemeFullName))
{
{
reInit = true;
reInit = true;
}
}
Config.getInstance().setCurrentThemeFullName(sep[2]);
Config.getInstance().setCurrentThemeFullName(sep[2]);
Config.getInstance().save();
Config.getInstance().save();
if(reInit)
if(reInit)
{
{
Platform.runLater(clientListener::init);
Platform.runLater(clientListener::init);
}
}
else
else
{
{
Platform.runLater(clientListener::loadSettings);
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]);
Platform.runLater(clientListener::loadSettings);
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()
));
));
if(clientListener.getCurrentProfile().getID().equals(message.getStringValue()))
if(clientListener.getCurrentProfile().getID().equals(message.getStringValue()))
{
{
Platform.runLater(clientListener::renderRootDefaultProfile);
Platform.runLater(clientListener::renderRootDefaultProfile);
}
}
}
}
public void onActionClicked(String profileID, String actionID, boolean toggleState) throws SevereException
public void onActionClicked(String profileID, String actionID, boolean toggleState) throws SevereException
{
{
Message m = new Message("action_clicked");
Message m = new Message("action_clicked");
m.setStringArrValue(profileID, actionID, toggleState+"");
m.setStringArrValue(profileID, actionID, toggleState+"");
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);
}
}
}
}
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.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionGridPaneListener;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionGridPaneListener;
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.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
public interface ClientListener
public interface ClientListener
{
{
void onActionFailed(String profileID, String actionID);
void onActionFailed(String profileID, String actionID);
void onActionClicked(String profileID, String actionID, boolean toggleState);
void onActionClicked(String profileID, String actionID, boolean toggleState);
ClientProfiles getClientProfiles();
ClientProfiles getClientProfiles();
Themes getThemes();
Themes getThemes();
String getDefaultThemeFullName();
String getDefaultThemeFullName();
Client getClient();
Client getClient();
void renderRootDefaultProfile();
void renderRootDefaultProfile();
void setConnected(boolean isConnected);
void setConnected(boolean isConnected);
boolean isConnected();
boolean isConnected();
void renderProfile(ClientProfile clientProfile, boolean freshRender);
void renderProfile(ClientProfile clientProfile, boolean freshRender);
void clearActionBox(int col, int row);
void clearActionBox(int col, int row);
void addBlankActionBox(int col, int row);
void addBlankActionBox(int col, int row);
void renderAction(String currentProfileID, Action action);
void renderAction(String currentProfileID, Action action);
void refreshGridIfCurrentProfile(String currentProfileID);
void refreshGridIfCurrentProfile(String currentProfileID);
ActionBox getActionBox(int col, int row);
ActionBox getActionBox(int col, int row);
ClientProfile getCurrentProfile();
ClientProfile getCurrentProfile();
String getCurrentParent();
String getCurrentParent();
Theme getCurrentTheme();
Theme getCurrentTheme();
void initLogger() throws SevereException;
void initLogger() throws SevereException;
void init();
void init();
void disconnect(String message) throws SevereException;
void disconnect(String message) throws SevereException;
void setupClientConnection();
void setupClientConnection();
void setupClientConnection(Runnable onConnect);
void updateSettingsConnectDisconnectButton();
void updateSettingsConnectDisconnectButton();
void onCloseRequest();
void onCloseRequest();
void loadSettings();
void loadSettings();
double getStageWidth();
double getStageWidth();
double getStageHeight();
double getStageHeight();
void onDisconnect();
void onDisconnect();
boolean getToggleStatus(String profileID, String actionID);
boolean getToggleStatus(String profileID, String actionID);
ActionBox getActionBoxByProfileAndID(String profileID, String actionID);
ActionBox getActionBoxByProfileAndID(String profileID, String actionID);
}
}
package com.stream_pi.client.controller;
package com.stream_pi.client.controller;
import com.gluonhq.attach.vibration.VibrationService;
import com.gluonhq.attach.vibration.VibrationService;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.action_api.action.Action;
import com.stream_pi.client.connection.Client;
import com.stream_pi.client.connection.Client;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.io.Config;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.info.ClientInfo;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfile;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.profile.ClientProfiles;
import com.stream_pi.client.window.Base;
import com.stream_pi.client.window.Base;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionGridPaneListener;
import com.stream_pi.client.window.dashboard.actiongridpane.ActionGridPaneListener;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlertListener;
import com.stream_pi.util.alert.StreamPiAlertListener;
import com.stream_pi.util.alert.StreamPiAlertType;
import com.stream_pi.util.alert.StreamPiAlertType;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.gluonhq.attach.lifecycle.LifecycleService;
import com.gluonhq.attach.lifecycle.LifecycleService;
import com.gluonhq.attach.util.Services;
import com.gluonhq.attach.util.Services;
import com.stream_pi.util.platform.PlatformType;
import com.stream_pi.util.platform.PlatformType;
import com.stream_pi.util.startatboot.StartAtBoot;
import com.stream_pi.util.startatboot.StartAtBoot;
import javafx.animation.Interpolator;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ChangeListener;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyCombination;
import javafx.util.Duration;
import javafx.util.Duration;
import java.io.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Level;
public class Controller extends Base
public class Controller extends Base
{
{
private Client client;
private Client client;
public Controller()
public Controller()
{
{
client = null;
client = null;
}
}
private boolean firstRun = true;
private boolean firstRun = true;
@Override
@Override
public void init()
public void init()
{
{
try
try
{
{
if(firstRun)
if(firstRun)
initBase();
initBase();
if(getClientInfo().getPlatform() != com.stream_pi.util.platform.Platform.ANDROID)
if(getClientInfo().getPlatform() != com.stream_pi.util.platform.Platform.ANDROID)
{
{
if(getConfig().isStartOnBoot())
if(getConfig().isStartOnBoot())
{
{
if(getClientInfo().isXMode() != getConfig().isStartupXMode())
if(getClientInfo().isXMode() != getConfig().isStartupXMode())
{
{
StartAtBoot startAtBoot = new StartAtBoot(PlatformType.CLIENT, ClientInfo.getInstance().getPlatform());
StartAtBoot startAtBoot = new StartAtBoot(PlatformType.CLIENT, ClientInfo.getInstance().getPlatform());
boolean result = startAtBoot.delete();
boolean result = startAtBoot.delete();
if(!result)
if(!result)
new StreamPiAlert("Uh Oh!", "Unable to delete the previous starter file.\n" +
new StreamPiAlert("Uh Oh!", "Unable to delete the previous starter file.\n" +
"This was probably because you ran Stream-Pi as root before. Restart stream pi as root, " +
"This was probably because you ran Stream-Pi as root before. Restart stream pi as root, " +
"delete the old starter file, then exit and restart Stream-Pi as normal user.", StreamPiAlertType.ERROR).show();
"delete the old starter file, then exit and restart Stream-Pi as normal user.", StreamPiAlertType.ERROR).show();
else
else
{
{
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()),
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()),
ClientInfo.getInstance().isXMode());
ClientInfo.getInstance().isXMode());
getConfig().setStartupIsXMode(ClientInfo.getInstance().isXMode());
getConfig().setStartupIsXMode(ClientInfo.getInstance().isXMode());
}
}
}
}
}
}
setupFlags();
setupFlags();
if(!getConfig().getIsFullScreenMode())
if(!getConfig().getIsFullScreenMode())
{
{
getStage().setWidth(getConfig().getStartupWindowWidth());
getStage().setWidth(getConfig().getStartupWindowWidth());
getStage().setHeight(getConfig().getStartupWindowHeight());
getStage().setHeight(getConfig().getStartupWindowHeight());
getStage().centerOnScreen();
getStage().centerOnScreen();
}
}
}
}
applyDefaultTheme();
applyDefaultTheme();
setupDashWindow();
setupDashWindow();
getStage().show();
getStage().show();
requestFocus();
requestFocus();
if(Config.getInstance().isFirstTimeUse())
if(Config.getInstance().isFirstTimeUse())
return;
return;
setupSettingsWindowsAnimations();
setupSettingsWindowsAnimations();
getDashboardPane().getSettingsButton().setOnAction(event -> {
getDashboardPane().getSettingsButton().setOnAction(event -> {
openSettingsTimeLine.play();
openSettingsTimeLine.play();
});
});
getSettingsPane().getCloseButton().setOnAction(event -> {
getSettingsPane().getCloseButton().setOnAction(event -> {
closeSettingsTimeLine.play();
closeSettingsTimeLine.play();
});
});
setClientProfiles(new ClientProfiles(new File(getConfig().getProfilesPath()), getConfig().getStartupProfileID()));
setClientProfiles(new ClientProfiles(new File(getConfig().getProfilesPath()), getConfig().getStartupProfileID()));
if(getClientProfiles().getLoadingErrors().size() > 0)
if(getClientProfiles().getLoadingErrors().size() > 0)
{
{
StringBuilder errors = new StringBuilder("Please rectify the following errors and try again");
StringBuilder errors = new StringBuilder("Please rectify the following errors and try again");
for(MinorException exception : getClientProfiles().getLoadingErrors())
for(MinorException exception : getClientProfiles().getLoadingErrors())
{
{
errors.append("\n * ")
errors.append("\n * ")
.append(exception.getMessage());
.append(exception.getMessage());
}
}
throw new MinorException("Profiles", errors.toString());
throw new MinorException("Profiles", errors.toString());
}
}
renderRootDefaultProfile();
renderRootDefaultProfile();
loadSettings();
loadSettings();
if(firstRun)
if(firstRun)
{
{
if(getConfig().isConnectOnStartup())
if(getConfig().isConnectOnStartup())
{
{
setupClientConnection();
setupClientConnection();
}
}
firstRun = false;
firstRun = false;
}
}
ChangeListener<Number> windowResizeListener = (observableValue, number, t1) -> {
ChangeListener<Number> windowResizeListener = (observableValue, number, t1) -> {
if(isConnected())
if(isConnected())
{
{
try {
try {
client.sendClientScreenDetails();
client.sendClientScreenDetails();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
};
};
getStage().widthProperty().addListener(windowResizeListener);
getStage().widthProperty().addListener(windowResizeListener);
getStage().heightProperty().addListener(windowResizeListener);
getStage().heightProperty().addListener(windowResizeListener);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
}
}
@Override
@Override
public void setupClientConnection()
public void setupClientConnection()
{
{
setupClientConnection(null);
}
@Override
public void setupClientConnection(Runnable onConnect)
{
if(getSettingsPane().getConnectDisconnectButton().isDisabled()) //probably already connecting
return;
Platform.runLater(()->getSettingsPane().setDisableStatus(true));
Platform.runLater(()->getSettingsPane().setDisableStatus(true));
client = new Client(getConfig().getSavedServerHostNameOrIP(), getConfig().getSavedServerPort(), this, this);
client = new Client(getConfig().getSavedServerHostNameOrIP(), getConfig().getSavedServerPort(), this, this, onConnect);
}
}
@Override
@Override
public void updateSettingsConnectDisconnectButton() {
public void updateSettingsConnectDisconnectButton() {
getSettingsPane().setConnectDisconnectButtonStatus();
getSettingsPane().setConnectDisconnectButtonStatus();
}
}
@Override
@Override
public void disconnect(String message) throws SevereException {
public void disconnect(String message) throws SevereException {
client.disconnect(message);
client.disconnect(message);
}
}
public void setupDashWindow()
public void setupDashWindow()
{
{
getStage().setTitle("Stream-Pi Client");
getStage().setTitle("Stream-Pi Client");
getStage().setOnCloseRequest(e->onCloseRequest());
getStage().setOnCloseRequest(e->onCloseRequest());
}
}
@Override
@Override
public void onCloseRequest()
public void onCloseRequest()
{
{
try
try
{
{
if(isConnected())
if(isConnected())
client.exit();
client.exit();
getConfig().setStartupWindowSize(getStageWidth(), getStageHeight());
getConfig().setStartupWindowSize(getStageWidth(), getStageHeight());
getConfig().save();
getConfig().save();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
finally
finally
{
{
getLogger().info("Shut down");
getLogger().info("Shut down");
closeLogger();
closeLogger();
if (ClientInfo.getInstance().getPlatform() == com.stream_pi.util.platform.Platform.ANDROID)
if (ClientInfo.getInstance().getPlatform() == com.stream_pi.util.platform.Platform.ANDROID)
Services.get(LifecycleService.class).ifPresent(LifecycleService::shutdown);
Services.get(LifecycleService.class).ifPresent(LifecycleService::shutdown);
}
}
}
}
@Override
@Override
public void loadSettings() {
public void loadSettings() {
try {
try {
getSettingsPane().loadData();
getSettingsPane().loadData();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
}
}
@Override
@Override
public Client getClient() {
public Client getClient() {
return client;
return client;
}
}
@Override
@Override
public void onDisconnect() {
public void onDisconnect() {
Platform.runLater(()->getDashboardPane().getActionGridPane().toggleOffAllToggleActions());
Platform.runLater(()->getDashboardPane().getActionGridPane().toggleOffAllToggleActions());
}
}
@Override
@Override
public boolean getToggleStatus(String profileID, String actionID)
public boolean getToggleStatus(String profileID, String actionID)
{
{
return getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID).getCurrentToggleStatus();
return getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID).getCurrentToggleStatus();
}
}
private Timeline openSettingsTimeLine;
private Timeline openSettingsTimeLine;
private Timeline closeSettingsTimeLine;
private Timeline closeSettingsTimeLine;
private void setupSettingsWindowsAnimations()
private void setupSettingsWindowsAnimations()
{
{
Node settingsNode = getSettingsPane();
Node settingsNode = getSettingsPane();
Node dashboardNode = getDashboardPane();
Node dashboardNode = getDashboardPane();
openSettingsTimeLine = new Timeline();
openSettingsTimeLine = new Timeline();
openSettingsTimeLine.setCycleCount(1);
openSettingsTimeLine.setCycleCount(1);
openSettingsTimeLine.getKeyFrames().addAll(
openSettingsTimeLine.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.EASE_IN)),
0.0D, Interpolator.EASE_IN)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR))
0.0D, Interpolator.LINEAR))
);
);
openSettingsTimeLine.setOnFinished(event1 -> settingsNode.toFront());
openSettingsTimeLine.setOnFinished(event1 -> settingsNode.toFront());
closeSettingsTimeLine = new Timeline();
closeSettingsTimeLine = new Timeline();
closeSettingsTimeLine.setCycleCount(1);
closeSettingsTimeLine.setCycleCount(1);
closeSettingsTimeLine.getKeyFrames().addAll(
closeSettingsTimeLine.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.LINEAR)),
0.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR)),
0.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR))
1.0D, Interpolator.LINEAR))
);
);
closeSettingsTimeLine.setOnFinished(event1 -> {
closeSettingsTimeLine.setOnFinished(event1 -> {
dashboardNode.toFront();
dashboardNode.toFront();
Platform.runLater(()-> {
Platform.runLater(()-> {
try {
try {
getSettingsPane().loadData();
getSettingsPane().loadData();
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
});
});
});
});
}
}
@Override
@Override
public void handleMinorException(MinorException e)
public void handleMinorException(MinorException e)
{
{
getLogger().log(Level.SEVERE, e.getMessage(), e);
getLogger().log(Level.SEVERE, e.getMessage(), e);
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()-> genNewAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
Platform.runLater(()-> genNewAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
}
}
@Override
@Override
public void handleSevereException(SevereException e)
public void handleSevereException(SevereException e)
{
{
getLogger().log(Level.SEVERE, e.getMessage(), e);
getLogger().log(Level.SEVERE, e.getMessage(), e);
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()->
Platform.runLater(()->
{
{
StreamPiAlert alert = genNewAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
StreamPiAlert alert = genNewAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
alert.setOnClicked(new StreamPiAlertListener()
alert.setOnClicked(new StreamPiAlertListener()
{
{
@Override
@Override
public void onClick(String txt)
public void onClick(String txt)
{
{
onCloseRequest();
onCloseRequest();
Platform.exit();
Platform.exit();
}
}
});
});
alert.show();
alert.show();
});
});
}
}
@Override
@Override
public void onAlert(String title, String body, StreamPiAlertType alertType) {
public void onAlert(String title, String body, StreamPiAlertType alertType) {
Platform.runLater(()-> genNewAlert(title, body, alertType).show());
Platform.runLater(()-> genNewAlert(title, body, alertType).show());
}
}
public StreamPiAlert genNewAlert(String title, String message, StreamPiAlertType alertType)
public StreamPiAlert genNewAlert(String title, String message, StreamPiAlertType alertType)
{
{
StreamPiAlert alert = new StreamPiAlert(title, message, alertType);
StreamPiAlert alert = new StreamPiAlert(title, message, alertType);
return alert;
return alert;
}
}
private boolean isConnected = false;
private boolean isConnected = false;
@Override
@Override
public void onActionFailed(String profileID, String actionID) {
public void onActionFailed(String profileID, String actionID) {
Platform.runLater(()-> getDashboardPane().getActionGridPane().actionFailed(profileID, actionID));
Platform.runLater(()-> getDashboardPane().getActionGridPane().actionFailed(profileID, actionID));
}
}
@Override
@Override
public void onActionClicked(String profileID, String actionID, boolean toggleState)
public void onActionClicked(String profileID, String actionID, boolean toggleState)
{
{
try {
try {
vibratePhone();
vibratePhone();
client.onActionClicked(profileID, actionID, toggleState);
client.onActionClicked(profileID, actionID, toggleState);
} catch (SevereException e) {
} catch (SevereException e) {
e.printStackTrace();
e.printStackTrace();
handleSevereException(e);
handleSevereException(e);
}
}
}
}
public void vibratePhone()
public void vibratePhone()
{
{
if(getConfig().isVibrateOnActionClicked())
if(getConfig().isVibrateOnActionClicked())
{
{
VibrationService.create().ifPresent(VibrationService::vibrate);
VibrationService.create().ifPresent(VibrationService::vibrate);
}
}
}
}
@Override
@Override
public void setConnected(boolean isConnected) {
public void setConnected(boolean isConnected) {
this.isConnected = isConnected;
this.isConnected = isConnected;
}
}
@Override
@Override
public ActionBox getActionBox(int col, int row)
public ActionBox getActionBox(int col, int row)
{
{
return getDashboardPane().getActionGridPane().getActionBox(col, row);
return getDashboardPane().getActionGridPane().getActionBox(col, row);
}
}
@Override
@Override
public boolean isConnected()
public boolean isConnected()
{
{
return isConnected;
return isConnected;
}
}
@Override
@Override
public void renderProfile(ClientProfile clientProfile, boolean freshRender)
public void renderProfile(ClientProfile clientProfile, boolean freshRender)
{
{
getDashboardPane().renderProfile(clientProfile, freshRender);
getDashboardPane().renderProfile(clientProfile, freshRender);
}
}
@Override
@Override
public void clearActionBox(int col, int row)
public void clearActionBox(int col, int row)
{
{
Platform.runLater(()->getDashboardPane().getActionGridPane().clearActionBox(col, row));
Platform.runLater(()->getDashboardPane().getActionGridPane().clearActionBox(col, row));
}
}
@Override
@Override
public void addBlankActionBox(int col, int row)
public void addBlankActionBox(int col, int row)
{
{
Platform.runLater(()->getDashboardPane().getActionGridPane().addBlankActionBox(col, row));
Platform.runLater(()->getDashboardPane().getActionGridPane().addBlankActionBox(col, row));
}
}
@Override
@Override
public void renderAction(String currentProfileID, Action action)
public void renderAction(String currentProfileID, Action action)
{
{
Platform.runLater(()->{
Platform.runLater(()->{
try {
try {
if(getDashboardPane().getActionGridPane().getCurrentParent().equals(action.getParent()) &&
if(getDashboardPane().getActionGridPane().getCurrentParent().equals(action.getParent()) &&
getCurrentProfile().getID().equals(currentProfileID))
getCurrentProfile().getID().equals(currentProfileID))
{
{
getDashboardPane().getActionGridPane().renderAction(action);
getDashboardPane().getActionGridPane().renderAction(action);
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
});
});
}
}
@Override
@Override
public void refreshGridIfCurrentProfile(String profileID) {
public void refreshGridIfCurrentProfile(String profileID) {
if(getCurrentProfile().getID().equals(profileID))
if(getCurrentProfile().getID().equals(profileID))
{
{
Platform.runLater(()-> getDashboardPane().renderProfile(getClientProfiles().getProfileFromID(profileID), true));
Platform.runLater(()-> getDashboardPane().renderProfile(getClientProfiles().getProfileFromID(profileID), true));
}
}
}
}
@Override
@Override
public ClientProfile getCurrentProfile() {
public ClientProfile getCurrentProfile() {
return getDashboardPane().getActionGridPane().getClientProfile();
return getDashboardPane().getActionGridPane().getClientProfile();
}
}
@Override
@Override
public String getCurrentParent()
public String getCurrentParent()
{
{
return getDashboardPane().getActionGridPane().getCurrentParent();
return getDashboardPane().getActionGridPane().getCurrentParent();
}
}
@Override
@Override
public ActionBox getActionBoxByProfileAndID(String profileID, String actionID)
public ActionBox getActionBoxByProfileAndID(String profileID, String actionID)
{
{
Action action = getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
Action action = getClientProfiles().getProfileFromID(profileID).getActionFromID(actionID);
if(!getCurrentProfile().getID().equals(profileID) && !getCurrentParent().equals(action.getParent()))
if(!getCurrentProfile().getID().equals(profileID) && !getCurrentParent().equals(action.getParent()))
return null;
return null;
return getDashboardPane().getActionGridPane().getActionBoxByLocation(action.getLocation());
return getDashboardPane().getActionGridPane().getActionBoxByLocation(action.getLocation());
}
}
}
}
package com.stream_pi.client.window.dashboard.actiongridpane;
package com.stream_pi.client.window.dashboard.actiongridpane;
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.client.connection.ClientListener;
import com.stream_pi.client.io.Config;
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.SevereException;
import javafx.animation.Interpolator;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.Timeline;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.CacheHint;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.Image;
import javafx.scene.layout.Background;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
import javafx.util.Duration;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectInputStream;
import java.nio.ByteBuffer;
import java.nio.ByteBuffer;
public class ActionBox extends StackPane
public class ActionBox extends StackPane
{
{
private Label displayTextLabel;
private Label displayTextLabel;
private int row;
private int row;
private int col;
private int col;
public int getRow() {
public int getRow() {
return row;
return row;
}
}
public int getCol() {
public int getCol() {
return col;
return col;
}
}
public void clear()
public void clear()
{
{
setStyle(null);
setStyle(null);
setAction(null);
setAction(null);
setCurrentToggleStatus(false);
setCurrentToggleStatus(false);
getStyleClass().clear();
getStyleClass().clear();
setBackground(Background.EMPTY);
setBackground(Background.EMPTY);
removeFontIcon();
removeFontIcon();
getChildren().clear();
getChildren().clear();
baseInit();
baseInit();
}
}
private FontIcon statusIcon;
private FontIcon statusIcon;
public void baseInit()
public void baseInit()
{
{
displayTextLabel = new Label();
displayTextLabel = new Label();
displayTextLabel.setWrapText(true);
displayTextLabel.setWrapText(true);
displayTextLabel.setTextAlignment(TextAlignment.CENTER);
displayTextLabel.setTextAlignment(TextAlignment.CENTER);
displayTextLabel.getStyleClass().add("action_box_display_text_label");
displayTextLabel.getStyleClass().add("action_box_display_text_label");
displayTextLabel.prefHeightProperty().bind(heightProperty());
displayTextLabel.prefHeightProperty().bind(heightProperty());
displayTextLabel.prefWidthProperty().bind(widthProperty());
displayTextLabel.prefWidthProperty().bind(widthProperty());
statusIcon = new FontIcon("fas-exclamation-triangle");
statusIcon = new FontIcon("fas-exclamation-triangle");
statusIcon.getStyleClass().add("action_box_error_icon");
statusIcon.getStyleClass().add("action_box_error_icon");
statusIcon.setOpacity(0);
statusIcon.setOpacity(0);
statusIcon.setCache(true);
statusIcon.setCache(true);
statusIcon.setCacheHint(CacheHint.SPEED);
statusIcon.setCacheHint(CacheHint.SPEED);
statusIcon.setIconSize(size - 30);
statusIcon.setIconSize(size - 30);
getChildren().addAll(statusIcon, displayTextLabel);
getChildren().addAll(statusIcon, displayTextLabel);
setMinSize(size, size);
setMinSize(size, size);
setMaxSize(size, size);
setMaxSize(size, size);
getStyleClass().clear();
getStyleClass().clear();
getStyleClass().add("action_box");
getStyleClass().add("action_box");
getStyleClass().add("action_box_"+row+"_"+col);
getStyleClass().add("action_box_"+row+"_"+col);
setIcon(null);
setIcon(null);
setOnMouseClicked(touchEvent -> actionClicked());
setOnMouseClicked(touchEvent -> actionClicked());
setOnMousePressed(TouchEvent -> {
setOnMousePressed(TouchEvent -> {
if(action != null)
if(action != null)
{
{
getStyleClass().add("action_box_onclick");
getStyleClass().add("action_box_onclick");
}
}
});
});
setOnMouseReleased(TouchEvent ->{
setOnMouseReleased(TouchEvent ->{
if(action != null)
if(action != null)
{
{
getStyleClass().remove("action_box_onclick");
getStyleClass().remove("action_box_onclick");
}
}
});
});
statusIconAnimation = new Timeline(
statusIconAnimation = new Timeline(
new KeyFrame(
new KeyFrame(
Duration.millis(0.0D),
Duration.millis(0.0D),
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_IN)),
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_IN)),
new KeyFrame(
new KeyFrame(
Duration.millis(100.0D),
Duration.millis(100.0D),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_IN)),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_IN)),
new KeyFrame(
new KeyFrame(
Duration.millis(600.0D),
Duration.millis(600.0D),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_OUT)),
new KeyValue(statusIcon.opacityProperty(), 1.0D, Interpolator.EASE_OUT)),
new KeyFrame(
new KeyFrame(
Duration.millis(700.0D),
Duration.millis(700.0D),
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_OUT))
new KeyValue(statusIcon.opacityProperty(), 0.0D, Interpolator.EASE_OUT))
);
);
statusIconAnimation.setOnFinished(event -> {
statusIconAnimation.setOnFinished(event -> {
statusIcon.toBack();
statusIcon.toBack();
});
});
setCache(true);
setCache(true);
setCacheHint(CacheHint.QUALITY);
setCacheHint(CacheHint.QUALITY);
}
}
public void actionClicked()
public void actionClicked()
{
{
if(action!=null)
if(action!=null)
{
{
if(!getActionGridPaneListener().isConnected())
if(!getActionGridPaneListener().isConnected())
{
{
exceptionAndAlertHandler.onAlert("Not Connected", "Not Connected to any Server", StreamPiAlertType.ERROR);
try
return;
{
if(Config.getInstance().isTryConnectingWhenActionClicked())
{
clientListener.setupClientConnection(this::actionClicked);
}
else
{
exceptionAndAlertHandler.onAlert("Not Connected", "Not Connected to any Server", StreamPiAlertType.ERROR);
}
return;
}
catch (SevereException e)
{
exceptionAndAlertHandler.handleSevereException(e);
}
}
}
if(action.getActionType() == ActionType.FOLDER)
if(action.getActionType() == ActionType.FOLDER)
{
{
getActionGridPaneListener().renderFolder(action.getID());
getActionGridPaneListener().renderFolder(action.getID());
}
}
else
else
{
{
if(action.getActionType() == ActionType.COMBINE)
if(action.getActionType() == ActionType.COMBINE)
{
{
getActionGridPaneListener().combineActionClicked(action.getID());
getActionGridPaneListener().combineActionClicked(action.getID());
}
}
else if(action.getActionType() == ActionType.NORMAL)
else if(action.getActionType() == ActionType.NORMAL)
{
{
getActionGridPaneListener().normalActionClicked(action.getID());
getActionGridPaneListener().normalActionClicked(action.getID());
}
}
else if(action.getActionType() == ActionType.TOGGLE)
else if(action.getActionType() == ActionType.TOGGLE)
{
{
toggle();
toggle();
getActionGridPaneListener().toggleActionClicked(action.getID(), getCurrentToggleStatus());
getActionGridPaneListener().toggleActionClicked(action.getID(), getCurrentToggleStatus());
}
}
}
}
}
}
}
}
private Timeline statusIconAnimation;
private Timeline statusIconAnimation;
public Timeline getStatusIconAnimation() {
public Timeline getStatusIconAnimation() {
return statusIconAnimation;
return statusIconAnimation;
}
}
public ActionGridPaneListener getActionGridPaneListener() {
public ActionGridPaneListener getActionGridPaneListener() {
return actionGridPaneListener;
return actionGridPaneListener;
}
}
private int size;
private int size;
private ActionGridPaneListener actionGridPaneListener;
private ActionGridPaneListener actionGridPaneListener;
private ClientListener clientListener;
public ActionBox(int size, ExceptionAndAlertHandler exceptionAndAlertHandler, ActionGridPaneListener actionGridPaneListener, int row, int col)
public ActionBox(int size, ExceptionAndAlertHandler exceptionAndAlertHandler,
ClientListener clientListener, ActionGridPaneListener actionGridPaneListener, int row, int col)
{
{
this.actionGridPaneListener = actionGridPaneListener;
this.actionGridPaneListener = actionGridPaneListener;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.size = size;
this.size = size;
this.row = row;
this.row = row;
this.col = col;
this.col = col;
this.clientListener = clientListener;
baseInit();
baseInit();
}
}
public static Action deserialize(ByteBuffer buffer) {
public static Action deserialize(ByteBuffer buffer) {
try {
try {
ByteArrayInputStream is = new ByteArrayInputStream(buffer.array());
ByteArrayInputStream is = new ByteArrayInputStream(buffer.array());
ObjectInputStream ois = new ObjectInputStream(is);
ObjectInputStream ois = new ObjectInputStream(is);
return (Action) ois.readObject();
return (Action) ois.readObject();
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
throw new RuntimeException(e);
throw new RuntimeException(e);
}
}
}
}
public void setIcon(byte[] iconByteArray)
public void setIcon(byte[] iconByteArray)
{
{
removeFontIcon();
removeFontIcon();
if(iconByteArray == null)
if(iconByteArray == null)
{
{
getStyleClass().remove("action_box_icon_present");
getStyleClass().remove("action_box_icon_present");
getStyleClass().add("action_box_icon_not_present");
getStyleClass().add("action_box_icon_not_present");
setBackground(null);
setBackground(null);
}
}
else
else
{
{
getStyleClass().add("action_box_icon_present");
getStyleClass().add("action_box_icon_present");
getStyleClass().remove("action_box_icon_not_present");
getStyleClass().remove("action_box_icon_not_present");
setBackground(
setBackground(
new Background(
new Background(
new BackgroundImage(new Image(
new BackgroundImage(new Image(
new ByteArrayInputStream(iconByteArray), size, size, false, true
new ByteArrayInputStream(iconByteArray), size, size, false, true
), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
new BackgroundSize(100, 100, true, true, true, false))
new BackgroundSize(100, 100, true, true, true, false))
)
)
);
);
}
}
}
}
private Action action = null;
private Action action = null;
public Action getAction() {
public Action getAction() {
return action;
return action;
}
}
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private String parent;
private String parent;
public String getStreamPiParent() {
public String getStreamPiParent() {
return parent;
return parent;
}
}
public void setStreamPiParent(String parent) {
public void setStreamPiParent(String parent) {
this.parent = parent;
this.parent = parent;
}
}
/*
public ActionBox(int size, Action action, ExceptionAndAlertHandler exceptionAndAlertHandler,
public ActionBox(int size, Action action, ExceptionAndAlertHandler exceptionAndAlertHandler,
ActionGridPaneListener actionGridPaneListener, int row, int col)
ClientListener clientListener, ActionGridPaneListener actionGridPaneListener, int row, int col)
{
{
this.actionGridPaneListener = actionGridPaneListener;
this.actionGridPaneListener = actionGridPaneListener;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.action = action;
this.action = action;
this.size = size;
this.size = size;
this.row = row;
this.row = row;
this.col = col;
this.col = col;
baseInit();
baseInit();
init();
init();
}
}*/
public void setAction(Action action)
public void setAction(Action action)
{
{
this.action = action;
this.action = action;
}
}
public void init()
public void init()
{
{
setDisplayTextFontColour(action.getDisplayTextFontColourHex());
setDisplayTextFontColour(action.getDisplayTextFontColourHex());
if(action.isShowDisplayText())
if(action.isShowDisplayText())
setDisplayTextLabel(action.getDisplayText());
setDisplayTextLabel(action.getDisplayText());
else
else
setDisplayTextLabel("");
setDisplayTextLabel("");
setDisplayTextAlignment(action.getDisplayTextAlignment());
setDisplayTextAlignment(action.getDisplayTextAlignment());
setBackgroundColour(action.getBgColourHex());
setBackgroundColour(action.getBgColourHex());
try
try
{
{
if(action.getActionType() == ActionType.TOGGLE)
if(action.getActionType() == ActionType.TOGGLE)
{
{
toggle(getCurrentToggleStatus());
toggle(getCurrentToggleStatus());
}
}
else
else
{
{
if(action.isHasIcon())
if(action.isHasIcon())
{
{
if(!action.getCurrentIconState().isBlank())
if(!action.getCurrentIconState().isBlank())
{
{
setIcon(action.getCurrentIcon());
setIcon(action.getCurrentIcon());
}
}
}
}
else
else
{
{
setIcon(null);
setIcon(null);
}
}
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
public void setCurrentToggleStatus(boolean currentToggleStatus)
public void setCurrentToggleStatus(boolean currentToggleStatus)
{
{
if(getAction() != null)
if(getAction() != null)
getAction().setCurrentToggleStatus(currentToggleStatus);
getAction().setCurrentToggleStatus(currentToggleStatus);
}
}
public boolean getCurrentToggleStatus()
public boolean getCurrentToggleStatus()
{
{
if(getAction() == null)
if(getAction() == null)
return false;
return false;
return getAction().getCurrentToggleStatus();
return getAction().getCurrentToggleStatus();
}
}
public void toggle()
public void toggle()
{
{
setCurrentToggleStatus(!getCurrentToggleStatus());
setCurrentToggleStatus(!getCurrentToggleStatus());
toggle(getCurrentToggleStatus());
toggle(getCurrentToggleStatus());
}
}
public void toggle(boolean isON)
public void toggle(boolean isON)
{
{
String[] toggleStatesHiddenStatus = action.getCurrentIconState().split("__");
String[] toggleStatesHiddenStatus = action.getCurrentIconState().split("__");
boolean isToggleOffHidden = toggleStatesHiddenStatus[0].equals("true");
boolean isToggleOffHidden = toggleStatesHiddenStatus[0].equals("true");
boolean isToggleOnHidden = toggleStatesHiddenStatus[1].equals("true");
boolean isToggleOnHidden = toggleStatesHiddenStatus[1].equals("true");
if(isON) // ON
if(isON) // ON
{
{
if(action.isHasIcon())
if(action.isHasIcon())
{
{
boolean isToggleOnPresent = action.getIcons().containsKey("toggle_on");
boolean isToggleOnPresent = action.getIcons().containsKey("toggle_on");
if(isToggleOnPresent)
if(isToggleOnPresent)
{
{
if(isToggleOnHidden)
if(isToggleOnHidden)
{
{
setDefaultToggleIcon(true);
setDefaultToggleIcon(true);
}
}
else
else
{
{
setIcon(action.getIcons().get("toggle_on"));
setIcon(action.getIcons().get("toggle_on"));
}
}
}
}
else
else
{
{
setDefaultToggleIcon(true);
setDefaultToggleIcon(true);
}
}
}
}
else
else
{
{
setDefaultToggleIcon(true);
setDefaultToggleIcon(true);
}
}
}
}
else // OFF
else // OFF
{
{
if(action.isHasIcon())
if(action.isHasIcon())
{
{
boolean isToggleOffPresent = action.getIcons().containsKey("toggle_off");
boolean isToggleOffPresent = action.getIcons().containsKey("toggle_off");
if(isToggleOffPresent)
if(isToggleOffPresent)
{
{
if(isToggleOffHidden)
if(isToggleOffHidden)
{
{
setDefaultToggleIcon(false);
setDefaultToggleIcon(false);
}
}
else
else
{
{
setIcon(action.getIcons().get("toggle_off"));
setIcon(action.getIcons().get("toggle_off"));
}
}
}
}
else
else
{
{
setDefaultToggleIcon(false);
setDefaultToggleIcon(false);
}
}
}
}
else
else
{
{
setDefaultToggleIcon(false);
setDefaultToggleIcon(false);
}
}
}
}
}
}
public void setDefaultToggleIcon(boolean isToggleOn)
public void setDefaultToggleIcon(boolean isToggleOn)
{
{
String styleClass;
String styleClass;
if(isToggleOn)
if(isToggleOn)
{
{
styleClass = "action_box_toggle_on";
styleClass = "action_box_toggle_on";
}
}
else
else
{
{
styleClass = "action_box_toggle_off";
styleClass = "action_box_toggle_off";
}
}
setBackground(null);
setBackground(null);
removeFontIcon();
removeFontIcon();
fontIcon = new FontIcon();
fontIcon = new FontIcon();
fontIcon.getStyleClass().add(styleClass);
fontIcon.getStyleClass().add(styleClass);
fontIcon.setIconSize((int) (size * 0.8));
fontIcon.setIconSize((int) (size * 0.8));
getChildren().add(fontIcon);
getChildren().add(fontIcon);
fontIcon.toBack();
fontIcon.toBack();
}
}
public void removeFontIcon()
public void removeFontIcon()
{
{
if(fontIcon!=null)
if(fontIcon!=null)
{
{
getChildren().remove(fontIcon);
getChildren().remove(fontIcon);
fontIcon = null;
fontIcon = null;
}
}
}
}
FontIcon fontIcon = null;
FontIcon fontIcon = null;
public void animateStatus()
public void animateStatus()
{
{
statusIcon.toFront();
statusIcon.toFront();
statusIconAnimation.play();
statusIconAnimation.play();
}
}
public void setDisplayTextLabel(String text)
public void setDisplayTextLabel(String text)
{
{
displayTextLabel.setText(text);
displayTextLabel.setText(text);
}
}
public void setDisplayTextAlignment(DisplayTextAlignment displayTextAlignment)
public void setDisplayTextAlignment(DisplayTextAlignment displayTextAlignment)
{
{
if(displayTextAlignment == DisplayTextAlignment.CENTER)
if(displayTextAlignment == DisplayTextAlignment.CENTER)
displayTextLabel.setAlignment(Pos.CENTER);
displayTextLabel.setAlignment(Pos.CENTER);
else if (displayTextAlignment == DisplayTextAlignment.BOTTOM)
else if (displayTextAlignment == DisplayTextAlignment.BOTTOM)
displayTextLabel.setAlignment(Pos.BOTTOM_CENTER);
displayTextLabel.setAlignment(Pos.BOTTOM_CENTER);
else if (displayTextAlignment == DisplayTextAlignment.TOP)
else if (displayTextAlignment == DisplayTextAlignment.TOP)
displayTextLabel.setAlignment(Pos.TOP_CENTER);
displayTextLabel.setAlignment(Pos.TOP_CENTER);
}
}
public void setDisplayTextFontColour(String colour)
public void setDisplayTextFontColour(String colour)
{
{
System.out.println("'"+colour+"'COLOR");
System.out.println("'"+colour+"'COLOR");
if(!colour.isEmpty())
if(!colour.isEmpty())
{
{
System.out.println(
System.out.println(
"putting ..." + Thread.currentThread().getName()
"putting ..." + Thread.currentThread().getName()
);
);
displayTextLabel.setStyle("-fx-text-fill : "+colour+";");
displayTextLabel.setStyle("-fx-text-fill : "+colour+";");
}
}
}
}
public void setBackgroundColour(String colour)
public void setBackgroundColour(String colour)
{
{
System.out.println("COLOr : "+colour);
System.out.println("COLOr : "+colour);
if(!colour.isEmpty())
if(!colour.isEmpty())
setStyle("-fx-background-color : "+colour);
setStyle("-fx-background-color : "+colour);
}
}
}
}
package com.stream_pi.client.window.dashboard.actiongridpane;
package com.stream_pi.client.window.dashboard.actiongridpane;
import java.util.logging.Logger;
import java.util.logging.Logger;
import com.stream_pi.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.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.profile.ClientProfiles;
import com.stream_pi.client.profile.ClientProfiles;
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.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);
setCache(true);
setCacheHint(CacheHint.SPEED);
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()
public StackPane getFolderBackButton()
{
{
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()
public void renderGrid()
{
{
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)
{
{
actionBoxes[col][row].clear();
actionBoxes[col][row].clear();
}
}
}
}
}
}
}
}
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];
}
}
public ActionBox addBlankActionBox(int col, int row)
public ActionBox addBlankActionBox(int col, int row)
{
{
ActionBox actionBox = new ActionBox(getClientProfile().getActionSize(), exceptionAndAlertHandler, this, row, col);
ActionBox actionBox = new ActionBox(getClientProfile().getActionSize(), exceptionAndAlertHandler, clientListener, this, row, col);
actionBox.setStreamPiParent(currentParent);
actionBox.setStreamPiParent(currentParent);
add(actionBox, col, row);
add(actionBox, col, row);
return actionBox;
return actionBox;
}
}
public void toggleOffAllToggleActions()
public void toggleOffAllToggleActions()
{
{
for(Node each : getChildren())
for(Node each : getChildren())
{
{
if(each instanceof ActionBox)
if(each instanceof ActionBox)
{
{
ActionBox eachActionBox = (ActionBox) each;
ActionBox eachActionBox = (ActionBox) each;
if(eachActionBox.getAction() != null)
if(eachActionBox.getAction() != null)
{
{
if(eachActionBox.getAction().getActionType() == ActionType.TOGGLE)
if(eachActionBox.getAction().getActionType() == ActionType.TOGGLE)
{
{
if(eachActionBox.getCurrentToggleStatus()) // ON
if(eachActionBox.getCurrentToggleStatus()) // ON
{
{
eachActionBox.toggle();
eachActionBox.toggle();
}
}
}
}
}
}
}
}
}
}
}
}
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();
boolean oldToggleStatus = actionBox.getCurrentToggleStatus();
boolean oldToggleStatus = actionBox.getCurrentToggleStatus();
actionBox.setAction(action);
actionBox.setAction(action);
actionBox.setCurrentToggleStatus(oldToggleStatus);
actionBox.setCurrentToggleStatus(oldToggleStatus);
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());
renderGrid();
renderGrid();
renderActions();
renderActions();
}
}
@Override
@Override
public void normalActionClicked(String ID)
public void normalActionClicked(String ID)
{
{
clientListener.onActionClicked(getClientProfile().getID(), ID, false);
clientListener.onActionClicked(getClientProfile().getID(), ID, false);
}
}
@Override
@Override
public void toggleActionClicked(String ID, boolean toggleState)
public void toggleActionClicked(String ID, boolean toggleState)
{
{
clientListener.onActionClicked(getClientProfile().getID(), ID, toggleState);
clientListener.onActionClicked(getClientProfile().getID(), ID, toggleState);
}
}
@Override
@Override
public ActionBox getActionBoxByLocation(Location location)
public ActionBox getActionBoxByLocation(Location location)
{
{
return getActionBox(location.getCol(), location.getRow());
return getActionBox(location.getCol(), location.getRow());
}
}
@Override
@Override
public boolean isConnected()
public boolean isConnected()
{
{
return clientListener.isConnected();
return clientListener.isConnected();
}
}
@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());
}
}
renderGrid();
renderGrid();
renderActions();
renderActions();
}
}
}
}
package com.stream_pi.client.window.settings;
package com.stream_pi.client.window.settings;
import java.io.File;
import java.io.File;
import java.io.IOException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URISyntaxException;
import java.util.function.Consumer;
import java.util.function.Consumer;
import com.gluonhq.attach.browser.BrowserService;
import com.gluonhq.attach.browser.BrowserService;
import com.gluonhq.attach.vibration.VibrationService;
import com.gluonhq.attach.vibration.VibrationService;
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.checkforupdates.CheckForUpdates;
import com.stream_pi.util.checkforupdates.UpdateHyperlinkOnClick;
import com.stream_pi.util.checkforupdates.UpdateHyperlinkOnClick;
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.Platform;
import com.stream_pi.util.platform.Platform;
import com.stream_pi.util.platform.PlatformType;
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.StartAtBoot;
import com.stream_pi.util.startatboot.StartAtBoot;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.CacheHint;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
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 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 tryConnectingToServerIfActionClickedToggleButton;
private ToggleButton connectOnStartupToggleButton;
private ToggleButton connectOnStartupToggleButton;
private ToggleButton vibrateOnActionPressToggleButton;
private ToggleButton vibrateOnActionPressToggleButton;
private ToggleButton fullScreenModeToggleButton;
private ToggleButton fullScreenModeToggleButton;
private ToggleButton showCursorToggleButton;
private ToggleButton showCursorToggleButton;
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;
private TextField autoReconnectTimeTextField;
private TextField autoReconnectTimeTextField;
private final Button checkForUpdatesButton;
private final Button checkForUpdatesButton;
private HostServices hostServices;
private HostServices hostServices;
public SettingsBase(ExceptionAndAlertHandler exceptionAndAlertHandler,
public SettingsBase(ExceptionAndAlertHandler exceptionAndAlertHandler,
ClientListener clientListener, HostServices hostServices)
ClientListener clientListener, HostServices hostServices)
{
{
getStyleClass().add("settings_base");
getStyleClass().add("settings_base");
this.hostServices = hostServices;
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, true);
clientListener.renderProfile(selectedItem, true);
}
}
});
});
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();
}
}
});
});
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());
tryConnectingToServerIfActionClickedToggleButton = new ToggleButton("Try Connecting to Server If not connected on Action click");
tryConnectingToServerIfActionClickedToggleButton.managedProperty().bind(tryConnectingToServerIfActionClickedToggleButton.visibleProperty());
fullScreenModeToggleButton = new ToggleButton("Full Screen");
fullScreenModeToggleButton = new ToggleButton("Full Screen");
fullScreenModeToggleButton.managedProperty().bind(fullScreenModeToggleButton.visibleProperty());
fullScreenModeToggleButton.managedProperty().bind(fullScreenModeToggleButton.visibleProperty());
vibrateOnActionPressToggleButton = new ToggleButton("Vibrate On Action Press");
vibrateOnActionPressToggleButton = new ToggleButton("Vibrate On Action Press");
vibrateOnActionPressToggleButton.managedProperty().bind(vibrateOnActionPressToggleButton.visibleProperty());
vibrateOnActionPressToggleButton.managedProperty().bind(vibrateOnActionPressToggleButton.visibleProperty());
connectOnStartupToggleButton = new ToggleButton("Connect On Startup");
connectOnStartupToggleButton = new ToggleButton("Connect On Startup");
connectOnStartupToggleButton.managedProperty().bind(connectOnStartupToggleButton.visibleProperty());
connectOnStartupToggleButton.managedProperty().bind(connectOnStartupToggleButton.visibleProperty());
showCursorToggleButton = new ToggleButton("Show Cursor");
showCursorToggleButton = new ToggleButton("Show Cursor");
showCursorToggleButton.managedProperty().bind(showCursorToggleButton.visibleProperty());
showCursorToggleButton.managedProperty().bind(showCursorToggleButton.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());
checkForUpdatesButton = new Button("Check for updates");
checkForUpdatesButton = new Button("Check for updates");
checkForUpdatesButton.setOnAction(event->checkForUpdates());
checkForUpdatesButton.setOnAction(event->checkForUpdates());
autoReconnectTimeTextField = new TextField();
autoReconnectTimeTextField = new TextField();
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
),
),
themesPathInputBox,
themesPathInputBox,
iconsPathInputBox,
iconsPathInputBox,
profilesPathInputBox
profilesPathInputBox
);
);
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());
Button exitButton = new Button("Exit");
Button exitButton = new Button("Exit");
exitButton.setOnAction(event -> onExitButtonClicked());
exitButton.setOnAction(event -> onExitButtonClicked());
HBox buttonBar = new HBox(connectDisconnectButton, saveButton);
HBox buttonBar = new HBox(connectDisconnectButton, saveButton);
shutdownButton = new Button("Shutdown");
shutdownButton = new Button("Shutdown");
shutdownButton.managedProperty().bind(shutdownButton.visibleProperty());
shutdownButton.managedProperty().bind(shutdownButton.visibleProperty());
shutdownButton.setOnAction(event -> onShutdownButtonClicked());
shutdownButton.setOnAction(event -> onShutdownButtonClicked());
vBox.getChildren().addAll(
vBox.getChildren().addAll(
shutdownButton,
shutdownButton,
tryConnectingToServerIfActionClickedToggleButton,
fullScreenModeToggleButton,
fullScreenModeToggleButton,
connectOnStartupToggleButton,
connectOnStartupToggleButton,
vibrateOnActionPressToggleButton,
vibrateOnActionPressToggleButton,
checkForUpdatesButton,
checkForUpdatesButton,
startOnBootToggleButton,
startOnBootToggleButton,
showCursorToggleButton,
showCursorToggleButton,
licenseLabel,
licenseLabel,
versionLabel
versionLabel
);
);
buttonBar.getChildren().add(closeButton);
buttonBar.getChildren().add(closeButton);
buttonBar.getStyleClass().add("settings_button_bar");
buttonBar.getStyleClass().add("settings_button_bar");
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);
setCache(true);
setCacheHint(CacheHint.SPEED);
setCacheHint(CacheHint.SPEED);
//Perform platform checks
//Perform platform checks
Platform platform = ClientInfo.getInstance().getPlatform();
Platform platform = ClientInfo.getInstance().getPlatform();
if(platform == Platform.ANDROID ||
if(platform == Platform.ANDROID ||
platform == Platform.IOS)
platform == Platform.IOS)
{
{
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);
fullScreenModeToggleButton.setVisible(false);
fullScreenModeToggleButton.setVisible(false);
}
}
else
else
{
{
if(!ClientInfo.getInstance().isShowShutDownButton())
if(!ClientInfo.getInstance().isShowShutDownButton())
{
{
shutdownButton.setVisible(false);
shutdownButton.setVisible(false);
}
}
vibrateOnActionPressToggleButton.setVisible(false);
vibrateOnActionPressToggleButton.setVisible(false);
buttonBar.getChildren().add(exitButton);
buttonBar.getChildren().add(exitButton);
}
}
if(!ClientInfo.getInstance().isShowFullScreenToggleButton())
if(!ClientInfo.getInstance().isShowFullScreenToggleButton())
{
{
fullScreenModeToggleButton.setVisible(false);
fullScreenModeToggleButton.setVisible(false);
}
}
}
}
private void checkForUpdates()
private void checkForUpdates()
{
{
new CheckForUpdates(checkForUpdatesButton,
new CheckForUpdates(checkForUpdatesButton,
PlatformType.CLIENT, ClientInfo.getInstance().getVersion(), new UpdateHyperlinkOnClick() {
PlatformType.CLIENT, ClientInfo.getInstance().getVersion(), new UpdateHyperlinkOnClick() {
@Override
@Override
public void handle(ActionEvent actionEvent) {
public void handle(ActionEvent actionEvent) {
Platform platform = ClientInfo.getInstance().getPlatform();
Platform platform = ClientInfo.getInstance().getPlatform();
if(platform == Platform.ANDROID || platform == Platform.IOS)
if(platform == Platform.ANDROID || platform == Platform.IOS)
{
{
BrowserService.create().ifPresentOrElse(s->
BrowserService.create().ifPresentOrElse(s->
{
{
try
try
{
{
s.launchExternalBrowser(getURL());
s.launchExternalBrowser(getURL());
}
}
catch (Exception e )
catch (Exception e )
{
{
exceptionAndAlertHandler.handleMinorException(
exceptionAndAlertHandler.handleMinorException(
new MinorException("Cant start browser!")
new MinorException("Cant start browser!")
);
);
}
}
},()-> exceptionAndAlertHandler.handleMinorException(
},()-> exceptionAndAlertHandler.handleMinorException(
new MinorException("Sorry!","No browser detected.")
new MinorException("Sorry!","No browser detected.")
));
));
}
}
else
else
{
{
hostServices.showDocument(getURL());
hostServices.showDocument(getURL());
}
}
}
}
});
});
}
}
public void onExitButtonClicked()
public void onExitButtonClicked()
{
{
clientListener.onCloseRequest();
clientListener.onCloseRequest();
javafx.application.Platform.exit();
javafx.application.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 Button getConnectDisconnectButton()
{
return connectDisconnectButton;
}
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()
{
{
javafx.application.Platform.runLater(()->{
javafx.application.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
{
{
Config config = Config.getInstance();
Config config = Config.getInstance();
nickNameTextField.setText(config.getClientNickName());
nickNameTextField.setText(config.getClientNickName());
serverHostNameOrIPTextField.setText(config.getSavedServerHostNameOrIP());
serverHostNameOrIPTextField.setText(config.getSavedServerHostNameOrIP());
serverPortTextField.setText(config.getSavedServerPort()+"");
serverPortTextField.setText(config.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);
themesPathTextField.setText(config.getThemesPath());
themesPathTextField.setText(config.getThemesPath());
iconsPathTextField.setText(config.getIconsPath());
iconsPathTextField.setText(config.getIconsPath());
profilesPathTextField.setText(config.getProfilesPath());
profilesPathTextField.setText(config.getProfilesPath());
startOnBootToggleButton.setSelected(config.isStartOnBoot());
startOnBootToggleButton.setSelected(config.isStartOnBoot());
fullScreenModeToggleButton.setSelected(config.getIsFullScreenMode());
fullScreenModeToggleButton.setSelected(config.getIsFullScreenMode());
showCursorToggleButton.setSelected(config.isShowCursor());
showCursorToggleButton.setSelected(config.isShowCursor());
connectOnStartupToggleButton.setSelected(config.isConnectOnStartup());
connectOnStartupToggleButton.setSelected(config.isConnectOnStartup());
vibrateOnActionPressToggleButton.setSelected(config.isVibrateOnActionClicked());
vibrateOnActionPressToggleButton.setSelected(config.isVibrateOnActionClicked());
tryConnectingToServerIfActionClickedToggleButton.setSelected(config.isTryConnectingWhenActionClicked());
}
}
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");
else if(port > 65535)
else if(port > 65535)
errors.append("* Server Port must be lesser than 65535\n");
errors.append("* Server Port must be lesser than 65535\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");
}
}
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 syncWithServer = false;
boolean syncWithServer = false;
Config config = Config.getInstance();
Config config = Config.getInstance();
if(!config.getCurrentThemeFullName().equals(themeComboBox.getCurrentSelectedItem().getFullName()))
if(!config.getCurrentThemeFullName().equals(themeComboBox.getCurrentSelectedItem().getFullName()))
{
{
syncWithServer = true;
syncWithServer = true;
toBeReloaded = true;
toBeReloaded = true;
}
}
config.setCurrentThemeFullName(themeComboBox.getCurrentSelectedItem().getFullName());
config.setCurrentThemeFullName(themeComboBox.getCurrentSelectedItem().getFullName());
if(!config.getClientNickName().equals(nickNameTextField.getText()))
if(!config.getClientNickName().equals(nickNameTextField.getText()))
{
{
syncWithServer = true;
syncWithServer = true;
}
}
config.setNickName(nickNameTextField.getText());
config.setNickName(nickNameTextField.getText());
if(port != config.getSavedServerPort() || !serverHostNameOrIPTextField.getText().equals(config.getSavedServerHostNameOrIP()))
if(port != config.getSavedServerPort() || !serverHostNameOrIPTextField.getText().equals(config.getSavedServerHostNameOrIP()))
{
{
syncWithServer = true;
syncWithServer = true;
}
}
config.setServerPort(port);
config.setServerPort(port);
config.setServerHostNameOrIP(serverHostNameOrIPTextField.getText());
config.setServerHostNameOrIP(serverHostNameOrIPTextField.getText());
boolean isFullScreen = fullScreenModeToggleButton.isSelected();
boolean isFullScreen = fullScreenModeToggleButton.isSelected();
if(config.getIsFullScreenMode() != isFullScreen)
if(config.getIsFullScreenMode() != isFullScreen)
{
{
toBeReloaded = true;
toBeReloaded = true;
}
}
config.setIsFullScreenMode(isFullScreen);
config.setIsFullScreenMode(isFullScreen);
config.setTryConnectingWhenActionClicked(tryConnectingToServerIfActionClickedToggleButton.isSelected());
boolean startOnBoot = startOnBootToggleButton.isSelected();
boolean startOnBoot = startOnBootToggleButton.isSelected();
if(config.isStartOnBoot() != startOnBoot)
if(config.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(PlatformType.CLIENT, ClientInfo.getInstance().getPlatform());
StartAtBoot startAtBoot = new StartAtBoot(PlatformType.CLIENT, ClientInfo.getInstance().getPlatform());
if(startOnBoot)
if(startOnBoot)
{
{
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()),
startAtBoot.create(new File(ClientInfo.getInstance().getRunnerFileName()),
ClientInfo.getInstance().isXMode());
ClientInfo.getInstance().isXMode());
config.setStartupIsXMode(ClientInfo.getInstance().isXMode());
config.setStartupIsXMode(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.setStartOnBoot(startOnBoot);
config.setStartOnBoot(startOnBoot);
config.setShowCursor(showCursorToggleButton.isSelected());
config.setShowCursor(showCursorToggleButton.isSelected());
if(!config.getThemesPath().equals(themesPathTextField.getText()))
if(!config.getThemesPath().equals(themesPathTextField.getText()))
toBeReloaded = true;
toBeReloaded = true;
config.setThemesPath(themesPathTextField.getText());
config.setThemesPath(themesPathTextField.getText());
if(!config.getIconsPath().equals(iconsPathTextField.getText()))
if(!config.getIconsPath().equals(iconsPathTextField.getText()))
toBeReloaded = true;
toBeReloaded = true;
config.setIconsPath(iconsPathTextField.getText());
config.setIconsPath(iconsPathTextField.getText());
if(!config.getProfilesPath().equals(profilesPathTextField.getText()))
if(!config.getProfilesPath().equals(profilesPathTextField.getText()))
toBeReloaded = true;
toBeReloaded = true;
config.setProfilesPath(profilesPathTextField.getText());
config.setProfilesPath(profilesPathTextField.getText());
config.setConnectOnStartup(connectOnStartupToggleButton.isSelected());
config.setConnectOnStartup(connectOnStartupToggleButton.isSelected());
boolean isVibrateOnActionClicked = vibrateOnActionPressToggleButton.isSelected();
boolean isVibrateOnActionClicked = vibrateOnActionPressToggleButton.isSelected();
if(config.isVibrateOnActionClicked() != isVibrateOnActionClicked && isVibrateOnActionClicked)
if(config.isVibrateOnActionClicked() != isVibrateOnActionClicked && isVibrateOnActionClicked)
{
{
if(VibrationService.create().isEmpty())
if(VibrationService.create().isEmpty())
{
{
isVibrateOnActionClicked = false;
isVibrateOnActionClicked = false;
new StreamPiAlert("Uh Oh!", "Vibration not supported", StreamPiAlertType.ERROR).show();
new StreamPiAlert("Uh Oh!", "Vibration not supported", StreamPiAlertType.ERROR).show();
}
}
}
}
config.setVibrateOnActionClicked(isVibrateOnActionClicked);
config.setVibrateOnActionClicked(isVibrateOnActionClicked);
config.save();
config.save();
loadData();
loadData();
if(syncWithServer)
if(syncWithServer)
{
{
if(clientListener.isConnected())
if(clientListener.isConnected())
{
{
clientListener.getClient().updateClientDetails();
clientListener.getClient().updateClientDetails();
}
}
}
}
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);
}
}
}
}
}
}
[
[
{"name":"com.stream_pi.util.comms.Message"},
{"name":"com.stream_pi.util.comms.Message"},
{"name": "java.lang.String"},
{"name": "java.lang.String"},
{"name": "java.lang.String[]"},
{"name": "java.lang.String[]"},
{"name": "byte[]"}
{"name": "byte"},
{"name": "byte[]"},
{"name": "int"},
{"name": "int[]"},
{"name": "double"},
{"name": "double[]"}
]
]