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.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.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())
{
{
firstTimeUse = new FirstTimeUse(this, this);
firstTimeUse = new FirstTimeUse(this, this);
getChildren().add(firstTimeUse);
getChildren().add(firstTimeUse);
firstTimeUse.toFront();
firstTimeUse.toFront();
getStage().setTitle("Stream-Pi Server");
getStage().setTitle("Stream-Pi Server");
getStage().show();
getStage().show();
}
}
else
else
{
{
if(getConfig().isAllowDonatePopup())
if(getConfig().isAllowDonatePopup())
{
{
if(new Random().nextInt(50) == 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();
}
}
StreamPiAlert.setIsShowPopup(getConfig().isShowAlertsPopup());
StreamPiAlert.setIsShowPopup(getConfig().isShowAlertsPopup());
}
}
catch(MinorException e)
catch(MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
if(getConfig().getSoundOnActionClickedStatus())
if(getConfig().getSoundOnActionClickedStatus())
{
{
initSoundOnActionClicked();
initSoundOnActionClicked();
}
}
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)
{
{
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();
ExternalPlugins.getInstance().shutDownActions();
ExternalPlugins.getInstance().shutDownActions();
closeLogger();
closeLogger();
Config.nullify();
Config.nullify();
}
}
public void exit()
public void exit()
{
{
executor.shutdown();
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 ...");
onQuitApp();
onQuitApp();
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();
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(()->{
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
public void onClick(String txt)
{
{
@Override
onQuitApp();
public void onClick(String txt)
exit();
{
}
onQuitApp();
exit();
}
});
alert.show();
});
});
alert.show();
}
}
private AudioClip audioClip = null;
private AudioClip audioClip = null;
private String audioFilePath = null;
private String audioFilePath = null;
private void playSound()
private void playSound()
{
{
if(audioClip.isPlaying())
if(audioClip.isPlaying())
{
{
Platform.runLater(audioClip::stop);
Platform.runLater(audioClip::stop);
return;
return;
}
}
if(!audioFilePath.equals(getConfig().getSoundOnActionClickedFilePath()))
{
initSoundOnActionClicked();
}
Platform.runLater(audioClip::play);
Platform.runLater(audioClip::play);
}
}
private void initSoundOnActionClicked()
@Override
public void initSoundOnActionClicked()
{
{
audioFilePath = getConfig().getSoundOnActionClickedFilePath();
audioFilePath = getConfig().getSoundOnActionClickedFilePath();
File file = new File(audioFilePath);
File file = new File(audioFilePath);
if(!file.exists())
if(!file.exists())
{
{
audioFilePath = null;
audioFilePath = null;
audioClip = null;
audioClip = null;
getConfig().setSoundOnActionClickedStatus(false);
getConfig().setSoundOnActionClickedStatus(false);
getConfig().setSoundOnActionClickedFilePath("");
handleMinorException(new MinorException("The sound file for on action click sound is missing."));
handleMinorException(new MinorException("The sound file for on action click sound is missing."));
return;
}
}
audioClip = new AudioClip(file.toURI().toString());
audioClip = new AudioClip(file.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(getConfig().getSoundOnActionClickedStatus())
if(getConfig().getSoundOnActionClickedStatus())
{
{
playSound();
playSound();
}
}
if(action.isInvalid())
if(action.isInvalid())
{
{
throw new MinorException(
throw new MinorException(
"The action isn't installed on the server."
"The action isn't installed on the server."
);
);
}
}
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
Thread.sleep(action.getDelayBeforeExecuting());
Thread.sleep(action.getDelayBeforeExecuting());
getLogger().info("action "+action.getID()+" clicked!");
getLogger().info("action "+action.getID()+" clicked!");
if(action instanceof ToggleAction)
if(action instanceof ToggleAction)
{
{
onToggleActionClicked((ToggleAction) action, toggle, profileID,
onToggleActionClicked((ToggleAction) action, toggle, profileID,
client.getRemoteSocketAddress());
client.getRemoteSocketAddress());
}
}
else if (action instanceof NormalAction)
else if (action instanceof NormalAction)
{
{
onNormalActionClicked((NormalAction) action, profileID,
onNormalActionClicked((NormalAction) action, profileID,
client.getRemoteSocketAddress());
client.getRemoteSocketAddress());
}
}
}
}
catch (InterruptedException e)
catch (InterruptedException e)
{
{
e.printStackTrace();
e.printStackTrace();
getLogger().info("onActionClicked scheduled task was interrupted ...");
getLogger().info("onActionClicked scheduled task was interrupted ...");
}
}
return null;
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();
}
}
}
}
package com.stream_pi.server.controller;
package com.stream_pi.server.controller;
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.server.client.Client;
import com.stream_pi.server.client.Client;
import com.stream_pi.server.window.dashboard.ClientAndProfileSelectorPane;
import com.stream_pi.server.window.dashboard.ClientAndProfileSelectorPane;
import com.stream_pi.server.window.dashboard.DashboardBase;
import com.stream_pi.server.window.dashboard.DashboardBase;
import com.stream_pi.server.window.settings.SettingsBase;
import com.stream_pi.server.window.settings.SettingsBase;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import javafx.stage.Stage;
import javafx.stage.Stage;
import java.net.SocketAddress;
import java.net.SocketAddress;
public interface ServerListener
public interface ServerListener
{
{
void onActionClicked(Client client, String profileID, String actionID, boolean toggle);
void onActionClicked(Client client, String profileID, String actionID, boolean toggle);
void clearTemp();
void clearTemp();
void init();
void init();
void restart();
void restart();
void othInit();
void othInit();
Stage getStage();
Stage getStage();
DashboardBase getDashboardBase();
DashboardBase getDashboardBase();
SettingsBase getSettingsBase();
SettingsBase getSettingsBase();
void initLogger() throws SevereException;
void initLogger() throws SevereException;
void factoryReset();
void factoryReset();
void initSoundOnActionClicked();
}
}
M
src/main/java/com/stream_pi/server/window/dashboard/actiondetailpane/ActionDetailsPane.java
+3
−11
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.*;
import com.stream_pi.action_api.actionproperty.property.*;
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.server.window.helper.Helper;
import com.stream_pi.server.window.helper.Helper;
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.HBoxWithSpaceBetween;
import com.stream_pi.util.uihelper.HBoxWithSpaceBetween;
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);
HBox.setMargin(hideDisplayTextCheckBox, new Insets(0, 0, 0, 45));
HBox.setMargin(hideDisplayTextCheckBox, new Insets(0, 0, 0, 45));
HBoxInputBox s = new HBoxInputBox("Display Name", displayNameTextField);
HBoxInputBox s = new HBoxInputBox("Display Name", displayNameTextField);
HBox.setHgrow(s, Priority.ALWAYS);
HBox.setHgrow(s, Priority.ALWAYS);
displayTextFieldHBox = new HBox(s, hideDisplayTextCheckBox);
displayTextFieldHBox = new HBox(s, 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;
Helper.ControlNodePair controlNodePair = new Helper().getControlNode(eachProperty);
Label label = new Label(eachProperty.getDisplayName());
UIPropertyBox clientProperty = new UIPropertyBox(i, eachProperty.getDisplayName(), controlNodePair.getControlNode(),
Node controlNode = Helper.getControlNode(eachProperty);
HBoxWithSpaceBetween hBoxWithSpaceBetween = new HBoxWithSpaceBetween(label, 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(controlNodePair.getUINode());
clientPropertiesVBox.getChildren().add(hBoxWithSpaceBetween);
}
}
}
}
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.TOGGLE)
if(getAction().getActionType() != ActionType.TOGGLE)
{
{
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 no icon.\n");
finalErrors.append(" * Display Text cannot be hidden since there is 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.helper;
package com.stream_pi.server.window.helper;
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.ListValue;
import com.stream_pi.action_api.actionproperty.property.ListValue;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.action_api.actionproperty.property.Property;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.uihelper.HBoxInputBoxWithFileChooser;
import com.stream_pi.util.uihelper.HBoxWithSpaceBetween;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.stage.FileChooser;
import javafx.util.Callback;
import javafx.util.Callback;
public class Helper
public class Helper
{
{
public static Node getControlNode(Property property) throws MinorException
public class ControlNodePair
{
{
private Node controlNode = null;
private Node UINode = null;
public ControlNodePair(Node controlNode, Node UINode)
{
this.controlNode = controlNode;
this.UINode = UINode;
}
public Node getUINode()
{
return UINode;
}
public Node getControlNode()
{
return controlNode;
}
}
public ControlNodePair getControlNode(Property property) throws MinorException
{
Node UINode = null, controlNode = null;
if(property.getControlType() == ControlType.COMBO_BOX)
if(property.getControlType() == ControlType.COMBO_BOX)
{
{
ComboBox<ListValue> comboBox = new ComboBox<>();
ComboBox<ListValue> comboBox = new ComboBox<>();
comboBox.getItems().addAll(property.getListValue());
comboBox.getItems().addAll(property.getListValue());
Callback<ListView<ListValue>, ListCell<ListValue>> clientsComboBoxFactory = new Callback<>() {
Callback<ListView<ListValue>, ListCell<ListValue>> clientsComboBoxFactory = new Callback<>() {
@Override
@Override
public ListCell<ListValue> call(ListView<ListValue> clientConnectionListView) {
public ListCell<ListValue> call(ListView<ListValue> clientConnectionListView) {
return new ListCell<>() {
return new ListCell<>() {
@Override
@Override
protected void updateItem(ListValue listValue, boolean b)
protected void updateItem(ListValue listValue, boolean b)
{
{
super.updateItem(listValue, b);
super.updateItem(listValue, b);
if(listValue == null)
if(listValue == null)
{
{
setText("Choose value");
setText("Choose value");
}
}
else
else
{
{
setText(listValue.getDisplayName());
setText(listValue.getDisplayName());
}
}
}
}
};
};
}
}
};
};
comboBox.setCellFactory(clientsComboBoxFactory);
comboBox.setCellFactory(clientsComboBoxFactory);
comboBox.setButtonCell(clientsComboBoxFactory.call(null));
comboBox.setButtonCell(clientsComboBoxFactory.call(null));
comboBox.getSelectionModel().select(property.getSelectedIndex());
comboBox.getSelectionModel().select(property.getSelectedIndex());
return comboBox;
controlNode = comboBox;
}
}
else if(property.getControlType() == ControlType.TEXT_FIELD)
else if(property.getControlType() == ControlType.TEXT_FIELD)
{
{
return new TextField(property.getRawValue());
controlNode = new TextField(property.getRawValue());
}
}
else if(property.getControlType() == ControlType.TEXT_FIELD_MASKED)
else if(property.getControlType() == ControlType.TEXT_FIELD_MASKED)
{
{
PasswordField textField = new PasswordField();
PasswordField textField = new PasswordField();
textField.setText(property.getRawValue());
textField.setText(property.getRawValue());
return textField;
controlNode = textField;
}
}
else if(property.getControlType() == ControlType.TOGGLE)
else if(property.getControlType() == ControlType.TOGGLE)
{
{
ToggleButton toggleButton = new ToggleButton();
ToggleButton toggleButton = new ToggleButton();
toggleButton.setSelected(property.getBoolValue());
toggleButton.setSelected(property.getBoolValue());
if(property.getBoolValue())
if(property.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");
});
});
return toggleButton;
controlNode = toggleButton;
}
}
else if(property.getControlType() == ControlType.SLIDER_DOUBLE)
else if(property.getControlType() == ControlType.SLIDER_DOUBLE)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(property.getDoubleValue());
slider.setValue(property.getDoubleValue());
slider.setMax(property.getMaxDoubleValue());
slider.setMax(property.getMaxDoubleValue());
slider.setMin(property.getMinDoubleValue());
slider.setMin(property.getMinDoubleValue());
return slider;
controlNode = slider;
}
}
else if(property.getControlType() == ControlType.SLIDER_INTEGER)
else if(property.getControlType() == ControlType.SLIDER_INTEGER)
{
{
Slider slider = new Slider();
Slider slider = new Slider();
slider.setValue(property.getIntValue());
slider.setValue(property.getIntValue());
slider.setMax(property.getMaxIntValue());
slider.setMax(property.getMaxIntValue());
slider.setMin(property.getMinIntValue());
slider.setMin(property.getMinIntValue());
slider.setBlockIncrement(1.0);
slider.setBlockIncrement(1.0);
slider.setSnapToTicks(true);
slider.setSnapToTicks(true);
return slider;
controlNode = slider;
}
else if(property.getControlType() == ControlType.FILE_PATH)
{
TextField textField = new TextField(property.getRawValue());
FileExtensionFilter[] fileExtensionFilters = property.getExtensionFilters();
FileChooser.ExtensionFilter[] extensionFilters = new FileChooser.ExtensionFilter[fileExtensionFilters.length];
for(int x = 0;x<fileExtensionFilters.length;x++)
{
extensionFilters[x] = new FileChooser.ExtensionFilter(
fileExtensionFilters[x].getDescription(),
fileExtensionFilters[x].getExtensions()
);
}
UINode = new HBoxInputBoxWithFileChooser(property.getDisplayName(), textField, null,
extensionFilters);
controlNode =textField;
}
if(property.getControlType() != ControlType.FILE_PATH)
{
UINode = new HBoxWithSpaceBetween(new Label(property.getDisplayName()), controlNode);
}
}
return null;
return new ControlNodePair(controlNode, UINode);
}
}
}
}
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.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.HBoxInputBox;
import com.stream_pi.util.uihelper.HBoxInputBoxWithDirectoryChooser;
import com.stream_pi.util.uihelper.HBoxInputBoxWithDirectoryChooser;
import com.stream_pi.util.uihelper.HBoxInputBoxWithFileChooser;
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 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 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 TextField soundOnActionClickedFilePathTextField;
private final ToggleSwitch soundOnActionClickedToggleSwitch;
private final ToggleSwitch soundOnActionClickedToggleSwitch;
private final HBoxWithSpaceBetween soundOnActionClickedToggleSwitchHBox;
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();
soundOnActionClickedToggleSwitch = new ToggleSwitch();
soundOnActionClickedToggleSwitchHBox = new HBoxWithSpaceBetween("Sound on Action Clicked", soundOnActionClickedToggleSwitch);
soundOnActionClickedToggleSwitchHBox = new HBoxWithSpaceBetween("Sound on Action Clicked", soundOnActionClickedToggleSwitch);
soundOnActionClickedFilePathTextField = new TextField();
soundOnActionClickedFilePathTextField = new TextField();
HBoxInputBoxWithFileChooser soundHBoxInputBoxWithFileChooser = new HBoxInputBoxWithFileChooser("Sound File Path", soundOnActionClickedFilePathTextField,
HBoxInputBoxWithFileChooser soundHBoxInputBoxWithFileChooser = new HBoxInputBoxWithFileChooser("Sound File Path", soundOnActionClickedFilePathTextField,
new FileChooser.ExtensionFilter("Sounds","*.mp3","*.mp4", "*.m4a", "*.m4v","*.wav","*.aif", "*.aiff","*.fxm","*.flv","*.m3u8"));
new FileChooser.ExtensionFilter("Sounds","*.mp3","*.mp4", "*.m4a", "*.m4v","*.wav","*.aif", "*.aiff","*.fxm","*.flv","*.m3u8"));
soundHBoxInputBoxWithFileChooser.setUseLast(false);
soundHBoxInputBoxWithFileChooser.setUseLast(false);
soundHBoxInputBoxWithFileChooser.setRememberThis(false);
soundHBoxInputBoxWithFileChooser.setRememberThis(false);
soundHBoxInputBoxWithFileChooser.getFileChooseButton().disableProperty().bind(soundOnActionClickedToggleSwitch.selectedProperty().not());
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(
new HBoxInputBox("Server Name", serverNameTextField),
new HBoxInputBox("Server Name", serverNameTextField),
new HBoxInputBox("Port", portTextField),
new HBoxInputBox("Port", portTextField),
new HBoxInputBox("Grid Pane - Box Size", actionGridPaneActionBoxSize),
new HBoxInputBox("Grid Pane - Box Size", actionGridPaneActionBoxSize),
new HBoxInputBox("Grid Pane - Box Gap", actionGridPaneActionBoxGap),
new HBoxInputBox("Grid Pane - Box Gap", actionGridPaneActionBoxGap),
new HBoxInputBoxWithDirectoryChooser("Plugins Path", pluginsPathTextField),
new HBoxInputBoxWithDirectoryChooser("Plugins Path", pluginsPathTextField),
new HBoxInputBoxWithDirectoryChooser("Themes Path", themesPathTextField),
new HBoxInputBoxWithDirectoryChooser("Themes Path", themesPathTextField),
soundHBoxInputBoxWithFileChooser,
soundHBoxInputBoxWithFileChooser,
soundOnActionClickedToggleSwitchHBox,
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());
}
}
});
});
}
}
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());
soundOnActionClickedToggleSwitch.setSelected(config.getSoundOnActionClickedStatus());
soundOnActionClickedFilePathTextField.setText(config.getSoundOnActionClickedFilePath());
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();
boolean soundOnActionClicked = soundOnActionClickedToggleSwitch.isSelected();
String soundOnActionClickedFilePath = soundOnActionClickedFilePathTextField.getText();
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(soundOnActionClicked)
{
{
if(soundOnActionClickedFilePath.isBlank())
if(soundOnActionClickedFilePath.isBlank())
{
{
StreamPiAlert alert = new StreamPiAlert("No sound file specified",
StreamPiAlert alert = new StreamPiAlert("No sound file specified",
"Sound File cannot be empty", StreamPiAlertType.ERROR);
"Sound File cannot be empty", StreamPiAlertType.ERROR);
alert.show();
alert.show();
soundOnActionClicked = false;
soundOnActionClicked = false;
}
}
else
else
{
{
File soundFile = new File(soundOnActionClickedFilePath);
File soundFile = new File(soundOnActionClickedFilePath);
if(!soundFile.exists() || !soundFile.isFile())
if(!soundFile.exists() || !soundFile.isFile())
{
{
StreamPiAlert alert = new StreamPiAlert("File not found",
StreamPiAlert alert = new StreamPiAlert("File not found",
"No sound file at \n"+soundOnActionClickedFilePath+"\n" +
"No sound file at \n"+soundOnActionClickedFilePath+"\n" +
"Unable to set sound on action clicked.", StreamPiAlertType.ERROR);
"Unable to set sound on action clicked.", StreamPiAlertType.ERROR);
alert.show();
alert.show();
soundOnActionClicked = false;
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);
if(soundOnActionClicked)
{
serverListener.initSoundOnActionClicked();
}
config.setSoundOnActionClickedStatus(soundOnActionClicked);
config.setSoundOnActionClickedStatus(soundOnActionClicked);
config.setSoundOnActionClickedFilePath(soundOnActionClickedFilePath);
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();
}
}
}
}
package com.stream_pi.server.window.settings;
package com.stream_pi.server.window.settings;
import com.stream_pi.action_api.actionproperty.property.ListValue;
import com.stream_pi.action_api.actionproperty.property.ListValue;
import com.stream_pi.action_api.externalplugin.ExternalPlugin;
import com.stream_pi.action_api.externalplugin.ExternalPlugin;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
import com.stream_pi.server.uipropertybox.UIPropertyBox;
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.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.server.action.ExternalPlugins;
import com.stream_pi.server.action.ExternalPlugins;
import com.stream_pi.server.controller.ServerListener;
import com.stream_pi.server.controller.ServerListener;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.ExceptionAndAlertHandler;
import com.stream_pi.server.window.helper.Helper;
import com.stream_pi.server.window.helper.Helper;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.uihelper.HBoxWithSpaceBetween;
import com.stream_pi.util.uihelper.HBoxWithSpaceBetween;
import com.stream_pi.util.uihelper.SpaceFiller;
import com.stream_pi.util.uihelper.SpaceFiller;
import javafx.util.Callback;
import javafx.util.Callback;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.javafx.FontIcon;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBox;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Logger;
public class PluginsSettings extends VBox {
public class PluginsSettings extends VBox {
private VBox pluginsSettingsVBox;
private VBox pluginsSettingsVBox;
private ServerListener serverListener;
private ServerListener serverListener;
private Logger logger;
private Logger logger;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private ExceptionAndAlertHandler exceptionAndAlertHandler;
private HostServices hostServices;
private HostServices hostServices;
public PluginsSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices)
public PluginsSettings(ExceptionAndAlertHandler exceptionAndAlertHandler, HostServices hostServices)
{
{
getStyleClass().add("plugins_settings");
getStyleClass().add("plugins_settings");
this.hostServices = hostServices;
this.hostServices = hostServices;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
this.exceptionAndAlertHandler = exceptionAndAlertHandler;
pluginProperties = new ArrayList<>();
pluginProperties = new ArrayList<>();
logger = Logger.getLogger(PluginsSettings.class.getName());
logger = Logger.getLogger(PluginsSettings.class.getName());
pluginsSettingsVBox = new VBox();
pluginsSettingsVBox = new VBox();
pluginsSettingsVBox.getStyleClass().add("plugins_settings_vbox");
pluginsSettingsVBox.getStyleClass().add("plugins_settings_vbox");
pluginsSettingsVBox.setAlignment(Pos.TOP_CENTER);
pluginsSettingsVBox.setAlignment(Pos.TOP_CENTER);
ScrollPane scrollPane = new ScrollPane();
ScrollPane scrollPane = new ScrollPane();
scrollPane.getStyleClass().add("plugins_settings_scroll_pane");
scrollPane.getStyleClass().add("plugins_settings_scroll_pane");
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
scrollPane.maxWidthProperty().bind(widthProperty().multiply(0.8));
pluginsSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
pluginsSettingsVBox.prefWidthProperty().bind(scrollPane.widthProperty().subtract(25));
scrollPane.setContent(pluginsSettingsVBox);
scrollPane.setContent(pluginsSettingsVBox);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
setAlignment(Pos.TOP_CENTER);
setAlignment(Pos.TOP_CENTER);
saveButton = new Button("Save");
saveButton = new Button("Save");
saveButton.setOnAction(event -> onSaveButtonClicked());
saveButton.setOnAction(event -> onSaveButtonClicked());
HBox hBox = new HBox(saveButton);
HBox hBox = new HBox(saveButton);
hBox.setAlignment(Pos.CENTER_RIGHT);
hBox.setAlignment(Pos.CENTER_RIGHT);
getChildren().addAll(scrollPane, hBox);
getChildren().addAll(scrollPane, hBox);
}
}
private Button saveButton;
private Button saveButton;
public void onSaveButtonClicked()
public void onSaveButtonClicked()
{
{
try {
try {
//form validation
//form validation
StringBuilder finalErrors = new StringBuilder();
StringBuilder finalErrors = new StringBuilder();
for (PluginProperties p : pluginProperties)
for (PluginProperties p : pluginProperties)
{
{
StringBuilder errors = new StringBuilder();
StringBuilder errors = new StringBuilder();
for(int j = 0; j < p.getServerPropertyUIBox().size(); j++)
for(int j = 0; j < p.getServerPropertyUIBox().size(); j++)
{
{
UIPropertyBox serverProperty = p.getServerPropertyUIBox().get(j);
UIPropertyBox serverProperty = p.getServerPropertyUIBox().get(j);
Node controlNode = serverProperty.getControlNode();
Node controlNode = serverProperty.getControlNode();
if (serverProperty.getControlType() == ControlType.TEXT_FIELD)
if (serverProperty.getControlType() == ControlType.TEXT_FIELD)
{
{
String value = ((TextField) controlNode).getText();
String value = ((TextField) controlNode).getText();
if(serverProperty.getType() == Type.INTEGER)
if(serverProperty.getType() == Type.INTEGER)
{
{
try
try
{
{
Integer.parseInt(value);
Integer.parseInt(value);
}
}
catch (NumberFormatException e)
catch (NumberFormatException e)
{
{
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" must be integer.\n");
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" must be integer.\n");
}
}
}
}
else
else
{
{
if(value.isBlank() && !serverProperty.isCanBeBlank())
if(value.isBlank() && !serverProperty.isCanBeBlank())
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" cannot be blank.\n");
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" cannot be blank.\n");
}
}
}
}
else if(serverProperty.getControlType() == ControlType.TEXT_FIELD_MASKED)
else if(serverProperty.getControlType() == ControlType.TEXT_FIELD_MASKED)
{
{
String value = ((TextField) controlNode).getText();
String value = ((TextField) controlNode).getText();
if(value.isBlank() && !serverProperty.isCanBeBlank())
if(value.isBlank() && !serverProperty.isCanBeBlank())
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" cannot be blank.\n");
errors.append(" -> ").append(serverProperty.getDisplayName()).append(" cannot be blank.\n");
}
}
}
}
if(!errors.toString().isBlank())
if(!errors.toString().isBlank())
{
{
finalErrors.append(" * ").append(p.getName()).append("\n").append(errors.toString()).append("\n");
finalErrors.append(" * ").append(p.getName()).append("\n").append(errors.toString()).append("\n");
}
}
}
}
if(!finalErrors.toString().isEmpty())
if(!finalErrors.toString().isEmpty())
{
{
throw new MinorException("Form Validation Errors",
throw new MinorException("Form Validation Errors",
"Please rectify the following errors and try again \n"+finalErrors.toString());
"Please rectify the following errors and try again \n"+finalErrors.toString());
}
}
//save
//save
for (PluginProperties pp : pluginProperties) {
for (PluginProperties pp : pluginProperties) {
for (int j = 0; j < pp.getServerPropertyUIBox().size(); j++) {
for (int j = 0; j < pp.getServerPropertyUIBox().size(); j++) {
UIPropertyBox serverProperty = pp.getServerPropertyUIBox().get(j);
UIPropertyBox serverProperty = pp.getServerPropertyUIBox().get(j);
String rawValue = serverProperty.getRawValue();
String rawValue = serverProperty.getRawValue();
ExternalPlugins.getInstance().getActionFromIndex(pp.getIndex())
ExternalPlugins.getInstance().getActionFromIndex(pp.getIndex())
.getServerProperties().get()
.getServerProperties().get()
.get(serverProperty.getIndex()).setRawValue(rawValue);
.get(serverProperty.getIndex()).setRawValue(rawValue);
}
}
}
}
ExternalPlugins.getInstance().saveServerSettings();
ExternalPlugins.getInstance().saveServerSettings();
ExternalPlugins.getInstance().initPlugins();
ExternalPlugins.getInstance().initPlugins();
}
}
catch (MinorException e)
catch (MinorException e)
{
{
e.printStackTrace();
e.printStackTrace();
exceptionAndAlertHandler.handleMinorException(e);
exceptionAndAlertHandler.handleMinorException(e);
}
}
}
}
private ArrayList<PluginProperties> pluginProperties;
private ArrayList<PluginProperties> pluginProperties;
public void showPluginInitError()
public void showPluginInitError()
{
{
Platform.runLater(()->{
Platform.runLater(()->{
pluginsSettingsVBox.getChildren().add(new Label("Plugin init error. Resolve issues and restart."));
pluginsSettingsVBox.getChildren().add(new Label("Plugin init error. Resolve issues and restart."));
saveButton.setVisible(false);
saveButton.setVisible(false);
});
});
}
}
public void loadPlugins() throws MinorException {
public void loadPlugins() throws MinorException {
pluginProperties.clear();
pluginProperties.clear();
List<ExternalPlugin> actions = ExternalPlugins.getInstance().getPlugins();
List<ExternalPlugin> actions = ExternalPlugins.getInstance().getPlugins();
Platform.runLater(()-> pluginsSettingsVBox.getChildren().clear());
Platform.runLater(()-> pluginsSettingsVBox.getChildren().clear());
if(actions.size() == 0)
if(actions.size() == 0)
{
{
Platform.runLater(()->{
Platform.runLater(()->{
Label l = new Label("No Plugins Installed.");
Label l = new Label("No Plugins Installed.");
l.getStyleClass().add("plugins_pane_no_plugins_installed_label");
l.getStyleClass().add("plugins_pane_no_plugins_installed_label");
pluginsSettingsVBox.getChildren().add(l);
pluginsSettingsVBox.getChildren().add(l);
saveButton.setVisible(false);
saveButton.setVisible(false);
});
});
return;
return;
}
}
else
else
{
{
Platform.runLater(()->saveButton.setVisible(true));
Platform.runLater(()->saveButton.setVisible(true));
}
}
for(int i = 0; i<actions.size(); i++)
for(int i = 0; i<actions.size(); i++)
{
{
ExternalPlugin action = actions.get(i);
ExternalPlugin action = actions.get(i);
if(!action.isVisibleInServerSettingsPane())
if(!action.isVisibleInServerSettingsPane())
continue;
continue;
Label headingLabel = new Label(action.getName());
Label headingLabel = new Label(action.getName());
headingLabel.getStyleClass().add("plugins_settings_each_plugin_heading_label");
headingLabel.getStyleClass().add("plugins_settings_each_plugin_heading_label");
HBox headerHBox = new HBox(headingLabel);
HBox headerHBox = new HBox(headingLabel);
headerHBox.getStyleClass().add("plugins_settings_each_plugin_header");
headerHBox.getStyleClass().add("plugins_settings_each_plugin_header");
if (action.getHelpLink()!=null)
if (action.getHelpLink()!=null)
{
{
Button helpButton = new Button();
Button helpButton = new Button();
helpButton.getStyleClass().add("plugins_settings_each_plugin_help_button");
helpButton.getStyleClass().add("plugins_settings_each_plugin_help_button");
FontIcon questionIcon = new FontIcon("fas-question");
FontIcon questionIcon = new FontIcon("fas-question");
questionIcon.getStyleClass().add("plugins_settings_each_plugin_help_icon");
questionIcon.getStyleClass().add("plugins_settings_each_plugin_help_icon");
helpButton.setGraphic(questionIcon);
helpButton.setGraphic(questionIcon);
helpButton.setOnAction(event -> hostServices.showDocument(action.getHelpLink()));
helpButton.setOnAction(event -> hostServices.showDocument(action.getHelpLink()));
headerHBox.getChildren().addAll(SpaceFiller.horizontal() ,helpButton);
headerHBox.getChildren().addAll(SpaceFiller.horizontal() ,helpButton);
}
}
Label authorLabel = new Label(action.getAuthor());
Label authorLabel = new Label(action.getAuthor());
authorLabel.getStyleClass().add("plugins_settings_each_plugin_author_label");
authorLabel.getStyleClass().add("plugins_settings_each_plugin_author_label");
Label moduleLabel = new Label(action.getModuleName());
Label moduleLabel = new Label(action.getModuleName());
moduleLabel.getStyleClass().add("plugins_settings_each_plugin_module_label");
moduleLabel.getStyleClass().add("plugins_settings_each_plugin_module_label");
Label versionLabel = new Label("Version : "+action.getVersion().getText());
Label versionLabel = new Label("Version : "+action.getVersion().getText());
versionLabel.getStyleClass().add("plugins_settings_each_plugin_version_label");
versionLabel.getStyleClass().add("plugins_settings_each_plugin_version_label");
VBox serverPropertiesVBox = new VBox();
VBox serverPropertiesVBox = new VBox();
serverPropertiesVBox.getStyleClass().add("plugins_settings_each_plugin_server_properties_box");
serverPropertiesVBox.getStyleClass().add("plugins_settings_each_plugin_server_properties_box");
serverPropertiesVBox.setSpacing(10.0);
serverPropertiesVBox.setSpacing(10.0);
List<Property> serverProperties = action.getServerProperties().get();
List<Property> serverProperties = action.getServerProperties().get();
ArrayList<UIPropertyBox> serverPropertyArrayList = new ArrayList<>();
ArrayList<UIPropertyBox> serverPropertyArrayList = new ArrayList<>();
for(int j =0; j<serverProperties.size(); j++)
for(int j =0; j<serverProperties.size(); j++)
{
{
Property eachProperty = serverProperties.get(j);
Property eachProperty = serverProperties.get(j);
if(!eachProperty.isVisible())
if(!eachProperty.isVisible())
continue;
continue;
Helper.ControlNodePair controlNodePair = new Helper().getControlNode(eachProperty);
UIPropertyBox serverProperty = new UIPropertyBox(j, eachProperty.getDisplayName(), controlNodePair.getControlNode(), eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
Label label = new Label(eachProperty.getDisplayName());
Node controlNode = Helper.getControlNode(eachProperty);
HBoxWithSpaceBetween hBoxWithSpaceBetween = new HBoxWithSpaceBetween(label, controlNode);
UIPropertyBox serverProperty = new UIPropertyBox(j, eachProperty.getDisplayName(), controlNode, eachProperty.getControlType(), eachProperty.getType(), eachProperty.isCanBeBlank());
serverPropertyArrayList.add(serverProperty);
serverPropertyArrayList.add(serverProperty);
serverPropertiesVBox.getChildren().add(controlNodePair.getUINode());
serverPropertiesVBox.getChildren().add(hBoxWithSpaceBetween);
}
}
PluginProperties pp = new PluginProperties(i, serverPropertyArrayList, action.getName());
PluginProperties pp = new PluginProperties(i, serverPropertyArrayList, action.getName());
pluginProperties.add(pp);
pluginProperties.add(pp);
Platform.runLater(()->{
Platform.runLater(()->{
VBox vBox = new VBox();
VBox vBox = new VBox();
vBox.getStyleClass().add("plugins_settings_each_plugin_box");
vBox.getStyleClass().add("plugins_settings_each_plugin_box");
vBox.setSpacing(5.0);
vBox.setSpacing(5.0);
vBox.getChildren().addAll(headerHBox, authorLabel, moduleLabel, versionLabel, serverPropertiesVBox);
vBox.getChildren().addAll(headerHBox, authorLabel, moduleLabel, versionLabel, serverPropertiesVBox);
if(action.getServerSettingsButtonBar()!=null)
if(action.getServerSettingsButtonBar()!=null)
{
{
action.getServerSettingsButtonBar().getStyleClass().add("plugins_settings_each_plugin_button_bar");
action.getServerSettingsButtonBar().getStyleClass().add("plugins_settings_each_plugin_button_bar");
HBox buttonBarHBox = new HBox(SpaceFiller.horizontal(), action.getServerSettingsButtonBar());
HBox buttonBarHBox = new HBox(SpaceFiller.horizontal(), action.getServerSettingsButtonBar());
buttonBarHBox.getStyleClass().add("plugins_settings_each_plugin_button_bar_hbox");
buttonBarHBox.getStyleClass().add("plugins_settings_each_plugin_button_bar_hbox");
vBox.getChildren().add(buttonBarHBox);
vBox.getChildren().add(buttonBarHBox);
}
}
pluginsSettingsVBox.getChildren().add(vBox);
pluginsSettingsVBox.getChildren().add(vBox);
});
});
}
}
}
}
public class PluginProperties
public class PluginProperties
{
{
private int index;
private int index;
private ArrayList<UIPropertyBox> serverProperty;
private ArrayList<UIPropertyBox> serverProperty;
private String name;
private String name;
public PluginProperties(int index, ArrayList<UIPropertyBox> serverProperty, String name)
public PluginProperties(int index, ArrayList<UIPropertyBox> serverProperty, String name)
{
{
this.index = index;
this.index = index;
this.serverProperty = serverProperty;
this.serverProperty = serverProperty;
this.name = name;
this.name = name;
}
}
public String getName()
public String getName()
{
{
return name;
return name;
}
}
public int getIndex() {
public int getIndex() {
return index;
return index;
}
}
public ArrayList<UIPropertyBox> getServerPropertyUIBox() {
public ArrayList<UIPropertyBox> getServerPropertyUIBox() {
return serverProperty;
return serverProperty;
}
}
}
}
}
}