diff options
author | Marko Živković <[email protected]> | 2015-03-04 01:41:52 +0000 |
---|---|---|
committer | Marko Živković <[email protected]> | 2015-03-04 01:41:52 +0000 |
commit | 23316d54f1070101a4e5d618e8689d8edaea0b34 (patch) | |
tree | 1fe0b9d10a4b8691988735b4edb9243d116158ae | |
parent | 094911feca43980c4f81582dfd8cdc0ad8faed71 (diff) |
Fix USB drive detection problems by using USBWorkspaceManager and refactoring related things
git-svn-id: https://svn.code.sf.net/p/xlogo4schools/svn/trunk@35 3b0d7934-f7ef-4143-9606-b51f2e2281fd
23 files changed, 626 insertions, 600 deletions
diff --git a/logo/src/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java b/logo/src/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java index a0d3de1..34b0c53 100644 --- a/logo/src/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java +++ b/logo/src/net/samuelcampos/usbdrivedectector/USBDeviceDetectorManager.java @@ -124,4 +124,11 @@ public class USBDeviceDetectorManager { } } + + /** + * @author Marko Zivkovic + */ + public synchronized void stop() { + timer.cancel(); + } } diff --git a/logo/src/xlogo/AppSettings.java b/logo/src/xlogo/AppSettings.java index aa1beba..cf0bccc 100644 --- a/logo/src/xlogo/AppSettings.java +++ b/logo/src/xlogo/AppSettings.java @@ -36,26 +36,51 @@ public class AppSettings implements Observable<AppSettings.AppProperty>{ private WorkspaceConfig wc;
- private PropertyChangeListener languageListener = () -> {
- setLanguage(wc.getLanguage());
+ private PropertyChangeListener languageListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ setLanguage(wc.getLanguage());
+ }
};
- private PropertyChangeListener logoLanguageListener= () -> {
- setLogoLanguage(wc.getLogoLanguage());
+ private PropertyChangeListener logoLanguageListener= new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ setLogoLanguage(wc.getLogoLanguage());
+ }
};
- private PropertyChangeListener syntaxListener = () -> {
- setSyntaxHighlightingStyles(wc.getSyntaxHighlightStyles());
+ private PropertyChangeListener syntaxListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ setSyntaxHighlightingStyles(wc.getSyntaxHighlightStyles());
+ }
};
- private PropertyChangeListener workspaceListener = () -> {
- setWorkspace(WSManager.getWorkspaceConfig());
+ private PropertyChangeListener workspaceListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ setWorkspace(WSManager.getWorkspaceConfig());
+ }
+ };
+
+ private PropertyChangeListener workspaceListListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ publisher.publishEvent(AppProperty.WORKSPACE_LIST);
+ }
};
- public AppSettings() {
+ private AppSettings() {
GlobalConfig gc = WSManager.getGlobalConfig();
WorkspaceConfig wc = WSManager.getWorkspaceConfig();
gc.addPropertyChangeListener(GlobalProperty.CURRENT_WORKSPACE, workspaceListener);
+ gc.addPropertyChangeListener(GlobalProperty.WORKSPACES, workspaceListListener);
if (wc != null) {
setWorkspace(gc.getCurrentWorkspace().get());
}
@@ -185,10 +210,10 @@ public class AppSettings implements Observable<AppSettings.AppProperty>{ * * * * * * */
public enum AppProperty {
- LANGUAGE, LOGO_LANGUAGE, SYNTAX_HIGHLIGHTING, FONT, WORKSPACE;
+ LANGUAGE, LOGO_LANGUAGE, SYNTAX_HIGHLIGHTING, FONT, WORKSPACE, WORKSPACE_LIST;
}
- private transient final PropertyChangePublisher<AppProperty> publisher = new PropertyChangePublisher<>();
+ private transient final PropertyChangePublisher<AppProperty> publisher = new PropertyChangePublisher<AppProperty>();
@Override
public void addPropertyChangeListener(AppProperty property, PropertyChangeListener listener) {
diff --git a/logo/src/xlogo/Application.java b/logo/src/xlogo/Application.java index cbc239f..3aa9f51 100644 --- a/logo/src/xlogo/Application.java +++ b/logo/src/xlogo/Application.java @@ -155,10 +155,17 @@ public class Application extends X4SFrame { focusCommandLine(); } + @Override public JFrame getFrame() { return mainFrame; } + @Override + public void closeFrame(){ + WSManager.getInstance().stopEverything(); + super.closeFrame(); + } + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * INIT * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ @@ -1096,6 +1103,7 @@ public class Application extends X4SFrame { public void closeWindow() { WSManager storageManager = WSManager.getInstance(); + storageManager.stopEverything(); try { String openFile = userSpace.getOpenFileName(); if (openFile != null) { diff --git a/logo/src/xlogo/Popup.java b/logo/src/xlogo/Popup.java index 480b869..f62990c 100644 --- a/logo/src/xlogo/Popup.java +++ b/logo/src/xlogo/Popup.java @@ -38,7 +38,6 @@ import javax.swing.text.BadLocationException; import javax.swing.JPopupMenu; import xlogo.storage.WSManager; -import xlogo.storage.workspace.Language; import xlogo.storage.workspace.LogoLanguage; import java.awt.event.*; diff --git a/logo/src/xlogo/gui/components/ColorStyleSelectionPanel.java b/logo/src/xlogo/gui/components/ColorStyleSelectionPanel.java index 7d9b024..bd5e039 100644 --- a/logo/src/xlogo/gui/components/ColorStyleSelectionPanel.java +++ b/logo/src/xlogo/gui/components/ColorStyleSelectionPanel.java @@ -55,13 +55,13 @@ public class ColorStyleSelectionPanel { private Integer[] intArray = new Integer[17]; private JButton bchoisir = new JButton( Logo.messages.getString("pref.highlight.other")); - private JComboBox<Integer> combo_couleur; + private JComboBox combo_couleur; private String[] msg = { Logo.messages.getString("style.none"), Logo.messages.getString("style.bold"), Logo.messages.getString("style.italic"), Logo.messages.getString("style.underline") }; - private JComboBox<String> style = new JComboBox<>(msg); + private JComboBox style = new JComboBox(msg); private JLabel titre = new JLabel(); private Color couleur_perso = Color.WHITE; private GridBagLayout gb = new GridBagLayout(); @@ -79,7 +79,7 @@ public class ColorStyleSelectionPanel { //titre.setFont(font); titre.setText(title + ":"); - combo_couleur = new JComboBox<>(intArray); + combo_couleur = new JComboBox(intArray); ComboBoxRenderer renderer = new ComboBoxRenderer(); combo_couleur.setRenderer(renderer); setColorAndStyle(rgb, sty); @@ -159,7 +159,7 @@ public class ColorStyleSelectionPanel { DrawPanel.defaultColors[combo_couleur.getSelectedIndex()]); } - private class ComboBoxRenderer extends JPanel implements ListCellRenderer<Object> { + private class ComboBoxRenderer extends JPanel implements ListCellRenderer { private static final long serialVersionUID = 1L; int id = 0; @@ -168,7 +168,7 @@ public class ColorStyleSelectionPanel { setPreferredSize(new Dimension(50, 20)); } - public Component getListCellRendererComponent(JList<?> list, Object value, + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { // Get the selected index. (The index param isn't // always valid, so just use the value.) diff --git a/logo/src/xlogo/gui/components/X4SGui.java b/logo/src/xlogo/gui/components/X4SGui.java index 9aacaae..bef236e 100644 --- a/logo/src/xlogo/gui/components/X4SGui.java +++ b/logo/src/xlogo/gui/components/X4SGui.java @@ -67,8 +67,11 @@ public abstract class X4SGui { stopListenForLanguageChangeEvents();
}
- private PropertyChangeListener languageChangeListener = () -> {
- setText();
+ private PropertyChangeListener languageChangeListener = new PropertyChangeListener(){
+ @Override
+ public void propertyChanged() {
+ setText();
+ }
};
/**
diff --git a/logo/src/xlogo/gui/preferences/AbstractPanelColor.java b/logo/src/xlogo/gui/preferences/AbstractPanelColor.java index d8b097b..0728e3d 100644 --- a/logo/src/xlogo/gui/preferences/AbstractPanelColor.java +++ b/logo/src/xlogo/gui/preferences/AbstractPanelColor.java @@ -47,7 +47,7 @@ public abstract class AbstractPanelColor extends JPanel implements ActionListene // private ImageIcon[] images=new ImageIcon[17]; private Integer[] intArray = new Integer[17]; private JButton bchoisir = new JButton(Logo.messages.getString("pref.highlight.other")); - protected JComboBox<Integer> combo_couleur; + protected JComboBox combo_couleur; private Color couleur_perso = Color.WHITE; public AbstractPanelColor(Color c) { @@ -55,7 +55,7 @@ public abstract class AbstractPanelColor extends JPanel implements ActionListene for (int i = 0; i < 17; i++) { intArray[i] = new Integer(i); } - combo_couleur = new JComboBox<>(intArray); + combo_couleur = new JComboBox(intArray); ComboBoxRenderer renderer = new ComboBoxRenderer(); combo_couleur.setRenderer(renderer); setColorAndStyle(c); diff --git a/logo/src/xlogo/gui/welcome/WelcomeScreen.java b/logo/src/xlogo/gui/welcome/WelcomeScreen.java index 61f27b6..b9eb304 100644 --- a/logo/src/xlogo/gui/welcome/WelcomeScreen.java +++ b/logo/src/xlogo/gui/welcome/WelcomeScreen.java @@ -32,6 +32,7 @@ import javax.swing.text.JTextComponent; import java.awt.*; import java.io.IOException; +import xlogo.AppSettings.AppProperty; import xlogo.gui.components.X4SFrame; import xlogo.interfaces.Observable.PropertyChangeListener; import xlogo.messages.MessageKeys; @@ -39,10 +40,10 @@ import xlogo.messages.async.dialog.DialogMessenger; import xlogo.storage.Storable; import xlogo.storage.WSManager; import xlogo.storage.global.GlobalConfig; -import xlogo.storage.global.GlobalConfig.GlobalProperty; import xlogo.storage.workspace.WorkspaceConfig; import xlogo.utils.Utils; import xlogo.utils.WebPage; +import xlogo.AppSettings; import xlogo.Application; /** @@ -61,8 +62,8 @@ public class WelcomeScreen extends X4SFrame { private JLabel workspace; private JLabel username; - private JComboBox<String> workspaceSelection; - private JComboBox<String> userSelection; + private JComboBox workspaceSelection; + private JComboBox userSelection; private JButton openWorkspaceSettingsBtn; private JButton enterButton; @@ -80,12 +81,13 @@ public class WelcomeScreen extends X4SFrame { private PropertyChangeListener onWorkspaceListChangeListener; private PropertyChangeListener onEnterWorkspaceListener; - + private WSManager wsManager; /** * * @param listener to be informed when the user is ready to enter the application */ public WelcomeScreen(ActionListener onApplicationEnterListener) { + wsManager = WSManager.getInstance(); this.onApplicationEnterListener = onApplicationEnterListener; } @@ -102,13 +104,12 @@ public class WelcomeScreen extends X4SFrame { @Override public void dispose() { - try { - WSManager.getInstance().storeAllSettings(); - } - catch (IOException e) { - DialogMessenger.getInstance().dispatchMessage(translate("ws.error.title"), - translate("storage.could.not.store.gc")); - } + //try { + //} + //catch (IOException e) { + // DialogMessenger.getInstance().dispatchMessage(translate("ws.error.title"), + // translate("storage.could.not.store.gc")); + //} super.dispose(); } @@ -121,8 +122,8 @@ public class WelcomeScreen extends X4SFrame { workspace = new JLabel("Workspace"); username = new JLabel("User"); - workspaceSelection = new JComboBox<>(); - userSelection = new JComboBox<>(); + workspaceSelection = new JComboBox(); + userSelection = new JComboBox(); openWorkspaceSettingsBtn = new JButton("Settings"); enterButton = new JButton("Enter"); @@ -209,24 +210,31 @@ public class WelcomeScreen extends X4SFrame { @Override protected void initEventListeners() { - GlobalConfig gc = WSManager.getGlobalConfig(); - - onWorkspaceListChangeListener = () -> { - ignoreGuiEvents = true; - populateWorkspaceList(); - populateUserList(); - ignoreGuiEvents = false; + onWorkspaceListChangeListener = new PropertyChangeListener(){ + + @Override + public void propertyChanged() { + ignoreGuiEvents = true; + populateWorkspaceList(); + populateUserList(); + ignoreGuiEvents = false; + } }; - onEnterWorkspaceListener = () -> { - ignoreGuiEvents = true; - populateWorkspaceList(); - populateUserList(); - ignoreGuiEvents = false; + onEnterWorkspaceListener = new PropertyChangeListener(){ + + @Override + public void propertyChanged() { + ignoreGuiEvents = true; + populateWorkspaceList(); + populateUserList(); + ignoreGuiEvents = false; + } }; - - gc.addPropertyChangeListener(GlobalProperty.CURRENT_WORKSPACE, onEnterWorkspaceListener); - gc.addPropertyChangeListener(GlobalProperty.WORKSPACES, onWorkspaceListChangeListener); + + AppSettings as = AppSettings.getInstance(); + as.addPropertyChangeListener(AppProperty.WORKSPACE, onEnterWorkspaceListener); + as.addPropertyChangeListener(AppProperty.WORKSPACE_LIST, onWorkspaceListChangeListener); workspaceSelection.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e) { @@ -310,7 +318,7 @@ public class WelcomeScreen extends X4SFrame { private void populateWorkspaceList() { GlobalConfig gc = WSManager.getGlobalConfig(); String[] workspaces = gc.getAllWorkspaces(); - workspaceSelection.setModel(new DefaultComboBoxModel<>(workspaces)); + workspaceSelection.setModel(new DefaultComboBoxModel(workspaces)); selectCurrentWorkspace(); } @@ -331,21 +339,21 @@ public class WelcomeScreen extends X4SFrame { } else { users = new String[0]; } - userSelection.setModel(new DefaultComboBoxModel<>(users)); + userSelection.setModel(new DefaultComboBoxModel(users)); userSelection.setSelectedItem(lastUser); enterButton.setEnabled(lastUser != null && lastUser.length() > 0); userSelection.setEditable(isUserCreationAllowed); } protected void enterWorkspace(String workspaceName) { - try { - WSManager.getInstance().enterWorkspace(workspaceName); + //try { + wsManager.enterWorkspace(workspaceName); populateUserList(); - } - catch (IOException e) { - DialogMessenger.getInstance().dispatchMessage(translate("ws.error.title"), - translate("ws.settings.could.not.enter.wp") + "\n\n" + e.toString()); - } + //} + //catch (IOException e) { + // DialogMessenger.getInstance().dispatchMessage(translate("ws.error.title"), + // translate("ws.settings.could.not.enter.wp") + "\n\n" + e.toString()); + //} } private synchronized void showWorkspaceSettings() { @@ -411,18 +419,19 @@ public class WelcomeScreen extends X4SFrame { } // The following is in case the user entered a new name : Need to create user first - WorkspaceConfig wc = WSManager.getInstance().getWorkspaceConfigInstance(); - if (!wc.existsUserLogically(username)) - WSManager.getInstance().createUser(username); - - try { - WSManager.getInstance().enterUserSpace(username); - } - catch (IOException e) { - DialogMessenger.getInstance().dispatchMessage(translate("ws.error.title"), - translate("welcome.could.not.enter.user") + "\n" + e.toString()); - return; + WorkspaceConfig wc = WSManager.getWorkspaceConfig(); + if (!wc.existsUserLogically(username)){ + wsManager.createUser(username); } + + //try { + wsManager.enterUserSpace(username); + //} + //catch (IOException e) { + // DialogMessenger.getInstance().dispatchMessage(translate("ws.error.title"), + // translate("welcome.could.not.enter.user") + "\n" + e.toString()); + // return; + //} cleanupAfterEnter(); } @@ -432,12 +441,14 @@ public class WelcomeScreen extends X4SFrame { // TODO remove each reference to workspace settings workspaceSettings = null; } - WSManager.getGlobalConfig().removePropertyChangeListener(GlobalProperty.CURRENT_WORKSPACE, onEnterWorkspaceListener); - WSManager.getGlobalConfig().removePropertyChangeListener(GlobalProperty.WORKSPACES, onWorkspaceListChangeListener); - try { - WSManager.getInstance().storeAllSettings(); - } - catch (IOException ignore) { } + AppSettings as = AppSettings.getInstance(); + as.removePropertyChangeListener(AppProperty.WORKSPACE, onEnterWorkspaceListener); + as.removePropertyChangeListener(AppProperty.WORKSPACE_LIST, onWorkspaceListChangeListener); + //try { + wsManager.storeAllSettings(); + wsManager.enterApplication(); + //} + //catch (IOException ignore) { } onApplicationEnterListener.actionPerformed(new ActionEvent(this, 0, null)); } diff --git a/logo/src/xlogo/gui/welcome/WorkspaceSettings.java b/logo/src/xlogo/gui/welcome/WorkspaceSettings.java index 39b9647..025626c 100644 --- a/logo/src/xlogo/gui/welcome/WorkspaceSettings.java +++ b/logo/src/xlogo/gui/welcome/WorkspaceSettings.java @@ -29,7 +29,6 @@ package xlogo.gui.welcome; import java.awt.Toolkit;
import java.awt.event.ActionListener;
-import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
@@ -39,7 +38,6 @@ import xlogo.gui.welcome.settings.tabs.SyntaxHighlightingTab; import xlogo.gui.welcome.settings.tabs.ContestTab;
import xlogo.gui.welcome.settings.tabs.GlobalTab;
import xlogo.gui.welcome.settings.tabs.WorkspaceTab;
-import xlogo.messages.async.dialog.DialogMessenger;
import xlogo.storage.WSManager;
import xlogo.utils.Utils;
@@ -84,13 +82,13 @@ public class WorkspaceSettings extends X4SFrame { @Override
public void dispose()
{
- try {
+ //try {
WSManager.getInstance().storeAllSettings();
- } catch (IOException e) {
- DialogMessenger.getInstance().dispatchMessage(
- translate("ws.error.title"),
- translate("storage.could.not.store.gc"));
- }
+ //} catch (IOException e) {
+ // DialogMessenger.getInstance().dispatchMessage(
+ // translate("ws.error.title"),
+ // translate("storage.could.not.store.gc"));
+ //}
listener.actionPerformed(null);
super.dispose();
diff --git a/logo/src/xlogo/gui/welcome/settings/tabs/AbstractWorkspacePanel.java b/logo/src/xlogo/gui/welcome/settings/tabs/AbstractWorkspacePanel.java index 6dc6835..b0eb029 100644 --- a/logo/src/xlogo/gui/welcome/settings/tabs/AbstractWorkspacePanel.java +++ b/logo/src/xlogo/gui/welcome/settings/tabs/AbstractWorkspacePanel.java @@ -30,19 +30,19 @@ package xlogo.gui.welcome.settings.tabs; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
-import java.io.IOException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
+import xlogo.AppSettings;
+import xlogo.AppSettings.AppProperty;
import xlogo.gui.components.X4SComponent;
import xlogo.interfaces.Observable.PropertyChangeListener;
import xlogo.messages.async.dialog.DialogMessenger;
import xlogo.storage.Storable;
import xlogo.storage.WSManager;
import xlogo.storage.global.GlobalConfig;
-import xlogo.storage.global.GlobalConfig.GlobalProperty;
import xlogo.storage.workspace.WorkspaceConfig;
public abstract class AbstractWorkspacePanel extends X4SComponent{
@@ -50,7 +50,7 @@ public abstract class AbstractWorkspacePanel extends X4SComponent{ private PropertyChangeListener enterWorkspaceListener;
private PropertyChangeListener workspaceListChangeListener;
- protected abstract JComboBox<String> getWorkspaceSelection();
+ protected abstract JComboBox getWorkspaceSelection();
private boolean ignoreGuiEvents = false;
@@ -72,37 +72,42 @@ public abstract class AbstractWorkspacePanel extends X4SComponent{ }
});
- enterWorkspaceListener = () -> {
- ignoreGuiEvents = true;
- if (WSManager.getWorkspaceConfig() != null){
- enableComponents();
- } else {
- disableComponents();
+ enterWorkspaceListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ ignoreGuiEvents = true;
+ if (WSManager.getWorkspaceConfig() != null){
+ enableComponents();
+ } else {
+ disableComponents();
+ }
+ selectCurrentWorkspace();
+ ignoreGuiEvents = false;
}
- selectCurrentWorkspace();
- ignoreGuiEvents = false;
};
- workspaceListChangeListener = () -> {
- ignoreGuiEvents = true;
- populateWorkspaceList();
- ignoreGuiEvents = false;
+ workspaceListChangeListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ ignoreGuiEvents = true;
+ populateWorkspaceList();
+ ignoreGuiEvents = false;
+ }
};
-
- final GlobalConfig gc = WSManager.getGlobalConfig();
-
- gc.addPropertyChangeListener(GlobalProperty.WORKSPACES, workspaceListChangeListener);
-
- gc.addPropertyChangeListener(GlobalProperty.CURRENT_WORKSPACE, enterWorkspaceListener);
+ AppSettings as = AppSettings.getInstance();
+ as.addPropertyChangeListener(AppProperty.WORKSPACE_LIST, workspaceListChangeListener);
+ as.addPropertyChangeListener(AppProperty.WORKSPACE, enterWorkspaceListener);
}
@Override
public void stopEventListeners()
{
super.stopEventListeners();
- GlobalConfig gc = WSManager.getGlobalConfig();
- gc.removePropertyChangeListener(GlobalProperty.WORKSPACES, workspaceListChangeListener);
- gc.removePropertyChangeListener(GlobalProperty.CURRENT_WORKSPACE, enterWorkspaceListener);
+ AppSettings as = AppSettings.getInstance();
+ as.removePropertyChangeListener(AppProperty.WORKSPACE_LIST, workspaceListChangeListener);
+ as.removePropertyChangeListener(AppProperty.WORKSPACE, enterWorkspaceListener);
}
protected abstract void setValues();
@@ -114,7 +119,7 @@ public abstract class AbstractWorkspacePanel extends X4SComponent{ protected void populateWorkspaceList() {
GlobalConfig gc = WSManager.getGlobalConfig();
String[] workspaces = gc.getAllWorkspaces();
- getWorkspaceSelection().setModel(new DefaultComboBoxModel<String>(workspaces));
+ getWorkspaceSelection().setModel(new DefaultComboBoxModel(workspaces));
selectCurrentWorkspace();
}
@@ -194,24 +199,19 @@ public abstract class AbstractWorkspacePanel extends X4SComponent{ }
protected void enterWorkspace(String wsName) {
- try {
- // enter workspace
- WSManager.getInstance().enterWorkspace(wsName);
- WorkspaceConfig wc = WSManager.getInstance().getWorkspaceConfigInstance();
- if (wc == null)
- {
- disableComponents();
- return;
- }
- enableComponents();
- setValues();
- } catch (IOException e) {
+ // enter workspace
+ WSManager.getInstance().enterWorkspace(wsName);
+ WorkspaceConfig wc = WSManager.getInstance().getWorkspaceConfigInstance();
+ if (wc == null)
+ {
+ disableComponents();
DialogMessenger.getInstance().dispatchMessage(
translate("ws.error.title"),
- translate("ws.settings.could.not.enter.wp") + e.toString());
- disableComponents();
+ translate("ws.settings.could.not.enter.wp"));
+ return;
}
-
+ enableComponents();
+ setValues();
}
protected void addWorkspace() {
@@ -262,15 +262,15 @@ public abstract class AbstractWorkspacePanel extends X4SComponent{ return;
}
// dir exists & wsName doesn't exist yet => fine to create WS now
- try {
+ //try {
WSManager.getInstance().createWorkspace(dir, wsName);
populateWorkspaceList();
- } catch (IOException e) {
+ /*} catch (IOException e) {
DialogMessenger.getInstance().dispatchMessage(
translate("ws.error.title"),
translate("ws.settings.could.not.create.ws"));
return;
- }
+ }*/
}
diff --git a/logo/src/xlogo/gui/welcome/settings/tabs/ContestTab.java b/logo/src/xlogo/gui/welcome/settings/tabs/ContestTab.java index 9583de5..7b8c0db 100644 --- a/logo/src/xlogo/gui/welcome/settings/tabs/ContestTab.java +++ b/logo/src/xlogo/gui/welcome/settings/tabs/ContestTab.java @@ -46,7 +46,7 @@ public class ContestTab extends AbstractWorkspacePanel { JPanel component;
JLabel workspaceLabel;
- JComboBox<String> workspaceSelection;
+ JComboBox workspaceSelection;
JLabel nOfFilesLabel;
JSpinner nOfFileSpinner;
JLabel nOfBonusFilesLabel;
@@ -58,7 +58,7 @@ public class ContestTab extends AbstractWorkspacePanel { }
@Override
- protected JComboBox<String> getWorkspaceSelection() {
+ protected JComboBox getWorkspaceSelection() {
return workspaceSelection;
}
@@ -76,7 +76,7 @@ public class ContestTab extends AbstractWorkspacePanel { component = new JPanel();
workspaceLabel = new JLabel();
- workspaceSelection = new JComboBox<>();
+ workspaceSelection = new JComboBox();
nOfFilesLabel = new JLabel();
nOfFileSpinner = new JSpinner(new SpinnerNumberModel(contestFiles, 0, 100, 1));
diff --git a/logo/src/xlogo/gui/welcome/settings/tabs/SyntaxHighlightingTab.java b/logo/src/xlogo/gui/welcome/settings/tabs/SyntaxHighlightingTab.java index 025135f..1b6c27a 100644 --- a/logo/src/xlogo/gui/welcome/settings/tabs/SyntaxHighlightingTab.java +++ b/logo/src/xlogo/gui/welcome/settings/tabs/SyntaxHighlightingTab.java @@ -54,7 +54,7 @@ public class SyntaxHighlightingTab extends AbstractWorkspacePanel{ private JPanel component;
private JLabel workspaceLabel;
- private JComboBox<String> workspaceSelection;
+ private JComboBox workspaceSelection;
private ColorStyleSelectionPanel commentStyleSelection;
private ColorStyleSelectionPanel braceStyleSelection;
private ColorStyleSelectionPanel primitiveStyleSelection;
@@ -85,7 +85,7 @@ public class SyntaxHighlightingTab extends AbstractWorkspacePanel{ //Font font = wc.getFont();
component = new JPanel();
workspaceLabel = new JLabel();
- workspaceSelection = new JComboBox<>();
+ workspaceSelection = new JComboBox();
commentStyleSelection=new ColorStyleSelectionPanel(syntaxHighlighting.getCommentColor(), syntaxHighlighting.getCommentStyle(), translate("pref.highlight.comment"));
braceStyleSelection=new ColorStyleSelectionPanel(syntaxHighlighting.getBraceColor(), syntaxHighlighting.getBraceStyle(), translate("pref.highlight.parenthesis"));
primitiveStyleSelection=new ColorStyleSelectionPanel(syntaxHighlighting.getPrimitiveColor(), syntaxHighlighting.getPrimitiveStyle(), translate("pref.highlight.primitive"));
@@ -191,14 +191,22 @@ public class SyntaxHighlightingTab extends AbstractWorkspacePanel{ }
});
- logoLanguageChangeListener = () -> {
- updateLogoLanguage();
+ logoLanguageChangeListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ updateLogoLanguage();
+ }
};
AppSettings.getInstance().addPropertyChangeListener(AppProperty.LOGO_LANGUAGE, logoLanguageChangeListener);
- syntaxHighlightChangeListener = () -> {
- updateSyntaxHighlightingPreview();
+ syntaxHighlightChangeListener = new PropertyChangeListener(){
+
+ @Override
+ public void propertyChanged() {
+ updateSyntaxHighlightingPreview();
+ }
};
AppSettings.getInstance().addPropertyChangeListener(AppProperty.SYNTAX_HIGHLIGHTING, syntaxHighlightChangeListener);
@@ -248,7 +256,7 @@ public class SyntaxHighlightingTab extends AbstractWorkspacePanel{ }
@Override
- protected JComboBox<String> getWorkspaceSelection() {
+ protected JComboBox getWorkspaceSelection() {
return workspaceSelection;
}
diff --git a/logo/src/xlogo/gui/welcome/settings/tabs/WorkspaceTab.java b/logo/src/xlogo/gui/welcome/settings/tabs/WorkspaceTab.java index 3651568..431bebd 100644 --- a/logo/src/xlogo/gui/welcome/settings/tabs/WorkspaceTab.java +++ b/logo/src/xlogo/gui/welcome/settings/tabs/WorkspaceTab.java @@ -50,32 +50,32 @@ import xlogo.storage.workspace.WorkspaceConfig; public class WorkspaceTab extends AbstractWorkspacePanel {
- JPanel component;
+ JPanel component;
- JLabel workspaceLabel;
- JLabel wsLocationLabel;
- JLabel wsLanguageLabel;
- JLabel wsLogoLanguageLabel;
- JLabel wsBackupLabel;
- JLabel userLabel;
+ JLabel workspaceLabel;
+ JLabel wsLocationLabel;
+ JLabel wsLanguageLabel;
+ JLabel wsLogoLanguageLabel;
+ JLabel wsBackupLabel;
+ JLabel userLabel;
- JButton addWorkspaceBtn;
- JButton addUserBtn;
+ JButton addWorkspaceBtn;
+ JButton addUserBtn;
- JButton removeWorkspaceBtn;
- JButton removeUserBtn;
+ JButton removeWorkspaceBtn;
+ JButton removeUserBtn;
- JButton importWorkspaceBtn;
- JButton importUserBtn;
+ JButton importWorkspaceBtn;
+ JButton importUserBtn;
- JComboBox<String> workspaceSelection;
- JComboBox<String> userSelection;
- JLabel wsLocation;
- JFileChooser wsLocationChooser;
- JComboBox<Language> languageSelection;
- JComboBox<LogoLanguage> logoLanguageSelection;
- JComboBox<NumberOfBackups> nOfBackupsSelection;
- JCheckBox userCreatable;
+ JComboBox workspaceSelection;
+ JComboBox userSelection;
+ JLabel wsLocation;
+ JFileChooser wsLocationChooser;
+ JComboBox languageSelection;
+ JComboBox logoLanguageSelection;
+ JComboBox nOfBackupsSelection;
+ JCheckBox userCreatable;
public WorkspaceTab() {
super();
@@ -87,7 +87,7 @@ public class WorkspaceTab extends AbstractWorkspacePanel { }
@Override
- protected JComboBox<String> getWorkspaceSelection() {
+ protected JComboBox getWorkspaceSelection() {
return workspaceSelection;
}
@@ -111,21 +111,22 @@ public class WorkspaceTab extends AbstractWorkspacePanel { importWorkspaceBtn = new JButton("Import");
importUserBtn = new JButton("Import");
- workspaceSelection = new JComboBox<>();
- userSelection = new JComboBox<>();
+ workspaceSelection = new JComboBox();
+ userSelection = new JComboBox();
wsLocation = new JLabel();
wsLocationChooser = new JFileChooser();
- languageSelection = new JComboBox<>(Language.values());
- logoLanguageSelection = new JComboBox<>(LogoLanguage.values());
- nOfBackupsSelection = new JComboBox<>(NumberOfBackups.values());
+ languageSelection = new JComboBox(Language.values());
+ logoLanguageSelection = new JComboBox(LogoLanguage.values());
+ nOfBackupsSelection = new JComboBox(NumberOfBackups.values());
userCreatable = new JCheckBox("Allow the users to create new user accounts?");
populateWorkspaceList();
setValues();
- if (WSManager.getWorkspaceConfig() == null){
+ if (WSManager.getWorkspaceConfig() == null) {
disableComponents();
- } else {
+ }
+ else {
enableComponents();
}
}
@@ -195,41 +196,49 @@ public class WorkspaceTab extends AbstractWorkspacePanel { .addComponent(nOfBackupsSelection))
.addGroup(groupLayout.createParallelGroup().addComponent(userCreatable)));
- groupLayout.setHorizontalGroup(groupLayout
- .createParallelGroup()
- .addGroup(
- groupLayout
- .createSequentialGroup()
- .addGroup(
- groupLayout.createParallelGroup().addComponent(workspaceLabel)
- .addComponent(userLabel).addComponent(wsLocationLabel)
- .addComponent(wsLanguageLabel).addComponent(wsLogoLanguageLabel)
- .addComponent(wsBackupLabel))
- .addGroup(
- groupLayout
- .createParallelGroup()
- .addGroup(
- groupLayout
- .createSequentialGroup()
- .addGroup(
- groupLayout.createParallelGroup()
- .addComponent(workspaceSelection)
- .addComponent(userSelection))
- .addGroup(
- groupLayout.createParallelGroup()
- .addComponent(addWorkspaceBtn)
- .addComponent(addUserBtn))
- .addGroup(
- groupLayout.createParallelGroup()
- .addComponent(removeWorkspaceBtn)
- .addComponent(removeUserBtn))
- .addGroup(
- groupLayout.createParallelGroup()
- .addComponent(importWorkspaceBtn)
- .addComponent(importUserBtn)))
- .addComponent(wsLocation)
- .addComponent(languageSelection).addComponent(logoLanguageSelection)
- .addComponent(nOfBackupsSelection))).addComponent(userCreatable));
+ groupLayout
+ .setHorizontalGroup(groupLayout
+ .createParallelGroup()
+ .addGroup(
+ groupLayout
+ .createSequentialGroup()
+ .addGroup(
+ groupLayout.createParallelGroup().addComponent(workspaceLabel)
+ .addComponent(userLabel).addComponent(wsLocationLabel)
+ .addComponent(wsLanguageLabel)
+ .addComponent(wsLogoLanguageLabel).addComponent(wsBackupLabel))
+ .addGroup(
+ groupLayout
+ .createParallelGroup()
+ .addGroup(
+ groupLayout
+ .createSequentialGroup()
+ .addGroup(
+ groupLayout
+ .createParallelGroup()
+ .addComponent(
+ workspaceSelection)
+ .addComponent(userSelection))
+ .addGroup(
+ groupLayout.createParallelGroup()
+ .addComponent(addWorkspaceBtn)
+ .addComponent(addUserBtn))
+ .addGroup(
+ groupLayout
+ .createParallelGroup()
+ .addComponent(
+ removeWorkspaceBtn)
+ .addComponent(removeUserBtn))
+ .addGroup(
+ groupLayout
+ .createParallelGroup()
+ .addComponent(
+ importWorkspaceBtn)
+ .addComponent(importUserBtn)))
+ .addComponent(wsLocation).addComponent(languageSelection)
+ .addComponent(logoLanguageSelection)
+ .addComponent(nOfBackupsSelection)))
+ .addComponent(userCreatable));
}
@Override
@@ -317,7 +326,7 @@ public class WorkspaceTab extends AbstractWorkspacePanel { }).run();
}
});
-
+
/*
* LOGO LANGUAGE
*/
@@ -435,7 +444,7 @@ public class WorkspaceTab extends AbstractWorkspacePanel { private void populateUserList() {
WorkspaceConfig wc = WSManager.getInstance().getWorkspaceConfigInstance();
String[] users = wc.getUserList();
- userSelection.setModel(new DefaultComboBoxModel<String>(users));
+ userSelection.setModel(new DefaultComboBoxModel(users));
//try {
//wc.enterInitialUserSpace(); // TODO maybe we still need this?
String lastUser = wc.getLastActiveUser();
diff --git a/logo/src/xlogo/interfaces/PropertyChangePublisher.java b/logo/src/xlogo/interfaces/PropertyChangePublisher.java index a953b8c..8cedafb 100644 --- a/logo/src/xlogo/interfaces/PropertyChangePublisher.java +++ b/logo/src/xlogo/interfaces/PropertyChangePublisher.java @@ -11,8 +11,8 @@ public class PropertyChangePublisher<E extends Enum<E>> implements Observable<E> private boolean enableEvents = true;
- private final HashMap<E, List<PropertyChangeListener>> listeners = new HashMap<>();
- private final List<PropertyChangeListener> allPropertiesListeners = new ArrayList<>();
+ private final HashMap<E, List<PropertyChangeListener>> listeners = new HashMap<E, List<PropertyChangeListener>>();
+ private final List<PropertyChangeListener> allPropertiesListeners = new ArrayList<PropertyChangeListener>();
@Override
public void addPropertyChangeListener(E property, PropertyChangeListener listener) {
@@ -26,7 +26,7 @@ public class PropertyChangePublisher<E extends Enum<E>> implements Observable<E> }
List<PropertyChangeListener> list = listeners.get(property);
if (list == null) {
- list = new ArrayList<>();
+ list = new ArrayList<PropertyChangeListener>();
listeners.put(property, list);
}
list.add(listener);
@@ -54,9 +54,15 @@ public class PropertyChangePublisher<E extends Enum<E>> implements Observable<E> return;
}
setEnableEvents(false);
- if (listeners.containsKey(property))
- listeners.get(property).forEach((listener) -> listener.propertyChanged());
- allPropertiesListeners.forEach((listener) -> listener.propertyChanged());
+ if (listeners.containsKey(property)){
+ for(PropertyChangeListener listener : listeners.get(property)){
+ listener.propertyChanged();
+ }
+ }
+ for(PropertyChangeListener listener : allPropertiesListeners){
+ listener.propertyChanged();
+ }
+
setEnableEvents(true);
}
diff --git a/logo/src/xlogo/kernel/DrawPanel.java b/logo/src/xlogo/kernel/DrawPanel.java index a631169..10e61ae 100644 --- a/logo/src/xlogo/kernel/DrawPanel.java +++ b/logo/src/xlogo/kernel/DrawPanel.java @@ -402,10 +402,15 @@ import xlogo.kernel.perspective.*; } shape=gp;*/ tryRecord2DMode(tortue.corX,tortue.corY); - g.draw(line); - //if (!tortue.isVisible()) - clip(); - // g.dispose(); + //g.draw(line); + //if (!tortue.isVisible()) + // clip(); + //g.dispose(); + + for (int i = 0; i < 7; i++) {// TODO find other solution for this hack + g.draw(line); + clip(); + } } montrecacheTortue(true); } else if (DrawPanel.WINDOW_MODE == DrawPanel.WINDOW_WRAP) { //mode enroule @@ -460,6 +465,8 @@ import xlogo.kernel.perspective.*; line.setLine(x1,y1,x2,y2); g.draw(line); + g.draw(line); + g.draw(line); clip(); } montrecacheTortue(true); diff --git a/logo/src/xlogo/storage/Storable.java b/logo/src/xlogo/storage/Storable.java index a3d57b3..2ba5350 100644 --- a/logo/src/xlogo/storage/Storable.java +++ b/logo/src/xlogo/storage/Storable.java @@ -93,10 +93,12 @@ public abstract class Storable implements Serializable { setPersisted(false);
try {
File file = getFilePath();
- mkParentDirs(file);
+ if (!mkParentDirs(file)){
+ return;
+ }
storeCopyToFile(file);
}
- catch (IOException ignore) { }
+ catch (Exception ignore) { }
setPersisted(true);
}
} else {
@@ -220,14 +222,16 @@ public abstract class Storable implements Serializable { "Cannot store this to specified location : " + location.toString()); }
}
- public void mkParentDirs(File file) {
+ public boolean mkParentDirs(File file) {
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
- if (!parent.isDirectory() || !parent.canWrite()) { throw new IllegalArgumentException(
- "Cannot store this to specified location : " + location.toString()); }
+ if (!parent.isDirectory() || !parent.canWrite()) {
+ return false;
+ }
+ return true;
}
/**
diff --git a/logo/src/xlogo/storage/StorableObject.java b/logo/src/xlogo/storage/StorableObject.java index 2d6fa5f..6641fea 100644 --- a/logo/src/xlogo/storage/StorableObject.java +++ b/logo/src/xlogo/storage/StorableObject.java @@ -31,6 +31,7 @@ import org.apache.logging.log4j.Logger; import xlogo.interfaces.Observable;
import xlogo.interfaces.Observable.PropertyChangeListener;
+import xlogo.storage.cache.ObjectCache;
import xlogo.storage.workspace.Serializer;
import xlogo.utils.Utils;
@@ -49,8 +50,9 @@ public class StorableObject<T extends Observable<E>, E extends Enum<E>> extends private Class<T> targetClass = null;
private T object = null;
private Serializer<T> serializer = null;
- private Initializer<T> creationInitilizer = null;
- private Initializer<T> loadInitilizer = null;
+ private Initializer<T> creationInitilizer = null;
+ private Initializer<T> loadInitilizer = null;
+ private boolean ignoreCacheOnce = false;
private transient final PropertyChangeListener objectDirtyListener = new PropertyChangeListener(){
@Override
@@ -137,28 +139,40 @@ public class StorableObject<T extends Observable<E>, E extends Enum<E>> extends * Create, Store & Load
*/
+ /**
+ * @return This must not necessarily return the same object but possibly a cached version
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ * @throws InvocationTargetException
+ * @throws NoSuchMethodException
+ * @throws SecurityException
+ */
public StorableObject<T, E> createOrLoad() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException {
- File file = getFilePath();
-
- if (file.exists()) {
- try {
- load();
- }
- catch (Exception e) {
- logger.warn("Could not load object from file " + e.toString());
- file.delete();
- }
+ StorableObject<T, E> res = null;
+ try {
+ res = load();
}
-
- if(!file.exists() || object == null){
- create();
- store();
+ catch (Exception e) {
+ logger.warn("Could not load object from file " + e.toString());
}
+ if(res == null){
+ res = create();
+ res.store();
+ }
- return this;
+ return res;
}
+ /**
+ *
+ * @return
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ * @throws InvocationTargetException
+ * @throws NoSuchMethodException
+ * @throws SecurityException
+ */
public StorableObject<T, E> create() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException {
set(getTargetClass().getConstructor().newInstance());
if (getCreationInitilizer() != null) {
@@ -168,7 +182,20 @@ public class StorableObject<T extends Observable<E>, E extends Enum<E>> extends return this;
}
+ /**
+ *
+ * @return Either a cached version
+ * @throws IOException
+ * @throws ClassNotFoundException
+ * @throws ClassCastException
+ */
public StorableObject<T, E> load() throws IOException, ClassNotFoundException, ClassCastException{
+ // Try to get object from the cache
+ StorableObject<T, E> res = ignoreCache()? null : ObjectCache.getInstance().get(getFilePath(), getTargetClass());
+ if (res != null){
+ return res;
+ }
+ // Otherwise load from file
setPersisted(false);
if (getSerializer() != null){
set(loadObject(getFilePath(), getSerializer()));
@@ -295,6 +322,7 @@ public class StorableObject<T extends Observable<E>, E extends Enum<E>> extends }
this.object = object;
+ ObjectCache.getInstance().cache(this);
if (this.object != null){
object.addPropertyChangeListener(null, objectDirtyListener);
@@ -354,6 +382,29 @@ public class StorableObject<T extends Observable<E>, E extends Enum<E>> extends return this;
}
+ /**
+ * The next time this object is loaded or created, the cached objects are being ignored (and possibly overwritten)
+ * @return
+ */
+ public StorableObject<T, E> ignoreCacheOnce(){
+ ignoreCacheOnce = true;
+ return this;
+ }
+
+ protected boolean ignoreCache(){
+ boolean result = ignoreCacheOnce;
+ ignoreCacheOnce = false;
+ return result;
+ }
+
+ /*
+ * Misc
+ */
+
+ public String toString(){
+ File path = getFilePath();
+ return getClass().getSimpleName() + ": {path:" + (path != null ? path.toString() : "undefined") + "}";
+ }
/*
* Interfaces
diff --git a/logo/src/xlogo/storage/WSManager.java b/logo/src/xlogo/storage/WSManager.java index 0e5f832..529417b 100644 --- a/logo/src/xlogo/storage/WSManager.java +++ b/logo/src/xlogo/storage/WSManager.java @@ -24,13 +24,6 @@ package xlogo.storage; import java.io.File;
import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-
-import net.samuelcampos.usbdrivedectector.USBDeviceDetectorManager;
-import net.samuelcampos.usbdrivedectector.USBStorageDevice;
-import net.samuelcampos.usbdrivedectector.events.IUSBDriveListener;
-import net.samuelcampos.usbdrivedectector.events.USBStorageEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -43,6 +36,7 @@ import xlogo.storage.global.GlobalConfig; import xlogo.storage.global.GlobalConfig.GlobalProperty;
import xlogo.storage.user.UserConfig;
import xlogo.storage.user.UserConfig.UserProperty;
+import xlogo.storage.user.UserConfigJSONSerializer;
import xlogo.storage.workspace.WorkspaceConfig;
import xlogo.storage.workspace.WorkspaceConfig.WorkspaceProperty;
import xlogo.storage.workspace.WorkspaceConfigJSONSerializer;
@@ -81,9 +75,9 @@ import xlogo.utils.Utils; public class WSManager {
private static Logger logger = LogManager.getLogger(WSManager.class.getSimpleName());
- /*
- * Singleton instantiation
- */
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Singleton
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private static WSManager instance;
private static boolean isConstructingSingleton = false;
@@ -98,6 +92,11 @@ public class WSManager { }
return instance;
}
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Config Access
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* This is a shortcut for {@code WSManager.getInstance().getWorkspaceConfigInstance()}
@@ -126,256 +125,150 @@ public class WSManager { public static UserConfig getUserConfig() {
return getInstance().getUserConfigInstance();
}
-
- private transient USBDeviceDetectorManager driveDetector = new USBDeviceDetectorManager();
- private StorableObject<GlobalConfig, GlobalProperty> globalConfig;
- private WSManager() {
- try {
- globalConfig = new StorableObject<>(GlobalConfig.class, GlobalConfig.DEFAULT_LOCATION)
- .withCreationInitializer(gc -> {
- createWorkspace(gc, WorkspaceConfig.DEFAULT_DIRECTORY);
- WorkspaceConfig wc = gc.getCurrentWorkspace().get(); // TODO wc.getLocation() is null at this place :(
- createUser(wc, UserConfig.DEFAULT_DIRECTORY);
- init(gc);
- })
- .withLoadInitializer(gc -> init(gc))
- .createOrLoad();
- }
- catch (Exception e) {
- DialogMessenger.getInstance().dispatchError("Unable to Initilize Global Configuration", e.toString());
- }
- }
-
- protected void init(GlobalConfig gc){
- initUSBWorkspaces(gc);
- gc.cleanUpWorkspaces();
- enterInitialWorkspace(gc);
+ /**
+ * @return the instance of the GlobalConfig
+ */
+ public GlobalConfig getGlobalConfigInstance() {
+ return globalConfig.get();
}
/**
- * This is used to have a workspace ready at the beginning, without any user interaction.
- * <p>
- * Tries to enter workspaces with the following priority.
- * 1. Last used workspace (if any)
- * 2. Default workspace, if there is no last used workspace
- * 3. Virtual Workspace, if entering or creating the default workspace failed for some reason.
+ * @return the active workspace
*/
- protected void enterInitialWorkspace(GlobalConfig gc) {
- logger.trace("Entering initial workspace.");
-
- if (gc.getAllWorkspaces().length == 0){
- logger.warn("No workspaces available.");
- return;
- }
-
- String initialWs = getFirstUSBWorkspace(gc);
-
- if (initialWs == null) {
- initialWs = gc.getLastUsedWorkspace();
- }
-
- if (initialWs == null) {
- logger.warn("No workspaces available.");
- initialWs = gc.getAllWorkspaces()[0];
- }
-
- try {
- enterWorkspace(gc, initialWs);
- }
- catch (IOException e1) {
- DialogMessenger.getInstance().dispatchError("Workspace Error", "Cannot enter workspace: " + e1.toString());
+ public WorkspaceConfig getWorkspaceConfigInstance() {
+ if (getGlobalConfigInstance().getCurrentWorkspace() != null){
+ return getGlobalConfigInstance().getCurrentWorkspace().get();
}
+ return null;
}
-
- /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
- * USB Detection & Handling
- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
-
+
/**
- * Detect External Drives
+ * @return the active user
*/
- protected void initUSBWorkspaces(GlobalConfig gc) {
- if (driveDetector != null){
- return;
- }
-
- driveDetector = new USBDeviceDetectorManager(800);
-
- for (USBStorageDevice rmDevice : driveDetector.getRemovableDevices()) {
- if (rmDevice.canRead() && rmDevice.canWrite()) {
- addUSBDrive(gc, rmDevice);
+ public UserConfig getUserConfigInstance() {
+ WorkspaceConfig wc = getWorkspaceConfigInstance();
+ if (wc == null)
+ return null;
+ else
+ return wc.getActiveUser().get();
+ }
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Initialization
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ private USBWorkspaceManager usbManager;
+ private StorableObject<GlobalConfig, GlobalProperty> globalConfig;
+ private boolean hasEnteredApplication = false;
+
+ private WSManager() {
+ usbManager = new USBWorkspaceManager(new USBWorkspaceManager.WorkspaceContainer(){
+ @Override
+ public void add(StorableObject<WorkspaceConfig, WorkspaceProperty> usbwc) {
+ GlobalConfig gc = getGlobalConfigInstance();
+ if (!hasEnteredApplication){
+ gc.addWorkspace(usbwc);
+ enterWorkspace(gc, usbwc);
+ }
}
- }
-
- driveDetector.addDriveListener(new IUSBDriveListener(){
@Override
- public void usbDriveEvent(USBStorageEvent event) {
- USBStorageDevice rmDevice = event.getStorageDevice();
- switch (event.getEventType()) {
- case CONNECTED:
- addUSBDrive(gc, rmDevice);
- break;
- case REMOVED:
- removeUSBDrive(gc, rmDevice);
- break;
+ public void remove(StorableObject<WorkspaceConfig, WorkspaceProperty> usbwc) {
+ GlobalConfig gc = getGlobalConfigInstance();
+ if (hasEnteredApplication){
+ if (usbwc.equals(gc.getCurrentWorkspace())){
+ // TODO translate
+ DialogMessenger.getInstance().dispatchError(
+ "USB Stick Removed",
+ "I will not be able to remember your changes. Please reinsert your USB stick.");
+ }
+ // else ignore
+ } else {
+ gc.removeWorkspace(usbwc.get().getWorkspaceName());
+ enterInitialWorkspace(gc);
}
}
});
- }
-
- protected void addUSBDrive(GlobalConfig gc, USBStorageDevice rmDevice) {
- if (gc.getWorkspaceDirectory(rmDevice.getSystemDisplayName()) == null) {
- logger.trace("USB Drive attached: " + rmDevice);
- String deviceName = rmDevice.getSystemDisplayName();
- File location = rmDevice.getRootDirectory();
- gc.addWorkspace(deviceName, location.getAbsolutePath());
- }
- }
-
- protected void removeUSBDrive(GlobalConfig gc, USBStorageDevice rmDevice) {
- logger.trace("USB Drive removed: " + rmDevice);
- String deviceName = rmDevice.getSystemDisplayName();
- gc.removeWorkspace(deviceName);
- }
-
- protected StorableObject<WorkspaceConfig, WorkspaceProperty> initUSBDrive(GlobalConfig gc, String deviceName) throws IOException {
- logger.trace("Initializing USB Drive: " + deviceName);
- File usbRoot = null;
- for (USBStorageDevice device : driveDetector.getRemovableDevices()) {
- if (deviceName.equals(device.getSystemDisplayName())) {
- usbRoot = device.getRootDirectory();
- break;
- }
- }
- if (usbRoot == null) { return null; }
- StorableObject<WorkspaceConfig, WorkspaceProperty> wsc =
- new StorableObject<>(WorkspaceConfig.class, usbRoot, WorkspaceConfig.USB_DEFAULT_WORKSPACE, true);
+ globalConfig = new StorableObject<GlobalConfig, GlobalProperty>(GlobalConfig.class,
+ GlobalConfig.DEFAULT_LOCATION).withCreationInitializer(new StorableObject.Initializer<GlobalConfig>(){
+ @Override
+ public void init(GlobalConfig gc) {
+ StorableObject<WorkspaceConfig,WorkspaceProperty> wc = createWorkspace(gc, WorkspaceConfig.DEFAULT_DIRECTORY);
+ createUser(wc, UserConfig.DEFAULT_DIRECTORY);
+ initGc(gc);
+ }
+
+ }).withLoadInitializer(new StorableObject.Initializer<GlobalConfig>(){
+ @Override
+ public void init(GlobalConfig gc) {
+ initGc(gc);
+ }
+ });
try {
- wsc.createOrLoad();
- gc.addWorkspace(wsc);
- }
- catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ globalConfig = globalConfig.createOrLoad();
}
- /*
- File wsDir = StorableObject.getDirectory(usbRoot, WorkspaceConfig.USB_DEFAULT_WORKSPACE);
- File wsConfigFile = StorableObject.getSerFile(wsDir, WorkspaceConfig.class);
- if (wsConfigFile.exists()) {
- logger.trace("Loading USB workspace from " + wsDir.getAbsolutePath());
- wsc = WorkspaceConfig.loadWorkspace(usbRoot, WorkspaceConfig.USB_DEFAULT_WORKSPACE);
- for (String user : wsc.getUserList()) {
- logger.trace("\t Having user " + user);
- }
+ catch (Exception e) {
+ DialogMessenger.getInstance().dispatchError("Unable to Initilize Global Configuration", e.toString());
}
- else {
- logger.trace("Creating new temporary USB workspace at " + usbRoot);
- wsc = WorkspaceConfig.createDeferredWorkspace(usbRoot, WorkspaceConfig.USB_DEFAULT_WORKSPACE);
- wsc.setUserCreationAllowed(true);
- }*/
- return wsc;
}
- public String getFirstUSBWorkspace(GlobalConfig gc) {
- for (String ws : gc.getAllWorkspaces()) {
- if (isUSBDrive(ws)) { return ws; }
+ protected void initGc(GlobalConfig gc){
+ usbManager.init();
+ gc.cleanUpWorkspaces();
+ StorableObject<WorkspaceConfig,WorkspaceProperty> wc = enterInitialWorkspace(gc);
+ if (wc != null && wc.get() != null){
+ enterInitialUserSpace(wc);
}
- return null;
}
- public boolean isUSBDrive(String workspaceName) {
- List<USBStorageDevice> devices = driveDetector.getRemovableDevices();
- logger.trace("Is '" + workspaceName + "' on a USB Drive?");
- for (USBStorageDevice device : devices) {
- if (workspaceName.equals(device.getSystemDisplayName())) {
- logger.trace("\t = Yes, corresponding USB Device found.");
- return true;
- }
- else {
- logger.trace("\t Does not corresponding to " + device.getSystemDisplayName());
- }
- }
-
- logger.trace("\t = No, could not find corresponding USB Drive.");
- return false;
+ public void enterApplication(){
+ hasEnteredApplication = true;
}
- /*
- * Config Creation
- */
-
/**
- * Load the specified user's settings from the current workspace
- * or create the user if it does not exist yet or if it was deleted for unknown reasons.
- * @param workspace
- * @param username
- * @return the loaded UserConfig
- * @throws IOException
+ * This is used to have a workspace ready at the beginning, without any user interaction.
+ * <p>
+ * Tries to enter workspaces with the following priority.
+ * 1. Last used workspace (if any)
+ * 2. Default workspace, if there is no last used workspace
+ * 3. Virtual Workspace, if entering or creating the default workspace failed for some reason.
*/
- public static StorableObject<UserConfig, UserProperty> getUser(File location, String username) {
+ protected StorableObject<WorkspaceConfig,WorkspaceProperty> enterInitialWorkspace(GlobalConfig gc) {
+ logger.trace("Entering initial workspace.");
- if (!isWorkspaceDirectory(location)) {
- DialogMessenger.getInstance().dispatchError(Logo.messages.getString(MessageKeys.WS_ERROR_TITLE),
- Logo.messages.getString(MessageKeys.WS_DOES_NOT_EXIST));
+ if (gc.getAllWorkspaces().length == 0){
+ logger.warn("No workspaces available.");
return null;
}
- if (!Storable.checkLegalName(username)) {
- DialogMessenger.getInstance().dispatchError(Logo.messages.getString(MessageKeys.NAME_ERROR_TITLE),
- Logo.messages.getString(MessageKeys.ILLEGAL_NAME));
- return null;
- }
- File userDir = Storable.getDirectory(location, username);
- StorableObject<UserConfig, UserProperty> userConfig = new StorableObject<>(UserConfig.class, userDir);
- try {
- userConfig.createOrLoad();
+ String initialWs = usbManager.getFirstUSBWorkspace(gc.getAllWorkspaces());
+ if (initialWs != null) {
+ File wsDir = usbManager.getWorkspaceDirectory(initialWs);
+ StorableObject<WorkspaceConfig, WorkspaceProperty> wc = WorkspaceConfigJSONSerializer.createOrLoad(wsDir, true);
+ return enterWorkspace(gc, wc);
}
- catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+
+ initialWs = gc.getLastUsedWorkspace();
+
+ if (initialWs == null) {
+ initialWs = gc.getAllWorkspaces()[0];
}
- userConfig.get().setDirectory(userDir);
- return userConfig;
+ return enterWorkspace(gc, initialWs);
}
- /*
- * Config access
- */
-
- /**
- * @return the instance of the GlobalConfig
- */
- public GlobalConfig getGlobalConfigInstance() {
- return globalConfig.get();
- }
-
- /**
- * @return the active workspace
- */
- public WorkspaceConfig getWorkspaceConfigInstance() {
- if (getGlobalConfigInstance().getCurrentWorkspace() != null){
- return getGlobalConfigInstance().getCurrentWorkspace().get();
+ public void enterInitialUserSpace(StorableObject<WorkspaceConfig,WorkspaceProperty> wc) {
+ String user = wc.get().getLastActiveUser();
+
+ if (user != null && wc.get().existsUserLogically(user)){
+ enterUserSpace(user);
}
- return null;
- }
-
- /**
- * @return the active user
- */
- public UserConfig getUserConfigInstance() {
- WorkspaceConfig wc = getWorkspaceConfigInstance();
- if (wc == null)
- return null;
- else
- return wc.getActiveUser().get();
}
- /*
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* WORKSPACE CONFIG : create, delete, enter
- */
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* A new workspace is created in the defined directory.
@@ -383,9 +276,8 @@ public class WSManager { * @see WorkspaceConfig#loadWorkspace(File)
* @param location
* @param name
- * @throws IOException
*/
- public void createWorkspace(File location, String name) throws IOException { // TODO delegate to overloaded method above
+ public void createWorkspace(File location, String name) {
File wsDir = StorableObject.getDirectory(location, name);
GlobalConfig gc = getGlobalConfig();
createWorkspace(gc, wsDir);
@@ -402,19 +294,13 @@ public class WSManager { StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> wc;
wc = WorkspaceConfigJSONSerializer.createOrLoad(wsDir);
if (wc != null){
- try {
- gc.addWorkspace(wc);
- enterWorkspace(gc, wsDir.getName());
- }
- catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ gc.addWorkspace(wc);
+ enterWorkspace(gc, wsDir.getName());
}
return wc;
}
- public void deleteWorkspace(String wsName, boolean deleteFromDisk) throws SecurityException {
+ public void deleteWorkspace(String wsName, boolean deleteFromDisk) {
GlobalConfig gc = getGlobalConfigInstance();
File wsDir = gc.getWorkspaceDirectory(wsName);
gc.leaveWorkspace();
@@ -436,10 +322,7 @@ public class WSManager { return;
}
getGlobalConfigInstance().addWorkspace(workspaceName, workspaceDir.getParent());
- try {
- enterWorkspace(workspaceName);
- }
- catch (IOException ignore) { /* This won't hopefully ever happen. */}
+ enterWorkspace(workspaceName);
}
/**
@@ -448,36 +331,51 @@ public class WSManager { * @param workspaceName - the workspace to load and enter
* @throws IOException - if the old workspace could not be loaded
*/
- public void enterWorkspace(String workspaceName) throws IOException {
+ public void enterWorkspace(String workspaceName) {
GlobalConfig gc = getGlobalConfigInstance();
enterWorkspace(gc, workspaceName);
}
- protected void enterWorkspace(GlobalConfig gc, String workspaceName) throws IOException {
- if(gc.getCurrentWorkspace() != null && workspaceName.equals(gc.getCurrentWorkspace().get().getWorkspaceName())){
+ protected StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> enterWorkspace(GlobalConfig gc, String workspaceName) {
+ StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> wc = gc.getCurrentWorkspace();
+ if(wc != null && workspaceName.equals(wc.get().getWorkspaceName())){
logger.trace("I'm already in workspace: " + workspaceName);
- return;
+ return gc.getCurrentWorkspace();
}
- if (isUSBDrive(workspaceName)) {
+ wc = null;
+
+ if (usbManager.isUSBDrive(workspaceName)) {
logger.trace("Retrieving USB workspace: " + workspaceName);
- initUSBDrive(gc, workspaceName);
+ wc = usbManager.createOrLoad(workspaceName);
}
- File wsDir = gc.getWorkspaceDirectory(workspaceName);
- if (wsDir == null){
- logger.error("Can't find workspace " + workspaceName);
- return;
+
+ if (wc == null){
+ File wsDir = gc.getWorkspaceDirectory(workspaceName);
+
+ if (wsDir == null){
+ logger.error("Can't find workspace " + workspaceName);
+ return gc.getCurrentWorkspace();
+ }
+ wc = WorkspaceConfigJSONSerializer.createOrLoad(wsDir);
}
- StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> wc = WorkspaceConfigJSONSerializer.createOrLoad(wsDir);
+
if (wc == null){
logger.error("Can't enter workspace because creation or laod failed for " + workspaceName);
- return;
+ return gc.getCurrentWorkspace();
}
- gc.enterWorkspace(wc);
+
+ return enterWorkspace(gc, wc);
+ }
+
+ protected StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> enterWorkspace(GlobalConfig gc, StorableObject<WorkspaceConfig, WorkspaceProperty> wc) {
+ gc.enterWorkspace(wc);
+ enterInitialUserSpace(wc);
+ return gc.getCurrentWorkspace();
}
- /*
- * USER CONFIG : create, delete, enter
- */
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * USER CONFIG : create, delete, enter
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* A new user is created in the current workspace.
@@ -490,24 +388,21 @@ public class WSManager { throw new IllegalStateException("Cannot create a user directory outside of workspaces. Use createUser(File dir) for special cases.");
}
File userDir = StorableObject.getDirectory(wc.getLocation(), username);
- createUser(wc.get(), userDir);
+ createUser(wc, userDir);
}
- private void createUser(WorkspaceConfig wc, File userDir){
- StorableObject<UserConfig, UserConfig.UserProperty> duc = new StorableObject<>(UserConfig.class, userDir);
+ private void createUser(StorableObject<WorkspaceConfig,WorkspaceProperty> wc, File userDir){
+ StorableObject<UserConfig, UserConfig.UserProperty> duc = new StorableObject<UserConfig,UserProperty>(UserConfig.class, userDir);
try {
- duc.createOrLoad();
+ duc = duc.createOrLoad();
}
- catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException e) { }
+ catch (Exception e) { }
if (!duc.isPersisted()){
logger.warn("Could not persist user files.");
}
duc.get().setDirectory(userDir);
- wc.addUser(duc);
- try {
- enterUserSpace(wc, userDir.getName());
- }
- catch (IOException ignore) { /* This won't ever happen hopefully */ }
+ wc.get().addUser(duc);
+ enterUserSpace(wc.get(), duc);
}
/**
@@ -555,22 +450,32 @@ public class WSManager { /**
* @throws IOException If the old userConfig could not be stored.
*/
- public void enterUserSpace(String name) throws IOException {
+ public void enterUserSpace(String name) {
WorkspaceConfig wc = getWorkspaceConfigInstance();
if (wc == null)
throw new IllegalStateException("Must be in WorkspaceDirectory first to enter UserSpace.");
enterUserSpace(wc, name);
}
- private void enterUserSpace(WorkspaceConfig wc, String name) throws IOException {
- wc.enterUserSpace(name);
+ protected void enterUserSpace(WorkspaceConfig wc, String username) {
+ File userDir = StorableObject.getDirectory(wc.getDirectory(), username);
+ StorableObject<UserConfig, UserProperty> uc = UserConfigJSONSerializer.createOrLoad(userDir);
+ if (uc != null){
+ enterUserSpace(wc, uc);
+ } else {
+ DialogMessenger.getInstance().dispatchError("Workspace Error", "Cannot enter workspace.");
+ }
}
- /*
- * Short cuts
- */
+ protected void enterUserSpace(WorkspaceConfig wc, StorableObject<UserConfig, UserProperty> uc) {
+ wc.enterUserSpace(uc);
+ }
- public void storeAllSettings() throws IOException {
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * SHORTCUTS
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+ public void storeAllSettings() {
globalConfig.store();
StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> swc = globalConfig.get().getCurrentWorkspace();
if (swc == null) { return; }
@@ -580,9 +485,17 @@ public class WSManager { suc.store();
}
- /*
- * DIRECTORIES & FILE MANIPULATION
+ /**
+ * Make sure all threads are stopped and open files saved and closed.
*/
+ public void stopEverything(){
+ usbManager.stop();
+ storeAllSettings();
+ }
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DIRECTORIES & FILE MANIPULATION
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
public static File[] listDirectories(File dir) {
File[] dirs = dir.listFiles(new java.io.FileFilter(){
diff --git a/logo/src/xlogo/storage/global/GlobalConfig.java b/logo/src/xlogo/storage/global/GlobalConfig.java index 6195142..61beb9f 100644 --- a/logo/src/xlogo/storage/global/GlobalConfig.java +++ b/logo/src/xlogo/storage/global/GlobalConfig.java @@ -25,7 +25,6 @@ package xlogo.storage.global; import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.File;
-import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
@@ -109,6 +108,12 @@ public class GlobalConfig implements Serializable, Observable<GlobalConfig.Globa * Logical Workspaces (name and location stored in Map)
*/
private Map<String, String> workspaces;
+
+ public void addWorkspace(StorableObject<WorkspaceConfig, WorkspaceProperty> wc) {
+ File location = wc.getLocation();
+ String name = wc.get().getWorkspaceName();
+ addWorkspace(name, location.getParentFile().toString());
+ }
/**
* @param workspaceName
@@ -118,13 +123,6 @@ public class GlobalConfig implements Serializable, Observable<GlobalConfig.Globa logger.trace("Adding workspace: '" + workspaceName + "' at " + location);
workspaces.put(workspaceName, location);
publisher.publishEvent(GlobalProperty.WORKSPACES);
- setLastUsedWorkspace(workspaceName);
- }
-
- public void addWorkspace(StorableObject<WorkspaceConfig, WorkspaceProperty> wc) {
- File location = wc.getLocation();
- String name = wc.get().getWorkspaceName();
- addWorkspace(name, location.getParentFile().toString());
}
public void removeWorkspace(String workspaceName) {
@@ -134,7 +132,7 @@ public class GlobalConfig implements Serializable, Observable<GlobalConfig.Globa leaveWorkspace();
}
- if (lastUsedWorkspace.equals(workspaceName)) {
+ if (workspaceName.equals(lastUsedWorkspace)) {
lastUsedWorkspace = null;
publisher.publishEvent(GlobalProperty.LAST_USED_WORKSPACE);
}
@@ -228,9 +226,8 @@ public class GlobalConfig implements Serializable, Observable<GlobalConfig.Globa * Load the workspace
* <p>Always succeeds if workspaceName equals {@link WorkspaceConfig#VIRTUAL_WORKSPACE}
* @param workspaceName - the workspace to load and enter
- * @throws IOException - if the workspace could not be loaded
*/
- public void enterWorkspace(StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> wc) throws IOException {
+ public void enterWorkspace(StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> wc) {
String name = wc.get().getWorkspaceName();
logger.trace("Entering workspace: " + name);
if (currentWorkspace != null) {
@@ -241,13 +238,10 @@ public class GlobalConfig implements Serializable, Observable<GlobalConfig.Globa setLastUsedWorkspace(name);
publisher.publishEvent(GlobalProperty.CURRENT_WORKSPACE);
-
- currentWorkspace.get().enterInitialUserSpace();
}
/**
* Afterwards, currentWorkspace is null
- * @throws IOException If workspace could not be saved.
*/
public void leaveWorkspace() {
if (currentWorkspace == null)
@@ -256,13 +250,7 @@ public class GlobalConfig implements Serializable, Observable<GlobalConfig.Globa logger.trace("Leaving workspace: " + currentWorkspace.get().getWorkspaceName());
if (currentWorkspace.get().getActiveUser() != null) {
- try {
- currentWorkspace.get().leaveUserSpace();
- }
- catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ currentWorkspace.get().leaveUserSpace();
}
if (currentWorkspace.isDirty())
@@ -458,12 +446,12 @@ public class GlobalConfig implements Serializable, Observable<GlobalConfig.Globa PATH, PASSWORD, LAST_USED_WORKSPACE, CURRENT_WORKSPACE, WORKSPACES;
}
- private transient PropertyChangePublisher<GlobalProperty> publisher = new PropertyChangePublisher<>();
+ private transient PropertyChangePublisher<GlobalProperty> publisher = new PropertyChangePublisher<GlobalProperty>();
@Override
public void addPropertyChangeListener(GlobalProperty property, PropertyChangeListener listener) {
if (publisher == null){
- publisher = new PropertyChangePublisher<>();
+ publisher = new PropertyChangePublisher<GlobalProperty>();
}
publisher.addPropertyChangeListener(property, listener);
}
diff --git a/logo/src/xlogo/storage/user/UserConfig.java b/logo/src/xlogo/storage/user/UserConfig.java index e0344f1..52a5b55 100644 --- a/logo/src/xlogo/storage/user/UserConfig.java +++ b/logo/src/xlogo/storage/user/UserConfig.java @@ -703,12 +703,12 @@ public class UserConfig implements Serializable, Observable<UserConfig.UserPrope TCP_PORT;
}
- private transient PropertyChangePublisher<UserProperty> publisher = new PropertyChangePublisher<>();
+ private transient PropertyChangePublisher<UserProperty> publisher = new PropertyChangePublisher<UserProperty>();
@Override
public void addPropertyChangeListener(UserProperty property, PropertyChangeListener listener) {
if (publisher == null){
- publisher = new PropertyChangePublisher<>();
+ publisher = new PropertyChangePublisher<UserProperty>();
}
publisher.addPropertyChangeListener(property, listener);
}
diff --git a/logo/src/xlogo/storage/workspace/WorkspaceConfig.java b/logo/src/xlogo/storage/workspace/WorkspaceConfig.java index 0f2154d..2f2a8db 100644 --- a/logo/src/xlogo/storage/workspace/WorkspaceConfig.java +++ b/logo/src/xlogo/storage/workspace/WorkspaceConfig.java @@ -29,11 +29,8 @@ package xlogo.storage.workspace; import java.awt.Font;
import java.io.File;
-import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
-import java.util.Map;
-import java.util.TreeMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -94,13 +91,22 @@ public class WorkspaceConfig implements Serializable, Observable<WorkspaceConfig this.wsDir = wsDir;
}
+ private transient String wsName;
+
public String getWorkspaceName(){
+ if (wsName != null){
+ return wsName;
+ }
File wsDir = getDirectory();
if (wsDir == null)
throw new IllegalStateException("Name is not available because location is null.");
return wsDir.getName();
}
+ public void setWorkspaceName(String wsName){
+ this.wsName = wsName;
+ }
+
/*
* Persistent Fields
*/
@@ -159,21 +165,7 @@ public class WorkspaceConfig implements Serializable, Observable<WorkspaceConfig return activeUser;
}
- public void enterInitialUserSpace() throws IOException{
- String user = getLastActiveUser();
- if (user != null && userList.contains(user)){
- enterUserSpace(user);
- }
- }
-
- /**
- * @throws IOException If the old userConfig could not be stored.
- */
- public void enterUserSpace(String username) throws IOException {
- enterUserSpace(retrieveUserSpace(username));
- }
-
- public void enterUserSpace(StorableObject<UserConfig, UserProperty> userConfig) throws IOException {
+ public void enterUserSpace(StorableObject<UserConfig, UserProperty> userConfig) {
if(userConfig == activeUser){
return;
}
@@ -184,51 +176,17 @@ public class WorkspaceConfig implements Serializable, Observable<WorkspaceConfig logger.trace("Entering user space: " + userConfig.get().getUserName());
activeUser = userConfig;
+ publisher.publishEvent(WorkspaceProperty.USER);
setLastActiveUser(userConfig.get().getUserName());
}
- /**
- * @throws IOException If userConfig could not be stored.
- */
- public void leaveUserSpace() throws IOException {
+ public void leaveUserSpace() {
logger.trace("Leaving user space: " + activeUser.get().getUserName());
if (activeUser.isDirty())
activeUser.store();
activeUser = null;
}
-
-
- protected StorableObject<UserConfig, UserProperty> retrieveUserSpace(String username){
- StorableObject<UserConfig, UserProperty> uc = getCachedUserSpace(username);
- if (uc == null && getDirectory() != null){
- uc = WSManager.getUser(getDirectory(), username);
- cacheUserSpace(username, uc);
- }
- return uc;
- }
-
- /**
- * User Cache
- *
- * UserConfigs that have already been created or loaded from disk.
- */
- private transient Map<String, StorableObject<UserConfig, UserProperty>> cachedUserSpaces;
-
- private StorableObject<UserConfig, UserProperty> getCachedUserSpace(String username) {
- if (cachedUserSpaces == null){
- cachedUserSpaces= new TreeMap<String, StorableObject<UserConfig, UserProperty>>();
- }
- return cachedUserSpaces.get(username);
- }
-
- private void cacheUserSpace(String username, StorableObject<UserConfig, UserProperty> wsc){
- if (cachedUserSpaces == null){
- cachedUserSpaces= new TreeMap<String, StorableObject<UserConfig, UserProperty>>();
- }
- cachedUserSpaces.put(username, wsc);
- }
-
/*
* User list
*/
@@ -244,23 +202,19 @@ public class WorkspaceConfig implements Serializable, Observable<WorkspaceConfig public void addUser(StorableObject<UserConfig, UserConfig.UserProperty> uc){
String name = uc.get().getUserName();
- cacheUserSpace(name, uc);
addUser(name);
}
/**
* @param userName will be removed logically only
- * @throws IOException
*/
public void removeUser(String username){
logger.trace("Removing user: " + username);
if (existsUserLogically(username)){
userList.remove(username);
- cachedUserSpaces.remove(username);
publisher.publishEvent(WorkspaceProperty.USER_LIST);
} else {
userList.remove(username);
- cachedUserSpaces.remove(username);
}
if (activeUser != null && activeUser.get().getUserName().equals(username)){
@@ -524,15 +478,15 @@ public class WorkspaceConfig implements Serializable, Observable<WorkspaceConfig */
public enum WorkspaceProperty {
- FONT, SYNTAX_HIGHLIGHTING, ALLOW_USER_CREATION, LANGUAGE, N_OF_BACKUPS, LAST_ACTIVE_USER, USER_LIST, CONTEST, LOGO_LANGUAGE;
+ FONT, SYNTAX_HIGHLIGHTING, ALLOW_USER_CREATION, LANGUAGE, N_OF_BACKUPS, LAST_ACTIVE_USER, USER_LIST, CONTEST, LOGO_LANGUAGE, USER;
}
- private transient PropertyChangePublisher<WorkspaceProperty> publisher = new PropertyChangePublisher<>();
+ private transient PropertyChangePublisher<WorkspaceProperty> publisher = new PropertyChangePublisher<WorkspaceProperty>();
@Override
public void addPropertyChangeListener(WorkspaceProperty property, PropertyChangeListener listener) {
if (publisher == null){
- publisher = new PropertyChangePublisher<>();
+ publisher = new PropertyChangePublisher<WorkspaceProperty>();
}
publisher.addPropertyChangeListener(property, listener);
}
diff --git a/logo/src/xlogo/storage/workspace/WorkspaceConfigJSONSerializer.java b/logo/src/xlogo/storage/workspace/WorkspaceConfigJSONSerializer.java index a53fab4..d48ff47 100644 --- a/logo/src/xlogo/storage/workspace/WorkspaceConfigJSONSerializer.java +++ b/logo/src/xlogo/storage/workspace/WorkspaceConfigJSONSerializer.java @@ -2,7 +2,6 @@ package xlogo.storage.workspace; import java.awt.Font;
import java.io.File;
-import java.lang.reflect.InvocationTargetException;
import org.json.JSONArray;
import org.json.JSONObject;
@@ -36,17 +35,26 @@ public class WorkspaceConfigJSONSerializer extends JSONSerializer<WorkspaceConfi private static final String NUMBER_OF_BACKUPS = "numberOfBackups";
private static final String USER_LIST = "userList";
private static final String LAST_ACTIVE_USER = "lastActiveUser";
+
+ public static StorableObject<WorkspaceConfig, WorkspaceProperty> createOrLoad(File wsDir){
+ return createOrLoad(wsDir, false, false);
+ }
+ public static StorableObject<WorkspaceConfig, WorkspaceProperty> createOrLoad(File wsDir, boolean isDeferred){
+ return createOrLoad(wsDir, isDeferred, false);
+ }
- public static StorableObject<WorkspaceConfig, WorkspaceProperty> createOrLoad(File wsDir){
+ public static StorableObject<WorkspaceConfig, WorkspaceProperty> createOrLoad(File wsDir, boolean isDeferred, boolean ignoreCacheOnce){
StorableObject<WorkspaceConfig, WorkspaceConfig.WorkspaceProperty> wc;
- wc = new StorableObject<>(WorkspaceConfig.class, wsDir).withSerializer(new WorkspaceConfigJSONSerializer());
+ wc = new StorableObject<WorkspaceConfig,WorkspaceProperty>(WorkspaceConfig.class, wsDir).withSerializer(new WorkspaceConfigJSONSerializer());
+ if (ignoreCacheOnce){
+ wc.ignoreCacheOnce();
+ }
try {
- wc.createOrLoad();
+ wc = wc.createOrLoad();
wc.get().setDirectory(wsDir);
- return wc;
}
- catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
+ catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
diff --git a/logo/src/xlogo/utils/Utils.java b/logo/src/xlogo/utils/Utils.java index 612d4b8..991cc8e 100644 --- a/logo/src/xlogo/utils/Utils.java +++ b/logo/src/xlogo/utils/Utils.java @@ -40,13 +40,13 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.nio.charset.Charset; -import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @@ -499,9 +499,36 @@ public class Utils { return readFile(src, Charset.forName("UTF8")); } - public static String readFile(File src, Charset charset) throws IOException { - byte[] encoded = Files.readAllBytes(src.toPath()); - return new String(encoded, charset); + public static String readFile(File file, Charset charset) throws IOException { + InputStream is = new FileInputStream(file); + + // Get the size of the file + long length = file.length(); + + if (length > Integer.MAX_VALUE) { + // File is too large + } + + // Create the byte array to hold the data + byte[] bytes = new byte[(int)length]; + + // Read in the bytes + int offset = 0; + int numRead = 0; + while (offset < bytes.length + && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { + offset += numRead; + } + + // Ensure all the bytes have been read in + if (offset < bytes.length) { + is.close(); + throw new IOException("Could not completely read file "+file.getName()); + } + + // Close the input stream and return bytes + is.close(); + return new String(bytes, charset); } /** |