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.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.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 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.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.net.SocketAddress;
import java.net.SocketAddress;
import java.util.Random;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Executors;
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 ExecutorService executor = Executors.newCachedThreadPool();
private ExecutorService executor = Executors.newCachedThreadPool();
private MainServer mainServer;
private MainServer mainServer;
private Animation openSettingsAnimation;
private Animation openSettingsAnimation;
private Animation closeSettingsAnimation;
private Animation closeSettingsAnimation;
public Controller(){
public Controller(){
mainServer = null;
mainServer = null;
}
}
public void setupDashWindow() throws SevereException
public void setupDashWindow() throws SevereException
{
{
try
try
{
{
getStage().setOnCloseRequest(this::onCloseRequest);
getStage().setOnCloseRequest(this::onCloseRequest);
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}
}
@Override
@Override
public void init()
public void init()
{
{
try {
try {
initBase();
initBase();
setupDashWindow();
setupDashWindow();
setupSettingsWindowsAnimations();
setupSettingsWindowsAnimations();
ExternalPlugins.getInstance().setPropertySaver(this);
ExternalPlugins.getInstance().setPropertySaver(this);
ExternalPlugins.getInstance().setToggleExtras(this);
ExternalPlugins.getInstance().setToggleExtras(this);
ExternalPlugins.getInstance().setServerConnection(this);
ExternalPlugins.getInstance().setServerConnection(this);
getDashboardBase().getPluginsPane().getSettingsButton().setOnAction(event -> {
getDashboardBase().getPluginsPane().getSettingsButton().setOnAction(event -> {
openSettingsAnimation.play();
openSettingsAnimation.play();
});
});
getSettingsBase().getCloseButton().setOnAction(event -> {
getSettingsBase().getCloseButton().setOnAction(event -> {
closeSettingsAnimation.play();
closeSettingsAnimation.play();
});
});
getSettingsBase().getThemesSettings().setController(this);
getSettingsBase().getThemesSettings().setController(this);
mainServer = new MainServer(this, this);
mainServer = new MainServer(this, this);
if(getConfig().isFirstTimeUse())
if(getConfig().isFirstTimeUse())
{
{
Stage stage = new Stage();
Stage stage = new Stage();
Scene s = new Scene(new FirstTimeUse(this, this),
Scene s = new Scene(new FirstTimeUse(this, this),
getConfig().getStartupWindowWidth(), getConfig().getStartupWindowHeight());
getConfig().getStartupWindowWidth(), getConfig().getStartupWindowHeight());
stage.setScene(s);
stage.setScene(s);
stage.setTitle("Stream-Pi Server Setup");
stage.setTitle("Stream-Pi Server Setup");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setOnCloseRequest(event->Platform.exit());
stage.setOnCloseRequest(event->Platform.exit());
stage.show();
stage.show();
}
}
else
else
{
{
if(getConfig().isAllowDonatePopup())
if(getConfig().isAllowDonatePopup())
{
{
if(new Random().nextInt(5) == 3)
if(new Random().nextInt(5) == 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(ServerInfo.getInstance().isStartMinimised() && SystemTray.isSupported())
if(ServerInfo.getInstance().isStartMinimised() && SystemTray.isSupported())
minimiseApp();
minimiseApp();
else
else
getStage().show();
getStage().show();
}
}
catch(MinorException e)
catch(MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
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;
}
}
});
});
}
}
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;
}
}
getConfig().setStartupWindowSize(getWidth(), getHeight());
getConfig().setStartupWindowSize(getWidth(), getHeight());
getConfig().save();
getConfig().save();
onQuitApp();
onQuitApp();
ExternalPlugins.getInstance().shutDownActions();
ExternalPlugins.getInstance().shutDownActions();
Platform.exit();
Platform.exit();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
finally
finally
{
{
getLogger().info("Shut down");
closeLogger();
closeLogger();
}
}
}
}
public void onQuitApp()
public void onQuitApp()
{
{
if(mainServer!=null)
if(mainServer!=null)
mainServer.stopListeningForConnections();
mainServer.stopListeningForConnections();
ClientConnections.getInstance().disconnectAll();
ClientConnections.getInstance().disconnectAll();
executor.shutdown();
executor.shutdown();
getLogger().info("Shutting down ...");
getLogger().info("Shutting down ...");
}
}
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();
Platform.exit();
Platform.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.getMessage(), e);
getLogger().log(Level.SEVERE, e.getMessage(), e);
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()-> new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
Platform.runLater(()-> new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.WARNING).show());
}
}
@Override
@Override
public void handleSevereException(SevereException e) {
public void handleSevereException(SevereException e) {
getLogger().log(Level.SEVERE, e.getMessage(), e);
getLogger().log(Level.SEVERE, e.getMessage(), e);
e.printStackTrace();
e.printStackTrace();
Platform.runLater(()->{
Platform.runLater(()->{
StreamPiAlert alert = new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
StreamPiAlert alert = new StreamPiAlert(e.getTitle(), e.getShortMessage(), StreamPiAlertType.ERROR);
alert.setOnClicked(new StreamPiAlertListener()
alert.setOnClicked(new StreamPiAlertListener()
{
{
@Override
@Override
public void onClick(String txt)
public void onClick(String txt)
{
{
onQuitApp();
onQuitApp();
Platform.exit();
Platform.exit();
}
}
});
});
alert.show();
alert.show();
});
});
}
}
@Override
@Override
public synchronized boolean onNormalActionClicked(NormalAction action, String profileID)
public synchronized boolean onNormalActionClicked(NormalAction action, String profileID)
{
{
try{
try{
getLogger().info("action "+action.getID()+" clicked!");
getLogger().info("action "+action.getID()+" clicked!");
action.onActionClicked();
action.onActionClicked();
return true;
return true;
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
//check if its windows UAC related
//check if its windows UAC related
if(e.getMessage().contains("operation requires elevation"))
if(e.getMessage().contains("operation requires elevation"))
{
{
handleMinorException(new MinorException(
handleMinorException(new MinorException(
"Action Execution Failed!",
"Action Execution Failed!",
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"This action requires higher UAC privileges. Re-launch Stream-Pi Server with 'Administrator Privileges' in order to run this command.")
"This action requires higher UAC privileges. Re-launch Stream-Pi Server with 'Administrator Privileges' in order to run this command.")
);
);
}
}
else
else
{
{
handleMinorException(new MinorException(
handleMinorException(new MinorException(
"Action Execution Failed!",
"Action Execution Failed!",
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Check stacktrace/log to know what exactly happened\n\nMessage : \n"+e.getMessage() )
"Check stacktrace/log to know what exactly happened\n\nMessage : \n"+e.getMessage() )
);
);
}
}
return false;
return false;
}
}
}
}
@Override
@Override
public boolean onToggleActionClicked(ToggleAction action, boolean toggle, String profileID)
public boolean onToggleActionClicked(ToggleAction action, boolean toggle, String profileID)
{
{
try{
try{
getLogger().info("action "+action.getID()+" clicked!");
getLogger().info("action "+action.getID()+" clicked!");
if(toggle)
if(toggle)
{
{
action.onToggleOn();
action.onToggleOn();
}
}
else
else
{
{
action.onToggleOff();
action.onToggleOff();
}
}
// 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(toggle));
// Platform.runLater(()->actionBox.init(toggle));
// }
// }
return true;
return true;
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
//check if its windows UAC related
//check if its windows UAC related
if(e.getMessage().contains("operation requires elevation"))
if(e.getMessage().contains("operation requires elevation"))
{
{
handleMinorException(new MinorException(
handleMinorException(new MinorException(
"Action Execution Failed!",
"Action Execution Failed!",
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"This action requires higher UAC privileges. Re-launch Stream-Pi Server with 'Administrator Privileges' in order to run this command.")
"This action requires higher UAC privileges. Re-launch Stream-Pi Server with 'Administrator Privileges' in order to run this command.")
);
);
}
}
else
else
{
{
handleMinorException(new MinorException(
handleMinorException(new MinorException(
"Action Execution Failed!",
"Action Execution Failed!",
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Error running action at ["+action.getLocation().getRow()+","+action.getLocation().getCol()+"] ("+action.getDisplayText()+")\n"+
"Check stacktrace/log to know what exactly happened\n\nMessage : \n"+e.getMessage() )
"Check stacktrace/log to know what exactly happened\n\nMessage : \n"+e.getMessage() )
);
);
}
}
return false;
return false;
}
}
}
}
@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();
}
}
private Animation createOpenSettingsAnimation(Node settingsNode, Node dashboardNode) {
private Animation createOpenSettingsAnimation(Node settingsNode, Node dashboardNode) {
Timeline openSettingsTimeline = new Timeline();
Timeline openSettingsTimeline = new Timeline();
openSettingsTimeline.setCycleCount(1);
openSettingsTimeline.setCycleCount(1);
openSettingsTimeline.getKeyFrames().addAll(
openSettingsTimeline.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.EASE_IN),
0.0D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.1D, Interpolator.EASE_IN),
1.1D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.1D, Interpolator.EASE_IN),
1.1D, Interpolator.EASE_IN),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.1D, Interpolator.EASE_IN)),
1.1D, Interpolator.EASE_IN)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
0.9D, Interpolator.LINEAR))
0.9D, Interpolator.LINEAR))
);
);
openSettingsTimeline.setOnFinished(e -> settingsNode.toFront());
openSettingsTimeline.setOnFinished(e -> settingsNode.toFront());
return openSettingsTimeline;
return openSettingsTimeline;
}
}
private Animation createCloseSettingsAnimation(Node settingsNode, Node dashboardNode) {
private Animation createCloseSettingsAnimation(Node settingsNode, Node dashboardNode) {
Timeline closeSettingsTimeline = new Timeline();
Timeline closeSettingsTimeline = new Timeline();
closeSettingsTimeline.setCycleCount(1);
closeSettingsTimeline.setCycleCount(1);
closeSettingsTimeline.getKeyFrames().addAll(
closeSettingsTimeline.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.0D, Interpolator.LINEAR)),
1.0D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(settingsNode.opacityProperty(),
new KeyValue(settingsNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleXProperty(),
new KeyValue(settingsNode.scaleXProperty(),
1.1D, Interpolator.LINEAR),
1.1D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleYProperty(),
new KeyValue(settingsNode.scaleYProperty(),
1.1D, Interpolator.LINEAR),
1.1D, Interpolator.LINEAR),
new KeyValue(settingsNode.scaleZProperty(),
new KeyValue(settingsNode.scaleZProperty(),
1.1D, Interpolator.LINEAR)),
1.1D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(0.0D),
new KeyFrame(Duration.millis(0.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
0.0D, Interpolator.LINEAR),
0.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
0.9D, Interpolator.LINEAR),
0.9D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
0.9D, Interpolator.LINEAR)),
0.9D, Interpolator.LINEAR)),
new KeyFrame(Duration.millis(90.0D),
new KeyFrame(Duration.millis(90.0D),
new KeyValue(dashboardNode.opacityProperty(),
new KeyValue(dashboardNode.opacityProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleXProperty(),
new KeyValue(dashboardNode.scaleXProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleYProperty(),
new KeyValue(dashboardNode.scaleYProperty(),
1.0D, Interpolator.LINEAR),
1.0D, Interpolator.LINEAR),
new KeyValue(dashboardNode.scaleZProperty(),
new KeyValue(dashboardNode.scaleZProperty(),
1.0D, Interpolator.LINEAR))
1.0D, Interpolator.LINEAR))
);
);
closeSettingsTimeline.setOnFinished(event1 -> {
closeSettingsTimeline.setOnFinished(event1 -> {
dashboardNode.toFront();
dashboardNode.toFront();
executor.execute(new Task<Void>() {
executor.execute(new Task<Void>() {
@Override
@Override
protected Void call() {
protected Void call() {
try {
try {
getSettingsBase().getClientsSettings().loadData();
getSettingsBase().getClientsSettings().loadData();
getSettingsBase().getGeneralSettings().loadDataFromConfig();
getSettingsBase().getGeneralSettings().loadDataFromConfig();
getSettingsBase().getPluginsSettings().loadPlugins();
getSettingsBase().getPluginsSettings().loadPlugins();
getSettingsBase().getThemesSettings().setThemes(getThemes());
getSettingsBase().getThemesSettings().setThemes(getThemes());
getSettingsBase().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsBase().getThemesSettings().setCurrentThemeFullName(getCurrentTheme().getFullName());
getSettingsBase().getThemesSettings().loadThemes();
getSettingsBase().getThemesSettings().loadThemes();
getSettingsBase().setDefaultTabToGeneral();
getSettingsBase().setDefaultTabToGeneral();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
catch (MinorException e)
catch (MinorException e)
{
{
handleMinorException(e);
handleMinorException(e);
}
}
return null;
return null;
}
}
});
});
});
});
return closeSettingsTimeline;
return closeSettingsTimeline;
}
}
@Override
@Override
public void setToggleStatus(boolean currentStatus, String profileID, String actionID, SocketAddress clientSocketAddress)
public void setToggleStatus(boolean currentStatus, String profileID, String actionID, SocketAddress clientSocketAddress)
throws MinorException
throws MinorException
{
{
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(
ClientConnection clientConnection = ClientConnections.getInstance().getClientConnectionBySocketAddress(
clientSocketAddress
clientSocketAddress
);
);
if(clientConnection == null)
if(clientConnection == null)
throw new ClientNotFoundException("setToggleStatus failed because no client found with given socket address");
throw new ClientNotFoundException("setToggleStatus failed because no client found with given socket address");
new Thread(new Task<Void>() {
new Thread(new Task<Void>() {
@Override
@Override
protected Void call()
protected Void call()
{
{
try
try
{
{
clientConnection.setToggleStatus(currentStatus, profileID, actionID);
clientConnection.setToggleStatus(currentStatus, profileID, actionID);
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
return null;
return null;
}
}
}).start();
}).start();
}
}
}
}
/*
/*
Config.java
Config.java
Contributor(s) : Debayan Sutradhar (@rnayabed)
Contributor(s) : Debayan Sutradhar (@rnayabed)
handler for config.xml
handler for config.xml
*/
*/
package com.stream_pi.server.io;
package com.stream_pi.server.io;
import java.awt.*;
import java.io.File;
import java.io.File;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamResult;
import com.stream_pi.server.Main;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.iohelper.IOHelper;
import com.stream_pi.util.xmlconfighelper.XMLConfigHelper;
import com.stream_pi.util.xmlconfighelper.XMLConfigHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Element;
public class Config
public class Config
{
{
private static Config instance = null;
private static Config instance = null;
private final File configFile;
private final File configFile;
private Document document;
private Document document;
private Config() throws SevereException {
private Config() throws SevereException {
try {
try {
configFile = new File(ServerInfo.getInstance().getPrePath()+"config.xml");
configFile = new File(ServerInfo.getInstance().getPrePath()+"config.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
document = docBuilder.parse(configFile);
document = docBuilder.parse(configFile);
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
throw new SevereException("Config", "unable to read config.xml");
throw new SevereException("Config", "unable to read config.xml");
}
}
}
}
public static synchronized Config getInstance() throws SevereException
public static synchronized Config getInstance() throws SevereException
{
{
if(instance == null)
if(instance == null)
instance = new Config();
instance = new Config();
return instance;
return instance;
}
}
Logger logger = Logger.getLogger(Config.class.getName());
Logger logger = Logger.getLogger(Config.class.getName());
public void save() throws SevereException {
public void save() throws SevereException {
try {
try {
logger.info("Saving config ...");
logger.info("Saving config ...");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(configFile);
Result output = new StreamResult(configFile);
Source input = new DOMSource(document);
Source input = new DOMSource(document);
transformer.transform(input, output);
transformer.transform(input, output);
logger.info("... Done!");
logger.info("... Done!");
} catch (Exception e) {
} catch (Exception e) {
throw new SevereException("Config", "unable to save config.xml");
throw new SevereException("Config", "unable to save config.xml");
}
}
}
}
//Getters
//Getters
//comms
//comms
private Element getCommsElement()
private Element getCommsElement()
{
{
return (Element) document.getElementsByTagName("comms").item(0);
return (Element) document.getElementsByTagName("comms").item(0);
}
}
public String getServerName()
public String getServerName()
{
{
return XMLConfigHelper.getStringProperty(getCommsElement(), "name",
return XMLConfigHelper.getStringProperty(getCommsElement(), "name",
getDefaultServerName(), false, true, document, configFile);
getDefaultServerName(), false, true, document, configFile);
}
}
public int getPort()
public int getPort()
{
{
return XMLConfigHelper.getIntProperty(getCommsElement(), "port",
return XMLConfigHelper.getIntProperty(getCommsElement(), "port",
getDefaultPort(), false, true, document, configFile);
getDefaultPort(), false, true, document, configFile);
}
}
//default getters
//default getters
public String getDefaultServerName()
public String getDefaultServerName()
{
{
return "Stream-Pi Server";
return "Stream-Pi Server";
}
}
public int getDefaultPort()
public int getDefaultPort()
{
{
return 2004;
return 2004;
}
}
private Element getServerElement()
private Element getServerElement()
{
{
return (Element) document.getElementsByTagName("server").item(0);
return (Element) document.getElementsByTagName("server").item(0);
}
}
//server
//server
private Element getActionGridElement()
private Element getActionGridElement()
{
{
return (Element) getServerElement().getElementsByTagName("action-grid").item(0);
return (Element) getServerElement().getElementsByTagName("action-grid").item(0);
}
}
public int getActionGridActionGap()
public int getActionGridActionGap()
{
{
return XMLConfigHelper.getIntProperty(getActionGridElement(), "gap",
return XMLConfigHelper.getIntProperty(getActionGridElement(), "gap",
getDefaultActionGridActionGap(), false, true, document, configFile);
getDefaultActionGridActionGap(), false, true, document, configFile);
}
}
public int getActionGridActionSize()
public int getActionGridActionSize()
{
{
return XMLConfigHelper.getIntProperty(getActionGridElement(), "size",
return XMLConfigHelper.getIntProperty(getActionGridElement(), "size",
getDefaultActionGridSize(), false, true, document, configFile);
getDefaultActionGridSize(), false, true, document, configFile);
}
}
public String getCurrentThemeFullName()
public String getCurrentThemeFullName()
{
{
return XMLConfigHelper.getStringProperty(getServerElement(), "current-theme-full-name",
return XMLConfigHelper.getStringProperty(getServerElement(), "current-theme-full-name",
getDefaultCurrentThemeFullName(), false, true, document, configFile);
getDefaultCurrentThemeFullName(), false, true, document, configFile);
}
}
public String getThemesPath()
public String getThemesPath()
{
{
return XMLConfigHelper.getStringProperty(getServerElement(), "themes-path",
return XMLConfigHelper.getStringProperty(getServerElement(), "themes-path",
getDefaultThemesPath(), false, true, document, configFile);
getDefaultThemesPath(), false, true, document, configFile);
}
}
public String getPluginsPath()
public String getPluginsPath()
{
{
return XMLConfigHelper.getStringProperty(getServerElement(), "plugins-path",
return XMLConfigHelper.getStringProperty(getServerElement(), "plugins-path",
getDefaultPluginsPath(), false, true, document, configFile);
getDefaultPluginsPath(), false, true, document, configFile);
}
}
//default getters
//default getters
public String getDefaultCurrentThemeFullName()
public String getDefaultCurrentThemeFullName()
{
{
return "com.stream_pi.defaultlight";
return "com.stream_pi.defaultlight";
}
}
public String getDefaultThemesPath()
public String getDefaultThemesPath()
{
{
return ServerInfo.getInstance().getPrePath()+"Themes/";
return ServerInfo.getInstance().getPrePath()+"Themes/";
}
}
public String getDefaultPluginsPath()
public String getDefaultPluginsPath()
{
{
return ServerInfo.getInstance().getPrePath()+"Plugins/";
return ServerInfo.getInstance().getPrePath()+"Plugins/";
}
}
//server > startup-window-size
//server > startup-window-size
private Element getStartupWindowSizeElement()
private Element getStartupWindowSizeElement()
{
{
return (Element) getServerElement().getElementsByTagName("startup-window-size").item(0);
return (Element) getServerElement().getElementsByTagName("startup-window-size").item(0);
}
}
public double getStartupWindowWidth()
public double getStartupWindowWidth()
{
{
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "width",
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "width",
getDefaultStartupWindowWidth(), false, true, document, configFile);
getDefaultStartupWindowWidth(), false, true, document, configFile);
}
}
public double getStartupWindowHeight()
public double getStartupWindowHeight()
{
{
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "height",
return XMLConfigHelper.getDoubleProperty(getStartupWindowSizeElement(), "height",
getDefaultStartupWindowHeight(), false, true, document, configFile);
getDefaultStartupWindowHeight(), false, true, document, configFile);
}
}
//default getters
//default getters
public int getDefaultStartupWindowWidth()
public int getDefaultStartupWindowWidth()
{
{
return 1024;
return 1024;
}
}
public int getDefaultStartupWindowHeight()
public int getDefaultStartupWindowHeight()
{
{
return 768;
return 768;
}
}
//others
//others
private Element getOthersElement()
private Element getOthersElement()
{
{
return (Element) document.getElementsByTagName("others").item(0);
return (Element) document.getElementsByTagName("others").item(0);
}
}
public boolean getStartOnBoot()
public boolean getStartOnBoot()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "start-on-boot",
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "start-on-boot",
getDefaultStartOnBoot(), false, true, document, configFile);
getDefaultStartOnBoot(), false, true, document, configFile);
}
}
public boolean getMinimiseToSystemTrayOnClose()
public boolean getMinimiseToSystemTrayOnClose()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "minimize-to-tray-on-close",
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "minimize-to-tray-on-close",
getDefaultMinimiseToSystemTrayOnClose(), false, true, document, configFile);
getDefaultMinimiseToSystemTrayOnClose(), false, true, document, configFile);
}
}
public boolean isFirstTimeUse()
public boolean isFirstTimeUse()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "first-time-use", true, false, true, document, configFile);
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "first-time-use", true, false, true, document, configFile);
}
}
public boolean isAllowDonatePopup()
public boolean isAllowDonatePopup()
{
{
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "allow-donate-popup", true, false, true, document, configFile);
return XMLConfigHelper.getBooleanProperty(getOthersElement(), "allow-donate-popup", true, false, true, document, configFile);
}
}
//default getters
//default getters
public boolean getDefaultStartOnBoot()
public boolean getDefaultStartOnBoot()
{
{
return false;
return false;
}
}
public boolean getDefaultMinimiseToSystemTrayOnClose()
public boolean getDefaultMinimiseToSystemTrayOnClose()
{
{
return true;
return true;
}
}
//Setters
//Setters
//comms
//comms
public void setServerName(String name)
public void setServerName(String name)
{
{
getCommsElement().getElementsByTagName("name").item(0).setTextContent(name);
getCommsElement().getElementsByTagName("name").item(0).setTextContent(name);
}
}
public void setServerPort(int port)
public void setServerPort(int port)
{
{
getCommsElement().getElementsByTagName("port").item(0).setTextContent(port+"");
getCommsElement().getElementsByTagName("port").item(0).setTextContent(port+"");
}
}
//server
//server
public int getDefaultActionGridActionGap()
public int getDefaultActionGridActionGap()
{
{
return 5;
return 5;
}
}
public int getDefaultActionGridSize()
public int getDefaultActionGridSize()
{
{
return 100;
return 100;
}
}
public void setActionGridSize(int size)
public void setActionGridSize(int size)
{
{
getActionGridElement().getElementsByTagName("size").item(0).setTextContent(size+"");
getActionGridElement().getElementsByTagName("size").item(0).setTextContent(size+"");
}
}
public void setActionGridGap(int size)
public void setActionGridGap(int size)
{
{
getActionGridElement().getElementsByTagName("gap").item(0).setTextContent(size+"");
getActionGridElement().getElementsByTagName("gap").item(0).setTextContent(size+"");
}
}
public void setPluginsPath(String path)
public void setPluginsPath(String path)
{
{
getServerElement().getElementsByTagName("plugins-path").item(0).setTextContent(path);
getServerElement().getElementsByTagName("plugins-path").item(0).setTextContent(path);
}
}
public void setThemesPath(String path)
public void setThemesPath(String path)
{
{
getServerElement().getElementsByTagName("themes-path").item(0).setTextContent(path);
getServerElement().getElementsByTagName("themes-path").item(0).setTextContent(path);
}
}
public void setCurrentThemeFullName(String themeName)
public void setCurrentThemeFullName(String themeName)
{
{
getServerElement().getElementsByTagName("current-theme-full-name").item(0).setTextContent(themeName);
getServerElement().getElementsByTagName("current-theme-full-name").item(0).setTextContent(themeName);
}
}
//server > startup-window-size
//server > startup-window-size
public void setStartupWindowSize(double width, double height)
public void setStartupWindowSize(double width, double height)
{
{
setStartupWindowWidth(width);
setStartupWindowWidth(width);
setStartupWindowHeight(height);
setStartupWindowHeight(height);
}
}
public void setStartupWindowWidth(double width)
public void setStartupWindowWidth(double width)
{
{
getStartupWindowSizeElement().getElementsByTagName("width").item(0).setTextContent(width+"");
getStartupWindowSizeElement().getElementsByTagName("width").item(0).setTextContent(width+"");
}
}
public void setStartupWindowHeight(double height)
public void setStartupWindowHeight(double height)
{
{
getStartupWindowSizeElement().getElementsByTagName("height").item(0).setTextContent(height+"");
getStartupWindowSizeElement().getElementsByTagName("height").item(0).setTextContent(height+"");
}
}
//others
//others
public void setStartupOnBoot(boolean value)
public void setStartupOnBoot(boolean value)
{
{
getOthersElement().getElementsByTagName("start-on-boot").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("start-on-boot").item(0).setTextContent(value+"");
}
}
public void setMinimiseToSystemTrayOnClose(boolean value)
public void setMinimiseToSystemTrayOnClose(boolean value)
{
{
getOthersElement().getElementsByTagName("minimize-to-tray-on-close").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("minimize-to-tray-on-close").item(0).setTextContent(value+"");
}
}
public void setFirstTimeUse(boolean value)
public void setFirstTimeUse(boolean value)
{
{
getOthersElement().getElementsByTagName("first-time-use").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("first-time-use").item(0).setTextContent(value+"");
}
}
public void setAllowDonatePopup(boolean value)
public void setAllowDonatePopup(boolean value)
{
{
getOthersElement().getElementsByTagName("allow-donate-popup").item(0).setTextContent(value+"");
getOthersElement().getElementsByTagName("allow-donate-popup").item(0).setTextContent(value+"");
}
}
public static void unzipToDefaultPrePath() throws Exception
{
IOHelper.unzip(Objects.requireNonNull(Main.class.getResourceAsStream("Default.zip")), ServerInfo.getInstance().getPrePath());
Config.getInstance().setThemesPath(ServerInfo.getInstance().getPrePath()+"Themes/");
Config.getInstance().setPluginsPath(ServerInfo.getInstance().getPrePath()+"Plugins/");
if(SystemTray.isSupported())
{
Config.getInstance().setMinimiseToSystemTrayOnClose(true);
}
Config.getInstance().save();
}
}
}
package com.stream_pi.server.window;
package com.stream_pi.server.window;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.connection.ServerListener;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.io.Config;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.info.ServerInfo;
import com.stream_pi.server.Main;
import com.stream_pi.server.Main;
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.theme_api.Theme;
import com.stream_pi.theme_api.Theme;
import com.stream_pi.theme_api.Themes;
import com.stream_pi.theme_api.Themes;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.alert.StreamPiAlert;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.MinorException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.exception.SevereException;
import com.stream_pi.util.iohelper.IOHelper;
import com.stream_pi.util.iohelper.IOHelper;
import com.stream_pi.util.loggerhelper.StreamPiLogFallbackHandler;
import com.stream_pi.util.loggerhelper.StreamPiLogFallbackHandler;
import com.stream_pi.util.loggerhelper.StreamPiLogFileHandler;
import com.stream_pi.util.loggerhelper.StreamPiLogFileHandler;
import com.stream_pi.util.platform.Platform;
import com.stream_pi.util.platform.Platform;
import javafx.application.HostServices;
import javafx.application.HostServices;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.beans.value.ObservableValue;
import javafx.scene.image.Image;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.Stage;
import java.awt.*;
import java.awt.*;
import java.io.File;
import java.io.File;
import java.util.logging.Logger;
import java.util.logging.Logger;
public abstract class Base extends StackPane implements ExceptionAndAlertHandler, ServerListener {
public abstract class Base extends StackPane implements ExceptionAndAlertHandler, ServerListener {
private Config config;
private Config config;
private ServerInfo serverInfo;
private ServerInfo serverInfo;
private Stage stage;
private Stage stage;
private HostServices hostServices;
private HostServices hostServices;
private SettingsBase settingsBase;
private SettingsBase settingsBase;
private DashboardBase dashboardBase;
private DashboardBase dashboardBase;
private StackPane alertStackPane;
private StackPane alertStackPane;
private StreamPiLogFileHandler logFileHandler = null;
private StreamPiLogFileHandler logFileHandler = null;
private StreamPiLogFallbackHandler logFallbackHandler = null;
private StreamPiLogFallbackHandler logFallbackHandler = null;
private Logger logger = null;
private Logger logger = null;
public Logger getLogger(){
public Logger getLogger(){
return logger;
return logger;
}
}
public void setHostServices(HostServices hostServices)
public void setHostServices(HostServices hostServices)
{
{
this.hostServices = hostServices;
this.hostServices = hostServices;
}
}
public HostServices getHostServices()
public HostServices getHostServices()
{
{
return hostServices;
return hostServices;
}
}
@Override
@Override
public void initLogger()
public void initLogger()
{
{
try
try
{
{
if(logFileHandler != null)
if(logFileHandler != null)
return;
return;
closeLogger();
closeLogger();
logger = Logger.getLogger("");
logger = Logger.getLogger("");
if(new File(ServerInfo.getInstance().getPrePath()).getAbsoluteFile().getParentFile().canWrite())
if(new File(ServerInfo.getInstance().getPrePath()).getAbsoluteFile().getParentFile().canWrite())
{
{
String path = ServerInfo.getInstance().getPrePath()+"../stream-pi-server.log";
String path = ServerInfo.getInstance().getPrePath()+"../stream-pi-server.log";
if(ServerInfo.getInstance().getPlatform() == Platform.ANDROID)
if(ServerInfo.getInstance().getPlatform() == Platform.ANDROID)
path = ServerInfo.getInstance().getPrePath()+"stream-pi-server.log";
path = ServerInfo.getInstance().getPrePath()+"stream-pi-server.log";
logFileHandler = new StreamPiLogFileHandler(path);
logFileHandler = new StreamPiLogFileHandler(path);
logger.addHandler(logFileHandler);
logger.addHandler(logFileHandler);
}
}
else
else
{
{
logFallbackHandler = new StreamPiLogFallbackHandler();
logFallbackHandler = new StreamPiLogFallbackHandler();
logger.addHandler(logFallbackHandler);
logger.addHandler(logFallbackHandler);
}
}
}
}
catch(Exception e)
catch(Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
logFallbackHandler = new StreamPiLogFallbackHandler();
logFallbackHandler = new StreamPiLogFallbackHandler();
logger.addHandler(logFallbackHandler);
logger.addHandler(logFallbackHandler);
}
}
}
}
public void closeLogger()
public void closeLogger()
{
{
if(logFileHandler != null)
if(logFileHandler != null)
logFileHandler.close();
logFileHandler.close();
else if(logFallbackHandler != null)
else if(logFallbackHandler != null)
logFallbackHandler.close();
logFallbackHandler.close();
}
}
public void initBase() throws SevereException
public void initBase() throws SevereException
{
{
stage = (Stage) getScene().getWindow();
stage = (Stage) getScene().getWindow();
getStage().getIcons().add(new Image(Main.class.getResourceAsStream("app_icon.png")));
getStage().getIcons().add(new Image(Main.class.getResourceAsStream("app_icon.png")));
getStage().setMinWidth(710);
getStage().setMinWidth(710);
getStage().setMinHeight(530);
getStage().setMinHeight(530);
serverInfo = ServerInfo.getInstance();
serverInfo = ServerInfo.getInstance();
settingsBase = new SettingsBase(getHostServices(), this, this);
settingsBase = new SettingsBase(getHostServices(), this, this);
settingsBase.prefWidthProperty().bind(widthProperty());
settingsBase.prefWidthProperty().bind(widthProperty());
settingsBase.prefHeightProperty().bind(heightProperty());
settingsBase.prefHeightProperty().bind(heightProperty());
dashboardBase = new DashboardBase(this, getHostServices());
dashboardBase = new DashboardBase(this, getHostServices());
dashboardBase.prefWidthProperty().bind(widthProperty());
dashboardBase.prefWidthProperty().bind(widthProperty());
dashboardBase.prefHeightProperty().bind(heightProperty());
dashboardBase.prefHeightProperty().bind(heightProperty());
alertStackPane = new StackPane();
alertStackPane = new StackPane();
alertStackPane.setVisible(false);
alertStackPane.setVisible(false);
StreamPiAlert.setParent(alertStackPane);
StreamPiAlert.setParent(alertStackPane);
getChildren().clear();
getChildren().clear();
getChildren().addAll(alertStackPane);
getChildren().addAll(alertStackPane);
initLogger();
initLogger();
checkPrePathDirectory();
checkPrePathDirectory();
getChildren().addAll(settingsBase, dashboardBase);
getChildren().addAll(settingsBase, dashboardBase);
config = Config.getInstance();
config = Config.getInstance();
initThemes();
initThemes();
stage.setWidth(config.getStartupWindowWidth());
stage.setWidth(config.getStartupWindowWidth());
stage.setHeight(config.getStartupWindowHeight());
stage.setHeight(config.getStartupWindowHeight());
stage.centerOnScreen();
stage.centerOnScreen();
dashboardBase.toFront();
dashboardBase.toFront();
}
}
private void checkPrePathDirectory() throws SevereException
private void checkPrePathDirectory() throws SevereException
{
{
try
try
{
{
File filex = new File(ServerInfo.getInstance().getPrePath());
File filex = new File(ServerInfo.getInstance().getPrePath());
if(!filex.exists())
if(!filex.exists())
{
{
boolean result = filex.mkdirs();
boolean result = filex.mkdirs();
if(result)
if(result)
{
{
IOHelper.unzip(Main.class.getResourceAsStream("Default.zip"), ServerInfo.getInstance().getPrePath());
Config.unzipToDefaultPrePath();
Config.getInstance().setThemesPath(ServerInfo.getInstance().getPrePath()+"Themes/");
Config.getInstance().setPluginsPath(ServerInfo.getInstance().getPrePath()+"Plugins/");
if(SystemTray.isSupported())
{
Config.getInstance().setMinimiseToSystemTrayOnClose(true);
}
Config.getInstance().save();
initLogger();
initLogger();
}
}
else
else
{
{
setPrefSize(300,300);
setPrefSize(300,300);
clearStylesheets();
clearStylesheets();
applyDefaultStylesheet();
applyDefaultStylesheet();
applyDefaultIconsStylesheet();
applyDefaultIconsStylesheet();
getStage().show();
getStage().show();
throw new SevereException("No storage permission. Give it!");
throw new SevereException("No storage permission. Give it!");
}
}
}
}
}
}
catch (Exception e)
catch (Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
throw new SevereException(e.getMessage());
throw new SevereException(e.getMessage());
}
}
}
}
public void initThemes() throws SevereException {
public void initThemes() throws SevereException {
clearStylesheets();
clearStylesheets();
registerThemes();
registerThemes();
applyDefaultStylesheet();
applyDefaultStylesheet();
applyDefaultTheme();
applyDefaultTheme();
applyDefaultIconsStylesheet();
applyDefaultIconsStylesheet();
}
}
@Override
@Override
public Stage getStage()
public Stage getStage()
{
{
return stage;
return stage;
}
}
public void applyDefaultStylesheet()
public void applyDefaultStylesheet()
{
{
logger.info("Applying default stylesheet ...");
logger.info("Applying default stylesheet ...");
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
getStylesheets().add(Main.class.getResource("style.css").toExternalForm());
getStylesheets().add(Main.class.getResource("style.css").toExternalForm());
logger.info("... Done!");
logger.info("... Done!");
}
}
public void applyDefaultIconsStylesheet()
public void applyDefaultIconsStylesheet()
{
{
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
Font.loadFont(Main.class.getResourceAsStream("Roboto.ttf"), 13);
getStylesheets().add(Main.class.getResource("default_icons.css").toExternalForm());
getStylesheets().add(Main.class.getResource("default_icons.css").toExternalForm());
}
}
public DashboardBase getDashboardBase()
public DashboardBase getDashboardBase()
{
{
return dashboardBase;
return dashboardBase;
}
}
public SettingsBase getSettingsBase()
public SettingsBase getSettingsBase()
{
{
return settingsBase;
return settingsBase;
}
}
public Config getConfig()
public Config getConfig()
{
{
return config;
return config;
}
}
public ServerInfo getServerInfo()
public ServerInfo getServerInfo()
{
{
return serverInfo;
return serverInfo;
}
}
private Theme currentTheme;
private Theme currentTheme;
public Theme getCurrentTheme()
public Theme getCurrentTheme()
{
{
return currentTheme;
return currentTheme;
}
}
public void applyTheme(Theme t)
public void applyTheme(Theme t)
{
{
logger.info("Applying theme '"+t.getFullName()+"' ...");
logger.info("Applying theme '"+t.getFullName()+"' ...");
if(t.getFonts() != null)
if(t.getFonts() != null)
{
{
for(String fontFile : t.getFonts())
for(String fontFile : t.getFonts())
{
{
Font.loadFont(fontFile.replace("%20",""), 13);
Font.loadFont(fontFile.replace("%20",""), 13);
}
}
}
}
currentTheme = t;
currentTheme = t;
getStylesheets().addAll(t.getStylesheets());
getStylesheets().addAll(t.getStylesheets());
logger.info("... Theme applied successfully!");
logger.info("... Theme applied successfully!");
}
}
public void clearStylesheets()
public void clearStylesheets()
{
{
getStylesheets().clear();
getStylesheets().clear();
}
}
Themes themes;
Themes themes;
public void registerThemes() throws SevereException
public void registerThemes() throws SevereException
{
{
logger.info("Loading themes ...");
logger.info("Loading themes ...");
themes = new Themes(getConfig().getThemesPath(), getConfig().getCurrentThemeFullName(), serverInfo.getMinThemeSupportVersion());
themes = new Themes(getConfig().getThemesPath(), getConfig().getCurrentThemeFullName(), serverInfo.getMinThemeSupportVersion());
if(!themes.getErrors().isEmpty())
if(!themes.getErrors().isEmpty())
{
{
StringBuilder themeErrors = new StringBuilder();
StringBuilder themeErrors = new StringBuilder();
for(MinorException eachException : themes.getErrors())
for(MinorException eachException : themes.getErrors())
{
{
themeErrors.append("\n * ").append(eachException.getShortMessage());
themeErrors.append("\n * ").append(eachException.getShortMessage());
}
}
if(themes.getIsBadThemeTheCurrentOne())
if(themes.getIsBadThemeTheCurrentOne())
{
{
themeErrors.append("\n\nReverted to default theme! (").append(getConfig().getDefaultCurrentThemeFullName()).append(")");
themeErrors.append("\n\nReverted to default theme! (").append(getConfig().getDefaultCurrentThemeFullName()).append(")");
getConfig().setCurrentThemeFullName(getConfig().getDefaultCurrentThemeFullName());
getConfig().setCurrentThemeFullName(getConfig().getDefaultCurrentThemeFullName());
getConfig().save();
getConfig().save();
}
}
handleMinorException(new MinorException("Theme Loading issues", themeErrors.toString()));
handleMinorException(new MinorException("Theme Loading issues", themeErrors.toString()));
}
}
logger.info("...Themes loaded successfully !");
logger.info("...Themes loaded successfully !");
}
}
public Themes getThemes()
public Themes getThemes()
{
{
return themes;
return themes;
}
}
public void applyDefaultTheme()
public void applyDefaultTheme()
{
{
logger.info("Applying default theme ...");
logger.info("Applying default theme ...");
boolean foundTheme = false;
boolean foundTheme = false;
for(Theme t: themes.getThemeList())
for(Theme t: themes.getThemeList())
{
{
if(t.getFullName().equals(config.getCurrentThemeFullName()))
if(t.getFullName().equals(config.getCurrentThemeFullName()))
{
{
foundTheme = true;
foundTheme = true;
applyTheme(t);
applyTheme(t);
break;
break;
}
}
}
}
if(!foundTheme)
if(!foundTheme)
{
{
logger.info("Theme not found. reverting to light theme ...");
logger.info("Theme not found. reverting to light theme ...");
try {
try {
Config.getInstance().setCurrentThemeFullName("com.streampi.DefaultLight");
Config.getInstance().setCurrentThemeFullName("com.streampi.DefaultLight");
Config.getInstance().save();
Config.getInstance().save();
applyDefaultTheme();
applyDefaultTheme();
}
}
catch (SevereException e)
catch (SevereException e)
{
{
handleSevereException(e);
handleSevereException(e);
}
}
}
}
}
}
}
}