server
Clone or download
Modified Files
package com.stream_pi.server.controller;
package com.stream_pi.server.controller;
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.PropertySaver;
import com.stream_pi.action_api.action.PropertySaver;
import com.stream_pi.action_api.action.ServerConnection;
import com.stream_pi.action_api.action.ServerConnection;
import com.stream_pi.action_api.externalplugin.NormalAction;
import com.stream_pi.action_api.externalplugin.NormalAction;
import com.stream_pi.action_api.externalplugin.ToggleAction;
import com.stream_pi.action_api.externalplugin.ToggleAction;
import com.stream_pi.action_api.externalplugin.ToggleExtras;
import com.stream_pi.action_api.externalplugin.ToggleExtras;
import com.stream_pi.server.Main;
import com.stream_pi.server.Main;
import com.stream_pi.server.action.ExternalPlugins;
import com.stream_pi.server.action.ExternalPlugins;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.MainServer;
import com.stream_pi.server.connection.MainServer;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.StartupFlags;
import com.stream_pi.server.info.StartupFlags;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.window.Base;
import com.stream_pi.server.window.Base;
import com.stream_pi.server.window.dashboard.DashboardBase;
import com.stream_pi.server.window.dashboard.DashboardBase;
import com.stream_pi.server.window.dashboard.DonatePopupContent;
import com.stream_pi.server.window.dashboard.DonatePopupContent;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.firsttimeuse.FirstTimeUse;
import com.stream_pi.server.window.firsttimeuse.FirstTimeUse;
import com.stream_pi.server.window.settings.SettingsBase;
import com.stream_pi.server.window.settings.SettingsBase;
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.*;
import com.stream_pi.util.exception.*;
import com.stream_pi.util.iohelper.IOHelper;
import com.stream_pi.util.iohelper.IOHelper;
import javafx.animation.Animation;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.Image;
import javafx.scene.media.AudioClip;
import javafx.stage.Modality;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import javafx.util.Duration;
import java.awt.MenuItem;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.TrayIcon;
import java.io.File;
import java.net.SocketAddress;
import java.net.SocketAddress;
import java.util.Objects;
import java.util.Objects;
import java.util.Random;
import java.util.Random;
import java.util.Timer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Level;
import java.util.logging.Level;
public class Controller extends Base implements PropertySaver, ServerConnection, ToggleExtras
public class Controller extends Base implements PropertySaver, ServerConnection, ToggleExtras
{
{
private final ExecutorService executor = Executors.newCachedThreadPool();
private final ExecutorService executor = Executors.newCachedThreadPool();
private MainServer mainServer;
private MainServer mainServer;
private Animation openSettingsAnimation;
private Animation openSettingsAnimation;
private Animation closeSettingsAnimation;
private Animation closeSettingsAnimation;
public Controller(){
public Controller(){
mainServer = null;
mainServer = null;
}
}
public void setupDashWindow() throws SevereException
public void setupDashWindow() throws SevereException
{
{
try
try
{
{
getStage().setOnCloseRequest(this::onCloseRequest);
getStage().setOnCloseRequest(this::onCloseRequest);
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}
}
@Override
@Override
public void init()
public void init()
{
{
try
try
{
{
initBase();
initBase();
setupDashWindow();
setupDashWindow();
setupSettingsWindowsAnimations();
setupSettingsWindowsAnimations();
ExternalPlugins.getInstance().setPropertySaver(this);
ExternalPlugins.getInstance().setPropertySaver(this);
ExternalPlugins.getInstance().setToggleExtras(this);
ExternalPlugins.getInstance().setToggleExtras(this);
ExternalPlugins.getInstance().setServerConnection(this);
ExternalPlugins.getInstance().setServerConnection(this);
getDashboardBase().getPluginsPane().getSettingsButton().setOnAction(event -> {
getDashboardBase().getPluginsPane().getSettingsButton().setOnAction(event -> {
openSettingsAnimation.play();
openSettingsAnimation.play();
});
});
getSettingsBase().getCloseButton().setOnAction(event -> {
getSettingsBase().getCloseButton().setOnAction(event -> {
closeSettingsAnimation.play();
closeSettingsAnimation.play();
});
});
getSettingsBase().getThemesSettings().setController(this);
getSettingsBase().getThemesSettings().setController(this);
mainServer = new MainServer(this, this);
mainServer = new MainServer(this, this);
if(getConfig().isFirstTimeUse())
if(getConfig().isFirstTimeUse())
{
{
Stage stage = new Stage();
Stage stage = new Stage();
Scene s = new Scene(new FirstTimeUse(this, this),
Scene s = new Scene(new FirstTimeUse(this, this),
getConfig().getStartupWindowWidth(), getConfig().getStartupWindowHeight());
getConfig().getStartupWindowWidth(), getConfig().getStartupWindowHeight());
stage.setScene(s);
stage.setScene(s);
stage.setMinHeight(500);
stage.setMinHeight(500);
stage.setMinWidth(700);
stage.setMinWidth(700);
stage.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResourceAsStream("app_icon.png"))));
stage.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResourceAsStream("app_icon.png"))));
stage.setTitle("Stream-Pi Server Setup");
stage.setTitle("Stream-Pi Server Setup");
stage.getScene().getStylesheets().addAll(getStylesheets());
stage.getScene().getStylesheets().addAll(getStylesheets());
stage.initModality(Modality.APPLICATION_MODAL);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setOnCloseRequest(event->Platform.exit());
stage.setOnCloseRequest(event->Platform.exit());
stage.show();
stage.show();
}
}
else
else
{
{
if(getConfig().isAllowDonatePopup())
if(getConfig().isAllowDonatePopup())
{
{
if(new Random().nextInt(5) == 3)
if(new Random().nextInt(50) == 3)
new DonatePopupContent(getHostServices(), this).show();
new DonatePopupContent(getHostServices(), this).show();
}
}
othInit();
othInit();
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
}
}
@Override
@Override
public void othInit()
public void othInit()
{
{
try
try
{
{
if(StartupFlags.START_MINIMISED && SystemTray.isSupported())
if(StartupFlags.START_MINIMISED && SystemTray.isSupported())
minimiseApp();
minimiseApp();
else
else
getStage().show();
getStage().show();
}
}
catch(MinorException e)
catch(MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
StreamPiAlert.setIsShowPopup(getConfig().isShowAlertsPopup());
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
getSettingsBase().getGeneralSettings().loadDataFromConfig();
getSettingsBase().getGeneralSettings().loadDataFromConfig();
//themes
//themes
getSettingsBase().getThemesSettings().setThemes(getThemes());
getSettingsBase().getThemesSettings().setThemes(getThemes());
getSettingsBase().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsBase().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsBase().getThemesSettings().loadThemes();
getSettingsBase().getThemesSettings().loadThemes();
//clients
//clients
getSettingsBase().getClientsSettings().loadData();
getSettingsBase().getClientsSettings().loadData();
try
try
{
{
//Plugins
//Plugins
Platform.runLater(()->{
Platform.runLater(()->{
getDashboardBase().getPluginsPane().clearData();
getDashboardBase().getPluginsPane().clearData();
getDashboardBase().getPluginsPane().loadOtherActions();
getDashboardBase().getPluginsPane().loadOtherActions();
});
});
ExternalPlugins.setPluginsLocation(getConfig().getPluginsPath());
ExternalPlugins.setPluginsLocation(getConfig().getPluginsPath());
ExternalPlugins.getInstance().init();
ExternalPlugins.getInstance().init();
Platform.runLater(()->getDashboardBase().getPluginsPane().loadData());
Platform.runLater(()->getDashboardBase().getPluginsPane().loadData());
getSettingsBase().getPluginsSettings().loadPlugins();
getSettingsBase().getPluginsSettings().loadPlugins();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
getSettingsBase().getPluginsSettings().showPluginInitError();
getSettingsBase().getPluginsSettings().showPluginInitError();
handleMinorException(e);
handleMinorException(e);
}
}
//Server
//Server
mainServer.setPort(getConfig().getPort());
mainServer.setPort(getConfig().getPort());
mainServer.start();
mainServer.start();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
return null;
return null;
}
}
});
});
}
}
@Override
@Override
public void factoryReset()
public void factoryReset()
{
{
getLogger().info("Reset to factory ...");
getLogger().info("Reset to factory ...");
onQuitApp();
onQuitApp();
boolean result = IOHelper.deleteFile(getServerInfo().getPrePath());
boolean result = IOHelper.deleteFile(getServerInfo().getPrePath());
if(result)
if(result)
{
{
getStage().close();
getStage().close();
init();
init();
}
}
else
else
{
{
handleSevereException(new SevereException("Unable to delete all files successfully. Installation corrupt. Re-install."));
handleSevereException(new SevereException("Unable to delete all files successfully. Installation corrupt. Re-install."));
}
}
}
}
private void setupSettingsWindowsAnimations()
private void setupSettingsWindowsAnimations()
{
{
Node settingsNode = getSettingsBase();
Node settingsNode = getSettingsBase();
Node dashboardNode = getDashboardBase();
Node dashboardNode = getDashboardBase();
openSettingsAnimation = createOpenSettingsAnimation(settingsNode, dashboardNode);
openSettingsAnimation = createOpenSettingsAnimation(settingsNode, dashboardNode);
closeSettingsAnimation = createCloseSettingsAnimation(settingsNode, dashboardNode);
closeSettingsAnimation = createCloseSettingsAnimation(settingsNode, dashboardNode);
}
}
public void onCloseRequest(WindowEvent event)
public void onCloseRequest(WindowEvent event)
{
{
try
try
{
{
if(Config.getInstance().getMinimiseToSystemTrayOnClose() &&
if(Config.getInstance().getMinimiseToSystemTrayOnClose() &&
SystemTray.isSupported())
SystemTray.isSupported())
{
{
minimiseApp();
minimiseApp();
event.consume();
event.consume();
return;
return;
}
}
onQuitApp();
onQuitApp();
exit();
exit();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
}
}
public void onQuitApp()
public void onQuitApp()
{
{
getLogger().info("Shutting down ...");
getLogger().info("Shutting down ...");
try
try
{
{
if(getConfig() != null)
if(getConfig() != null)
{
{
getConfig().setStartupWindowSize(getWidth(), getHeight());
getConfig().setStartupWindowSize(getWidth(), getHeight());
getConfig().setRightDividerPositions(getDashboardBase().getDividerPositions());
getConfig().setRightDividerPositions(getDashboardBase().getDividerPositions());
getConfig().setLeftDividerPositions(getDashboardBase().getLeftSplitPane().getDividerPositions());
getConfig().setLeftDividerPositions(getDashboardBase().getLeftSplitPane().getDividerPositions());
getConfig().save();
getConfig().save();
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
stopServerAndAllConnections();
stopServerAndAllConnections();
executor.shutdown();
ExternalPlugins.getInstance().shutDownActions();
ExternalPlugins.getInstance().shutDownActions();
closeLogger();
closeLogger();
Config.nullify();
Config.nullify();
}
}
public void exit()
public void exit()
{
{
executor.shutdown();
Platform.exit();
Platform.exit();
}
}
private void stopServerAndAllConnections()
private void stopServerAndAllConnections()
{
{
if(mainServer!=null)
if(mainServer!=null)
mainServer.stopListeningForConnections();
mainServer.stopListeningForConnections();
ClientConnections.getInstance().disconnectAll();
ClientConnections.getInstance().disconnectAll();
}
}
@Override
@Override
public void restart()
public void restart()
{
{
getLogger().info("Restarting ...");
getLogger().info("Restarting ...");
stopServerAndAllConnections();
stopServerAndAllConnections();
Platform.runLater(this::init);
Platform.runLater(this::init);
}
}
public void minimiseApp() throws MinorException
public void minimiseApp() throws MinorException
{
{
try
try
{
{
SystemTray systemTray = SystemTray.getSystemTray();
SystemTray systemTray = SystemTray.getSystemTray();
if(getTrayIcon() == null)
if(getTrayIcon() == null)
initIconTray(systemTray);
initIconTray(systemTray);
systemTray.add(getTrayIcon());
systemTray.add(getTrayIcon());
getStage().hide();
getStage().hide();
getStage().setOnShown(windowEvent -> {
getStage().setOnShown(windowEvent -> {
systemTray.remove(getTrayIcon());
systemTray.remove(getTrayIcon());
});
});
}
}
catch(Exception e)
catch(Exception e)
{
{
throw new MinorException(e.getMessage());
throw new MinorException(e.getMessage());
}
}
}
}
public void initIconTray(SystemTray systemTray)
public void initIconTray(SystemTray systemTray)
{
{
Platform.setImplicitExit(false);
Platform.setImplicitExit(false);
PopupMenu popup = new PopupMenu();
PopupMenu popup = new PopupMenu();
MenuItem exitItem = new MenuItem("Exit");
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(l->{
exitItem.addActionListener(l->{
systemTray.remove(getTrayIcon());
systemTray.remove(getTrayIcon());
onQuitApp();
onQuitApp();
exit();
exit();
});
});
popup.add(exitItem);
popup.add(exitItem);
TrayIcon trayIcon = new TrayIcon(
TrayIcon trayIcon = new TrayIcon(
Toolkit.getDefaultToolkit().getImage(Main.class.getResource("app_icon.png")),
Toolkit.getDefaultToolkit().getImage(Main.class.getResource("app_icon.png")),
"Stream-Pi Server",
"Stream-Pi Server",
popup
popup
);
);
trayIcon.addActionListener(l-> Platform.runLater(()-> {
trayIcon.addActionListener(l-> Platform.runLater(()-> {
getStage().show();
getStage().show();
getStage().setAlwaysOnTop(true);
getStage().setAlwaysOnTop(true);
getStage().setAlwaysOnTop(false);
getStage().setAlwaysOnTop(false);
}));
}));
trayIcon.setImageAutoSize(true);
trayIcon.setImageAutoSize(true);
this.trayIcon = trayIcon;
this.trayIcon = trayIcon;
}
}
private TrayIcon trayIcon = null;
private TrayIcon trayIcon = null;
public TrayIcon getTrayIcon()
public TrayIcon getTrayIcon()
{
{
return trayIcon;
return trayIcon;
}
}
@Override
@Override
public void handleMinorException(MinorException e)
public void handleMinorException(MinorException e)
{
{
getLogger().log(Level.SEVERE, e.getShortMessage(), e);
getLogger().log(Level.SEVERE, e.getShortMessage(), e);
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()-> new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
Platform.runLater(()-> new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
}
}
@Override
@Override
public void handleSevereException(SevereException e) {
public void handleSevereException(SevereException e)
{
getLogger().log(Level.SEVERE, e.getShortMessage(), e);
getLogger().log(Level.SEVERE, e.getShortMessage(), e);
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()->{
Platform.runLater(()->{
StreamPiAlert alert = new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
StreamPiAlert alert = new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
alert.setOnClicked(new StreamPiAlertListener()
alert.setOnClicked(new StreamPiAlertListener()
{
{
@Override
@Override
public void onClick(String txt)
public void onClick(String txt)
{
{
onQuitApp();
onQuitApp();
exit();
exit();
}
}
});
});
alert.show();
alert.show();
});
});
}
}
private AudioClip audioClip = null;
private String audioFilePath = null;
private void playSound()
{
if(audioClip == null)
{
updateSound();
}
else
{
if(audioClip.isPlaying())
{
Platform.runLater(audioClip::stop);
return;
}
}
if(!audioFilePath.equals(getConfig().getSoundOnActionClickedFilePath()))
{
updateSound();
}
Platform.runLater(audioClip::play);
}
private void updateSound()
{
audioFilePath = getConfig().getSoundOnActionClickedFilePath();
audioClip = new AudioClip(new File(audioFilePath).toURI().toString());
}
@Override
@Override
public void onActionClicked(Client client, String profileID, String actionID, boolean toggle)
public void onActionClicked(Client client, String profileID, String actionID, boolean toggle)
{
{
try
try
{
{
Action action = client.getProfileByID(profileID).getActionByID(actionID);
Action action = client.getProfileByID(profileID).getActionByID(actionID);
if(action.getActionType() == ActionType.NORMAL || action.getActionType() == ActionType.TOGGLE)
if(getConfig().getSoundOnActionClickedStatus())
{
{
if(action.isInvalid())
playSound();
{
}
throw new MinorException(
"The action isn't installed on the server."
if(action.isInvalid())
);
{
}
throw new MinorException(
else
"The action isn't installed on the server."
);
}
executor.execute(new Task<Void>() {
@Override
protected Void call()
{
{
executor.execute(new Task<Void>() {
try
@Override
{
protected Void call()
Thread.sleep(action.getDelayBeforeExecuting());
getLogger().info("action "+action.getID()+" clicked!");
if(action instanceof ToggleAction)
{
onToggleActionClicked((ToggleAction) action, toggle, profileID,
client.getRemoteSocketAddress());
}
else if (action instanceof NormalAction)
{
{
try {
onNormalActionClicked((NormalAction) action, profileID,
Thread.sleep(action.getDelayBeforeExecuting());
client.getRemoteSocketAddress());
getLogger().info("action "+action.getID()+" clicked!");
if(action instanceof ToggleAction)
{
onToggleActionClicked((ToggleAction) action, toggle, profileID,
client.getRemoteSocketAddress());
}
else if (action instanceof NormalAction)
{
onNormalActionClicked((NormalAction) action, profileID,
client.getRemoteSocketAddress());
}
}
catch (InterruptedException e)
{
e.printStackTrace();
getLogger().info("onActionClicked scheduled task was interrupted ...");
}
return null;
}
}
});
}
catch (InterruptedException e)
{
e.printStackTrace();
getLogger().info("onActionClicked scheduled task was interrupted ...");
}
return null;
}
}
}
});
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
handleMinorException(new MinorException(e.getMessage()));
handleMinorException(new MinorException(e.getMessage()));
}
}
}
}
public synchronized void onNormalActionClicked(NormalAction action, String profileID, SocketAddress socketAddress)
public synchronized void onNormalActionClicked(NormalAction action, String profileID, SocketAddress socketAddress)
{
{
try
try
{
{
action.onActionClicked();
action.onActionClicked();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
sendActionFailed(e, socketAddress, profileID, action.getID());
sendActionFailed(e, socketAddress, profileID, action.getID());
}
}
}
}
public synchronized void onToggleActionClicked(ToggleAction action, boolean toggle, String profileID, SocketAddress socketAddress)
public synchronized void onToggleActionClicked(ToggleAction action, boolean toggle, String profileID, SocketAddress socketAddress)
{
{
try
try
{
{
if(toggle)
if(toggle)
{
{
action.onToggleOn();
action.onToggleOn();
}
}
else
else
{
{
action.onToggleOff();
action.onToggleOff();
}
}
}
}
catch (MinorException e)
catch (MinorException e)
{
{
sendActionFailed(e, socketAddress, profileID, action.getID());
sendActionFailed(e, socketAddress, profileID, action.getID());
}
}
}
}
@Override
@Override
public void clearTemp() {
public void clearTemp() {
Platform.runLater(() -> {
Platform.runLater(() -> {
getDashboardBase().getClientAndProfileSelectorPane().refresh();
getDashboardBase().getClientAndProfileSelectorPane().refresh();
getDashboardBase().getActionGridPane().clear();
getDashboardBase().getActionGridPane().clear();
getDashboardBase().getActionGridPane().setFreshRender(true);
getDashboardBase().getActionGridPane().setFreshRender(true);
getDashboardBase().getActionDetailsPane().clear();
getDashboardBase().getActionDetailsPane().clear();
getSettingsBase().getClientsSettings().loadData();
getSettingsBase().getClientsSettings().loadData();
});
});
}
}
@Override
@Override
public void saveServerProperties()
public void saveServerProperties()
{
{
try
try
{
{
ExternalPlugins.getInstance().saveServerSettings();
ExternalPlugins.getInstance().saveServerSettings();
getSettingsBase().getPluginsSettings().loadPlugins();
getSettingsBase().getPluginsSettings().loadPlugins();
} catch (MinorException e) {
} catch (MinorException e) {
e.printStackTrace();
e.printStackTrace();
handleMinorException(e);
handleMinorException(e);
}
}
}
}
private void saveClientActionMain(String profileID, String actionID, SocketAddress socketAddress, boolean sendIcons)
private void saveClientActionMain(String profileID, String actionID, SocketAddress socketAddress, boolean sendIcons)
{
{
try {
try {
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress);
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress);
ClientProfile clientProfile = clientConnection.getClient().getProfileByID(profileID);
ClientProfile clientProfile = clientConnection.getClient().getProfileByID(profileID);
Action action = clientProfile.getActionByID(actionID);
Action action = clientProfile.getActionByID(actionID);
clientConnection.saveActionDetails(profileID, action);
clientConnection.saveActionDetails(profileID, action);
if(sendIcons && action.isHasIcon())
if(sendIcons && action.isHasIcon())
{
{
saveAllIcons(profileID, actionID, socketAddress, false);
saveAllIcons(profileID, actionID, socketAddress, false);
}
}
Platform.runLater(()->{
Platform.runLater(()->{
try {
try {
ActionBox actionBox = getDashboardBase().getActionGridPane().getActionBoxByIDAndProfileID(
ActionBox actionBox = getDashboardBase().getActionGridPane().getActionBoxByIDAndProfileID(
action.getID(),
action.getID(),
profileID
profileID
);
);
if(actionBox != null)
if(actionBox != null)
{
{
Platform.runLater(actionBox::init);
Platform.runLater(actionBox::init);
}
}
if(getDashboardBase().getActionDetailsPane().getAction() != null)
if(getDashboardBase().getActionDetailsPane().getAction() != null)
{
{
// This block is executed when no Action is selected.
// This block is executed when no Action is selected.
if(getDashboardBase().getActionDetailsPane().getAction().getID().equals(actionID))
if(getDashboardBase().getActionDetailsPane().getAction().getID().equals(actionID))
{
{
getDashboardBase().getActionDetailsPane().setAction(action);
getDashboardBase().getActionDetailsPane().setAction(action);
getDashboardBase().getActionDetailsPane().refresh();
getDashboardBase().getActionDetailsPane().refresh();
}
}
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
});
});
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
}
}
@Override
@Override
public void saveClientAction(String profileID, String actionID, SocketAddress socketAddress, boolean sendIcons, boolean runAsync)
public void saveClientAction(String profileID, String actionID, SocketAddress socketAddress, boolean sendIcons, boolean runAsync)
{
{
if(runAsync)
if(runAsync)
{
{
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
saveClientActionMain(profileID, actionID, socketAddress, sendIcons);
saveClientActionMain(profileID, actionID, socketAddress, sendIcons);
return null;
return null;
}
}
});
});
}
}
else
else
{
{
saveClientActionMain(profileID, actionID, socketAddress, sendIcons);
saveClientActionMain(profileID, actionID, socketAddress, sendIcons);
}
}
}
}
@Override
@Override
public void saveAllIcons(String profileID, String actionID, SocketAddress socketAddress)
public void saveAllIcons(String profileID, String actionID, SocketAddress socketAddress)
{
{
saveAllIcons(profileID, actionID, socketAddress, true);
saveAllIcons(profileID, actionID, socketAddress, true);
}
}
public void saveAllIcons(String profileID, String actionID, SocketAddress socketAddress, boolean async)
public void saveAllIcons(String profileID, String actionID, SocketAddress socketAddress, boolean async)
{
{
if(async)
if(async)
{
{
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
saveAllIconsMain(profileID, actionID, socketAddress);
saveAllIconsMain(profileID, actionID, socketAddress);
return null;
return null;
}
}
});
});
}
}
else
else
{
{
saveAllIconsMain(profileID, actionID, socketAddress);
saveAllIconsMain(profileID, actionID, socketAddress);
}
}
}
}
private void saveAllIconsMain(String profileID, String actionID, SocketAddress socketAddress)
private void saveAllIconsMain(String profileID, String actionID, SocketAddress socketAddress)
{
{
try {
try {
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress);
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress);
ClientProfile clientProfile = clientConnection.getClient().getProfileByID(profileID);
ClientProfile clientProfile = clientConnection.getClient().getProfileByID(profileID);
Action action = clientProfile.getActionByID(actionID);
Action action = clientProfile.getActionByID(actionID);
for(String eachState : action.getIcons().keySet())
for(String eachState : action.getIcons().keySet())
{
{
clientConnection.sendIcon(profileID, actionID, eachState,
clientConnection.sendIcon(profileID, actionID, eachState,
action.getIcon(eachState));
action.getIcon(eachState));
}
}
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
}
}
@Override
@Override
public void saveIcon(String state, String profileID, String actionID, SocketAddress socketAddress) {
public void saveIcon(String state, String profileID, String actionID, SocketAddress socketAddress) {
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try {
try {
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress);
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress);
ClientProfile clientProfile = clientConnection.getClient().getProfileByID(profileID);
ClientProfile clientProfile = clientConnection.getClient().getProfileByID(profileID);
Action action = clientProfile.getActionByID(actionID);
Action action = clientProfile.getActionByID(actionID);
clientConnection.sendIcon(profileID, actionID, state, action.getIcon(state));
clientConnection.sendIcon(profileID, actionID, state, action.getIcon(state));
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
return null;
return null;
}
}
});
});
}
}
@Override
@Override
public com.stream_pi.util.platform.Platform getPlatform() {
public com.stream_pi.util.platform.Platform getPlatform() {
return ServerInfo.getInstance().getPlatform();
return ServerInfo.getInstance().getPlatform();
}
}
@Override
@Override
public void sendActionFailed(MinorException exception, SocketAddress socketAddress, String profileID, String actionID)
public void sendActionFailed(MinorException exception, SocketAddress socketAddress, String profileID, String actionID)
{
{
if(exception.getTitle() != null)
if(exception.getTitle() != null)
{
{
exception.setShortMessage(exception.getTitle()+"\n"+exception.getShortMessage());
exception.setShortMessage(exception.getTitle()+"\n"+exception.getShortMessage());
}
}
exception.setTitle("Error while running action");
exception.setTitle("Error while running action");
handleMinorException(exception);
handleMinorException(exception);
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try {
try {
ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress)
ClientConnections.getInstance().getClientConnectionBySocketAddress(socketAddress)
.sendActionFailed(profileID, actionID);
.sendActionFailed(profileID, actionID);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
return null;
return null;
}
}
});
});
}
}
private Animation createOpenSettingsAnimation(Node settingsNode, Node dashboardNode) {
private Animation createOpenSettingsAnimation(Node settingsNode, Node dashboardNode) {
Timeline openSettingsTimeline = new Timeline();
Timeline openSettingsTimeline = new Timeline();
openSettingsTimeline.setCycleCount(1);
openSettingsTimeline.setCycleCount(1);
openSettingsTimeline.getKeyFrames().addAll(
openSettingsTimeline.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.EASE_IN),
0.0D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.1D, Interpolator.EASE_IN),
1.1D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.1D, Interpolator.EASE_IN),
1.1D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.1D, Interpolator.EASE_IN)),
1.1D, Interpolator.EASE_IN)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
0.9D, Interpolator.LINEAR))
0.9D, Interpolator.LINEAR))
);
);
openSettingsTimeline.setOnFinished(e -> settingsNode.toFront());
openSettingsTimeline.setOnFinished(e -> settingsNode.toFront());
return openSettingsTimeline;
return openSettingsTimeline;
}
}
private Animation createCloseSettingsAnimation(Node settingsNode, Node dashboardNode) {
private Animation createCloseSettingsAnimation(Node settingsNode, Node dashboardNode) {
Timeline closeSettingsTimeline = new Timeline();
Timeline closeSettingsTimeline = new Timeline();
closeSettingsTimeline.setCycleCount(1);
closeSettingsTimeline.setCycleCount(1);
closeSettingsTimeline.getKeyFrames().addAll(
closeSettingsTimeline.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.1D, Interpolator.LINEAR),
1.1D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.1D, Interpolator.LINEAR),
1.1D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.1D, Interpolator.LINEAR)),
1.1D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
0.9D, Interpolator.LINEAR)),
0.9D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
1.0D, Interpolator.LINEAR))
1.0D, Interpolator.LINEAR))
);
);
closeSettingsTimeline.setOnFinished(event1 -> {
closeSettingsTimeline.setOnFinished(event1 -> {
dashboardNode.toFront();
dashboardNode.toFront();
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call() {
protected Void call() {
try {
try {
getSettingsBase().getClientsSettings().loadData();
getSettingsBase().getClientsSettings().loadData();
getSettingsBase().getGeneralSettings().loadDataFromConfig();
getSettingsBase().getGeneralSettings().loadDataFromConfig();
getSettingsBase().getPluginsSettings().loadPlugins();
getSettingsBase().getPluginsSettings().loadPlugins();
getSettingsBase().getThemesSettings().setThemes(getThemes());
getSettingsBase().getThemesSettings().setThemes(getThemes());
getSettingsBase().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsBase().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsBase().getThemesSettings().loadThemes();
getSettingsBase().getThemesSettings().loadThemes();
getSettingsBase().setDefaultTabToGeneral();
getSettingsBase().setDefaultTabToGeneral();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
return null;
return null;
}
}
});
});
});
});
return closeSettingsTimeline;
return closeSettingsTimeline;
}
}
@Override
@Override
public void setToggleStatus(boolean currentStatus, String profileID, String actionID, SocketAddress clientSocketAddress)
public void setToggleStatus(boolean currentStatus, String profileID, String actionID, SocketAddress clientSocketAddress)
throws MinorException
throws MinorException
{
{
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(
clientSocketAddress
clientSocketAddress
);
);
if(clientConnection == null)
if(clientConnection == null)
throw new ClientNotFoundException("setToggleStatus failed because no client found with given socket address");
throw new ClientNotFoundException("setToggleStatus failed because no client found with given socket address");
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
clientConnection.setToggleStatus(currentStatus, profileID, actionID);
clientConnection.setToggleStatus(currentStatus, profileID, actionID);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
return null;
return null;
}
}
}).start();
}).start();
}
}
}
}
/*
/*
Config.java
Config.java
Contributor(s) : Debayan Sutradhar (@rnayabed)
Contributor(s) : Debayan Sutradhar (@rnayabed)
handler for config.xml
handler for config.xml
*/
*/
package com.stream_pi.server.io;
package com.stream_pi.server.io;
import java.awt.*;
import java.awt.*;
import java.io.File;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Arrays;
import java.util.Objects;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamResult;
import com.stream_pi.server.Main;
import com.stream_pi.server.Main;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.iohelper.IOHelper;
import com.stream_pi.util.iohelper.IOHelper;
import com.stream_pi.util.xmlconfighelper.XMLConfigHelper;
import com.stream_pi.util.xmlconfighelper.XMLConfigHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Config
public class Config
{
{
private static Config instance = null;
private static Config instance = null;
private final File configFile;
private final File configFile;
private Document document;
private Document document;
private Config() throws SevereException {
private Config() throws SevereException {
try {
try {
configFile = new File(ServerInfo.getInstance().getPrePath()+"config.xml");
configFile = new File(ServerInfo.getInstance().getPrePath()+"config.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
document = docBuilder.parse(configFile);
document = docBuilder.parse(configFile);
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Config", "Unable to read config.xml\n"+e.getMessage());
throw new SevereException("Config", "Unable to read config.xml\n"+e.getMessage());
}
}
}
}
public static synchronized Config getInstance() throws SevereException
public static synchronized Config getInstance() throws SevereException
{
{
if(instance == null)
if(instance == null)
instance = new Config();
instance = new Config();
return instance;
return instance;
}
}
public static void nullify()
public static void nullify()
{
{
instance = null;
instance = null;
}
}
Logger logger = Logger.getLogger(Config.class.getName());
Logger logger = Logger.getLogger(Config.class.getName());
public void save() throws SevereException {
public void save() throws SevereException {
try {
try {
logger.info("Saving config ...");
logger.info("Saving config ...");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(configFile);
Result output = new StreamResult(configFile);
Source input = new DOMSource(document);
Source input = new DOMSource(document);
transformer.transform(input, output);
transformer.transform(input, output);
logger.info("... Done!");
logger.info("... Done!");
} catch (Exception e) {
} catch (Exception e) {
throw new SevereException("Config", "unable to save config.xml");
throw new SevereException("Config", "unable to save config.xml");
}
}
}
}
//Getters
//Getters
//comms
//comms
private Element getCommsElement()
private Element getCommsElement()
{
{
return (Element) document.getElementsByTagName("comms").item(0);
return (Element) document.getElementsByTagName("comms").item(0);
}
}
public String getServerName()
public String getServerName()
{
{
return XMLConfigHelper.getStringProperty(getCommsElement(), "name",
return XMLConfigHelper.getStringProperty(getCommsElement(), "name",
getDefaultServerName(), false, true, document, configFile);
getDefaultServerName(), false, true, document, configFile);
}
}
public int getPort()
public int getPort()
{
{
return XMLConfigHelper.getIntProperty(getCommsElement(), "port",
return XMLConfigHelper.getIntProperty(getCommsElement(), "port",
getDefaultPort(), false, true, document, configFile);
getDefaultPort(), false, true, document, configFile);
}
}
//default getters
//default getters
public String getDefaultServerName()
public String getDefaultServerName()
{
{
return "Stream-Pi Server";
return "Stream-Pi Server";
}
}
public static int getDefaultPort()
public static int getDefaultPort()
{
{
return 6504;
return 6504;
}
}
//server
//server
private Element getDividerPositionsElement()
private Element getDividerPositionsElement()
{
{
return (Element) document.getElementsByTagName("divider-positions").item(0);
return (Element) document.getElementsByTagName("divider-positions").item(0);
}
}
public String getDefaultLeftDividerPositions()
public String getDefaultLeftDividerPositions()
{
{
return "3.0";
return "3.0";
}
}
public double[] getLeftDividerPositions()
public double[] getLeftDividerPositions()
{
{
String[] strArr = XMLConfigHelper.getStringProperty(getDividerPositionsElement(), "left",
String[] strArr = XMLConfigHelper.getStringProperty(getDividerPositionsElement(), "left",
getDefaultLeftDividerPositions(), false, true, document, configFile)
getDefaultLeftDividerPositions(), false, true, document, configFile)
.split(",");
.split(",");
double[] r = new double[strArr.length];
double[] r = new double[strArr.length];
for (int i = 0;i<strArr.length;i++)
for (int i = 0;i<strArr.length;i++)
{
{
r[i] = Double.parseDouble(strArr[i]);
r[i] = Double.parseDouble(strArr[i]);
}
}
return r;
return r;
}
}
public void setLeftDividerPositions(double[] position)
public void setLeftDividerPositions(double[] position)
{
{
String r = Arrays.toString(position);
String r = Arrays.toString(position);
getDividerPositionsElement().getElementsByTagName("left").item(0).setTextContent(r.substring(1, r.length()-1));
getDividerPositionsElement().getElementsByTagName("left").item(0).setTextContent(r.substring(1, r.length()-1));
}
}
public String getDefaultRightDividerPositions()
public String getDefaultRightDividerPositions()
{
{
return "3.0";
return "3.0";
}
}
public double[] getRightDividerPositions()
public double[] getRightDividerPositions()
{
{
String[] strArr = XMLConfigHelper.getStringProperty(getDividerPositionsElement(), "right",
String[] strArr = XMLConfigHelper.getStringProperty(getDividerPositionsElement(), "right",
getDefaultRightDividerPositions(), false, true, document, configFile)
getDefaultRightDividerPositions(), false, true, document, configFile)
.split(",");
.split(",");
double[] r = new double[strArr.length];
double[] r = new double[strArr.length];
for (int i = 0;i<strArr.length;i++)
for (int i = 0;i<strArr.length;i++)
{
{
r[i] = Double.parseDouble(strArr[i]);
r[i] = Double.parseDouble(strArr[i]);
}
}
return r;
return r;
}
}
public void setRightDividerPositions(double[] position)
public void setRightDividerPositions(double[] position)
{
{
String r = Arrays.toString(position);
String r = Arrays.toString(position);
getDividerPositionsElement().getElementsByTagName("right").item(0).setTextContent(r.substring(1, r.length()-1));
getDividerPositionsElement().getElementsByTagName("right").item(0).setTextContent(r.substring(1, r.length()-1));
}
}
private Element getActionGridElement()
private Element getActionGridElement()
{
{
return (Element) document.getElementsByTagName("action-grid").item(0);
return (Element) document.getElementsByTagName("action-grid").item(0);
}
}
public int getActionGridActionGap()
public int getActionGridActionGap()
{
{
return XMLConfigHelper.getIntProperty(getActionGridElement(), "gap",
return XMLConfigHelper.getIntProperty(getActionGridElement(), "gap",
getDefaultActionGridActionGap(), false, true, document, configFile);
getDefaultActionGridActionGap(), false, true, document, configFile);
}
}
public int getActionGridActionSize()
public int getActionGridActionSize()
{
{
return XMLConfigHelper.getIntProperty(getActionGridElement(), "size",
return XMLConfigHelper.getIntProperty(getActionGridElement(), "size",
getDefaultActionGridSize(), false, true, document, configFile);
getDefaultActionGridSize(), false, true, document, configFile);
}
}
public String getCurrentThemeFullName()
public String getCurrentThemeFullName()
{
{
return XMLConfigHelper.getStringProperty((Element) document, "current-theme-full-name",
return XMLConfigHelper.getStringProperty(document, "current-theme-full-name",
getDefaultCurrentThemeFullName(), false, true, document, configFile);
getDefaultCurrentThemeFullName(), false, true, document, configFile);
}
}
public String getThemesPath()
public String getThemesPath()
{
{
return XMLConfigHelper.getStringProperty((Element) document, "themes-path",
return XMLConfigHelper.getStringProperty(document, "themes-path",
getDefaultThemesPath(), false, true, document, configFile);
getDefaultThemesPath(), false, true, document, configFile);
}
}
public String getPluginsPath()
public String getPluginsPath()
{
{
return XMLConfigHelper.getStringProperty((Element) document, "plugins-path",
return XMLConfigHelper.getStringProperty(document, "plugins-path",
getDefaultPluginsPath(), false, true, document, configFile);
getDefaultPluginsPath(), false, true, document, configFile);
}
}
//default getters
//default getters
public String getDefaultCurrentThemeFullName()
public String getDefaultCurrentThemeFullName()
{
{
return "com.stream_pi.defaultlight";
return "com.stream_pi.defaultlight";
}
}
public String getDefaultThemesPath()
public String getDefaultThemesPath()
{
{
return ServerInfo.getInstance().getPrePath()+"Themes/";
return ServerInfo.getInstance().getPrePath()+"Themes/";
}
}
public String getDefaultPluginsPath()
public String getDefaultPluginsPath()
{
{
return ServerInfo.getInstance().getPrePath()+"Plugins/";
return ServerInfo.getInstance().getPrePath()+"Plugins/";
}
}
//server > startup-window-size
//server > startup-window-size
private Element getStartupWindowSizeElement()
private Element getStartupWindowSizeElement()
{
{
return (Element) document.getElementsByTagName("startup-window-size").item(0);
return (Element) document.getElementsByTagName("startup-window-size").item(0);
}
}
public double getStartupWindowWidth()
public double getStartupWindowWidth()
{
{
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "width",
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "width",
getDefaultStartupWindowWidth(), false, true, document, configFile);
getDefaultStartupWindowWidth(), false, true, document, configFile);
}
}
public double getStartupWindowHeight()
public double getStartupWindowHeight()
{
{
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "height",
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "height",
getDefaultStartupWindowHeight(), false, true, document, configFile);
getDefaultStartupWindowHeight(), false, true, document, configFile);
}
}
//default getters
//default getters
public int getDefaultStartupWindowWidth()
public int getDefaultStartupWindowWidth()
{
{
return 1024;
return 1024;
}
}
public int getDefaultStartupWindowHeight()
public int getDefaultStartupWindowHeight()
{
{
return 768;
return 768;
}
}
//sound on action clicked
//sound on action clicked
private Element getSoundOnActionClickedElement()
private Element getSoundOnActionClickedElement()
{
{
return (Element) document.getElementsByTagName("sound-on-action-clicked").item(0);
return (Element) document.getElementsByTagName("sound-on-action-clicked").item(0);
}
}
//others
//others
private Element getOthersElement()
private Element getOthersElement()
{
{
return (Element) document.getElementsByTagName("others").item(0);
return (Element) document.getElementsByTagName("others").item(0);
}
}
public boolean getStartOnBoot()
public boolean getStartOnBoot()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "start-on-boot",
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "start-on-boot",
getDefaultStartOnBoot(), false, true, document, configFile);
getDefaultStartOnBoot(), false, true, document, configFile);
}
}
public boolean getMinimiseToSystemTrayOnClose()
public boolean getMinimiseToSystemTrayOnClose()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "minimize-to-tray-on-close",
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "minimize-to-tray-on-close",
getDefaultMinimiseToSystemTrayOnClose(), false, true, document, configFile);
getDefaultMinimiseToSystemTrayOnClose(), false, true, document, configFile);
}
}
public boolean isFirstTimeUse()
public boolean isFirstTimeUse()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "first-time-use", true, false, true, document, configFile);
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "first-time-use", true, false, true, document, configFile);
}
}
public boolean isAllowDonatePopup()
public boolean isAllowDonatePopup()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "allow-donate-popup", true, false, true, document, configFile);
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "allow-donate-popup", true, false, true, document, configFile);
}
}
//default getters
//default getters
public boolean getDefaultStartOnBoot()
public boolean getDefaultStartOnBoot()
{
{
return false;
return false;
}
}
public boolean getDefaultMinimiseToSystemTrayOnClose()
public boolean getDefaultMinimiseToSystemTrayOnClose()
{
{
return true;
return true;
}
}
//Setters
//Setters
//comms
//comms
public void setServerName(String name)
public void setServerName(String name)
{
{
getCommsElement().getElementsByTagName("name").item(0).setTextContent(name);
getCommsElement().getElementsByTagName("name").item(0).setTextContent(name);
}
}
public void setServerPort(int port)
public void setServerPort(int port)
{
{
getCommsElement().getElementsByTagName("port").item(0).setTextContent(port+"");
getCommsElement().getElementsByTagName("port").item(0).setTextContent(port+"");
}
}
//server
//server
public int getDefaultActionGridActionGap()
public int getDefaultActionGridActionGap()
{
{
return 5;
return 5;
}
}
public int getDefaultActionGridSize()
public int getDefaultActionGridSize()
{
{
return 100;
return 100;
}
}
public void setActionGridSize(int size)
public void setActionGridSize(int size)
{
{
getActionGridElement().getElementsByTagName("size").item(0).setTextContent(size+"");
getActionGridElement().getElementsByTagName("size").item(0).setTextContent(size+"");
}
}
public void setActionGridGap(int size)
public void setActionGridGap(int size)
{
{
getActionGridElement().getElementsByTagName("gap").item(0).setTextContent(size+"");
getActionGridElement().getElementsByTagName("gap").item(0).setTextContent(size+"");
}
}
public void setPluginsPath(String path)
public void setPluginsPath(String path)
{
{
document.getElementsByTagName("plugins-path").item(0).setTextContent(path);
document.getElementsByTagName("plugins-path").item(0).setTextContent(path);
}
}
public void setThemesPath(String path)
public void setThemesPath(String path)
{
{
document.getElementsByTagName("themes-path").item(0).setTextContent(path);
document.getElementsByTagName("themes-path").item(0).setTextContent(path);
}
}
public void setCurrentThemeFullName(String themeName)
public void setCurrentThemeFullName(String themeName)
{
{
document.getElementsByTagName("current-theme-full-name").item(0).setTextContent(themeName);
document.getElementsByTagName("current-theme-full-name").item(0).setTextContent(themeName);
}
}
//server > startup-window-size
//server > startup-window-size
public void setStartupWindowSize(double width, double height)
public void setStartupWindowSize(double width, double height)
{
{
setStartupWindowWidth(width);
setStartupWindowWidth(width);
setStartupWindowHeight(height);
setStartupWindowHeight(height);
}
}
public void setStartupWindowWidth(double width)
public void setStartupWindowWidth(double width)
{
{
getStartupWindowSizeElement().getElementsByTagName("width").item(0).setTextContent(width+"");
getStartupWindowSizeElement().getElementsByTagName("width").item(0).setTextContent(width+"");
}
}
public void setStartupWindowHeight(double height)
public void setStartupWindowHeight(double height)
{
{
getStartupWindowSizeElement().getElementsByTagName("height").item(0).setTextContent(height+"");
getStartupWindowSizeElement().getElementsByTagName("height").item(0).setTextContent(height+"");
}
}
//others
//others
public void setStartupOnBoot(boolean value)
public void setStartupOnBoot(boolean value)
{
{
getOthersElement().getElementsByTagName("start-on-boot").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("start-on-boot").item(0).setTextContent(value+"");
}
}
public void setMinimiseToSystemTrayOnClose(boolean value)
public void setMinimiseToSystemTrayOnClose(boolean value)
{
{
getOthersElement().getElementsByTagName("minimize-to-tray-on-close").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("minimize-to-tray-on-close").item(0).setTextContent(value+"");
}
}
public void setFirstTimeUse(boolean value)
public void setFirstTimeUse(boolean value)
{
{
getOthersElement().getElementsByTagName("first-time-use").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("first-time-use").item(0).setTextContent(value+"");
}
}
public void setAllowDonatePopup(boolean value)
public void setAllowDonatePopup(boolean value)
{
{
getOthersElement().getElementsByTagName("allow-donate-popup").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("allow-donate-popup").item(0).setTextContent(value+"");
}
}
public static void unzipToDefaultPrePath() throws Exception
public static void unzipToDefaultPrePath() throws Exception
{
{
IOHelper.unzip(Objects.requireNonNull(Main.class.getResourceAsStream("Default.zip")), ServerInfo.getInstance().getPrePath());
IOHelper.unzip(Objects.requireNonNull(Main.class.getResourceAsStream("Default.zip")), ServerInfo.getInstance().getPrePath());
Config config = Config.getInstance();
Config config = Config.getInstance();
config.setThemesPath(config.getDefaultThemesPath());
config.setThemesPath(config.getDefaultThemesPath());
config.setPluginsPath(config.getDefaultPluginsPath());
config.setPluginsPath(config.getDefaultPluginsPath());
if(SystemTray.isSupported())
if(SystemTray.isSupported())
{
{
config.setMinimiseToSystemTrayOnClose(true);
config.setMinimiseToSystemTrayOnClose(true);
}
}
config.save();
config.save();
}
}
public void setShowAlertsPopup(boolean value)
public void setShowAlertsPopup(boolean value)
{
{
getOthersElement().getElementsByTagName("alerts-popup").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("alerts-popup").item(0).setTextContent(value+"");
}
}
public boolean isShowAlertsPopup()
public boolean isShowAlertsPopup()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "alerts-popup", getDefaultIsShowAlertsPopup(), false, true, document, configFile);
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "alerts-popup", getDefaultIsShowAlertsPopup(), false, true, document, configFile);
}
}
public boolean getDefaultIsShowAlertsPopup()
public boolean getDefaultIsShowAlertsPopup()
{
{
return true;
return true;
}
}
public void setSoundOnActionClickedStatus(boolean value)
public void setSoundOnActionClickedStatus(boolean value)
{
{
getSoundOnActionClickedElement().getElementsByTagName("status").item(0).setTextContent(value+"");
getSoundOnActionClickedElement().getElementsByTagName("status").item(0).setTextContent(value+"");
}
}
public boolean getSoundOnActionClickedStatus()
public boolean getSoundOnActionClickedStatus()
{
{
return XMLConfigHelper.getBooleanProperty(getSoundOnActionClickedElement(), "status", getDefaultSoundOnActionClickedStatus(), false, true, document, configFile);
return XMLConfigHelper.getBooleanProperty(getSoundOnActionClickedElement(), "status", getDefaultSoundOnActionClickedStatus(), false, true, document, configFile);
}
}
public boolean getDefaultSoundOnActionClickedStatus()
public boolean getDefaultSoundOnActionClickedStatus()
{
{
return false;
return false;
}
}
public void setSoundOnActionClickedFilePath(String value)
public void setSoundOnActionClickedFilePath(String value)
{
{
getSoundOnActionClickedElement().getElementsByTagName("file-path").item(0).setTextContent(value);
getSoundOnActionClickedElement().getElementsByTagName("file-path").item(0).setTextContent(value);
}
}
public String getSoundOnActionClickedFilePath()
public String getSoundOnActionClickedFilePath()
{
{
return XMLConfigHelper.getStringProperty(getSoundOnActionClickedElement(), "file-path", getDefaultSoundOnActionClickedFilePath(), false, true, document, configFile);
return XMLConfigHelper.getStringProperty(getSoundOnActionClickedElement(), "file-path", getDefaultSoundOnActionClickedFilePath(), false, true, document, configFile);
}
}
public String getDefaultSoundOnActionClickedFilePath()
public String getDefaultSoundOnActionClickedFilePath()
{
{
return null; //To be replaced with a real default beep sound later.
return null; //To be replaced with a real default beep sound later.
}
}
}
}
package com.stream_pi.server.window.dashboard;
package com.stream_pi.server.window.dashboard;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.util.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 javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
public class DonatePopupContent{
public class DonatePopupContent{
public DonatePopupContent(HostServices hostServices, ExceptionAndAlertHandler exceptionAndAlertHandler)
public DonatePopupContent(HostServices hostServices, ExceptionAndAlertHandler exceptionAndAlertHandler)
{
{
Label label = new Label("We are a very small team working very hard on this project for best user experience.\n\n" +
Label label = new Label("We are a very small team working very hard on this project for best user experience.\n\n" +
"Something like Stream-Pi takes time, effort and resources. But we will always keep this 100% opensource and free.\n\n" +
"Something like Stream-Pi takes time, effort and resources. But we will always keep this 100% opensource and free.\n\n" +
"If you find this project helpful, and would want to help us, please consider donating :)\n\n"+
"If you find this project helpful, and would want to help us, please consider donating :)\n\n"+
"If you are unable to do so even a small shout-out and share across social media would be very helpful.");
"If you are unable to do so even a small shout-out and share across social media would be very helpful.\n\n" +
"This is also the first and the last time this dialogue will be shown :D");
label.setWrapText(true);
label.setWrapText(true);
label.getStyleClass().add("donate_request_popup_label");
label.getStyleClass().add("donate_request_popup_label");
Hyperlink patreonLink = new Hyperlink("Our Patreon");
Hyperlink patreonLink = new Hyperlink("Our Patreon");
patreonLink.setOnAction(event ->{
patreonLink.setOnAction(event ->{
hostServices.showDocument("https://patreon.com/streampi");
hostServices.showDocument("https://patreon.com/streampi");
});
});
patreonLink.getStyleClass().add("donate_request_popup_patreon_link");
patreonLink.getStyleClass().add("donate_request_popup_patreon_link");
VBox pane = new VBox(label, patreonLink);
VBox pane = new VBox(label, patreonLink);
pane.setSpacing(5.0);
pane.setSpacing(5.0);
streamPiAlert = new StreamPiAlert("Hey!", StreamPiAlertType.INFORMATION, pane);
streamPiAlert = new StreamPiAlert("Hey!", StreamPiAlertType.INFORMATION, pane);
streamPiAlert.setOnClicked(new StreamPiAlertListener()
streamPiAlert.setOnClicked(new StreamPiAlertListener()
{
{
@Override
@Override
public void onClick(String buttonClicked)
public void onClick(String buttonClicked)
{
{
try
try
{
{
Config.getInstance().setAllowDonatePopup(false);
Config.getInstance().setAllowDonatePopup(false);
Config.getInstance().save();
Config.getInstance().save();
}
}
catch(SevereException e)
catch(SevereException e)
{
{
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
}
}
});
});
}
}
private StreamPiAlert streamPiAlert;
private StreamPiAlert streamPiAlert;
public void show()
public void show()
{
{
streamPiAlert.show();
streamPiAlert.show();
}
}
}
}
package com.stream_pi.server.window.dashboard.actiondetailpane;
package com.stream_pi.server.window.dashboard.actiondetailpane;
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.ControlType;
import com.stream_pi.action_api.actionproperty.property.ControlType;
import com.stream_pi.action_api.actionproperty.property.FileExtensionFilter;
import com.stream_pi.action_api.actionproperty.property.FileExtensionFilter;
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.action_api.externalplugin.ExternalPlugin;
import com.stream_pi.action_api.externalplugin.ExternalPlugin;
import com.stream_pi.action_api.otheractions.CombineAction;
import com.stream_pi.action_api.otheractions.CombineAction;
import com.stream_pi.action_api.otheractions.FolderAction;
import com.stream_pi.action_api.otheractions.FolderAction;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.client.ClientProfile;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnection;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.connection.ClientConnections;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionBox;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.controller.ActionDataFormats;
import com.stream_pi.server.controller.ActionDataFormats;
import com.stream_pi.server.window.dashboard.actiongridpane.ActionGridPaneListener;
import com.stream_pi.server.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.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBoxWithFileChooser;
import com.stream_pi.util.uihelper.HBoxInputBoxWithFileChooser;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.collections.FXCollections;
import javafx.collections.FXCollections;
import javafx.concurrent.Task;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.input.Dragboard;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import javafx.stage.Window;
import javafx.util.Callback;
import javafx.util.Callback;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import java.io.File;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class ActionDetailsPane extends VBox implements ActionDetailsPaneListener
public class ActionDetailsPane extends VBox implements ActionDetailsPaneListener
{
{
private ScrollPane scrollPane;
private ScrollPane scrollPane;
private VBox vbox;
private VBox vbox;
private VBox clientPropertiesVBox;
private VBox clientPropertiesVBox;
private Button saveButton;
private Button saveButton;
private Button deleteButton;
private Button deleteButton;
private Button openFolderButton;
private Button openFolderButton;
private Button resetToDefaultsButton;
private Button resetToDefaultsButton;
private HBox buttonBar;
private HBox buttonBar;
private VBox pluginExtraButtonBar;
private VBox pluginExtraButtonBar;
private Label actionHeadingLabel;
private Label actionHeadingLabel;
private Logger logger;
private Logger logger;
private Button returnButtonForCombineActionChild;
private Button returnButtonForCombineActionChild;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private HostServices hostServices;
private HostServices hostServices;
private ActionGridPaneListener actionGridPaneListener;
private ActionGridPaneListener actionGridPaneListener;
public ActionDetailsPane(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices,
public ActionDetailsPane(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices,
ActionGridPaneListener actionGridPaneListener)
ActionGridPaneListener actionGridPaneListener)
{
{
this.hostServices = hostServices;
this.hostServices = hostServices;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.actionGridPaneListener = actionGridPaneListener;
this.actionGridPaneListener = actionGridPaneListener;
logger = Logger.getLogger(ActionDetailsPane.class.getName());
logger = Logger.getLogger(ActionDetailsPane.class.getName());
setSpacing(10.0);
setSpacing(10.0);
clientPropertiesVBox = new VBox();
clientPropertiesVBox = new VBox();
clientPropertiesVBox.setSpacing(10.0);
clientPropertiesVBox.setSpacing(10.0);
vbox = new VBox();
vbox = new VBox();
vbox.setPadding(new Insets(0, 25, 0, 5));
vbox.setPadding(new Insets(0, 25, 0, 5));
vbox.getStyleClass().add("action_details_pane_vbox");
vbox.getStyleClass().add("action_details_pane_vbox");
vbox.setSpacing(10.0);
vbox.setSpacing(10.0);
pluginExtraButtonBar = new VBox();
pluginExtraButtonBar = new VBox();
pluginExtraButtonBar.setSpacing(10.0);
pluginExtraButtonBar.setSpacing(10.0);
getStyleClass().add("action_details_pane");
getStyleClass().add("action_details_pane");
scrollPane = new ScrollPane();
scrollPane = new ScrollPane();
VBox.setMargin(scrollPane, new Insets(0, 0, 0, 10));
VBox.setMargin(scrollPane, new Insets(0, 0, 0, 10));
scrollPane.getStyleClass().add("action_details_pane_scroll_pane");
scrollPane.getStyleClass().add("action_details_pane_scroll_pane");
setMinHeight(210);
setMinHeight(210);
scrollPane.setContent(vbox);
scrollPane.setContent(vbox);
vbox.prefWidthProperty().bind(scrollPane.widthProperty());
vbox.prefWidthProperty().bind(scrollPane.widthProperty());
scrollPane.prefWidthProperty().bind(widthProperty());
scrollPane.prefWidthProperty().bind(widthProperty());
VBox.setVgrow(scrollPane, Priority.ALWAYS);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
openFolderButton = new Button("Open Folder");
openFolderButton = new Button("Open Folder");
openFolderButton.managedProperty().bind(openFolderButton.visibleProperty());
openFolderButton.managedProperty().bind(openFolderButton.visibleProperty());
FontIcon folderOpenIcon = new FontIcon("far-folder-open");
FontIcon folderOpenIcon = new FontIcon("far-folder-open");
openFolderButton.setGraphic(folderOpenIcon);
openFolderButton.setGraphic(folderOpenIcon);
openFolderButton.setOnAction(event -> onOpenFolderButtonClicked());
openFolderButton.setOnAction(event -> onOpenFolderButtonClicked());
saveButton = new Button("Save");
saveButton = new Button("Save");
saveButton.getStyleClass().add("action_details_pane_save_button");
saveButton.getStyleClass().add("action_details_pane_save_button");
FontIcon syncIcon = new FontIcon("far-save");
FontIcon syncIcon = new FontIcon("far-save");
syncIcon.getStyleClass().add("action_details_save_delete_button_icon");
syncIcon.getStyleClass().add("action_details_save_delete_button_icon");
saveButton.setGraphic(syncIcon);
saveButton.setGraphic(syncIcon);
saveButton.setOnAction(event -> onSaveButtonClicked());
saveButton.setOnAction(event -> onSaveButtonClicked());
deleteButton = new Button();
deleteButton = new Button();
deleteButton.getStyleClass().add("action_details_pane_delete_button");
deleteButton.getStyleClass().add("action_details_pane_delete_button");
FontIcon deleteIcon = new FontIcon("fas-trash");
FontIcon deleteIcon = new FontIcon("fas-trash");
deleteIcon.getStyleClass().add("action_details_pane_delete_button_icon");
deleteIcon.getStyleClass().add("action_details_pane_delete_button_icon");
deleteButton.setGraphic(deleteIcon);
deleteButton.setGraphic(deleteIcon);
deleteButton.setOnAction(event -> onDeleteButtonClicked());
deleteButton.setOnAction(event -> onDeleteButtonClicked());
resetToDefaultsButton = new Button("Reset");
resetToDefaultsButton = new Button("Reset");
resetToDefaultsButton.managedProperty().bind(resetToDefaultsButton.visibleProperty());
resetToDefaultsButton.managedProperty().bind(resetToDefaultsButton.visibleProperty());
resetToDefaultsButton.getStyleClass().add("action_details_pane_reset_button");
resetToDefaultsButton.getStyleClass().add("action_details_pane_reset_button");
FontIcon resetToDefaultsIcon = new FontIcon("fas-sync-alt");
FontIcon resetToDefaultsIcon = new FontIcon("fas-sync-alt");
resetToDefaultsIcon.getStyleClass().add("action_details_pane_reset_button_icon");
resetToDefaultsIcon.getStyleClass().add("action_details_pane_reset_button_icon");
resetToDefaultsButton.setGraphic(resetToDefaultsIcon);
resetToDefaultsButton.setGraphic(resetToDefaultsIcon);
resetToDefaultsButton.setOnAction(event -> onResetToDefaultsButtonClicked());
resetToDefaultsButton.setOnAction(event -> onResetToDefaultsButtonClicked());
returnButtonForCombineActionChild = new Button("Return");
returnButtonForCombineActionChild = new Button("Return");
returnButtonForCombineActionChild.setGraphic(new FontIcon("fas-caret-left"));
returnButtonForCombineActionChild.setGraphic(new FontIcon("fas-caret-left"));
returnButtonForCombineActionChild.managedProperty().bind(returnButtonForCombineActionChild.visibleProperty());
returnButtonForCombineActionChild.managedProperty().bind(returnButtonForCombineActionChild.visibleProperty());
returnButtonForCombineActionChild.setOnAction(event -> {
returnButtonForCombineActionChild.setOnAction(event -> {
try
try
{
{
onActionClicked(getClientProfile().getActionByID(getAction().getParent()), getActionBox());
onActionClicked(getClientProfile().getActionByID(getAction().getParent()), getActionBox());
} catch (MinorException e)
} catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
});
});
buttonBar = new HBox(openFolderButton, resetToDefaultsButton, returnButtonForCombineActionChild, saveButton, deleteButton);
buttonBar = new HBox(openFolderButton, resetToDefaultsButton, returnButtonForCombineActionChild, saveButton, deleteButton);
buttonBar.getStyleClass().add("action_details_pane_button_bar");
buttonBar.getStyleClass().add("action_details_pane_button_bar");
buttonBar.setPadding(new Insets(10, 10, 10, 0));
buttonBar.setPadding(new Insets(10, 10, 10, 0));
buttonBar.setAlignment(Pos.CENTER_RIGHT);
buttonBar.setAlignment(Pos.CENTER_RIGHT);
buttonBar.setVisible(false);
buttonBar.setVisible(false);
buttonBar.setSpacing(10.0);
buttonBar.setSpacing(10.0);
actionHeadingLabel = new Label();
actionHeadingLabel = new Label();
actionHeadingLabel.getStyleClass().add("action_details_pane_heading_label");
actionHeadingLabel.getStyleClass().add("action_details_pane_heading_label");
HBox headingHBox = new HBox(actionHeadingLabel);
HBox headingHBox = new HBox(actionHeadingLabel);
headingHBox.getStyleClass().add("action_details_pane_heading_box");
headingHBox.getStyleClass().add("action_details_pane_heading_box");
headingHBox.setPadding(new Insets(5, 10, 0, 10));
headingHBox.setPadding(new Insets(5, 10, 0, 10));
getChildren().addAll(headingHBox, scrollPane, buttonBar);
getChildren().addAll(headingHBox, scrollPane, buttonBar);
displayTextAlignmentComboBox = new ComboBox<>(FXCollections.observableArrayList(DisplayTextAlignment.TOP,
displayTextAlignmentComboBox = new ComboBox<>(FXCollections.observableArrayList(DisplayTextAlignment.TOP,
DisplayTextAlignment.CENTER, DisplayTextAlignment.BOTTOM));
DisplayTextAlignment.CENTER, DisplayTextAlignment.BOTTOM));
displayTextAlignmentComboBox.managedProperty().bind(displayTextAlignmentComboBox.visibleProperty());
displayTextAlignmentComboBox.managedProperty().bind(displayTextAlignmentComboBox.visibleProperty());
Callback<ListView<DisplayTextAlignment>, ListCell<DisplayTextAlignment>> displayTextAlignmentComboBoxFactory = new Callback<>() {
Callback<ListView<DisplayTextAlignment>, ListCell<DisplayTextAlignment>> displayTextAlignmentComboBoxFactory = new Callback<>() {
@Override
@Override
public ListCell<DisplayTextAlignment> call(ListView<DisplayTextAlignment> displayTextAlignment) {
public ListCell<DisplayTextAlignment> call(ListView<DisplayTextAlignment> displayTextAlignment) {
return new ListCell<>() {
return new ListCell<>() {
@Override
@Override
protected void updateItem(DisplayTextAlignment displayTextAlignment, boolean b) {
protected void updateItem(DisplayTextAlignment displayTextAlignment, boolean b) {
super.updateItem(displayTextAlignment, b);
super.updateItem(displayTextAlignment, b);
if (displayTextAlignment != null) {
if (displayTextAlignment != null) {
setText(displayTextAlignment.getUIName());
setText(displayTextAlignment.getUIName());
}
}
}
}
};
};
}
}
};
};
displayTextAlignmentComboBox.setCellFactory(displayTextAlignmentComboBoxFactory);
displayTextAlignmentComboBox.setCellFactory(displayTextAlignmentComboBoxFactory);
displayTextAlignmentComboBox.setButtonCell(displayTextAlignmentComboBoxFactory.call(null));
displayTextAlignmentComboBox.setButtonCell(displayTextAlignmentComboBoxFactory.call(null));
actionClientProperties = new ArrayList<>();
actionClientProperties = new ArrayList<>();
displayNameTextField = new TextField();
displayNameTextField = new TextField();
displayNameTextField.managedProperty().bind(displayNameTextField.visibleProperty());
displayNameTextField.managedProperty().bind(displayNameTextField.visibleProperty());
defaultIconFileTextField = new TextField();
defaultIconFileTextField = new TextField();
defaultIconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
defaultIconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
try {
try {
if (!s.equals(t1) && t1.length() > 0) {
if (!s.equals(t1) && t1.length() > 0) {
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
hideDefaultIconCheckBox.setDisable(false);
hideDefaultIconCheckBox.setDisable(false);
hideDefaultIconCheckBox.setSelected(false);
hideDefaultIconCheckBox.setSelected(false);
clearIconButton.setDisable(false);
clearIconButton.setDisable(false);
getAction().addIcon("default", iconFileByteArray);
getAction().addIcon("default", iconFileByteArray);
getAction().setCurrentIconState("default");
getAction().setCurrentIconState("default");
setSendIcon(true);
setSendIcon(true);
}
}
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
});
});
toggleOffIconFileTextField = new TextField();
toggleOffIconFileTextField = new TextField();
toggleOffIconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
toggleOffIconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
try {
try {
if (!s.equals(t1) && t1.length() > 0) {
if (!s.equals(t1) && t1.length() > 0) {
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
hideToggleOffIconCheckBox.setDisable(false);
hideToggleOffIconCheckBox.setDisable(false);
hideToggleOffIconCheckBox.setSelected(false);
hideToggleOffIconCheckBox.setSelected(false);
clearIconButton.setDisable(false);
clearIconButton.setDisable(false);
getAction().addIcon("toggle_off", iconFileByteArray);
getAction().addIcon("toggle_off", iconFileByteArray);
setSendIcon(true);
setSendIcon(true);
}
}
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
});
});
toggleOnIconFileTextField = new TextField();
toggleOnIconFileTextField = new TextField();
toggleOnIconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
toggleOnIconFileTextField.textProperty().addListener((observableValue, s, t1) -> {
try {
try {
if (!s.equals(t1) && t1.length() > 0) {
if (!s.equals(t1) && t1.length() > 0) {
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
byte[] iconFileByteArray = Files.readAllBytes(new File(t1).toPath());
hideToggleOnIconCheckBox.setDisable(false);
hideToggleOnIconCheckBox.setDisable(false);
hideToggleOnIconCheckBox.setSelected(false);
hideToggleOnIconCheckBox.setSelected(false);
clearIconButton.setDisable(false);
clearIconButton.setDisable(false);
getAction().addIcon("toggle_on", iconFileByteArray);
getAction().addIcon("toggle_on", iconFileByteArray);
setSendIcon(true);
setSendIcon(true);
}
}
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
exceptionAndAlertHandler.handleMinorException(new MinorException(e.getMessage()));
}
}
});
});
clearIconButton = new Button("Clear Icon");
clearIconButton = new Button("Clear Icon");
clearIconButton.managedProperty().bind(clearIconButton.visibleProperty());
clearIconButton.managedProperty().bind(clearIconButton.visibleProperty());
clearIconButton.setOnAction(event ->
clearIconButton.setOnAction(event ->
{
{
hideDefaultIconCheckBox.setDisable(true);
hideDefaultIconCheckBox.setDisable(true);
hideDefaultIconCheckBox.setSelected(false);
hideDefaultIconCheckBox.setSelected(false);
hideToggleOffIconCheckBox.setDisable(true);
hideToggleOffIconCheckBox.setDisable(true);
hideToggleOffIconCheckBox.setSelected(false);
hideToggleOffIconCheckBox.setSelected(false);
hideToggleOnIconCheckBox.setDisable(true);
hideToggleOnIconCheckBox.setDisable(true);
hideToggleOnIconCheckBox.setSelected(false);
hideToggleOnIconCheckBox.setSelected(false);
clearIconButton.setDisable(true);
clearIconButton.setDisable(true);
setSendIcon(false);
setSendIcon(false);
defaultIconFileTextField.clear();
defaultIconFileTextField.clear();
toggleOffIconFileTextField.clear();
toggleOffIconFileTextField.clear();
toggleOnIconFileTextField.clear();
toggleOnIconFileTextField.clear();
});
});
hideDisplayTextCheckBox = new CheckBox("Hide");
hideDisplayTextCheckBox = new CheckBox("Hide");
hideDisplayTextCheckBox.managedProperty().bind(hideDisplayTextCheckBox.visibleProperty());
hideDisplayTextCheckBox.managedProperty().bind(hideDisplayTextCheckBox.visibleProperty());
hideDefaultIconCheckBox = new CheckBox("Hide");
hideDefaultIconCheckBox = new CheckBox("Hide");
hideToggleOnIconCheckBox = new CheckBox("Hide");
hideToggleOnIconCheckBox = new CheckBox("Hide");
hideToggleOffIconCheckBox = new CheckBox("Hide");
hideToggleOffIconCheckBox = new CheckBox("Hide");
actionBackgroundColourPicker = new ColorPicker();
actionBackgroundColourPicker = new ColorPicker();
actionBackgroundColourPicker.managedProperty().bind(actionBackgroundColourPicker.visibleProperty());
actionBackgroundColourPicker.managedProperty().bind(actionBackgroundColourPicker.visibleProperty());
displayTextColourPicker = new ColorPicker();
displayTextColourPicker = new ColorPicker();
displayTextColourPicker.managedProperty().bind(displayTextColourPicker.visibleProperty());
displayTextColourPicker.managedProperty().bind(displayTextColourPicker.visibleProperty());
actionBackgroundColourTransparentCheckBox = new CheckBox("Default");
actionBackgroundColourTransparentCheckBox = new CheckBox("Default");
actionBackgroundColourPicker.disableProperty()
actionBackgroundColourPicker.disableProperty()
.bind(actionBackgroundColourTransparentCheckBox.selectedProperty());
.bind(actionBackgroundColourTransparentCheckBox.selectedProperty());
HBox.setMargin(actionBackgroundColourTransparentCheckBox, new Insets(0, 0, 0, 10));
HBox.setMargin(actionBackgroundColourTransparentCheckBox, new Insets(0, 0, 0, 10));
displayTextColourDefaultCheckBox = new CheckBox("Default");
displayTextColourDefaultCheckBox = new CheckBox("Default");
displayTextColourPicker.disableProperty()
displayTextColourPicker.disableProperty()
.bind(displayTextColourDefaultCheckBox.selectedProperty());
.bind(displayTextColourDefaultCheckBox.selectedProperty());
HBox.setMargin(displayTextColourDefaultCheckBox, new Insets(0, 0, 0, 10));
HBox.setMargin(displayTextColourDefaultCheckBox, new Insets(0, 0, 0, 10));
HBox displayTextColourHBox = new HBox(new Label("Display Text Colour"), SpaceFiller.horizontal(), displayTextColourPicker,
HBox displayTextColourHBox = new HBox(new Label("Display Text Colour"), SpaceFiller.horizontal(), displayTextColourPicker,
displayTextColourDefaultCheckBox);
displayTextColourDefaultCheckBox);
displayTextColourHBox.setAlignment(Pos.CENTER);
displayTextColourHBox.setAlignment(Pos.CENTER);
displayTextColourHBox.setSpacing(5.0);
displayTextColourHBox.setSpacing(5.0);
HBox bgColourHBox = new HBox(new Label("Background Colour"), SpaceFiller.horizontal(), actionBackgroundColourPicker,
HBox bgColourHBox = new HBox(new Label("Background Colour"), SpaceFiller.horizontal(), actionBackgroundColourPicker,
actionBackgroundColourTransparentCheckBox);
actionBackgroundColourTransparentCheckBox);
bgColourHBox.setAlignment(Pos.CENTER);
bgColourHBox.setAlignment(Pos.CENTER);
bgColourHBox.setSpacing(5.0);
bgColourHBox.setSpacing(5.0);
HBox clearIconHBox = new HBox(clearIconButton);
HBox clearIconHBox = new HBox(clearIconButton);
clearIconHBox.setAlignment(Pos.CENTER_RIGHT);
clearIconHBox.setAlignment(Pos.CENTER_RIGHT);
displayTextFieldHBox = new HBoxInputBox("Display Name", displayNameTextField, hideDisplayTextCheckBox);
HBox.setMargin(hideDisplayTextCheckBox, new Insets(0, 0, 0, 45));
displayTextFieldHBox = new HBox(new HBoxInputBox("Display Name", displayNameTextField), hideDisplayTextCheckBox);
HBox alignmentHBox = new HBox(new Label("Alignment"), SpaceFiller.horizontal(),
HBox alignmentHBox = new HBox(new Label("Alignment"), SpaceFiller.horizontal(),
displayTextAlignmentComboBox);
displayTextAlignmentComboBox);
normalToggleActionCommonPropsVBox = new VBox(
normalToggleActionCommonPropsVBox = new VBox(
displayTextColourHBox,
displayTextColourHBox,
alignmentHBox,
alignmentHBox,
bgColourHBox
bgColourHBox
);
);
normalToggleActionCommonPropsVBox.managedProperty().bind(normalToggleActionCommonPropsVBox.visibleProperty());
normalToggleActionCommonPropsVBox.managedProperty().bind(normalToggleActionCommonPropsVBox.visibleProperty());
normalToggleActionCommonPropsVBox.setSpacing(10.0);
normalToggleActionCommonPropsVBox.setSpacing(10.0);
FileChooser.ExtensionFilter iconExtensions = new FileChooser.ExtensionFilter("Images", "*.jpeg", "*.jpg", "*.png", "*.gif");
FileChooser.ExtensionFilter iconExtensions = new FileChooser.ExtensionFilter("Images", "*.jpeg", "*.jpg", "*.png", "*.gif");
normalActionsPropsVBox = new VBox(
normalActionsPropsVBox = new VBox(
new HBoxInputBoxWithFileChooser("Icon", defaultIconFileTextField, hideDefaultIconCheckBox,
new HBoxInputBoxWithFileChooser("Icon", defaultIconFileTextField, hideDefaultIconCheckBox,
iconExtensions)
iconExtensions)
);
);
normalActionsPropsVBox.managedProperty().bind(normalActionsPropsVBox.visibleProperty());
normalActionsPropsVBox.managedProperty().bind(normalActionsPropsVBox.visibleProperty());
normalActionsPropsVBox.setSpacing(10.0);
normalActionsPropsVBox.setSpacing(10.0);
toggleActionsPropsVBox = new VBox(
toggleActionsPropsVBox = new VBox(
new HBoxInputBoxWithFileChooser("Toggle Off Icon", toggleOffIconFileTextField, hideToggleOffIconCheckBox,
new HBoxInputBoxWithFileChooser("Toggle Off Icon", toggleOffIconFileTextField, hideToggleOffIconCheckBox,
iconExtensions),
iconExtensions),
new HBoxInputBoxWithFileChooser("Toggle On Icon", toggleOnIconFileTextField, hideToggleOnIconCheckBox,
new HBoxInputBoxWithFileChooser("Toggle On Icon", toggleOnIconFileTextField, hideToggleOnIconCheckBox,
iconExtensions)
iconExtensions)
);
);
toggleActionsPropsVBox.managedProperty().bind(toggleActionsPropsVBox.visibleProperty());
toggleActionsPropsVBox.managedProperty().bind(toggleActionsPropsVBox.visibleProperty());
toggleActionsPropsVBox.setSpacing(10.0);
toggleActionsPropsVBox.setSpacing(10.0);
vbox.getChildren().addAll(displayTextFieldHBox,normalToggleActionCommonPropsVBox,
vbox.getChildren().addAll(displayTextFieldHBox,normalToggleActionCommonPropsVBox,
normalActionsPropsVBox, toggleActionsPropsVBox,
normalActionsPropsVBox, toggleActionsPropsVBox,
clearIconHBox, clientPropertiesVBox,
clearIconHBox, clientPropertiesVBox,
pluginExtraButtonBar);
pluginExtraButtonBar);
vbox.setVisible(false);
vbox.setVisible(false);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
setOnDragOver(dragEvent -> {
setOnDragOver(dragEvent -> {
if (dragEvent.getDragboard().hasContent(ActionDataFormats.ACTION_TYPE) && action != null) {
if (dragEvent.getDragboard().hasContent(ActionDataFormats.ACTION_TYPE) && action != null) {
if (getAction().getActionType() == ActionType.COMBINE) {
if (getAction().getActionType() == ActionType.COMBINE) {
dragEvent.acceptTransferModes(TransferMode.ANY);
dragEvent.acceptTransferModes(TransferMode.ANY);
dragEvent.consume();
dragEvent.consume();
}
}
}
}
});
});
setOnDragDropped(dragEvent -> {
setOnDragDropped(dragEvent -> {
try {
try {
Dragboard db = dragEvent.getDragboard();
Dragboard db = dragEvent.getDragboard();
ActionType actionType = (ActionType) db.getContent(ActionDataFormats.ACTION_TYPE);
ActionType actionType = (ActionType) db.getContent(ActionDataFormats.ACTION_TYPE);
if(actionType == ActionType.NORMAL || actionType == ActionType.TOGGLE)
if(actionType == ActionType.NORMAL || actionType == ActionType.TOGGLE)
{
{
ExternalPlugin newAction = actionGridPaneListener.createNewActionFromExternalPlugin(
ExternalPlugin newAction = actionGridPaneListener.createNewActionFromExternalPlugin(
(String) db.getContent(ActionDataFormats.MODULE_NAME)
(String) db.getContent(ActionDataFormats.MODULE_NAME)
);
);
boolean isNew = (boolean) db.getContent(ActionDataFormats.IS_NEW);
boolean isNew = (boolean) db.getContent(ActionDataFormats.IS_NEW);
if(isNew)
if(isNew)
{
{
newAction.setDisplayText("Untitled Action");
newAction.setDisplayText("Untitled Action");
newAction.setShowDisplayText(true);
newAction.setShowDisplayText(true);
newAction.setDisplayTextAlignment(DisplayTextAlignment.CENTER);
newAction.setDisplayTextAlignment(DisplayTextAlignment.CENTER);
if(actionType == ActionType.TOGGLE)
if(actionType == ActionType.TOGGLE)
newAction.setCurrentIconState("false__false");
newAction.setCurrentIconState("false__false");
}
}
else
else
{
{
newAction.setClientProperties((ClientProperties) db.getContent(ActionDataFormats.CLIENT_PROPERTIES));
newAction.setClientProperties((ClientProperties) db.getContent(ActionDataFormats.CLIENT_PROPERTIES));
newAction.setIcons((HashMap<String, byte[]>) db.getContent(ActionDataFormats.ICONS));
newAction.setIcons((HashMap<String, byte[]>) db.getContent(ActionDataFormats.ICONS));
newAction.setCurrentIconState((String) db.getContent(ActionDataFormats.CURRENT_ICON_STATE));
newAction.setCurrentIconState((String) db.getContent(ActionDataFormats.CURRENT_ICON_STATE));
newAction.setBgColourHex((String) db.getContent(ActionDataFormats.BACKGROUND_COLOUR));
newAction.setBgColourHex((String) db.getContent(ActionDataFormats.BACKGROUND_COLOUR));
newAction.setDisplayTextFontColourHex((String) db.getContent(ActionDataFormats.DISPLAY_TEXT_FONT_COLOUR));
newAction.setDisplayTextFontColourHex((String) db.getContent(ActionDataFormats.DISPLAY_TEXT_FONT_COLOUR));
newAction.setDisplayText((String) db.getContent(ActionDataFormats.DISPLAY_TEXT));
newAction.setDisplayText((String) db.getContent(ActionDataFormats.DISPLAY_TEXT));
newAction.setDisplayTextAlignment((DisplayTextAlignment) db.getContent(ActionDataFormats.DISPLAY_TEXT_ALIGNMENT));
newAction.setDisplayTextAlignment((DisplayTextAlignment) db.getContent(ActionDataFormats.DISPLAY_TEXT_ALIGNMENT));
newAction.setShowDisplayText((boolean) db.getContent(ActionDataFormats.DISPLAY_TEXT_SHOW));
newAction.setShowDisplayText((boolean) db.getContent(ActionDataFormats.DISPLAY_TEXT_SHOW));
}
}
newAction.setLocation(new Location(-1, -1));
newAction.setLocation(new Location(-1, -1));
newAction.setParent(getAction().getID());
newAction.setParent(getAction().getID());
newAction.setProfileID(actionGridPaneListener.getCurrentProfile().getID());
newAction.setProfileID(actionGridPaneListener.getCurrentProfile().getID());
newAction.setSocketAddressForClient(actionGridPaneListener.getClientConnection().getRemoteSocketAddress());
newAction.setSocketAddressForClient(actionGridPaneListener.getClientConnection().getRemoteSocketAddress());
try
try
{
{
newAction.onActionCreate();
newAction.onActionCreate();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.setTitle("Error");
e.setTitle("Error");
e.setShortMessage("onCreate() failed for "+getAction().getModuleName()+"\n\n"+e.getShortMessage());
e.setShortMessage("onCreate() failed for "+getAction().getModuleName()+"\n\n"+e.getShortMessage());
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
combineActionPropertiesPane.getCombineAction().addChild(newAction.getID());
combineActionPropertiesPane.getCombineAction().addChild(newAction.getID());
addActionToCurrentClientProfile(newAction);
addActionToCurrentClientProfile(newAction);
ClientConnection connection = ClientConnections.getInstance()
ClientConnection connection = ClientConnections.getInstance()
.getClientConnectionBySocketAddress(getClient().getRemoteSocketAddress());
.getClientConnectionBySocketAddress(getClient().getRemoteSocketAddress());
connection.saveActionDetails(getClientProfile().getID(), newAction);
connection.saveActionDetails(getClientProfile().getID(), newAction);
combineActionPropertiesPane.renderProps();
combineActionPropertiesPane.renderProps();
saveAction(true, false);
saveAction(true, false);
}
}
} catch (MinorException e) {
} catch (MinorException e) {
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
e.printStackTrace();
e.printStackTrace();
} catch (SevereException e) {
} catch (SevereException e) {
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
e.printStackTrace();
e.printStackTrace();
} catch (CloneNotSupportedException e) {
} catch (CloneNotSupportedException e) {
e.printStackTrace();
e.printStackTrace();
} catch (Exception e)
} catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
});
});
}
}
private void onResetToDefaultsButtonClicked()
private void onResetToDefaultsButtonClicked()
{
{
StreamPiAlert streamPiAlert = new StreamPiAlert(
StreamPiAlert streamPiAlert = new StreamPiAlert(
"Warning",
"Warning",
"Are you sure you want to reset the action?",
"Are you sure you want to reset the action?",
StreamPiAlertType.WARNING
StreamPiAlertType.WARNING
);
);
String optionYes = "Yes";
String optionYes = "Yes";
String optionNo = "No";
String optionNo = "No";
streamPiAlert.setButtons(optionYes, optionNo);
streamPiAlert.setButtons(optionYes, optionNo);
streamPiAlert.setOnClicked(new StreamPiAlertListener() {
streamPiAlert.setOnClicked(new StreamPiAlertListener() {
@Override
@Override
public void onClick(String s) {
public void onClick(String s) {
if(s.equals(optionYes))
if(s.equals(optionYes))
{
{
getAction().getClientProperties().resetToDefaults();
getAction().getClientProperties().resetToDefaults();
try
try
{
{
onActionClicked(getAction(), getActionBox());
onActionClicked(getAction(), getActionBox());
saveAction(true, true);
saveAction(true, true);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
}
}
});
});
streamPiAlert.show();
streamPiAlert.show();
}
}
private VBox normalActionsPropsVBox;
private VBox normalActionsPropsVBox;
private VBox normalToggleActionCommonPropsVBox;
private VBox normalToggleActionCommonPropsVBox;
private VBox toggleActionsPropsVBox;
private VBox toggleActionsPropsVBox;
private HBox displayTextFieldHBox;
private HBox displayTextFieldHBox;
private ClientConnection clientConnection;
private ClientConnection clientConnection;
private ClientProfile clientProfile;
private ClientProfile clientProfile;
public void setClientConnection(ClientConnection clientConnection) {
public void setClientConnection(ClientConnection clientConnection) {
this.clientConnection = clientConnection;
this.clientConnection = clientConnection;
}
}
public ClientConnection getClientConnection() {
public ClientConnection getClientConnection() {
return clientConnection;
return clientConnection;
}
}
public Client getClient()
public Client getClient()
{
{
return getClientConnection().getClient();
return getClientConnection().getClient();
}
}
public void setClientProfile(ClientProfile clientProfile) {
public void setClientProfile(ClientProfile clientProfile) {
this.clientProfile = clientProfile;
this.clientProfile = clientProfile;
}
}
public ClientProfile getClientProfile() {
public ClientProfile getClientProfile() {
return clientProfile;
return clientProfile;
}
}
public void setActionHeadingLabelText(String text) {
public void setActionHeadingLabelText(String text) {
actionHeadingLabel.setText(text);
actionHeadingLabel.setText(text);
}
}
private Action action;
private Action action;
public synchronized Action getAction() {
public synchronized Action getAction() {
return action;
return action;
}
}
private ActionBox actionBox;
private ActionBox actionBox;
public ActionBox getActionBox() {
public ActionBox getActionBox() {
return actionBox;
return actionBox;
}
}
@Override
@Override
public void onActionClicked(Action action, ActionBox actionBox) throws MinorException
public void onActionClicked(Action action, ActionBox actionBox) throws MinorException
{
{
clear();
clear();
setAction(action);
setAction(action);
this.actionBox = actionBox;
this.actionBox = actionBox;
actionBox.setSelected(true);
actionBox.setSelected(true);
renderActionProperties();
renderActionProperties();
}
}
public void refresh()
public void refresh()
{
{
clear(false);
clear(false);
try
try
{
{
renderActionProperties();
renderActionProperties();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
private TextField displayNameTextField;
private TextField displayNameTextField;
private CheckBox hideDisplayTextCheckBox;
private CheckBox hideDisplayTextCheckBox;
private CheckBox hideDefaultIconCheckBox;
private CheckBox hideDefaultIconCheckBox;
private TextField defaultIconFileTextField;
private TextField defaultIconFileTextField;
private CheckBox hideToggleOnIconCheckBox;
private CheckBox hideToggleOnIconCheckBox;
private TextField toggleOnIconFileTextField;
private TextField toggleOnIconFileTextField;
private CheckBox hideToggleOffIconCheckBox;
private CheckBox hideToggleOffIconCheckBox;
private TextField toggleOffIconFileTextField;
private TextField toggleOffIconFileTextField;
private Button clearIconButton;
private Button clearIconButton;
private ColorPicker actionBackgroundColourPicker;
private ColorPicker actionBackgroundColourPicker;
private ColorPicker displayTextColourPicker;
private ColorPicker displayTextColourPicker;
private CheckBox actionBackgroundColourTransparentCheckBox;
private CheckBox actionBackgroundColourTransparentCheckBox;
private CheckBox displayTextColourDefaultCheckBox;
private CheckBox displayTextColourDefaultCheckBox;
private ComboBox<DisplayTextAlignment> displayTextAlignmentComboBox;
private ComboBox<DisplayTextAlignment> displayTextAlignmentComboBox;
public void clear(boolean actionNull)
public void clear(boolean actionNull)
{
{
sendIcon = false;
sendIcon = false;
actionClientProperties.clear();
actionClientProperties.clear();
displayNameTextField.clear();
displayNameTextField.clear();
defaultIconFileTextField.clear();
defaultIconFileTextField.clear();
toggleOffIconFileTextField.clear();
toggleOffIconFileTextField.clear();
toggleOnIconFileTextField.clear();
toggleOnIconFileTextField.clear();
clientPropertiesVBox.getChildren().clear();
clientPropertiesVBox.getChildren().clear();
pluginExtraButtonBar.getChildren().clear();
pluginExtraButtonBar.getChildren().clear();
vbox.setVisible(false);
vbox.setVisible(false);
normalActionsPropsVBox.setVisible(false);
normalActionsPropsVBox.setVisible(false);
toggleActionsPropsVBox.setVisible(false);
toggleActionsPropsVBox.setVisible(false);
saveButton.setVisible(false);
saveButton.setVisible(false);
openFolderButton.setVisible(false);
openFolderButton.setVisible(false);
resetToDefaultsButton.setVisible(false);
resetToDefaultsButton.setVisible(false);
returnButtonForCombineActionChild.setVisible(false);
returnButtonForCombineActionChild.setVisible(false);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
buttonBar.setVisible(false);
buttonBar.setVisible(false);
setActionHeadingLabelText("");
setActionHeadingLabelText("");
actionBackgroundColourPicker.setValue(Color.WHITE);
actionBackgroundColourPicker.setValue(Color.WHITE);
displayTextColourPicker.setValue(Color.WHITE);
displayTextColourPicker.setValue(Color.WHITE);
if(actionNull)
if(actionNull)
{
{
action = null;
action = null;
if(actionBox !=null)
if(actionBox !=null)
{
{
actionBox.setSelected(false);
actionBox.setSelected(false);
actionBox = null;
actionBox = null;
}
}
}
}
}
}
@Override
@Override
public void clear()
public void clear()
{
{
clear(true);
clear(true);
}
}
boolean isCombineChild = false;
boolean isCombineChild = false;
public boolean isCombineChild() {
public boolean isCombineChild() {
return isCombineChild;
return isCombineChild;
}
}
public void renderActionProperties() throws MinorException
public void renderActionProperties() throws MinorException
{
{
//Combine Child action
//Combine Child action
isCombineChild = getAction().getLocation().getCol() == -1;
isCombineChild = getAction().getLocation().getCol() == -1;
displayNameTextField.setText(getAction().getDisplayText());
displayNameTextField.setText(getAction().getDisplayText());
vbox.setVisible(true);
vbox.setVisible(true);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
buttonBar.setVisible(true);
buttonBar.setVisible(true);
displayTextAlignmentComboBox.getSelectionModel().select(getAction().getDisplayTextAlignment());
displayTextAlignmentComboBox.getSelectionModel().select(getAction().getDisplayTextAlignment());
if(!getAction().getBgColourHex().isEmpty())
if(!getAction().getBgColourHex().isEmpty())
actionBackgroundColourPicker.setValue(Color.valueOf(getAction().getBgColourHex()));
actionBackgroundColourPicker.setValue(Color.valueOf(getAction().getBgColourHex()));
else
else
actionBackgroundColourTransparentCheckBox.setSelected(true);
actionBackgroundColourTransparentCheckBox.setSelected(true);
if(!getAction().getDisplayTextFontColourHex().isEmpty())
if(!getAction().getDisplayTextFontColourHex().isEmpty())
displayTextColourPicker.setValue(Color.valueOf(getAction().getDisplayTextFontColourHex()));
displayTextColourPicker.setValue(Color.valueOf(getAction().getDisplayTextFontColourHex()));
else
else
displayTextColourDefaultCheckBox.setSelected(true);
displayTextColourDefaultCheckBox.setSelected(true);
hideDisplayTextCheckBox.setSelected(!getAction().isShowDisplayText());
hideDisplayTextCheckBox.setSelected(!getAction().isShowDisplayText());
if(getAction().isInvalid())
if(getAction().isInvalid())
{
{
setActionHeadingLabelText("Invalid action ("+getAction().getModuleName()+")");
setActionHeadingLabelText("Invalid action ("+getAction().getModuleName()+")");
return;
return;
}
}
saveButton.setVisible(!getAction().isInvalid());
saveButton.setVisible(!getAction().isInvalid());
if(isCombineChild)
if(isCombineChild)
{
{
setReturnButtonForCombineActionChildVisible(true);
setReturnButtonForCombineActionChildVisible(true);
normalActionsPropsVBox.setVisible(false);
normalActionsPropsVBox.setVisible(false);
normalToggleActionCommonPropsVBox.setVisible(false);
normalToggleActionCommonPropsVBox.setVisible(false);
hideDisplayTextCheckBox.setSelected(false);
hideDisplayTextCheckBox.setSelected(false);
hideDisplayTextCheckBox.setVisible(false);
hideDisplayTextCheckBox.setVisible(false);
}
}
else
else
{
{
normalToggleActionCommonPropsVBox.setVisible(true);
normalToggleActionCommonPropsVBox.setVisible(true);
if(getAction().getActionType() == ActionType.TOGGLE)
if(getAction().getActionType() == ActionType.TOGGLE)
{
{
normalActionsPropsVBox.setVisible(false);
normalActionsPropsVBox.setVisible(false);
toggleActionsPropsVBox.setVisible(true);
toggleActionsPropsVBox.setVisible(true);
boolean doesToggleOnExist = getAction().getIcons().containsKey("toggle_on");
boolean doesToggleOnExist = getAction().getIcons().containsKey("toggle_on");
boolean isToggleOnHidden = getAction().getCurrentIconState().contains("toggle_on");
boolean isToggleOnHidden = getAction().getCurrentIconState().contains("toggle_on");
if(!doesToggleOnExist)
if(!doesToggleOnExist)
isToggleOnHidden = false;
isToggleOnHidden = false;
hideToggleOnIconCheckBox.setDisable(!doesToggleOnExist);
hideToggleOnIconCheckBox.setDisable(!doesToggleOnExist);
hideToggleOnIconCheckBox.setSelected(isToggleOnHidden);
hideToggleOnIconCheckBox.setSelected(isToggleOnHidden);
boolean doesToggleOffExist = getAction().getIcons().containsKey("toggle_off");
boolean doesToggleOffExist = getAction().getIcons().containsKey("toggle_off");
boolean isToggleOffHidden = getAction().getCurrentIconState().contains("toggle_off");
boolean isToggleOffHidden = getAction().getCurrentIconState().contains("toggle_off");
if(!doesToggleOffExist)
if(!doesToggleOffExist)
isToggleOffHidden = false;
isToggleOffHidden = false;
hideToggleOffIconCheckBox.setDisable(!doesToggleOffExist);
hideToggleOffIconCheckBox.setDisable(!doesToggleOffExist);
hideToggleOffIconCheckBox.setSelected(isToggleOffHidden);
hideToggleOffIconCheckBox.setSelected(isToggleOffHidden);
}
}
else
else
{
{
normalActionsPropsVBox.setVisible(true);
normalActionsPropsVBox.setVisible(true);
toggleActionsPropsVBox.setVisible(false);
toggleActionsPropsVBox.setVisible(false);
boolean doesDefaultExist = getAction().getIcons().containsKey("default");
boolean doesDefaultExist = getAction().getIcons().containsKey("default");
boolean isDefaultHidden = !getAction().getCurrentIconState().equals("default");
boolean isDefaultHidden = !getAction().getCurrentIconState().equals("default");
if(!doesDefaultExist)
if(!doesDefaultExist)
isDefaultHidden = false;
isDefaultHidden = false;
hideDefaultIconCheckBox.setDisable(!doesDefaultExist);
hideDefaultIconCheckBox.setDisable(!doesDefaultExist);
hideDefaultIconCheckBox.setSelected(isDefaultHidden);
hideDefaultIconCheckBox.setSelected(isDefaultHidden);
}
}
setReturnButtonForCombineActionChildVisible(false);
setReturnButtonForCombineActionChildVisible(false);
hideDisplayTextCheckBox.setVisible(true);
hideDisplayTextCheckBox.setVisible(true);
setFolderButtonVisible(getAction().getActionType().equals(ActionType.FOLDER));
setFolderButtonVisible(getAction().getActionType().equals(ActionType.FOLDER));
setResetToDefaultsButtonVisible(!(getAction().getActionType().equals(ActionType.FOLDER) || getAction().getActionType().equals(ActionType.COMBINE)));
setResetToDefaultsButtonVisible(!(getAction().getActionType().equals(ActionType.FOLDER) || getAction().getActionType().equals(ActionType.COMBINE)));
clearIconButton.setDisable(!getAction().isHasIcon());
clearIconButton.setDisable(!getAction().isHasIcon());
}
}
if(getAction().getActionType() == ActionType.NORMAL || getAction().getActionType() == ActionType.TOGGLE)
if(getAction().getActionType() == ActionType.NORMAL || getAction().getActionType() == ActionType.TOGGLE)
{
{
setActionHeadingLabelText(getAction().getName());
setActionHeadingLabelText(getAction().getName());
}
}
else if(getAction().getActionType() == ActionType.COMBINE)
else if(getAction().getActionType() == ActionType.COMBINE)
{
{
setActionHeadingLabelText("Combine action");
setActionHeadingLabelText("Combine action");
}
}
else if(getAction().getActionType() == ActionType.FOLDER)
else if(getAction().getActionType() == ActionType.FOLDER)
{
{
setActionHeadingLabelText("Folder action");
setActionHeadingLabelText("Folder action");
}
}
if(getAction().getActionType() == ActionType.NORMAL || getAction().getActionType() == ActionType.TOGGLE)
if(getAction().getActionType() == ActionType.NORMAL || getAction().getActionType() == ActionType.TOGGLE)
{
{
renderClientProperties();
renderClientProperties();
renderPluginExtraButtonBar();
renderPluginExtraButtonBar();
}
}
else if(getAction().getActionType() == ActionType.COMBINE)
else if(getAction().getActionType() == ActionType.COMBINE)
renderCombineActionProperties();
renderCombineActionProperties();
}
}
private void renderPluginExtraButtonBar()
private void renderPluginExtraButtonBar()
{
{
ExternalPlugin externalPlugin = (ExternalPlugin) getAction();
ExternalPlugin externalPlugin = (ExternalPlugin) getAction();
externalPlugin.initClientActionSettingsButtonBar();
externalPlugin.initClientActionSettingsButtonBar();
if(externalPlugin.getClientActionSettingsButtonBar() != null)
if(externalPlugin.getClientActionSettingsButtonBar() != null)
{
{
HBox tba = new HBox(SpaceFiller.horizontal(), externalPlugin.getClientActionSettingsButtonBar());
HBox tba = new HBox(SpaceFiller.horizontal(), externalPlugin.getClientActionSettingsButtonBar());
pluginExtraButtonBar.getChildren().add(tba);
pluginExtraButtonBar.getChildren().add(tba);
}
}
}
}
private CombineActionPropertiesPane combineActionPropertiesPane;
private CombineActionPropertiesPane combineActionPropertiesPane;
public CombineActionPropertiesPane getCombineActionPropertiesPane() {
public CombineActionPropertiesPane getCombineActionPropertiesPane() {
return combineActionPropertiesPane;
return combineActionPropertiesPane;
}
}
public void setReturnButtonForCombineActionChildVisible(boolean visible)
public void setReturnButtonForCombineActionChildVisible(boolean visible)
{
{
returnButtonForCombineActionChild.setVisible(visible);
returnButtonForCombineActionChild.setVisible(visible);
}
}
public void renderCombineActionProperties()
public void renderCombineActionProperties()
{
{
try
try
{
{
combineActionPropertiesPane = new CombineActionPropertiesPane((CombineAction) getAction(),
combineActionPropertiesPane = new CombineActionPropertiesPane((CombineAction) getAction(),
getClientProfile(),
getClientProfile(),
this
this
);
);
clientPropertiesVBox.getChildren().add(combineActionPropertiesPane);
clientPropertiesVBox.getChildren().add(combineActionPropertiesPane);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
@Override
@Override
public synchronized void setAction(Action action) {
public synchronized void setAction(Action action) {
this.action = action;
this.action = action;
}
}
@Override
@Override
public void onOpenFolderButtonClicked()
public void onOpenFolderButtonClicked()
{
{
actionBox.getActionGridPaneListener().renderFolder((FolderAction) getAction());
actionBox.getActionGridPaneListener().renderFolder((FolderAction) getAction());
clear();
clear();
}
}
@Override
@Override
public Window getCurrentWindow() {
public Window getCurrentWindow() {
return getScene().getWindow();
return getScene().getWindow();
}
}
private ArrayList<UIPropertyBox> actionClientProperties;
private ArrayList<UIPropertyBox> actionClientProperties;
private TextField delayBeforeRunningTextField;
private TextField delayBeforeRunningTextField;
public void renderClientProperties() throws MinorException
public void renderClientProperties() throws MinorException
{
{
delayBeforeRunningTextField = new TextField();
delayBeforeRunningTextField = new TextField();
delayBeforeRunningTextField.setText(getAction().getDelayBeforeExecuting()+"");
delayBeforeRunningTextField.setText(getAction().getDelayBeforeExecuting()+"");
clientPropertiesVBox.getChildren().add(
clientPropertiesVBox.getChildren().add(
new HBoxInputBox("Delay before running (milli-seconds)", delayBeforeRunningTextField, 100)
new HBoxInputBox("Delay before running (milli-seconds)", delayBeforeRunningTextField, 100)
);
);
for(int i =0;i< getAction().getClientProperties().getSize(); i++)
for(int i =0;i< getAction().getClientProperties().getSize(); i++)
{
{
Property eachProperty = getAction().getClientProperties().get().get(i);
Property eachProperty = getAction().getClientProperties().get().get(i);
if(!eachProperty.isVisible())
if(!eachProperty.isVisible())
continue;
continue;
Label label = new Label(eachProperty.getDisplayName());
Label label = new Label(eachProperty.getDisplayName());
HBox hBox = new HBox(label);
HBox hBox = new HBox(label);
hBox.setSpacing(5.0);
hBox.setSpacing(5.0);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.setAlignment(Pos.CENTER_LEFT);
Node controlNode = null;
Node controlNode = null;
if(eachProperty.getHelpLink() != null)
if(eachProperty.getHelpLink() != null)
{
{
Button helpButton = new Button();
Button helpButton = new Button();
FontIcon questionIcon = new FontIcon("fas-question");
FontIcon questionIcon = new FontIcon("fas-question");
helpButton.setGraphic(questionIcon);
helpButton.setGraphic(questionIcon);
helpButton.setOnAction(event -> {
helpButton.setOnAction(event -> {
hostServices.showDocument(eachProperty.getHelpLink());
hostServices.showDocument(eachProperty.getHelpLink());
});
});
hBox.getChildren().add(helpButton);
hBox.getChildren().add(helpButton);
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
}
}
hBox.getChildren().add(SpaceFiller.horizontal());
hBox.getChildren().add(SpaceFiller.horizontal());
if(eachProperty.getControlType() == ControlType.COMBO_BOX)
if(eachProperty.getControlType() == ControlType.COMBO_BOX)
{
{
ComboBox<String> comboBox = new ComboBox<>();
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll(eachProperty.getListValue());
comboBox.getItems().addAll(eachProperty.getListValue());
comboBox.getSelectionModel().select(eachProperty.getSelectedIndex());
comboBox.getSelectionModel().select(eachProperty.getSelectedIndex());
controlNode = comboBox;
controlNode = comboBox;
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
}
}
else if(eachProperty.getControlType() == ControlType.FILE_PATH)
else if(eachProperty.getControlType() == ControlType.FILE_PATH)
{
{
TextField textField = new TextField(eachProperty.getRawValue());
TextField textField = new TextField(eachProperty.getRawValue());
FileExtensionFilter[] fileExtensionFilters = eachProperty.getExtensionFilters();
FileExtensionFilter[] fileExtensionFilters = eachProperty.getExtensionFilters();
FileChooser.ExtensionFilter[] extensionFilters = new FileChooser.ExtensionFilter[fileExtensionFilters.length];
FileChooser.ExtensionFilter[] extensionFilters = new FileChooser.ExtensionFilter[fileExtensionFilters.length];
for(int x = 0;x<fileExtensionFilters.length;x++)
for(int x = 0;x<fileExtensionFilters.length;x++)
{
{
extensionFilters[x] = new FileChooser.ExtensionFilter(
extensionFilters[x] = new FileChooser.ExtensionFilter(
fileExtensionFilters[x].getDescription(),
fileExtensionFilters[x].getDescription(),
fileExtensionFilters[x].getExtensions()
fileExtensionFilters[x].getExtensions()
);
);
}
}
hBox = new HBoxInputBoxWithFileChooser(eachProperty.getDisplayName(), textField, null,
hBox = new HBoxInputBoxWithFileChooser(eachProperty.getDisplayName(), textField, null,
extensionFilters);
extensionFilters);
controlNode = textField;
controlNode = textField;
}
}
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD)
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD)
{
{
controlNode= new TextField(eachProperty.getRawValue());
controlNode= new TextField(eachProperty.getRawValue());
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
}
}
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD_MASKED)
else if(eachProperty.getControlType() == ControlType.TEXT_FIELD_MASKED)
{
{
PasswordField textField = new PasswordField();
PasswordField textField = new PasswordField();
textField.setText(eachProperty.getRawValue());
textField.setText(eachProperty.getRawValue());
controlNode= textField;
controlNode= textField;
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
}
}
else if(eachProperty.getControlType() == ControlType.TOGGLE)
else if(eachProperty.getControlType() == ControlType.TOGGLE)
{
{
ToggleButton toggleButton = new ToggleButton();
ToggleButton toggleButton = new ToggleButton();
toggleButton.setSelected(eachProperty.getBoolValue());
toggleButton.setSelected(eachProperty.getBoolValue());
if(eachProperty.getBoolValue())
if(eachProperty.getBoolValue())
toggleButton.setText("ON");
toggleButton.setText("ON");
else
else
toggleButton.setText("OFF");
toggleButton.setText("OFF");
toggleButton.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
toggleButton.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
if(t1)
if(t1)
toggleButton.setText("ON");
toggleButton.setText("ON");
else
else
toggleButton.setText("OFF");
toggleButton.setText("OFF");
});
});
controlNode = toggleButton;
controlNode = toggleButton;
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
}
}
else if(eachProperty.getControlType() == ControlType.SLIDER_DOUBLE)
else if(eachProperty.getControlType() == ControlType.SLIDER_DOUBLE)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(eachProperty.getDoubleValue());
slider.setValue(eachProperty.getDoubleValue());
slider.setMax(eachProperty.getMaxDoubleValue());
slider.setMax(eachProperty.getMaxDoubleValue());
slider.setMin(eachProperty.getMinDoubleValue());
slider.setMin(eachProperty.getMinDoubleValue());
controlNode = slider;
controlNode = slider;
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
}
}
else if(eachProperty.getControlType() == ControlType.SLIDER_INTEGER)
else if(eachProperty.getControlType() == ControlType.SLIDER_INTEGER)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(eachProperty.getIntValue());
slider.setValue(eachProperty.getIntValue());
slider.setMax(eachProperty.getMaxIntValue());
slider.setMax(eachProperty.getMaxIntValue());
slider.setMin(eachProperty.getMinIntValue());
slider.setMin(eachProperty.getMinIntValue());
slider.setBlockIncrement(1.0);
slider.setBlockIncrement(1.0);
slider.setSnapToTicks(true);
slider.setSnapToTicks(true);
controlNode = slider;
controlNode = slider;
hBox.getChildren().add(controlNode);
hBox.getChildren().add(controlNode);
}
}
UIPropertyBox clientProperty = new UIPropertyBox(i, eachProperty.getDisplayName(), controlNode,
UIPropertyBox clientProperty = new UIPropertyBox(i, eachProperty.getDisplayName(), controlNode,
eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
actionClientProperties.add(clientProperty);
actionClientProperties.add(clientProperty);
clientPropertiesVBox.getChildren().add(hBox);
clientPropertiesVBox.getChildren().add(hBox);
}
}
}
}
public void onSaveButtonClicked()
public void onSaveButtonClicked()
{
{
try
try
{
{
validateForm();
validateForm();
saveAction(true, true);
saveAction(true, true);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
private boolean sendIcon = false;
private boolean sendIcon = false;
@Override
@Override
public void setSendIcon(boolean sendIcon)
public void setSendIcon(boolean sendIcon)
{
{
this.sendIcon = sendIcon;
this.sendIcon = sendIcon;
}
}
public void addActionToCurrentClientProfile(Action newAction) throws CloneNotSupportedException {
public void addActionToCurrentClientProfile(Action newAction) throws CloneNotSupportedException {
getClientProfile().addAction(newAction);
getClientProfile().addAction(newAction);
}
}
@Override
@Override
public synchronized void saveAction(Action action, boolean runAsync, boolean runOnActionSavedFromServer)
public synchronized void saveAction(Action action, boolean runAsync, boolean runOnActionSavedFromServer)
{
{
String delayBeforeRunning = "0";
String delayBeforeRunning = "0";
if(action.getActionType() != ActionType.FOLDER && action.getActionType() !=ActionType.COMBINE)
if(action.getActionType() != ActionType.FOLDER && action.getActionType() !=ActionType.COMBINE)
delayBeforeRunning =delayBeforeRunningTextField.getText();
delayBeforeRunning =delayBeforeRunningTextField.getText();
new OnSaveActionTask(
new OnSaveActionTask(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
getClient().getRemoteSocketAddress()
getClient().getRemoteSocketAddress()
),
),
action, delayBeforeRunning,
action, delayBeforeRunning,
displayNameTextField.getText(),
displayNameTextField.getText(),
isCombineChild(),
isCombineChild(),
!hideDisplayTextCheckBox.isSelected(),
!hideDisplayTextCheckBox.isSelected(),
displayTextColourDefaultCheckBox.isSelected(),
displayTextColourDefaultCheckBox.isSelected(),
"#" + displayTextColourPicker.getValue().toString().substring(2),
"#" + displayTextColourPicker.getValue().toString().substring(2),
clearIconButton.isDisable(),
clearIconButton.isDisable(),
hideDefaultIconCheckBox.isSelected(),
hideDefaultIconCheckBox.isSelected(),
hideToggleOffIconCheckBox.isSelected(),
hideToggleOffIconCheckBox.isSelected(),
hideToggleOnIconCheckBox.isSelected(),
hideToggleOnIconCheckBox.isSelected(),
displayTextAlignmentComboBox.getSelectionModel().getSelectedItem(),
displayTextAlignmentComboBox.getSelectionModel().getSelectedItem(),
actionBackgroundColourTransparentCheckBox.isSelected(),
actionBackgroundColourTransparentCheckBox.isSelected(),
"#" + actionBackgroundColourPicker.getValue().toString().substring(2),
"#" + actionBackgroundColourPicker.getValue().toString().substring(2),
getCombineActionPropertiesPane(),
getCombineActionPropertiesPane(),
clientProfile, sendIcon, actionBox, actionClientProperties, exceptionAndAlertHandler,
clientProfile, sendIcon, actionBox, actionClientProperties, exceptionAndAlertHandler,
saveButton, deleteButton, resetToDefaultsButton, runOnActionSavedFromServer, runAsync, this
saveButton, deleteButton, resetToDefaultsButton, runOnActionSavedFromServer, runAsync, this
);
);
}
}
@Override
@Override
public void saveAction(boolean runAsync, boolean runOnActionSavedFromServer)
public void saveAction(boolean runAsync, boolean runOnActionSavedFromServer)
{
{
saveAction(getAction(), runAsync, runOnActionSavedFromServer);
saveAction(getAction(), runAsync, runOnActionSavedFromServer);
}
}
public void setFolderButtonVisible(boolean visible)
public void setFolderButtonVisible(boolean visible)
{
{
openFolderButton.setVisible(visible);
openFolderButton.setVisible(visible);
}
}
public void setResetToDefaultsButtonVisible(boolean visible)
public void setResetToDefaultsButtonVisible(boolean visible)
{
{
resetToDefaultsButton.setVisible(visible);
resetToDefaultsButton.setVisible(visible);
}
}
public void validateForm() throws MinorException
public void validateForm() throws MinorException
{
{
String displayNameStr = displayNameTextField.getText();
String displayNameStr = displayNameTextField.getText();
StringBuilder finalErrors = new StringBuilder();
StringBuilder finalErrors = new StringBuilder();
if(displayNameStr.isBlank())
if(displayNameStr.isBlank())
{
{
finalErrors.append(" * Display Name cannot be blank\n");
finalErrors.append(" * Display Name cannot be blank\n");
}
}
if(!isCombineChild())
if(!isCombineChild())
{
{
if(getAction().getActionType() == ActionType.NORMAL)
if(getAction().getActionType() == ActionType.NORMAL)
{
{
if(getAction().isHasIcon())
if(getAction().isHasIcon())
{
{
if(hideDisplayTextCheckBox.isSelected() && hideDefaultIconCheckBox.isSelected())
if(hideDisplayTextCheckBox.isSelected() && hideDefaultIconCheckBox.isSelected())
{
{
finalErrors.append(" * Both Icon and display text check box cannot be hidden.\n");
finalErrors.append(" * Both Icon and display text check box cannot be hidden.\n");
}
}
}
}
else
else
{
{
if(hideDisplayTextCheckBox.isSelected())
if(hideDisplayTextCheckBox.isSelected())
finalErrors.append(" * Display Text cannot be hidden, since there is also no icon.\n");
finalErrors.append(" * Display Text cannot be hidden, since there is also no icon.\n");
}
}
}
}
}
}
if(getAction().getActionType() == ActionType.NORMAL)
if(getAction().getActionType() == ActionType.NORMAL)
{
{
try
try
{
{
int n = Integer.parseInt(delayBeforeRunningTextField.getText());
int n = Integer.parseInt(delayBeforeRunningTextField.getText());
if (n<0)
if (n<0)
{
{
finalErrors.append(" * Sleep should be greater than 0.\n");
finalErrors.append(" * Sleep should be greater than 0.\n");
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
finalErrors.append(" * Sleep should be a number.\n");
finalErrors.append(" * Sleep should be a number.\n");
}
}
}
}
for (UIPropertyBox clientProperty : actionClientProperties) {
for (UIPropertyBox clientProperty : actionClientProperties) {
Node controlNode = clientProperty.getControlNode();
Node controlNode = clientProperty.getControlNode();
if (clientProperty.getControlType() == ControlType.TEXT_FIELD ||
if (clientProperty.getControlType() == ControlType.TEXT_FIELD ||
clientProperty.getControlType() == ControlType.FILE_PATH)
clientProperty.getControlType() == ControlType.FILE_PATH)
{
{
String value = ((TextField) controlNode).getText();
String value = ((TextField) controlNode).getText();
if(clientProperty.getType() == Type.INTEGER)
if(clientProperty.getType() == Type.INTEGER)
{
{
try
try
{
{
Integer.parseInt(value);
Integer.parseInt(value);
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" must be integer.\n");
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" must be integer.\n");
}
}
}
}
else
else
{
{
if(value.isBlank() && !clientProperty.isCanBeBlank())
if(value.isBlank() && !clientProperty.isCanBeBlank())
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" cannot be blank.\n");
finalErrors.append(" -> ").append(clientProperty.getDisplayName()).append(" cannot be blank.\n");
}
}
}
}
}
}
if(!finalErrors.toString().isEmpty())
if(!finalErrors.toString().isEmpty())
{
{
throw new MinorException("You made mistakes",
throw new MinorException("You made mistakes",
finalErrors.toString());
finalErrors.toString());
}
}
}
}
@Override
@Override
public void onDeleteButtonClicked()
public void onDeleteButtonClicked()
{
{
StreamPiAlert streamPiAlert = new StreamPiAlert(
StreamPiAlert streamPiAlert = new StreamPiAlert(
"Warning",
"Warning",
"Are you sure you want to delete the action?",
"Are you sure you want to delete the action?",
StreamPiAlertType.WARNING
StreamPiAlertType.WARNING
);
);
String optionYes = "Yes";
String optionYes = "Yes";
String optionNo = "No";
String optionNo = "No";
streamPiAlert.setButtons(optionYes, optionNo);
streamPiAlert.setButtons(optionYes, optionNo);
ActionDetailsPane actionDetailsPane = this;
ActionDetailsPane actionDetailsPane = this;
streamPiAlert.setOnClicked(new StreamPiAlertListener() {
streamPiAlert.setOnClicked(new StreamPiAlertListener() {
@Override
@Override
public void onClick(String s) {
public void onClick(String s) {
if(s.equals(optionYes))
if(s.equals(optionYes))
{
{
new OnDeleteActionTask(
new OnDeleteActionTask(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
ClientConnections.getInstance().getClientConnectionBySocketAddress(
getClient().getRemoteSocketAddress()
getClient().getRemoteSocketAddress()
),
),
action,
action,
isCombineChild(),
isCombineChild(),
getCombineActionPropertiesPane(),
getCombineActionPropertiesPane(),
clientProfile, actionBox, actionDetailsPane, exceptionAndAlertHandler,
clientProfile, actionBox, actionDetailsPane, exceptionAndAlertHandler,
!isCombineChild
!isCombineChild
);
);
}
}
}
}
});
});
streamPiAlert.show();
streamPiAlert.show();
}
}
}
}
package com.stream_pi.server.window.settings;
package com.stream_pi.server.window.settings;
import com.stream_pi.action_api.actionproperty.property.FileExtensionFilter;
import com.stream_pi.server.controller.ServerListener;
import com.stream_pi.server.controller.ServerListener;
import com.stream_pi.server.info.StartupFlags;
import com.stream_pi.server.info.StartupFlags;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
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.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.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.platform.PlatformType;
import com.stream_pi.util.platform.PlatformType;
import com.stream_pi.util.startatboot.StartAtBoot;
import com.stream_pi.util.startatboot.StartAtBoot;
import com.stream_pi.util.uihelper.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBoxWithDirectoryChooser;
import com.stream_pi.util.uihelper.HBoxInputBoxWithFileChooser;
import com.stream_pi.util.uihelper.HBoxWithSpaceBetween;
import com.stream_pi.util.uihelper.HBoxWithSpaceBetween;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.application.Platform;
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.control.Button;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.scene.layout.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import org.controlsfx.control.ToggleSwitch;
import org.controlsfx.control.ToggleSwitch;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import org.w3c.dom.Text;
import java.awt.SystemTray;
import java.awt.SystemTray;
import java.io.File;
import java.io.File;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class GeneralSettings extends VBox {
public class GeneralSettings extends VBox {
private final TextField serverNameTextField;
private final TextField serverNameTextField;
private final TextField portTextField;
private final TextField portTextField;
private final TextField pluginsPathTextField;
private final TextField pluginsPathTextField;
private final TextField themesPathTextField;
private final TextField themesPathTextField;
private final TextField actionGridPaneActionBoxSize;
private final TextField actionGridPaneActionBoxSize;
private final TextField actionGridPaneActionBoxGap;
private final TextField actionGridPaneActionBoxGap;
private final ToggleSwitch startOnBootToggleSwitch;
private final ToggleSwitch startOnBootToggleSwitch;
private final HBoxWithSpaceBetween startOnBootHBox;
private final HBoxWithSpaceBetween startOnBootHBox;
private final TextField soundOnActionClickedFilePathTextField;
private final ToggleSwitch soundOnActionClickedToggleSwitch;
private final HBoxWithSpaceBetween soundOnActionClickedToggleSwitchHBox;
private final ToggleSwitch minimizeToSystemTrayOnCloseToggleSwitch;
private final ToggleSwitch minimizeToSystemTrayOnCloseToggleSwitch;
private final HBoxWithSpaceBetween minimizeToSystemTrayOnCloseHBox;
private final HBoxWithSpaceBetween minimizeToSystemTrayOnCloseHBox;
private final ToggleSwitch showAlertsPopupToggleSwitch;
private final ToggleSwitch showAlertsPopupToggleSwitch;
private final HBoxWithSpaceBetween showAlertsPopupHBox;
private final HBoxWithSpaceBetween showAlertsPopupHBox;
private final Button saveButton;
private final Button saveButton;
private final Button checkForUpdatesButton;
private final Button checkForUpdatesButton;
private final Button factoryResetButton;
private final Button factoryResetButton;
private Logger logger;
private Logger logger;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ServerListener serverListener;
private ServerListener serverListener;
private HostServices hostServices;
private HostServices hostServices;
public GeneralSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener, HostServices hostServices)
public GeneralSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, ServerListener serverListener, HostServices hostServices)
{
{
this.hostServices = hostServices;
this.hostServices = hostServices;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.serverListener = serverListener;
this.serverListener = serverListener;
logger = Logger.getLogger(GeneralSettings.class.getName());
logger = Logger.getLogger(GeneralSettings.class.getName());
serverNameTextField = new TextField();
serverNameTextField = new TextField();
portTextField = new TextField();
portTextField = new TextField();
pluginsPathTextField = new TextField();
pluginsPathTextField = new TextField();
themesPathTextField = new TextField();
themesPathTextField = new TextField();
actionGridPaneActionBoxSize = new TextField();
actionGridPaneActionBoxSize = new TextField();
actionGridPaneActionBoxGap = new TextField();
actionGridPaneActionBoxGap = new TextField();
startOnBootToggleSwitch = new ToggleSwitch();
startOnBootToggleSwitch = new ToggleSwitch();
startOnBootHBox = new HBoxWithSpaceBetween("Start on Boot", startOnBootToggleSwitch);
startOnBootHBox = new HBoxWithSpaceBetween("Start on Boot", startOnBootToggleSwitch);
startOnBootHBox.managedProperty().bind(startOnBootHBox.visibleProperty());
startOnBootHBox.managedProperty().bind(startOnBootHBox.visibleProperty());
soundOnActionClickedToggleSwitch = new ToggleSwitch();
soundOnActionClickedToggleSwitchHBox = new HBoxWithSpaceBetween("Sound on Action Clicked", soundOnActionClickedToggleSwitch);
soundOnActionClickedFilePathTextField = new TextField();
HBoxInputBoxWithFileChooser soundHBoxInputBoxWithFileChooser = new HBoxInputBoxWithFileChooser("Sound File Path", soundOnActionClickedFilePathTextField,
new FileChooser.ExtensionFilter("Sounds","*.mp3","*.mp4", "*.m4a", "*.m4v","*.wav","*.aif", "*.aiff","*.fxm","*.flv","*.m3u8"));
soundHBoxInputBoxWithFileChooser.setUseLast(false);
soundHBoxInputBoxWithFileChooser.setRememberThis(false);
soundHBoxInputBoxWithFileChooser.getFileChooseButton().disableProperty().bind(soundOnActionClickedToggleSwitch.selectedProperty().not());
minimizeToSystemTrayOnCloseToggleSwitch = new ToggleSwitch();
minimizeToSystemTrayOnCloseToggleSwitch = new ToggleSwitch();
minimizeToSystemTrayOnCloseHBox = new HBoxWithSpaceBetween("Minimise To Tray On Close", minimizeToSystemTrayOnCloseToggleSwitch);
minimizeToSystemTrayOnCloseHBox = new HBoxWithSpaceBetween("Minimise To Tray On Close", minimizeToSystemTrayOnCloseToggleSwitch);
showAlertsPopupToggleSwitch = new ToggleSwitch();
showAlertsPopupToggleSwitch = new ToggleSwitch();
showAlertsPopupHBox = new HBoxWithSpaceBetween("Show Popup On Alert", showAlertsPopupToggleSwitch);
showAlertsPopupHBox = new HBoxWithSpaceBetween("Show Popup On Alert", showAlertsPopupToggleSwitch);
checkForUpdatesButton = new Button("Check for updates");
checkForUpdatesButton = new Button("Check for updates");
checkForUpdatesButton.setOnAction(event->checkForUpdates());
checkForUpdatesButton.setOnAction(event->checkForUpdates());
factoryResetButton = new Button("Factory Reset");
factoryResetButton = new Button("Factory Reset");
factoryResetButton.setOnAction(actionEvent -> onFactoryResetButtonClicked());
factoryResetButton.setOnAction(actionEvent -> onFactoryResetButtonClicked());
getStyleClass().add("general_settings");
getStyleClass().add("general_settings");
prefWidthProperty().bind(widthProperty());
prefWidthProperty().bind(widthProperty());
setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
setSpacing(5);
setSpacing(5);
getChildren().addAll(
getChildren().addAll(
getUIInputBox("Server Name", serverNameTextField),
new HBoxInputBox("Server Name", serverNameTextField),
getUIInputBox("Port", portTextField),
new HBoxInputBox("Port", portTextField),
getUIInputBox("Grid Pane - Box Size", actionGridPaneActionBoxSize),
new HBoxInputBox("Grid Pane - Box Size", actionGridPaneActionBoxSize),
getUIInputBox("Grid Pane - Box Gap", actionGridPaneActionBoxGap),
new HBoxInputBox("Grid Pane - Box Gap", actionGridPaneActionBoxGap),
getUIInputBoxWithDirectoryChooser("Plugins Path", pluginsPathTextField),
new HBoxInputBoxWithDirectoryChooser("Plugins Path", pluginsPathTextField),
getUIInputBoxWithDirectoryChooser("Themes Path", themesPathTextField),
new HBoxInputBoxWithDirectoryChooser("Themes Path", themesPathTextField),
soundHBoxInputBoxWithFileChooser,
soundOnActionClickedToggleSwitchHBox,
minimizeToSystemTrayOnCloseHBox,
minimizeToSystemTrayOnCloseHBox,
startOnBootHBox,
startOnBootHBox,
showAlertsPopupHBox
showAlertsPopupHBox
);
);
serverNameTextField.setPrefWidth(200);
serverNameTextField.setPrefWidth(200);
saveButton = new Button("Save");
saveButton = new Button("Save");
saveButton.setOnAction(event->save());
saveButton.setOnAction(event->save());
getChildren().addAll(factoryResetButton, checkForUpdatesButton, saveButton);
getChildren().addAll(factoryResetButton, checkForUpdatesButton, saveButton);
setPadding(new Insets(10));
setPadding(new Insets(10));
}
}
private void checkForUpdates()
private void checkForUpdates()
{
{
new CheckForUpdates(checkForUpdatesButton,
new CheckForUpdates(checkForUpdatesButton,
PlatformType.SERVER, ServerInfo.getInstance().getVersion(), new UpdateHyperlinkOnClick() {
PlatformType.SERVER, ServerInfo.getInstance().getVersion(), new UpdateHyperlinkOnClick() {
@Override
@Override
public void handle(ActionEvent actionEvent) {
public void handle(ActionEvent actionEvent) {
hostServices.showDocument(getURL());
hostServices.showDocument(getURL());
}
}
});
});
}
}
private HBox getUIInputBoxWithDirectoryChooser(String labelText, TextField textField)
{
HBox hBox = getUIInputBox(labelText, textField);
hBox.setSpacing(5.0);
TextField tf = (TextField) hBox.getChildren().get(2);
tf.setPrefWidth(300);
tf.setDisable(true);
Button button = new Button();
FontIcon fontIcon = new FontIcon("far-folder");
button.setGraphic(fontIcon);
button.setOnAction(event -> {
DirectoryChooser directoryChooser = new DirectoryChooser();
try {
File selectedDirectory = directoryChooser.showDialog(getScene().getWindow());
textField.setText(selectedDirectory.getAbsolutePath());
}
catch (NullPointerException e)
{
logger.info("No folder selected");
}
});
hBox.getChildren().add(button);
return hBox;
}
private HBox getUIInputBox(String labelText, TextField textField)
{
textField.setPrefWidth(100);
Label label = new Label(labelText);
Region region = new Region();
HBox.setHgrow(region, Priority.ALWAYS);
return new HBox(label, region, textField);
}
public void loadDataFromConfig() throws SevereException {
public void loadDataFromConfig() throws SevereException {
Config config = Config.getInstance();
Config config = Config.getInstance();
Platform.runLater(()->
Platform.runLater(()->
{
{
serverNameTextField.setText(config.getServerName());
serverNameTextField.setText(config.getServerName());
portTextField.setText(config.getPort()+"");
portTextField.setText(config.getPort()+"");
pluginsPathTextField.setText(config.getPluginsPath());
pluginsPathTextField.setText(config.getPluginsPath());
themesPathTextField.setText(config.getThemesPath());
themesPathTextField.setText(config.getThemesPath());
actionGridPaneActionBoxSize.setText(config.getActionGridActionSize()+"");
actionGridPaneActionBoxSize.setText(config.getActionGridActionSize()+"");
actionGridPaneActionBoxGap.setText(config.getActionGridActionGap()+"");
actionGridPaneActionBoxGap.setText(config.getActionGridActionGap()+"");
minimizeToSystemTrayOnCloseToggleSwitch.setSelected(config.getMinimiseToSystemTrayOnClose());
minimizeToSystemTrayOnCloseToggleSwitch.setSelected(config.getMinimiseToSystemTrayOnClose());
showAlertsPopupToggleSwitch.setSelected(config.isShowAlertsPopup());
showAlertsPopupToggleSwitch.setSelected(config.isShowAlertsPopup());
startOnBootToggleSwitch.setSelected(config.getStartOnBoot());
startOnBootToggleSwitch.setSelected(config.getStartOnBoot());
soundOnActionClickedToggleSwitch.setSelected(config.getSoundOnActionClickedStatus());
soundOnActionClickedFilePathTextField.setText(config.getSoundOnActionClickedFilePath());
});
});
}
}
public void save()
public void save()
{
{
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try {
try {
boolean toBeReloaded = false;
boolean toBeReloaded = false;
boolean dashToBeReRendered = false;
boolean dashToBeReRendered = false;
Platform.runLater(()->{
Platform.runLater(()->{
saveButton.setDisable(true);
saveButton.setDisable(true);
});
});
String serverNameStr = serverNameTextField.getText();
String serverNameStr = serverNameTextField.getText();
String serverPortStr = portTextField.getText();
String serverPortStr = portTextField.getText();
String pluginsPathStr = pluginsPathTextField.getText();
String pluginsPathStr = pluginsPathTextField.getText();
String themesPathStr = themesPathTextField.getText();
String themesPathStr = themesPathTextField.getText();
String actionGridActionBoxSize = actionGridPaneActionBoxSize.getText();
String actionGridActionBoxSize = actionGridPaneActionBoxSize.getText();
String actionGridActionBoxGap = actionGridPaneActionBoxGap.getText();
String actionGridActionBoxGap = actionGridPaneActionBoxGap.getText();
boolean minimizeToSystemTrayOnClose = minimizeToSystemTrayOnCloseToggleSwitch.isSelected();
boolean minimizeToSystemTrayOnClose = minimizeToSystemTrayOnCloseToggleSwitch.isSelected();
boolean showAlertsPopup = showAlertsPopupToggleSwitch.isSelected();
boolean showAlertsPopup = showAlertsPopupToggleSwitch.isSelected();
boolean startOnBoot = startOnBootToggleSwitch.isSelected();
boolean startOnBoot = startOnBootToggleSwitch.isSelected();
boolean soundOnActionClicked = soundOnActionClickedToggleSwitch.isSelected();
String soundOnActionClickedFilePath = soundOnActionClickedFilePathTextField.getText();
Config config = Config.getInstance();
Config config = Config.getInstance();
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
if(serverNameStr.isBlank())
if(serverNameStr.isBlank())
{
{
errors.append("* Server Name cannot be blank.\n");
errors.append("* Server Name cannot be blank.\n");
}
}
else
else
{
{
if(!config.getServerName().equals(serverNameStr))
if(!config.getServerName().equals(serverNameStr))
{
{
toBeReloaded = true;
toBeReloaded = true;
}
}
}
}
int serverPort=-1;
int serverPort=-1;
try {
try {
serverPort = Integer.parseInt(serverPortStr);
serverPort = Integer.parseInt(serverPortStr);
if (serverPort < 1024)
if (serverPort < 1024)
errors.append("* Server Port must be more than 1024\n");
errors.append("* Server Port must be more than 1024\n");
else if(serverPort > 65535)
else if(serverPort > 65535)
errors.append("* Server Port must be lesser than 65535\n");
errors.append("* Server Port must be lesser than 65535\n");
if(config.getPort()!=serverPort)
if(config.getPort()!=serverPort)
{
{
toBeReloaded = true;
toBeReloaded = true;
}
}
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append("* Server Port must be integer.\n");
errors.append("* Server Port must be integer.\n");
}
}
int actionSize=-1;
int actionSize=-1;
try {
try {
actionSize = Integer.parseInt(actionGridActionBoxSize);
actionSize = Integer.parseInt(actionGridActionBoxSize);
if(config.getActionGridActionSize() != actionSize)
if(config.getActionGridActionSize() != actionSize)
{
{
dashToBeReRendered = true;
dashToBeReRendered = true;
}
}
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append("* action Size must be integer.\n");
errors.append("* action Size must be integer.\n");
}
}
int actionGap=-1;
int actionGap=-1;
try {
try {
actionGap = Integer.parseInt(actionGridActionBoxGap);
actionGap = Integer.parseInt(actionGridActionBoxGap);
if(config.getActionGridActionGap() != actionGap)
if(config.getActionGridActionGap() != actionGap)
{
{
dashToBeReRendered = true;
dashToBeReRendered = true;
}
}
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append("* action Gap must be integer.\n");
errors.append("* action Gap must be integer.\n");
}
}
if(pluginsPathStr.isBlank())
if(pluginsPathStr.isBlank())
{
{
errors.append("* Plugins Path must not be blank.\n");
errors.append("* Plugins Path must not be blank.\n");
}
}
else
else
{
{
if(!config.getPluginsPath().equals(pluginsPathStr))
if(!config.getPluginsPath().equals(pluginsPathStr))
{
{
toBeReloaded = true;
toBeReloaded = true;
}
}
}
}
if(themesPathStr.isBlank())
if(themesPathStr.isBlank())
{
{
errors.append("* Themes Path must not be blank.\n");
errors.append("* Themes Path must not be blank.\n");
}
}
else
else
{
{
if(!config.getThemesPath().equals(themesPathStr))
if(!config.getThemesPath().equals(themesPathStr))
{
{
toBeReloaded = true;
toBeReloaded = true;
}
}
}
}
if(!errors.toString().isEmpty())
if(!errors.toString().isEmpty())
{
{
throw new MinorException("Uh Oh!", "Please rectify the following errors and try again :\n"+errors.toString());
throw new MinorException("Uh Oh!", "Please rectify the following errors and try again :\n"+errors.toString());
}
}
if(config.getStartOnBoot() != startOnBoot)
if(config.getStartOnBoot() != startOnBoot)
{
{
if(StartupFlags.RUNNER_FILE_NAME == null)
if(StartupFlags.RUNNER_FILE_NAME == 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.SERVER, ServerInfo.getInstance().getPlatform());
StartAtBoot startAtBoot = new StartAtBoot(PlatformType.SERVER, ServerInfo.getInstance().getPlatform());
if(startOnBoot)
if(startOnBoot)
{
{
startAtBoot.create(new File(StartupFlags.RUNNER_FILE_NAME));
startAtBoot.create(new File(StartupFlags.RUNNER_FILE_NAME));
}
}
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();
}
}
}
}
}
}
if(minimizeToSystemTrayOnClose)
if(minimizeToSystemTrayOnClose)
{
{
if(!SystemTray.isSupported())
if(!SystemTray.isSupported())
{
{
StreamPiAlert alert = new StreamPiAlert("Not Supported", "Tray System not supported on this platform ", StreamPiAlertType.ERROR);
StreamPiAlert alert = new StreamPiAlert("Not Supported", "Tray System not supported on this platform ", StreamPiAlertType.ERROR);
alert.show();
alert.show();
minimizeToSystemTrayOnClose = false;
minimizeToSystemTrayOnClose = false;
}
}
}
}
if(soundOnActionClicked)
{
if(soundOnActionClickedFilePath.isBlank())
{
StreamPiAlert alert = new StreamPiAlert("No sound file specified",
"Sound File cannot be empty", StreamPiAlertType.ERROR);
alert.show();
soundOnActionClicked = false;
}
else
{
File soundFile = new File(soundOnActionClickedFilePath);
if(!soundFile.exists() || !soundFile.isFile())
{
StreamPiAlert alert = new StreamPiAlert("File not found",
"No sound file at \n"+soundOnActionClickedFilePath+"\n" +
"Unable to set sound on action clicked.", StreamPiAlertType.ERROR);
alert.show();
soundOnActionClicked = false;
}
}
}
config.setServerName(serverNameStr);
config.setServerName(serverNameStr);
config.setServerPort(serverPort);
config.setServerPort(serverPort);
config.setActionGridGap(actionGap);
config.setActionGridGap(actionGap);
config.setActionGridSize(actionSize);
config.setActionGridSize(actionSize);
config.setPluginsPath(pluginsPathStr);
config.setPluginsPath(pluginsPathStr);
config.setThemesPath(themesPathStr);
config.setThemesPath(themesPathStr);
config.setMinimiseToSystemTrayOnClose(minimizeToSystemTrayOnClose);
config.setMinimiseToSystemTrayOnClose(minimizeToSystemTrayOnClose);
StreamPiAlert.setIsShowPopup(showAlertsPopup);
StreamPiAlert.setIsShowPopup(showAlertsPopup);
config.setShowAlertsPopup(showAlertsPopup);
config.setShowAlertsPopup(showAlertsPopup);
config.setStartupOnBoot(startOnBoot);
config.setStartupOnBoot(startOnBoot);
config.setSoundOnActionClickedStatus(soundOnActionClicked);
config.setSoundOnActionClickedFilePath(soundOnActionClickedFilePath);
config.save();
config.save();
loadDataFromConfig();
loadDataFromConfig();
if(toBeReloaded)
if(toBeReloaded)
{
{
StreamPiAlert restartPrompt = new StreamPiAlert(
StreamPiAlert restartPrompt = new StreamPiAlert(
"Warning",
"Warning",
"Stream-Pi Server needs to be restarted for these changes to take effect. Restart?\n" +
"Stream-Pi Server needs to be restarted for these changes to take effect. Restart?\n" +
"All your current connections will be disconnected.",
"All your current connections will be disconnected.",
StreamPiAlertType.WARNING
StreamPiAlertType.WARNING
);
);
String yesOption = "Yes";
String yesOption = "Yes";
String noOption = "No";
String noOption = "No";
restartPrompt.setButtons(yesOption, noOption);
restartPrompt.setButtons(yesOption, noOption);
restartPrompt.setOnClicked(new StreamPiAlertListener() {
restartPrompt.setOnClicked(new StreamPiAlertListener() {
@Override
@Override
public void onClick(String s) {
public void onClick(String s) {
if(s.equals(yesOption))
if(s.equals(yesOption))
{
{
serverListener.restart();
serverListener.restart();
}
}
}
}
});
});
restartPrompt.show();
restartPrompt.show();
}
}
if(dashToBeReRendered)
if(dashToBeReRendered)
{
{
serverListener.clearTemp();
serverListener.clearTemp();
}
}
}
}
catch (MinorException e)
catch (MinorException e)
{
{
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
exceptionAndAlertHandler.handleSevereException(e);
exceptionAndAlertHandler.handleSevereException(e);
}
}
finally {
finally {
Platform.runLater(()->{
Platform.runLater(()->{
saveButton.setDisable(false);
saveButton.setDisable(false);
});
});
}
}
return null;
return null;
}
}
}).start();
}).start();
}
}
private void onFactoryResetButtonClicked()
private void onFactoryResetButtonClicked()
{
{
StreamPiAlert confirmation = new StreamPiAlert("Warning","Are you sure?\n" +
StreamPiAlert confirmation = new StreamPiAlert("Warning","Are you sure?\n" +
"This will erase everything.",StreamPiAlertType.WARNING);
"This will erase everything.",StreamPiAlertType.WARNING);
String yesButton = "Yes";
String yesButton = "Yes";
String noButton = "No";
String noButton = "No";
confirmation.setButtons(yesButton, noButton);
confirmation.setButtons(yesButton, noButton);
confirmation.setOnClicked(new StreamPiAlertListener() {
confirmation.setOnClicked(new StreamPiAlertListener() {
@Override
@Override
public void onClick(String s) {
public void onClick(String s) {
if(s.equals(yesButton))
if(s.equals(yesButton))
{
{
serverListener.factoryReset();
serverListener.factoryReset();
}
}
}
}
});
});
confirmation.show();
confirmation.show();
}
}
}
}